Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38ebce24ab |
@@ -4,6 +4,11 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `a
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
### Contracts
|
||||||
|
|
||||||
|
- AI status (Hub protocol §3b): optional `usedInputTokens`, `usedOutputTokens`, `capInputTokens`,
|
||||||
|
`capOutputTokens` (Hub 2.0.1). Churches see tokens; the cents stay for the Hub and older installs.
|
||||||
|
|
||||||
### Docs
|
### Docs
|
||||||
|
|
||||||
- The roadmap (`docs/ROADMAP-v3.md`) and the Hub protocol (`docs/hub-protocol.md`) move here from
|
- The roadmap (`docs/ROADMAP-v3.md`) and the Hub protocol (`docs/hub-protocol.md`) move here from
|
||||||
|
|||||||
@@ -9,14 +9,17 @@ and this project follows [Semantic Versioning](https://semver.org/).
|
|||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- **Everything the backend serves is under `/api`** (for 2.3.0), so the site and its API can share
|
- **AI use is shown in tokens, not rand** (for 2.3.0; needs Hub 2.0.1 for the token figures). Site
|
||||||
one address (`events.church.co.za`, no `events-api.` record) with a single proxy rule: `/api` →
|
settings → AI shows the percentage used, the input and output tokens used this month and an
|
||||||
backend port, everything else → frontend port (DEPLOYMENT.md, "One address, one rule"). The
|
estimated allowance in tokens; the per-person, per-helper and per-day tables show tokens instead
|
||||||
status page is at `/api` (`/` redirects there), health at `/api/health`, the API reference at
|
of cost. The 80% email names tokens instead of rand. The rand amounts the Hub sends are dropped
|
||||||
`/api/docs/v2` and uploaded files at `/api/uploads/…`. Stored paths stay `/uploads/…`; pictures,
|
on arrival, so they never reach a browser. With a Hub before 2.0.1 only the percentage shows.
|
||||||
logos and attachments are given out as `/api/uploads/…`, and so are WhatsApp ticket PDFs.
|
- **API (v2):** `GET /api/v2/ai/status` (and the `status` in every AI reply and in `/ai/usage`) no
|
||||||
- The old paths keep working on the backend: `/health` and `/uploads/…` answer as before, and
|
longer has `capCents` / `usedCents`; it has `usedInputTokens`, `usedOutputTokens`,
|
||||||
`/docs` and `/docs/v2` redirect to `/api/docs/v2`. A missing file under `/api/uploads` is 404.
|
`capInputTokens`, `capOutputTokens` (null from an older Hub). `/ai/usage` rows have
|
||||||
|
`inputTokens` / `outputTokens` instead of `chargedCents`.
|
||||||
|
- `AiCall` keeps each call's tokens (migration `20261117120000_ai_tokens`). Calls from before it
|
||||||
|
show 0 tokens.
|
||||||
|
|
||||||
## [2.1.1] - 2026-11-03
|
## [2.1.1] - 2026-11-03
|
||||||
|
|
||||||
|
|||||||
@@ -38,27 +38,6 @@ visitor ──http───▶ frps (vhost_http_port) ══tunnel══▶ frp
|
|||||||
On this server, nginx sends `/api`, `/uploads`, `/health` and `/docs` to the backend (port 5000)
|
On this server, nginx sends `/api`, `/uploads`, `/health` and `/docs` to the backend (port 5000)
|
||||||
and everything else to the Next.js site (port 3000), the same as a normal install.
|
and everything else to the Next.js site (port 3000), the same as a normal install.
|
||||||
|
|
||||||
### One address, one rule (2.3.0 and later)
|
|
||||||
|
|
||||||
From 2.3.0 everything the backend serves is under **`/api`**: the API (`/api/v2`), the status page
|
|
||||||
(`/api`), health (`/api/health`), the API reference (`/api/docs/v2`) and uploaded files
|
|
||||||
(`/api/uploads/…`). So the site and its API share one address (`events.yourchurch.org`, no
|
|
||||||
separate `events-api.` record), and a web server or panel such as FastPanel needs a single
|
|
||||||
rule:
|
|
||||||
|
|
||||||
| Path | Goes to |
|
|
||||||
|------|---------|
|
|
||||||
| `/api` and everything under it | the backend, `http://127.0.0.1:5000` |
|
|
||||||
| everything else | the frontend, `http://127.0.0.1:3000` |
|
|
||||||
|
|
||||||
Set `BACKEND_URL` (backend `.env`) and `NEXT_PUBLIC_API_URL` (frontend `.env.production`) to the
|
|
||||||
same `https://` address as `FRONTEND_URL`, then rebuild the frontend. The old paths (`/health`,
|
|
||||||
`/docs/v2`, `/uploads/…`) still answer on the backend's port, so a site with a separate API
|
|
||||||
address keeps working unchanged. With only `/api` routed, links made before 2.3.0 that point at
|
|
||||||
`https://<site>/uploads/…` stop working (they aren't stored that way, but could be in an old
|
|
||||||
email); keep the four-path rule above if that matters. Pictures, logos and attachments are all
|
|
||||||
given out as `/api/uploads/…` from 2.3.0.
|
|
||||||
|
|
||||||
## 2. Before you start
|
## 2. Before you start
|
||||||
|
|
||||||
- Ubuntu 22.04 or 24.04 on this server, with `frpc` already installed and connected (it runs as
|
- Ubuntu 22.04 or 24.04 on this server, with `frpc` already installed and connected (it runs as
|
||||||
@@ -285,7 +264,7 @@ setup). If the `[hope-events-https]` section fails to start, check `journalctl -
|
|||||||
|
|
||||||
## 6. Finish in the browser
|
## 6. Finish in the browser
|
||||||
|
|
||||||
1. Open `https://events.yourchurch.org/api/health` (`/health` before 2.3.0) — it should answer with the version.
|
1. Open `https://events.yourchurch.org/health` — it should answer with the version.
|
||||||
2. Open `https://events.yourchurch.org/setup`: create the admin account.
|
2. Open `https://events.yourchurch.org/setup`: create the admin account.
|
||||||
3. **Site settings → Licence**: enter the licence key to connect to the Hub. The site checks in
|
3. **Site settings → Licence**: enter the licence key to connect to the Hub. The site checks in
|
||||||
every 15 minutes from then on (outgoing HTTPS to `events-hub.crosscode.co.za`, which frp
|
every 15 minutes from then on (outgoing HTTPS to `events-hub.crosscode.co.za`, which frp
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ The backend provides a RESTful API for managing users, events, registrations, pa
|
|||||||
- Static uploads for event images
|
- Static uploads for event images
|
||||||
|
|
||||||
Documentation: see Backend API Documentation and Backend README for environment setup and endpoints.
|
Documentation: see Backend API Documentation and Backend README for environment setup and endpoints.
|
||||||
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.3.0) — ./backend/API_DOCUMENTATION.md
|
- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./backend/API_DOCUMENTATION.md
|
||||||
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||||
- Backend README: ./backend/README.md
|
- Backend README: ./backend/README.md
|
||||||
|
|
||||||
@@ -156,7 +156,7 @@ set names that match your PM2 apps (`pm2 ls`) and the port you use.
|
|||||||
|
|
||||||
## Useful Links
|
## Useful Links
|
||||||
|
|
||||||
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.3.0) — ./backend/API_DOCUMENTATION.md
|
- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./backend/API_DOCUMENTATION.md
|
||||||
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||||
- Backend README: ./backend/README.md
|
- Backend README: ./backend/README.md
|
||||||
- Frontend README: ./frontend/README.md
|
- Frontend README: ./frontend/README.md
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- 2.3.0: tokens per AI call, which is what the site shows (the rand amount is the Hub's business).
|
||||||
|
ALTER TABLE "AiCall" ADD COLUMN "inputTokens" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE "AiCall" ADD COLUMN "outputTokens" INTEGER NOT NULL DEFAULT 0;
|
||||||
@@ -2341,8 +2341,12 @@ model AiCall {
|
|||||||
helper String
|
helper String
|
||||||
// ok, refused, incomplete, failed, cap_reached, unavailable
|
// ok, refused, incomplete, failed, cap_reached, unavailable
|
||||||
outcome String
|
outcome String
|
||||||
// What the church was charged, in cents (fractions of a cent).
|
// What the church was charged, in cents (fractions of a cent). Kept for the record; the site
|
||||||
|
// shows tokens (2.3.0), and only the Hub shows rand.
|
||||||
chargedCents Float @default(0)
|
chargedCents Float @default(0)
|
||||||
|
// Tokens the call used (2.3.0): input counts cached prompt tokens. 0 when the call failed.
|
||||||
|
inputTokens Int @default(0)
|
||||||
|
outputTokens Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* AI helpers (2.0, roadmap §15). The site never holds a Claude API key: every call goes through
|
* AI helpers (2.0, roadmap §15). The site never holds a Claude API key: every call goes through
|
||||||
* the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap in rand,
|
* the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap, calls
|
||||||
* calls Claude and meters the call. This module:
|
* Claude and meters the call. The site shows that use as tokens and a percentage (2.3.0); the cap's
|
||||||
|
* rand amount stays on the Hub. This module:
|
||||||
* - works out what the AI buttons do (`aiStatus`): hidden, working, or disabled until the
|
* - works out what the AI buttons do (`aiStatus`): hidden, working, or disabled until the
|
||||||
* allowance renews — from the licence token first, then the Hub (cached for a minute);
|
* allowance renews — from the licence token first, then the Hub (cached for a minute);
|
||||||
* - runs one helper call (`runHelper`), with this site's own switches per helper and an optional
|
* - runs one helper call (`runHelper`), with this site's own switches per helper and an optional
|
||||||
@@ -32,8 +33,16 @@ const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(en
|
|||||||
export const HELPERS = ['draft_event', 'summarise_report', 'draft_message', 'summarise_feedback', 'improve_text'] as const;
|
export const HELPERS = ['draft_event', 'summarise_report', 'draft_message', 'summarise_feedback', 'improve_text'] as const;
|
||||||
export type HelperName = (typeof HELPERS)[number];
|
export type HelperName = (typeof HELPERS)[number];
|
||||||
|
|
||||||
/** What the Hub says (§3b). Cents are charged rand, with fractions. */
|
/**
|
||||||
export type HubAiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string | null };
|
* What the Hub says (§3b), as the site keeps it. The Hub also sends the allowance in rand
|
||||||
|
* (`capCents`, `usedCents`); the site drops those (2.3.0): people see tokens and a percentage,
|
||||||
|
* and only the Hub shows rand. The token fields are null from a Hub before 2.0.1.
|
||||||
|
*/
|
||||||
|
export type HubAiStatus = {
|
||||||
|
enabled: boolean; capReached: boolean; usedPercent: number; renewsOn: string | null;
|
||||||
|
usedInputTokens: number | null; usedOutputTokens: number | null;
|
||||||
|
capInputTokens: number | null; capOutputTokens: number | null;
|
||||||
|
};
|
||||||
/** What the buttons need: the Hub's answer, whether it could be reached, and this site's switches. */
|
/** What the buttons need: the Hub's answer, whether it could be reached, and this site's switches. */
|
||||||
export type AiStatus = HubAiStatus & { available: boolean; helpers: Record<HelperName, boolean> };
|
export type AiStatus = HubAiStatus & { available: boolean; helpers: Record<HelperName, boolean> };
|
||||||
|
|
||||||
@@ -44,7 +53,28 @@ const STATUS_TTL_MS = 60 * 1000;
|
|||||||
const CALL_TIMEOUT_MS = 90 * 1000;
|
const CALL_TIMEOUT_MS = 90 * 1000;
|
||||||
const KEEP_CALLS_DAYS = 400;
|
const KEEP_CALLS_DAYS = 400;
|
||||||
|
|
||||||
const OFF: HubAiStatus = { enabled: false, capReached: false, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null };
|
const OFF: HubAiStatus = { enabled: false, capReached: false, usedPercent: 0, renewsOn: null, usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null };
|
||||||
|
|
||||||
|
const tokens = (n: unknown): number | null => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.round(n) : null);
|
||||||
|
|
||||||
|
/** The Hub's status without its rand amounts. */
|
||||||
|
function fromHub(v: Record<string, unknown>): HubAiStatus {
|
||||||
|
return {
|
||||||
|
enabled: v.enabled === true,
|
||||||
|
capReached: v.capReached === true,
|
||||||
|
usedPercent: typeof v.usedPercent === 'number' ? v.usedPercent : 0,
|
||||||
|
renewsOn: typeof v.renewsOn === 'string' ? v.renewsOn : null,
|
||||||
|
usedInputTokens: tokens(v.usedInputTokens), usedOutputTokens: tokens(v.usedOutputTokens),
|
||||||
|
capInputTokens: tokens(v.capInputTokens), capOutputTokens: tokens(v.capOutputTokens),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "1.2M", "450K", "800": tokens for people. */
|
||||||
|
export function tokenText(n: number): string {
|
||||||
|
if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, '')}M`;
|
||||||
|
if (n >= 1e3) return `${Math.round(n / 1e3)}K`;
|
||||||
|
return String(n);
|
||||||
|
}
|
||||||
|
|
||||||
// ─── This site's settings ─────────────────────────────────────────────────────
|
// ─── This site's settings ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -78,8 +108,8 @@ let cached: { at: number; value: HubAiStatus; available: boolean } | null = null
|
|||||||
|
|
||||||
/** Keep what the Hub just said (every AI reply and error carries it). */
|
/** Keep what the Hub just said (every AI reply and error carries it). */
|
||||||
function remember(value: unknown, available = true): void {
|
function remember(value: unknown, available = true): void {
|
||||||
const v = value as Partial<HubAiStatus> | null;
|
const v = value as Record<string, unknown> | null;
|
||||||
if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: { ...OFF, ...v } as HubAiStatus, available };
|
if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: fromHub(v), available };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearAiStatusCache(): void {
|
export function clearAiStatusCache(): void {
|
||||||
@@ -185,7 +215,10 @@ async function warnAt80(status: HubAiStatus): Promise<void> {
|
|||||||
if (!email.isSmtpConfigured()) return;
|
if (!email.isSmtpConfigured()) return;
|
||||||
const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } });
|
const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } });
|
||||||
const when = renewsText(status.renewsOn);
|
const when = renewsText(status.renewsOn);
|
||||||
const text = `This site has used ${status.usedPercent}% of this month's AI allowance (R${(status.usedCents / 100).toFixed(2)} of R${(status.capCents / 100).toFixed(2)}). The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`;
|
const used = status.usedInputTokens != null && status.usedOutputTokens != null
|
||||||
|
? ` (${tokenText(status.usedInputTokens)} input and ${tokenText(status.usedOutputTokens)} output tokens)`
|
||||||
|
: '';
|
||||||
|
const text = `This site has used ${status.usedPercent}% of this month's AI allowance${used}. The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`;
|
||||||
for (const a of admins) {
|
for (const a of admins) {
|
||||||
await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`<p>${text}</p>`) })
|
await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`<p>${text}</p>`) })
|
||||||
.catch(e => console.warn('[ai] 80% warning email failed:', (e as Error).message));
|
.catch(e => console.warn('[ai] 80% warning email failed:', (e as Error).message));
|
||||||
@@ -210,9 +243,13 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
|||||||
|
|
||||||
let outcome = 'ok';
|
let outcome = 'ok';
|
||||||
let chargedCents = 0;
|
let chargedCents = 0;
|
||||||
|
let inputTokens = 0;
|
||||||
|
let outputTokens = 0;
|
||||||
try {
|
try {
|
||||||
const reply = await hub.signedPost('/api/installs/ai/complete', { protocolVersion: hub.PROTOCOL_VERSION, helper, ...req }, { timeoutMs: CALL_TIMEOUT_MS });
|
const reply = await hub.signedPost('/api/installs/ai/complete', { protocolVersion: hub.PROTOCOL_VERSION, helper, ...req }, { timeoutMs: CALL_TIMEOUT_MS });
|
||||||
chargedCents = Number(reply.chargedCents) || 0;
|
chargedCents = Number(reply.chargedCents) || 0;
|
||||||
|
inputTokens = tokens(reply.usage?.inputTokens) ?? 0;
|
||||||
|
outputTokens = tokens(reply.usage?.outputTokens) ?? 0;
|
||||||
remember(reply.status);
|
remember(reply.status);
|
||||||
await warnAt80(reply.status).catch(e => console.warn('[ai] 80% check failed:', (e as Error).message));
|
await warnAt80(reply.status).catch(e => console.warn('[ai] 80% check failed:', (e as Error).message));
|
||||||
return { output: reply.output, status: { ...(cached?.value || OFF), available: true, helpers: status.helpers } };
|
return { output: reply.output, status: { ...(cached?.value || OFF), available: true, helpers: status.helpers } };
|
||||||
@@ -223,7 +260,7 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
|||||||
if ((e as { code?: string }).code === 'HUB_UNREACHABLE') remember(cached?.value || { ...OFF, enabled: true }, false);
|
if ((e as { code?: string }).code === 'HUB_UNREACHABLE') remember(cached?.value || { ...OFF, enabled: true }, false);
|
||||||
throw mapped.error;
|
throw mapped.error;
|
||||||
} finally {
|
} finally {
|
||||||
await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message));
|
await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents, inputTokens, outputTokens } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message));
|
||||||
await pruneOldCalls();
|
await pruneOldCalls();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -234,27 +271,30 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
|||||||
export async function usageThisMonth(now = new Date()) {
|
export async function usageThisMonth(now = new Date()) {
|
||||||
const sast = new Date(now.getTime() + 2 * 3600 * 1000);
|
const sast = new Date(now.getTime() + 2 * 3600 * 1000);
|
||||||
const from = new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), 1) - 2 * 3600 * 1000);
|
const from = new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), 1) - 2 * 3600 * 1000);
|
||||||
const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, chargedCents: true, createdAt: true } });
|
const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, inputTokens: true, outputTokens: true, createdAt: true } });
|
||||||
const add = (m: Map<string, { uses: number; chargedCents: number }>, key: string, cents: number) => {
|
type Use = { uses: number; inputTokens: number; outputTokens: number };
|
||||||
const v = m.get(key) || { uses: 0, chargedCents: 0 };
|
const add = (m: Map<string, Use>, key: string, c: { inputTokens: number; outputTokens: number }) => {
|
||||||
|
const v = m.get(key) || { uses: 0, inputTokens: 0, outputTokens: 0 };
|
||||||
v.uses++;
|
v.uses++;
|
||||||
v.chargedCents += cents;
|
v.inputTokens += c.inputTokens;
|
||||||
|
v.outputTokens += c.outputTokens;
|
||||||
m.set(key, v);
|
m.set(key, v);
|
||||||
};
|
};
|
||||||
const byPerson = new Map<string, { uses: number; chargedCents: number }>();
|
const byPerson = new Map<string, Use>();
|
||||||
const byHelper = new Map<string, { uses: number; chargedCents: number }>();
|
const byHelper = new Map<string, Use>();
|
||||||
const byDay = new Map<string, { uses: number; chargedCents: number }>();
|
const byDay = new Map<string, Use>();
|
||||||
for (const c of calls) {
|
for (const c of calls) {
|
||||||
if (c.outcome === 'cap_reached' || c.outcome === 'unavailable') continue;
|
if (c.outcome === 'cap_reached' || c.outcome === 'unavailable') continue;
|
||||||
add(byPerson, c.userId || '', c.chargedCents);
|
add(byPerson, c.userId || '', c);
|
||||||
add(byHelper, c.helper, c.chargedCents);
|
add(byHelper, c.helper, c);
|
||||||
add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c.chargedCents);
|
add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c);
|
||||||
}
|
}
|
||||||
const people = await prisma.user.findMany({ where: { id: { in: [...byPerson.keys()].filter(Boolean) } }, select: { id: true, name: true } });
|
const people = await prisma.user.findMany({ where: { id: { in: [...byPerson.keys()].filter(Boolean) } }, select: { id: true, name: true } });
|
||||||
const names = new Map(people.map(p => [p.id, p.name]));
|
const names = new Map(people.map(p => [p.id, p.name]));
|
||||||
|
const most = (a: Use, b: Use) => (b.inputTokens + b.outputTokens) - (a.inputTokens + a.outputTokens) || b.uses - a.uses;
|
||||||
return {
|
return {
|
||||||
people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort((a, b) => b.chargedCents - a.chargedCents),
|
people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort(most),
|
||||||
helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort((a, b) => b.chargedCents - a.chargedCents),
|
helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort(most),
|
||||||
days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)),
|
days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,12 +153,8 @@ app.use((req, res, next) => {
|
|||||||
// Licence suspended, revoked or missing: no new or edited events, registrations or payments (src/hub/readOnly.js).
|
// Licence suspended, revoked or missing: no new or edited events, registrations or payments (src/hub/readOnly.js).
|
||||||
app.use(require('./hub/readOnly').licenceReadOnly);
|
app.use(require('./hub/readOnly').licenceReadOnly);
|
||||||
|
|
||||||
// Everything the backend serves is under /api (2.3.0), so the site and its API can share one
|
|
||||||
// address: the web server sends /api to the backend and everything else to the frontend. The old
|
|
||||||
// paths (/, /health, /docs/v2, /uploads) still work for sites with a separate API address.
|
|
||||||
|
|
||||||
// Health for monitoring (and the Hub): no secrets, no personal information.
|
// Health for monitoring (and the Hub): no secrets, no personal information.
|
||||||
app.get(['/api/health', '/health'], async (req, res) => {
|
app.get('/health', async (req, res) => {
|
||||||
const report = require('./hub/report');
|
const report = require('./hub/report');
|
||||||
let db = true;
|
let db = true;
|
||||||
try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; }
|
try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; }
|
||||||
@@ -178,11 +174,11 @@ app.use('/api/v2', linksRouter);
|
|||||||
app.use('/api/v2', require('./v2').v2Router());
|
app.use('/api/v2', require('./v2').v2Router());
|
||||||
// Links in messages already sent: v1 addresses answer 308 with their v2 one.
|
// Links in messages already sent: v1 addresses answer 308 with their v2 one.
|
||||||
app.use(legacyLinkRedirects);
|
app.use(legacyLinkRedirects);
|
||||||
app.use('/api/docs/v2', require('./v2').v2DocsRouter());
|
app.use('/docs/v2', require('./v2').v2DocsRouter());
|
||||||
app.get('/api/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
||||||
// Before 2.3.0 the reference was at /docs/v2 (bookmarks, the old status page).
|
// address) and links in messages already sent (308s above, a mail app's one-click POST here).
|
||||||
app.use('/docs/v2', (req, res) => res.redirect(301, `/api${req.originalUrl}`));
|
app.use('/api', legacyV1Router);
|
||||||
app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
app.use('/api', v1Removed);
|
||||||
|
|
||||||
// Pre-warm the settings cache so synchronous helpers have DB values from startup
|
// Pre-warm the settings cache so synchronous helpers have DB values from startup
|
||||||
const { getSettingSync, warmCache } = require('./utils/settingsCache');
|
const { getSettingSync, warmCache } = require('./utils/settingsCache');
|
||||||
@@ -191,16 +187,12 @@ warmCache().catch(() => {});
|
|||||||
// handlers. Serving them inline lets a compromised/malicious upload run script
|
// handlers. Serving them inline lets a compromised/malicious upload run script
|
||||||
// in the site's origin if opened directly, so pin the safe response headers
|
// in the site's origin if opened directly, so pin the safe response headers
|
||||||
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
|
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
|
||||||
// Stored paths stay "/uploads/…"; they're given out as /api/uploads/… (v2/schemas.ts absoluteUrl).
|
app.use('/uploads', express.static('public/uploads', {
|
||||||
// /uploads still answers for links made before 2.3.0.
|
|
||||||
const uploads = express.static('public/uploads', {
|
|
||||||
setHeaders: (res) => {
|
setHeaders: (res) => {
|
||||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
},
|
},
|
||||||
});
|
}));
|
||||||
app.use('/api/uploads', uploads, notFound); // a missing file is 404, not "API v1 removed"
|
|
||||||
app.use('/uploads', uploads);
|
|
||||||
|
|
||||||
// ── Shared page helpers ────────────────────────────────────────────────────────
|
// ── Shared page helpers ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -276,9 +268,8 @@ app.get('/favicon.ico', (req, res) => {
|
|||||||
res.sendFile(path.join(__dirname, '..', 'src', 'favicon.ico'));
|
res.sendFile(path.join(__dirname, '..', 'src', 'favicon.ico'));
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Status page, at /api (2.3.0); / sends you there ─────────────────────────
|
// ── Root route — status page ────────────────────────────────────────────────
|
||||||
app.get('/', (req, res) => res.redirect(302, '/api'));
|
app.get('/', async (req, res) => {
|
||||||
app.get('/api', async (req, res) => {
|
|
||||||
const mem = process.memoryUsage();
|
const mem = process.memoryUsage();
|
||||||
const uptimeSec = process.uptime();
|
const uptimeSec = process.uptime();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -344,18 +335,15 @@ app.get('/api', async (req, res) => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="note">
|
<div class="note">
|
||||||
API documentation (OpenAPI) is at <a href="/api/docs/v2">/api/docs/v2</a> — it needs an admin account token.
|
API documentation (OpenAPI) is at <a href="/docs/v2">/docs/v2</a> — it needs an admin account token.
|
||||||
</div>
|
</div>
|
||||||
`);
|
`);
|
||||||
|
|
||||||
res.send(html);
|
res.send(html);
|
||||||
});
|
});
|
||||||
|
|
||||||
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
// /docs: the v1 reference went with v1 in 2.0; the API is documented at /docs/v2 (OpenAPI).
|
||||||
// address) and links in messages already sent (308s above, a mail app's one-click POST here).
|
app.get('/docs', (req, res) => res.redirect(301, '/docs/v2'));
|
||||||
// Mounted after everything else under /api, since v1Removed answers 410 for any other /api path.
|
|
||||||
app.use('/api', legacyV1Router);
|
|
||||||
app.use('/api', v1Removed);
|
|
||||||
|
|
||||||
// Error middleware
|
// Error middleware
|
||||||
app.use(notFound);
|
app.use(notFound);
|
||||||
|
|||||||
@@ -45,10 +45,9 @@ function toAbsoluteUrl(req, url) {
|
|||||||
}
|
}
|
||||||
return raw; // keep as-is if already absolute and not localhost
|
return raw; // keep as-is if already absolute and not localhost
|
||||||
}
|
}
|
||||||
// Relative path like /uploads/... => prefix with request origin; uploads are served under
|
// Relative path like /uploads/... => prefix with request origin
|
||||||
// /api/uploads (2.3.0) so they reach the backend when the site and API share one address
|
|
||||||
if (raw.startsWith('/')) {
|
if (raw.startsWith('/')) {
|
||||||
return `${req.protocol}://${req.get('host')}${raw.startsWith('/uploads/') ? `/api${raw}` : raw}`;
|
return `${req.protocol}://${req.get('host')}${raw}`;
|
||||||
}
|
}
|
||||||
// Any other case, return as-is
|
// Any other case, return as-is
|
||||||
return raw;
|
return raw;
|
||||||
|
|||||||
@@ -269,7 +269,7 @@ async function sendPdf(toPhone, localPdfPath, filename, caption) {
|
|||||||
`Set BACKEND_URL to your public backend URL (e.g. https://api.yourdomain.com) in your .env file.`
|
`Set BACKEND_URL to your public backend URL (e.g. https://api.yourdomain.com) in your .env file.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const pdfUrl = `${backendUrl}/api/uploads/tickets-temp/${tempName}`;
|
const pdfUrl = `${backendUrl}/uploads/tickets-temp/${tempName}`;
|
||||||
|
|
||||||
const { token, instanceId } = await getConfig();
|
const { token, instanceId } = await getConfig();
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ export function v2Router(): Router {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* /api/docs/v2 (2.3.0; /docs/v2 before, which now redirects): Swagger UI (served from swagger-ui-dist, nothing from a CDN). The page itself is
|
* /docs/v2: Swagger UI (served from swagger-ui-dist, nothing from a CDN). The page itself is
|
||||||
* public; it asks for an admin token and uses it to load openapi.json and to try requests.
|
* public; it asks for an admin token and uses it to load openapi.json and to try requests.
|
||||||
*/
|
*/
|
||||||
export function v2DocsRouter(): Router {
|
export function v2DocsRouter(): Router {
|
||||||
@@ -62,7 +62,7 @@ const DOCS_HTML = `<!doctype html>
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Cross Events API v2</title>
|
<title>Cross Events API v2</title>
|
||||||
<link rel="stylesheet" href="/api/docs/v2/assets/swagger-ui.css">
|
<link rel="stylesheet" href="/docs/v2/assets/swagger-ui.css">
|
||||||
<style>
|
<style>
|
||||||
body { margin: 0; font-family: system-ui, sans-serif; }
|
body { margin: 0; font-family: system-ui, sans-serif; }
|
||||||
#login { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
|
#login { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
|
||||||
@@ -81,7 +81,7 @@ const DOCS_HTML = `<!doctype html>
|
|||||||
<p class="err" id="err" role="alert"></p>
|
<p class="err" id="err" role="alert"></p>
|
||||||
</main>
|
</main>
|
||||||
<div id="ui"></div>
|
<div id="ui"></div>
|
||||||
<script src="/api/docs/v2/assets/swagger-ui-bundle.js"></script>
|
<script src="/docs/v2/assets/swagger-ui-bundle.js"></script>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var params = new URLSearchParams(location.search);
|
var params = new URLSearchParams(location.search);
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ legacyV1Router.post('/privacy/unsubscribe/:token/one-click', express.urlencoded(
|
|||||||
/** Any other v1 address: gone since 2.0 (410, pointing at v2). /api/v2 misses fall through to 404. */
|
/** Any other v1 address: gone since 2.0 (410, pointing at v2). /api/v2 misses fall through to 404. */
|
||||||
export const v1Removed: RequestHandler = (req, res, next) => {
|
export const v1Removed: RequestHandler = (req, res, next) => {
|
||||||
if (req.path === '/v2' || req.path.startsWith('/v2/')) return next();
|
if (req.path === '/v2' || req.path.startsWith('/v2/')) return next();
|
||||||
res.status(410).json({ code: 'API_V1_REMOVED', message: 'API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /api/docs/v2.' });
|
res.status(410).json({ code: 'API_V1_REMOVED', message: 'API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /docs/v2.' });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const legacyLinkRedirects: RequestHandler = (req, res, next) => {
|
export const legacyLinkRedirects: RequestHandler = (req, res, next) => {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { PATH_HELP, QUERY_HELP } from './docs';
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The OpenAPI 3.1 document for /api/v2, built from the route declarations (route.ts), so it is
|
* The OpenAPI 3.1 document for /api/v2, built from the route declarations (route.ts), so it is
|
||||||
* always what the code does. Served at /api/v2/openapi.json, shown at /api/docs/v2.
|
* always what the code does. Served at /api/v2/openapi.json, shown at /docs/v2.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
type JsonSchema = Record<string, unknown>;
|
type JsonSchema = Record<string, unknown>;
|
||||||
|
|||||||
@@ -21,9 +21,11 @@ const status = z.object({
|
|||||||
enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'),
|
enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'),
|
||||||
capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'),
|
capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'),
|
||||||
available: z.boolean().describe('false: the Hub couldn\'t be reached just now'),
|
available: z.boolean().describe('false: the Hub couldn\'t be reached just now'),
|
||||||
capCents: z.number().describe('The monthly allowance, in cents'),
|
usedPercent: z.number().describe('How much of this month\'s allowance is used (0–100)'),
|
||||||
usedCents: z.number().describe('Used this month, in cents (fractions of a cent)'),
|
usedInputTokens: z.number().int().nullable().describe('Input tokens used this month by all the church\'s products (null from a Hub before 2.0.1)'),
|
||||||
usedPercent: z.number(),
|
usedOutputTokens: z.number().int().nullable().describe('Output tokens used this month'),
|
||||||
|
capInputTokens: z.number().int().nullable().describe('About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)'),
|
||||||
|
capOutputTokens: z.number().int().nullable().describe('About how many output tokens the allowance holds, if half of it went on output'),
|
||||||
renewsOn: z.string().nullable().describe('YYYY-MM-DD'),
|
renewsOn: z.string().nullable().describe('YYYY-MM-DD'),
|
||||||
helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'),
|
helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'),
|
||||||
});
|
});
|
||||||
@@ -33,7 +35,7 @@ const settings = z.object({
|
|||||||
dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'),
|
dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'),
|
||||||
});
|
});
|
||||||
|
|
||||||
const use = z.object({ uses: z.number().int(), chargedCents: z.number() });
|
const use = z.object({ uses: z.number().int(), inputTokens: z.number().int(), outputTokens: z.number().int() });
|
||||||
|
|
||||||
export const getAiStatus = defineRoute({
|
export const getAiStatus = defineRoute({
|
||||||
method: 'get',
|
method: 'get',
|
||||||
|
|||||||
@@ -14,20 +14,12 @@ export function iso(d: Date | string | null | undefined): string | null {
|
|||||||
return d == null ? null : new Date(d).toISOString();
|
return d == null ? null : new Date(d).toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Where a stored upload path is served: "/uploads/…" (as stored) → "/api/uploads/…" (2.3.0), so it
|
|
||||||
* reaches the backend when the site and its API share one address. Anything else is unchanged.
|
|
||||||
*/
|
|
||||||
export function uploadPath(raw: string): string {
|
|
||||||
return /^\/uploads\//.test(raw) ? `/api${raw}` : raw;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A stored picture path ("/uploads/…") as an absolute URL on the host the request came to. */
|
/** A stored picture path ("/uploads/…") as an absolute URL on the host the request came to. */
|
||||||
export function absoluteUrl(req: Request, url: string | null | undefined): string | null {
|
export function absoluteUrl(req: Request, url: string | null | undefined): string | null {
|
||||||
const raw = String(url || '').trim();
|
const raw = String(url || '').trim();
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
if (/^https?:\/\//.test(raw)) return raw;
|
if (/^https?:\/\//.test(raw)) return raw;
|
||||||
return `${req.protocol}://${req.get('host')}${uploadPath(raw.startsWith('/') ? raw : `/${raw}`)}`;
|
return `${req.protocol}://${req.get('host')}${raw.startsWith('/') ? '' : '/'}${raw}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const campusRef = z.object({ id, name: z.string(), slug: z.string() });
|
export const campusRef = z.object({ id, name: z.string(), slug: z.string() });
|
||||||
|
|||||||
@@ -28,9 +28,12 @@ const mockMail = jest.fn(async (_m: unknown) => undefined);
|
|||||||
jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true }));
|
jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true }));
|
||||||
jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) }));
|
jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) }));
|
||||||
|
|
||||||
import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, _internal } from '../src/ai';
|
import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, tokenText, _internal } from '../src/ai';
|
||||||
|
|
||||||
const hubStatus = (over = {}) => ({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01', ...over });
|
const hubStatus = (over = {}) => ({
|
||||||
|
enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01',
|
||||||
|
usedInputTokens: 40000, usedOutputTokens: 9000, capInputTokens: 1785000, capOutputTokens: 357000, ...over,
|
||||||
|
});
|
||||||
const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 };
|
const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 };
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -55,7 +58,7 @@ describe('status', () => {
|
|||||||
|
|
||||||
test('asks the Hub and caches its answer for a minute', async () => {
|
test('asks the Hub and caches its answer for a minute', async () => {
|
||||||
mockPost.mockResolvedValue(hubStatus());
|
mockPost.mockResolvedValue(hubStatus());
|
||||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedCents: 100, helpers: { draft_event: true } });
|
expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedInputTokens: 40000, capOutputTokens: 357000, helpers: { draft_event: true } });
|
||||||
await aiStatus();
|
await aiStatus();
|
||||||
expect(mockPost).toHaveBeenCalledTimes(1);
|
expect(mockPost).toHaveBeenCalledTimes(1);
|
||||||
expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 });
|
expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 });
|
||||||
@@ -68,16 +71,32 @@ describe('status', () => {
|
|||||||
mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502));
|
mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502));
|
||||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: false });
|
expect(await aiStatus()).toMatchObject({ enabled: true, available: false });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('the Hub\'s rand amounts never leave the site (2.3.0); a Hub before 2.0.1 sends no tokens', async () => {
|
||||||
|
mockPost.mockResolvedValueOnce(hubStatus());
|
||||||
|
const s = await aiStatus() as unknown as Record<string, unknown>;
|
||||||
|
expect(s).not.toHaveProperty('capCents');
|
||||||
|
expect(s).not.toHaveProperty('usedCents');
|
||||||
|
clearAiStatusCache();
|
||||||
|
mockPost.mockResolvedValueOnce({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01' });
|
||||||
|
expect(await aiStatus()).toMatchObject({ usedPercent: 2, usedInputTokens: null, capInputTokens: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tokens for people', () => {
|
||||||
|
expect(['800', '45K', '1.2M', '2M', '12M']).toEqual([800, 45000, 1200000, 2000000, 12300000].map(tokenText));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('running a helper', () => {
|
describe('running a helper', () => {
|
||||||
test('sends the request to the Hub, logs the call, returns the answer', async () => {
|
test('sends the request to the Hub, logs the call, returns the answer', async () => {
|
||||||
mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'Hi all!', chargedCents: 0.31, status: hubStatus({ usedCents: 100.31 }) });
|
mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({
|
||||||
|
output: 'Hi all!', usage: { inputTokens: 1840, outputTokens: 420 }, chargedCents: 0.31, status: hubStatus({ usedInputTokens: 41840, usedOutputTokens: 9420 }),
|
||||||
|
});
|
||||||
const r = await runHelper('draft_message', 'u1', req);
|
const r = await runHelper('draft_message', 'u1', req);
|
||||||
expect(r.output).toBe('Hi all!');
|
expect(r.output).toBe('Hi all!');
|
||||||
expect(r.status.usedCents).toBe(100.31);
|
expect(r.status).toMatchObject({ usedInputTokens: 41840, usedOutputTokens: 9420 });
|
||||||
expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 });
|
expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 });
|
||||||
expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31 }]);
|
expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31, inputTokens: 1840, outputTokens: 420 }]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a helper switched off, or the cap reached, never reaches the Hub', async () => {
|
test('a helper switched off, or the cap reached, never reaches the Hub', async () => {
|
||||||
@@ -102,7 +121,7 @@ describe('running a helper', () => {
|
|||||||
.mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) }));
|
.mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) }));
|
||||||
await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') });
|
await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') });
|
||||||
expect((await aiStatus()).capReached).toBe(true);
|
expect((await aiStatus()).capReached).toBe(true);
|
||||||
expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0 });
|
expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0, inputTokens: 0, outputTokens: 0 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('admins are emailed once a month at 80%', async () => {
|
test('admins are emailed once a month at 80%', async () => {
|
||||||
@@ -112,6 +131,9 @@ describe('running a helper', () => {
|
|||||||
await runHelper('draft_message', 'u1', req);
|
await runHelper('draft_message', 'u1', req);
|
||||||
expect(mockMail).toHaveBeenCalledTimes(1);
|
expect(mockMail).toHaveBeenCalledTimes(1);
|
||||||
expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]);
|
expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]);
|
||||||
|
const text = (mockMail.mock.calls[0] as unknown as [{ text: string }])[0].text;
|
||||||
|
expect(text).toContain('40K input and 9K output tokens');
|
||||||
|
expect(text).not.toMatch(/R\d/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer,
|
draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer,
|
||||||
} from '../src/ai/helpers';
|
} from '../src/ai/helpers';
|
||||||
|
|
||||||
const status = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: {} };
|
const status = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: {} };
|
||||||
const now = new Date('2026-10-30T08:00:00Z');
|
const now = new Date('2026-10-30T08:00:00Z');
|
||||||
|
|
||||||
beforeEach(() => mockRun.mockReset());
|
beforeEach(() => mockRun.mockReset());
|
||||||
|
|||||||
@@ -108,7 +108,6 @@ import { v2Router } from '../src/v2';
|
|||||||
import { ServiceError } from '../src/services/errors';
|
import { ServiceError } from '../src/services/errors';
|
||||||
import { routes } from '../src/v2/route';
|
import { routes } from '../src/v2/route';
|
||||||
import { buildOpenApi } from '../src/v2/openapi';
|
import { buildOpenApi } from '../src/v2/openapi';
|
||||||
import { absoluteUrl, uploadPath } from '../src/v2/schemas';
|
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
@@ -130,7 +129,7 @@ describe('GET /api/v2/events', () => {
|
|||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
expect(res.body.meta).toEqual({ page: 2, limit: 10, total: 31, pages: 4 });
|
expect(res.body.meta).toEqual({ page: 2, limit: 10, total: 31, pages: 4 });
|
||||||
expect(res.body.data[0]).toMatchObject({ id: 'e1', startDate: '2026-12-04T16:00:00.000Z', series: { slug: 'camps' } });
|
expect(res.body.data[0]).toMatchObject({ id: 'e1', startDate: '2026-12-04T16:00:00.000Z', series: { slug: 'camps' } });
|
||||||
expect(res.body.data[0].pictureUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/api\/uploads\/events\/camp\.jpg$/);
|
expect(res.body.data[0].pictureUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/uploads\/events\/camp\.jpg$/);
|
||||||
const args = mockDb.event.findMany.mock.calls[0][0];
|
const args = mockDb.event.findMany.mock.calls[0][0];
|
||||||
expect(args).toMatchObject({ skip: 10, take: 10 });
|
expect(args).toMatchObject({ skip: 10, take: 10 });
|
||||||
expect(args.where.AND).toEqual(expect.arrayContaining([{ isActive: true, isHidden: false, goLiveAt: { lte: expect.any(Date) } }, { title: { contains: 'camp', mode: 'insensitive' } }]));
|
expect(args.where.AND).toEqual(expect.arrayContaining([{ isActive: true, isHidden: false, goLiveAt: { lte: expect.any(Date) } }, { title: { contains: 'camp', mode: 'insensitive' } }]));
|
||||||
@@ -425,7 +424,7 @@ describe('events (staff)', () => {
|
|||||||
const res = await request(app).get('/api/v2/events/manage?past=true');
|
const res = await request(app).get('/api/v2/events/manage?past=true');
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
expect(res.body.data[0]).toMatchObject({ id: 'e1', isHidden: true, waitlistEnabled: true, startDate: '2026-12-04T16:00:00.000Z' });
|
expect(res.body.data[0]).toMatchObject({ id: 'e1', isHidden: true, waitlistEnabled: true, startDate: '2026-12-04T16:00:00.000Z' });
|
||||||
expect(res.body.data[0].picture).toMatch(/^http:\/\/[^/]+\/api\/uploads\/events\/c\.jpg$/);
|
expect(res.body.data[0].picture).toMatch(/^http:\/\/.*\/uploads\/events\/c\.jpg$/);
|
||||||
expect(mockEvents.listManagedEvents).toHaveBeenCalledWith({ includePast: true, includeInactive: false, excludeClosed: false, campus: undefined }, expect.objectContaining({ scope: null }));
|
expect(mockEvents.listManagedEvents).toHaveBeenCalledWith({ includePast: true, includeInactive: false, excludeClosed: false, campus: undefined }, expect.objectContaining({ scope: null }));
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -555,16 +554,7 @@ describe('sections, costs, image uploads', () => {
|
|||||||
mockImage.file = { filename: 'event-123.jpg' };
|
mockImage.file = { filename: 'event-123.jpg' };
|
||||||
const res = await request(app).post('/api/v2/uploads/event-image');
|
const res = await request(app).post('/api/v2/uploads/event-image');
|
||||||
expect(res.body.data.path).toBe('/uploads/events/event-123.jpg');
|
expect(res.body.data.path).toBe('/uploads/events/event-123.jpg');
|
||||||
expect(res.body.data.url).toMatch(/^http:\/\/[^/]+\/api\/uploads\/events\/event-123\.jpg$/);
|
expect(res.body.data.url).toMatch(/^http:\/\/.*\/uploads\/events\/event-123\.jpg$/);
|
||||||
});
|
|
||||||
|
|
||||||
test('stored uploads are given out under /api/uploads (2.3.0); other addresses are left alone', () => {
|
|
||||||
expect(uploadPath('/uploads/branding/logo.png')).toBe('/api/uploads/branding/logo.png');
|
|
||||||
expect(uploadPath('/api/uploads/x.png')).toBe('/api/uploads/x.png');
|
|
||||||
expect(uploadPath('/images/x.png')).toBe('/images/x.png');
|
|
||||||
const req = { protocol: 'https', get: () => 'events.church.co.za' } as unknown as Parameters<typeof absoluteUrl>[0];
|
|
||||||
expect(absoluteUrl(req, 'uploads/events/a.jpg')).toBe('https://events.church.co.za/api/uploads/events/a.jpg');
|
|
||||||
expect(absoluteUrl(req, 'https://cdn.example.org/uploads/a.jpg')).toBe('https://cdn.example.org/uploads/a.jpg');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('branding images are for admins once accounts exist', async () => {
|
test('branding images are for admins once accounts exist', async () => {
|
||||||
@@ -693,7 +683,7 @@ describe('money (v1 handlers behind v2 routes)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('AI helpers (2.0)', () => {
|
describe('AI helpers (2.0)', () => {
|
||||||
const st = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } };
|
const st = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } };
|
||||||
|
|
||||||
test('supervisors only', async () => {
|
test('supervisors only', async () => {
|
||||||
signedIn = { id: 's1', role: 'staff' };
|
signedIn = { id: 's1', role: 'staff' };
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { test, expect, seed, API } from "./fixtures";
|
import { test, expect, seed, API } from "./fixtures";
|
||||||
|
|
||||||
// /api/v2 (1.51.0) against the real server and database: paged public events, the v2 error
|
// /api/v2 (1.51.0) against the real server and database: paged public events, the v2 error
|
||||||
// shape, the signed-in person, and the OpenAPI reference at /api/docs/v2.
|
// shape, the signed-in person, and the OpenAPI reference at /docs/v2.
|
||||||
test.describe("API v2", () => {
|
test.describe("API v2", () => {
|
||||||
test("public events come a page at a time; errors have a code", async ({ request }) => {
|
test("public events come a page at a time; errors have a code", async ({ request }) => {
|
||||||
const res = await request.get(`${API}/api/v2/events?limit=2`);
|
const res = await request.get(`${API}/api/v2/events?limit=2`);
|
||||||
@@ -99,11 +99,9 @@ test.describe("API v2", () => {
|
|||||||
expect(ics.headers()["location"]).toBe(`/api/v2/events/${seed().events.conference}/calendar.ics`);
|
expect(ics.headers()["location"]).toBe(`/api/v2/events/${seed().events.conference}/calendar.ics`);
|
||||||
const followed = await request.get(`${API}/api/events/${seed().events.conference}/ics`);
|
const followed = await request.get(`${API}/api/events/${seed().events.conference}/ics`);
|
||||||
expect(followed.headers()["content-type"]).toContain("text/calendar");
|
expect(followed.headers()["content-type"]).toContain("text/calendar");
|
||||||
// The old API reference addresses send people to the v2 one, under /api (2.3.0).
|
// The old API reference sends people to the v2 one.
|
||||||
const docs = await request.get(`${API}/docs`, { maxRedirects: 0 });
|
const docs = await request.get(`${API}/docs`, { maxRedirects: 0 });
|
||||||
expect(docs.headers()["location"]).toBe("/api/docs/v2");
|
expect(docs.headers()["location"]).toBe("/docs/v2");
|
||||||
const oldDocs = await request.get(`${API}/docs/v2?x=1`, { maxRedirects: 0 });
|
|
||||||
expect(oldDocs.headers()["location"]).toBe("/api/docs/v2?x=1");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("staff list every event; supervisors create, change and admins deactivate", async ({ request }) => {
|
test("staff list every event; supervisors create, change and admins deactivate", async ({ request }) => {
|
||||||
@@ -341,11 +339,11 @@ test.describe("API v2", () => {
|
|||||||
expect((await request.get(`${API}/api/v2/admin/audit-log`, { headers: user })).status()).toBe(403);
|
expect((await request.get(`${API}/api/v2/admin/audit-log`, { headers: user })).status()).toBe(403);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("an admin can read the OpenAPI reference at /api/docs/v2", async ({ page, request }) => {
|
test("an admin can read the OpenAPI reference at /docs/v2", async ({ page, request }) => {
|
||||||
const headers = { Authorization: `Bearer ${seed().users.user.token}` };
|
const headers = { Authorization: `Bearer ${seed().users.user.token}` };
|
||||||
expect((await request.get(`${API}/api/v2/openapi.json`, { headers })).status()).toBe(403);
|
expect((await request.get(`${API}/api/v2/openapi.json`, { headers })).status()).toBe(403);
|
||||||
|
|
||||||
await page.goto(`${API}/api/docs/v2?token=${seed().users.admin.token}`);
|
await page.goto(`${API}/docs/v2?token=${seed().users.admin.token}`);
|
||||||
await expect(page.getByRole("heading", { name: /Cross Events API/ })).toBeVisible();
|
await expect(page.getByRole("heading", { name: /Cross Events API/ })).toBeVisible();
|
||||||
// Sections start collapsed (there are hundreds of endpoints): open Events.
|
// Sections start collapsed (there are hundreds of endpoints): open Events.
|
||||||
await page.locator('h3.opblock-tag[data-tag="Events"]').click();
|
await page.locator('h3.opblock-tag[data-tag="Events"]').click();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import React, { useEffect, useState } from "react";
|
|||||||
import { Sparkles } from "lucide-react";
|
import { Sparkles } from "lucide-react";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||||
import { loadAiStatus, renewsText } from "@/lib/ai";
|
import { loadAiStatus, renewsText, tokenText } from "@/lib/ai";
|
||||||
import { errorMessage } from "@/lib/utils";
|
import { errorMessage } from "@/lib/utils";
|
||||||
|
|
||||||
type Usage = V2Result<"/ai/usage", "get">["data"];
|
type Usage = V2Result<"/ai/usage", "get">["data"];
|
||||||
@@ -18,8 +18,8 @@ const HELPERS: { key: Helper; label: string; where: string }[] = [
|
|||||||
{ key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" },
|
{ key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Fractions of a cent add up: show R0.0123 below a rand.
|
/** "12K in · 3K out" for a row of use. */
|
||||||
const money = (cents: number) => (cents > 0 && cents < 100 ? `R${(cents / 100).toFixed(4)}` : `R${(cents / 100).toFixed(2)}`);
|
const inOut = (u: { inputTokens: number; outputTokens: number }) => `${tokenText(u.inputTokens)} in · ${tokenText(u.outputTokens)} out`;
|
||||||
|
|
||||||
/** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */
|
/** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */
|
||||||
export function AiTab({ active }: { active: boolean }) {
|
export function AiTab({ active }: { active: boolean }) {
|
||||||
@@ -53,7 +53,10 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
|
|
||||||
if (!usage) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
if (!usage) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
||||||
const s = usage.status;
|
const s = usage.status;
|
||||||
const maxDay = Math.max(0.0001, ...usage.days.map(d => d.chargedCents));
|
const dayTokens = (d: { inputTokens: number; outputTokens: number }) => d.inputTokens + d.outputTokens;
|
||||||
|
const maxDay = Math.max(1, ...usage.days.map(dayTokens));
|
||||||
|
const hasTokens = s.usedInputTokens != null && s.usedOutputTokens != null;
|
||||||
|
const hasCap = s.capInputTokens != null && s.capOutputTokens != null && s.capInputTokens > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
@@ -72,14 +75,23 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
<div className="rounded-lg border p-4">
|
<div className="rounded-lg border p-4">
|
||||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||||
<span className="text-sm font-medium">This month</span>
|
<span className="text-sm font-medium">This month</span>
|
||||||
<span className="text-sm text-gray-600">{money(s.usedCents)} of {money(s.capCents)} · renews on {renewsText(s.renewsOn)}</span>
|
<span className="text-sm text-gray-600">{s.usedPercent}% used · renews on {renewsText(s.renewsOn)}</span>
|
||||||
</div>
|
</div>
|
||||||
|
{hasTokens && (
|
||||||
|
<p className="mt-1 text-sm text-gray-700">
|
||||||
|
{tokenText(s.usedInputTokens!)} input and {tokenText(s.usedOutputTokens!)} output tokens used
|
||||||
|
{hasCap && <> of about {tokenText(s.capInputTokens!)} input and {tokenText(s.capOutputTokens!)} output</>}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100" role="progressbar" aria-label="AI allowance used" aria-valuenow={s.usedPercent} aria-valuemin={0} aria-valuemax={100}>
|
<div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100" role="progressbar" aria-label="AI allowance used" aria-valuenow={s.usedPercent} aria-valuemin={0} aria-valuemax={100}>
|
||||||
<div className={`h-full ${s.usedPercent >= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
|
<div className={`h-full ${s.usedPercent >= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
|
||||||
</div>
|
</div>
|
||||||
{s.capReached && <p className="mt-2 text-sm text-amber-800">The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.</p>}
|
{s.capReached && <p className="mt-2 text-sm text-amber-800">The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.</p>}
|
||||||
{!s.available && <p className="mt-2 text-sm text-amber-800">The provider's Hub can't be reached right now, so AI is unavailable. Everything else works as usual.</p>}
|
{!s.available && <p className="mt-2 text-sm text-amber-800">The provider's Hub can't be reached right now, so AI is unavailable. Everything else works as usual.</p>}
|
||||||
<p className="mt-2 text-xs text-gray-500">Admins get an email when 80% is used.</p>
|
<p className="mt-2 text-xs text-gray-500">
|
||||||
|
Admins get an email when 80% is used.
|
||||||
|
{hasCap && " The allowance in tokens is an estimate: it's what you'd get if half went on input (what's sent) and half on output (the answers). Repeated instructions are cached and cost less, so most sites get more input than this."}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -114,8 +126,8 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
<h3 className="mb-2 font-medium">By person this month</h3>
|
<h3 className="mb-2 font-medium">By person this month</h3>
|
||||||
{usage.people.length === 0 ? <p className="text-sm text-gray-500">Nobody has used AI yet this month.</p> : (
|
{usage.people.length === 0 ? <p className="text-sm text-gray-500">Nobody has used AI yet this month.</p> : (
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm">
|
||||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
|
||||||
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{money(p.chargedCents)}</td></tr>)}</tbody>
|
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{inOut(p)}</td></tr>)}</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -123,16 +135,16 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
<h3 className="mb-2 font-medium">By helper this month</h3>
|
<h3 className="mb-2 font-medium">By helper this month</h3>
|
||||||
{usage.helpers.length === 0 ? <p className="text-sm text-gray-500">—</p> : (
|
{usage.helpers.length === 0 ? <p className="text-sm text-gray-500">—</p> : (
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm">
|
||||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
|
||||||
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{money(h.chargedCents)}</td></tr>)}</tbody>
|
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{inOut(h)}</td></tr>)}</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{usage.days.length > 0 && (
|
{usage.days.length > 0 && (
|
||||||
<div className="md:col-span-2">
|
<div className="md:col-span-2">
|
||||||
<h3 className="mb-2 font-medium">Per day</h3>
|
<h3 className="mb-2 font-medium">Per day</h3>
|
||||||
<div className="flex h-20 items-end gap-1" aria-label="AI cost per day this month">
|
<div className="flex h-20 items-end gap-1" aria-label="AI tokens per day this month">
|
||||||
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${money(d.chargedCents)}`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (d.chargedCents / maxDay) * 100)}%` }} />)}
|
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${inOut(d)} tokens`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (dayTokens(d) / maxDay) * 100)}%` }} />)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { V2Result } from "@/lib/apiV2";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* AI helpers (2.0). The site calls AI through the Cross Events Hub, which keeps a monthly
|
* AI helpers (2.0). The site calls AI through the Cross Events Hub, which keeps a monthly
|
||||||
* allowance in rand per licence. One status per page load is shared by every AI button
|
* allowance per licence, shown here as tokens and a percentage (2.3.0). One status per page load is shared by every AI button
|
||||||
* (`useAiStatus`), and every helper call refreshes it — so the buttons disable straight after the
|
* (`useAiStatus`), and every helper call refreshes it — so the buttons disable straight after the
|
||||||
* call that used up the allowance.
|
* call that used up the allowance.
|
||||||
*/
|
*/
|
||||||
@@ -12,7 +12,8 @@ export type AiStatus = V2Result<"/ai/status", "get">["data"];
|
|||||||
export type AiHelper = keyof AiStatus["helpers"];
|
export type AiHelper = keyof AiStatus["helpers"];
|
||||||
|
|
||||||
const OFF: AiStatus = {
|
const OFF: AiStatus = {
|
||||||
enabled: false, capReached: false, available: true, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null,
|
enabled: false, capReached: false, available: true, usedPercent: 0, renewsOn: null,
|
||||||
|
usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null,
|
||||||
helpers: { draft_event: false, summarise_report: false, draft_message: false, summarise_feedback: false, improve_text: false },
|
helpers: { draft_event: false, summarise_report: false, draft_message: false, summarise_feedback: false, improve_text: false },
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -46,6 +47,13 @@ export function currentAiStatus(): AiStatus | null {
|
|||||||
return current;
|
return current;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** "800", "45K", "1.2M": token counts for people (the allowance is shown in tokens, never rand). */
|
||||||
|
export function tokenText(n: number): string {
|
||||||
|
if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, "")}M`;
|
||||||
|
if (n >= 1e3) return `${Math.round(n / 1e3)}K`;
|
||||||
|
return String(n);
|
||||||
|
}
|
||||||
|
|
||||||
/** "1 December" from "2026-12-01". */
|
/** "1 December" from "2026-12-01". */
|
||||||
export function renewsText(renewsOn: string | null): string {
|
export function renewsText(renewsOn: string | null): string {
|
||||||
if (!renewsOn) return "next month";
|
if (!renewsOn) return "next month";
|
||||||
|
|||||||
@@ -67449,16 +67449,61 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "false: the Hub couldn't be reached just now"
|
"description": "false: the Hub couldn't be reached just now"
|
||||||
},
|
},
|
||||||
"capCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "The monthly allowance, in cents"
|
|
||||||
},
|
|
||||||
"usedCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "Used this month, in cents (fractions of a cent)"
|
|
||||||
},
|
|
||||||
"usedPercent": {
|
"usedPercent": {
|
||||||
"type": "number"
|
"type": "number",
|
||||||
|
"description": "How much of this month's allowance is used (0–100)"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Output tokens used this month"
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||||
},
|
},
|
||||||
"renewsOn": {
|
"renewsOn": {
|
||||||
"description": "YYYY-MM-DD",
|
"description": "YYYY-MM-DD",
|
||||||
@@ -67501,9 +67546,11 @@
|
|||||||
"enabled",
|
"enabled",
|
||||||
"capReached",
|
"capReached",
|
||||||
"available",
|
"available",
|
||||||
"capCents",
|
|
||||||
"usedCents",
|
|
||||||
"usedPercent",
|
"usedPercent",
|
||||||
|
"usedInputTokens",
|
||||||
|
"usedOutputTokens",
|
||||||
|
"capInputTokens",
|
||||||
|
"capOutputTokens",
|
||||||
"renewsOn",
|
"renewsOn",
|
||||||
"helpers"
|
"helpers"
|
||||||
],
|
],
|
||||||
@@ -67581,16 +67628,61 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "false: the Hub couldn't be reached just now"
|
"description": "false: the Hub couldn't be reached just now"
|
||||||
},
|
},
|
||||||
"capCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "The monthly allowance, in cents"
|
|
||||||
},
|
|
||||||
"usedCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "Used this month, in cents (fractions of a cent)"
|
|
||||||
},
|
|
||||||
"usedPercent": {
|
"usedPercent": {
|
||||||
"type": "number"
|
"type": "number",
|
||||||
|
"description": "How much of this month's allowance is used (0–100)"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Output tokens used this month"
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||||
},
|
},
|
||||||
"renewsOn": {
|
"renewsOn": {
|
||||||
"description": "YYYY-MM-DD",
|
"description": "YYYY-MM-DD",
|
||||||
@@ -67633,9 +67725,11 @@
|
|||||||
"enabled",
|
"enabled",
|
||||||
"capReached",
|
"capReached",
|
||||||
"available",
|
"available",
|
||||||
"capCents",
|
|
||||||
"usedCents",
|
|
||||||
"usedPercent",
|
"usedPercent",
|
||||||
|
"usedInputTokens",
|
||||||
|
"usedOutputTokens",
|
||||||
|
"capInputTokens",
|
||||||
|
"capOutputTokens",
|
||||||
"renewsOn",
|
"renewsOn",
|
||||||
"helpers"
|
"helpers"
|
||||||
],
|
],
|
||||||
@@ -67695,8 +67789,15 @@
|
|||||||
"minimum": -9007199254740991,
|
"minimum": -9007199254740991,
|
||||||
"maximum": 9007199254740991
|
"maximum": 9007199254740991
|
||||||
},
|
},
|
||||||
"chargedCents": {
|
"inputTokens": {
|
||||||
"type": "number"
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"outputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
},
|
},
|
||||||
"userId": {
|
"userId": {
|
||||||
"type": [
|
"type": [
|
||||||
@@ -67710,7 +67811,8 @@
|
|||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"uses",
|
"uses",
|
||||||
"chargedCents",
|
"inputTokens",
|
||||||
|
"outputTokens",
|
||||||
"userId",
|
"userId",
|
||||||
"name"
|
"name"
|
||||||
],
|
],
|
||||||
@@ -67727,8 +67829,15 @@
|
|||||||
"minimum": -9007199254740991,
|
"minimum": -9007199254740991,
|
||||||
"maximum": 9007199254740991
|
"maximum": 9007199254740991
|
||||||
},
|
},
|
||||||
"chargedCents": {
|
"inputTokens": {
|
||||||
"type": "number"
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"outputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
},
|
},
|
||||||
"helper": {
|
"helper": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
@@ -67736,7 +67845,8 @@
|
|||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"uses",
|
"uses",
|
||||||
"chargedCents",
|
"inputTokens",
|
||||||
|
"outputTokens",
|
||||||
"helper"
|
"helper"
|
||||||
],
|
],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
@@ -67752,8 +67862,15 @@
|
|||||||
"minimum": -9007199254740991,
|
"minimum": -9007199254740991,
|
||||||
"maximum": 9007199254740991
|
"maximum": 9007199254740991
|
||||||
},
|
},
|
||||||
"chargedCents": {
|
"inputTokens": {
|
||||||
"type": "number"
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"outputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
},
|
},
|
||||||
"day": {
|
"day": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
@@ -67761,7 +67878,8 @@
|
|||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"uses",
|
"uses",
|
||||||
"chargedCents",
|
"inputTokens",
|
||||||
|
"outputTokens",
|
||||||
"day"
|
"day"
|
||||||
],
|
],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
@@ -68184,16 +68302,61 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "false: the Hub couldn't be reached just now"
|
"description": "false: the Hub couldn't be reached just now"
|
||||||
},
|
},
|
||||||
"capCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "The monthly allowance, in cents"
|
|
||||||
},
|
|
||||||
"usedCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "Used this month, in cents (fractions of a cent)"
|
|
||||||
},
|
|
||||||
"usedPercent": {
|
"usedPercent": {
|
||||||
"type": "number"
|
"type": "number",
|
||||||
|
"description": "How much of this month's allowance is used (0–100)"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Output tokens used this month"
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||||
},
|
},
|
||||||
"renewsOn": {
|
"renewsOn": {
|
||||||
"description": "YYYY-MM-DD",
|
"description": "YYYY-MM-DD",
|
||||||
@@ -68236,9 +68399,11 @@
|
|||||||
"enabled",
|
"enabled",
|
||||||
"capReached",
|
"capReached",
|
||||||
"available",
|
"available",
|
||||||
"capCents",
|
|
||||||
"usedCents",
|
|
||||||
"usedPercent",
|
"usedPercent",
|
||||||
|
"usedInputTokens",
|
||||||
|
"usedOutputTokens",
|
||||||
|
"capInputTokens",
|
||||||
|
"capOutputTokens",
|
||||||
"renewsOn",
|
"renewsOn",
|
||||||
"helpers"
|
"helpers"
|
||||||
],
|
],
|
||||||
@@ -68479,16 +68644,61 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "false: the Hub couldn't be reached just now"
|
"description": "false: the Hub couldn't be reached just now"
|
||||||
},
|
},
|
||||||
"capCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "The monthly allowance, in cents"
|
|
||||||
},
|
|
||||||
"usedCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "Used this month, in cents (fractions of a cent)"
|
|
||||||
},
|
|
||||||
"usedPercent": {
|
"usedPercent": {
|
||||||
"type": "number"
|
"type": "number",
|
||||||
|
"description": "How much of this month's allowance is used (0–100)"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Output tokens used this month"
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||||
},
|
},
|
||||||
"renewsOn": {
|
"renewsOn": {
|
||||||
"description": "YYYY-MM-DD",
|
"description": "YYYY-MM-DD",
|
||||||
@@ -68531,9 +68741,11 @@
|
|||||||
"enabled",
|
"enabled",
|
||||||
"capReached",
|
"capReached",
|
||||||
"available",
|
"available",
|
||||||
"capCents",
|
|
||||||
"usedCents",
|
|
||||||
"usedPercent",
|
"usedPercent",
|
||||||
|
"usedInputTokens",
|
||||||
|
"usedOutputTokens",
|
||||||
|
"capInputTokens",
|
||||||
|
"capOutputTokens",
|
||||||
"renewsOn",
|
"renewsOn",
|
||||||
"helpers"
|
"helpers"
|
||||||
],
|
],
|
||||||
@@ -68677,16 +68889,61 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "false: the Hub couldn't be reached just now"
|
"description": "false: the Hub couldn't be reached just now"
|
||||||
},
|
},
|
||||||
"capCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "The monthly allowance, in cents"
|
|
||||||
},
|
|
||||||
"usedCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "Used this month, in cents (fractions of a cent)"
|
|
||||||
},
|
|
||||||
"usedPercent": {
|
"usedPercent": {
|
||||||
"type": "number"
|
"type": "number",
|
||||||
|
"description": "How much of this month's allowance is used (0–100)"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Output tokens used this month"
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||||
},
|
},
|
||||||
"renewsOn": {
|
"renewsOn": {
|
||||||
"description": "YYYY-MM-DD",
|
"description": "YYYY-MM-DD",
|
||||||
@@ -68729,9 +68986,11 @@
|
|||||||
"enabled",
|
"enabled",
|
||||||
"capReached",
|
"capReached",
|
||||||
"available",
|
"available",
|
||||||
"capCents",
|
|
||||||
"usedCents",
|
|
||||||
"usedPercent",
|
"usedPercent",
|
||||||
|
"usedInputTokens",
|
||||||
|
"usedOutputTokens",
|
||||||
|
"capInputTokens",
|
||||||
|
"capOutputTokens",
|
||||||
"renewsOn",
|
"renewsOn",
|
||||||
"helpers"
|
"helpers"
|
||||||
],
|
],
|
||||||
@@ -68916,16 +69175,61 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "false: the Hub couldn't be reached just now"
|
"description": "false: the Hub couldn't be reached just now"
|
||||||
},
|
},
|
||||||
"capCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "The monthly allowance, in cents"
|
|
||||||
},
|
|
||||||
"usedCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "Used this month, in cents (fractions of a cent)"
|
|
||||||
},
|
|
||||||
"usedPercent": {
|
"usedPercent": {
|
||||||
"type": "number"
|
"type": "number",
|
||||||
|
"description": "How much of this month's allowance is used (0–100)"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Output tokens used this month"
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||||
},
|
},
|
||||||
"renewsOn": {
|
"renewsOn": {
|
||||||
"description": "YYYY-MM-DD",
|
"description": "YYYY-MM-DD",
|
||||||
@@ -68968,9 +69272,11 @@
|
|||||||
"enabled",
|
"enabled",
|
||||||
"capReached",
|
"capReached",
|
||||||
"available",
|
"available",
|
||||||
"capCents",
|
|
||||||
"usedCents",
|
|
||||||
"usedPercent",
|
"usedPercent",
|
||||||
|
"usedInputTokens",
|
||||||
|
"usedOutputTokens",
|
||||||
|
"capInputTokens",
|
||||||
|
"capOutputTokens",
|
||||||
"renewsOn",
|
"renewsOn",
|
||||||
"helpers"
|
"helpers"
|
||||||
],
|
],
|
||||||
@@ -69122,16 +69428,61 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "false: the Hub couldn't be reached just now"
|
"description": "false: the Hub couldn't be reached just now"
|
||||||
},
|
},
|
||||||
"capCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "The monthly allowance, in cents"
|
|
||||||
},
|
|
||||||
"usedCents": {
|
|
||||||
"type": "number",
|
|
||||||
"description": "Used this month, in cents (fractions of a cent)"
|
|
||||||
},
|
|
||||||
"usedPercent": {
|
"usedPercent": {
|
||||||
"type": "number"
|
"type": "number",
|
||||||
|
"description": "How much of this month's allowance is used (0–100)"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)"
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Output tokens used this month"
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)"
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": -9007199254740991,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "About how many output tokens the allowance holds, if half of it went on output"
|
||||||
},
|
},
|
||||||
"renewsOn": {
|
"renewsOn": {
|
||||||
"description": "YYYY-MM-DD",
|
"description": "YYYY-MM-DD",
|
||||||
@@ -69174,9 +69525,11 @@
|
|||||||
"enabled",
|
"enabled",
|
||||||
"capReached",
|
"capReached",
|
||||||
"available",
|
"available",
|
||||||
"capCents",
|
|
||||||
"usedCents",
|
|
||||||
"usedPercent",
|
"usedPercent",
|
||||||
|
"usedInputTokens",
|
||||||
|
"usedOutputTokens",
|
||||||
|
"capInputTokens",
|
||||||
|
"capOutputTokens",
|
||||||
"renewsOn",
|
"renewsOn",
|
||||||
"helpers"
|
"helpers"
|
||||||
],
|
],
|
||||||
|
|||||||
+69
-31
@@ -37676,11 +37676,16 @@ export interface operations {
|
|||||||
capReached: boolean;
|
capReached: boolean;
|
||||||
/** @description false: the Hub couldn't be reached just now */
|
/** @description false: the Hub couldn't be reached just now */
|
||||||
available: boolean;
|
available: boolean;
|
||||||
/** @description The monthly allowance, in cents */
|
/** @description How much of this month's allowance is used (0–100) */
|
||||||
capCents: number;
|
|
||||||
/** @description Used this month, in cents (fractions of a cent) */
|
|
||||||
usedCents: number;
|
|
||||||
usedPercent: number;
|
usedPercent: number;
|
||||||
|
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||||
|
usedInputTokens: number | null;
|
||||||
|
/** @description Output tokens used this month */
|
||||||
|
usedOutputTokens: number | null;
|
||||||
|
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||||
|
capInputTokens: number | null;
|
||||||
|
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||||
|
capOutputTokens: number | null;
|
||||||
/** @description YYYY-MM-DD */
|
/** @description YYYY-MM-DD */
|
||||||
renewsOn: string | null;
|
renewsOn: string | null;
|
||||||
/** @description Each helper switched on or off in Site settings → AI */
|
/** @description Each helper switched on or off in Site settings → AI */
|
||||||
@@ -37739,11 +37744,16 @@ export interface operations {
|
|||||||
capReached: boolean;
|
capReached: boolean;
|
||||||
/** @description false: the Hub couldn't be reached just now */
|
/** @description false: the Hub couldn't be reached just now */
|
||||||
available: boolean;
|
available: boolean;
|
||||||
/** @description The monthly allowance, in cents */
|
/** @description How much of this month's allowance is used (0–100) */
|
||||||
capCents: number;
|
|
||||||
/** @description Used this month, in cents (fractions of a cent) */
|
|
||||||
usedCents: number;
|
|
||||||
usedPercent: number;
|
usedPercent: number;
|
||||||
|
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||||
|
usedInputTokens: number | null;
|
||||||
|
/** @description Output tokens used this month */
|
||||||
|
usedOutputTokens: number | null;
|
||||||
|
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||||
|
capInputTokens: number | null;
|
||||||
|
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||||
|
capOutputTokens: number | null;
|
||||||
/** @description YYYY-MM-DD */
|
/** @description YYYY-MM-DD */
|
||||||
renewsOn: string | null;
|
renewsOn: string | null;
|
||||||
/** @description Each helper switched on or off in Site settings → AI */
|
/** @description Each helper switched on or off in Site settings → AI */
|
||||||
@@ -37768,18 +37778,21 @@ export interface operations {
|
|||||||
};
|
};
|
||||||
people: {
|
people: {
|
||||||
uses: number;
|
uses: number;
|
||||||
chargedCents: number;
|
inputTokens: number;
|
||||||
|
outputTokens: number;
|
||||||
userId: string | null;
|
userId: string | null;
|
||||||
name: string;
|
name: string;
|
||||||
}[];
|
}[];
|
||||||
helpers: {
|
helpers: {
|
||||||
uses: number;
|
uses: number;
|
||||||
chargedCents: number;
|
inputTokens: number;
|
||||||
|
outputTokens: number;
|
||||||
helper: string;
|
helper: string;
|
||||||
}[];
|
}[];
|
||||||
days: {
|
days: {
|
||||||
uses: number;
|
uses: number;
|
||||||
chargedCents: number;
|
inputTokens: number;
|
||||||
|
outputTokens: number;
|
||||||
day: string;
|
day: string;
|
||||||
}[];
|
}[];
|
||||||
};
|
};
|
||||||
@@ -37945,11 +37958,16 @@ export interface operations {
|
|||||||
capReached: boolean;
|
capReached: boolean;
|
||||||
/** @description false: the Hub couldn't be reached just now */
|
/** @description false: the Hub couldn't be reached just now */
|
||||||
available: boolean;
|
available: boolean;
|
||||||
/** @description The monthly allowance, in cents */
|
/** @description How much of this month's allowance is used (0–100) */
|
||||||
capCents: number;
|
|
||||||
/** @description Used this month, in cents (fractions of a cent) */
|
|
||||||
usedCents: number;
|
|
||||||
usedPercent: number;
|
usedPercent: number;
|
||||||
|
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||||
|
usedInputTokens: number | null;
|
||||||
|
/** @description Output tokens used this month */
|
||||||
|
usedOutputTokens: number | null;
|
||||||
|
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||||
|
capInputTokens: number | null;
|
||||||
|
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||||
|
capOutputTokens: number | null;
|
||||||
/** @description YYYY-MM-DD */
|
/** @description YYYY-MM-DD */
|
||||||
renewsOn: string | null;
|
renewsOn: string | null;
|
||||||
/** @description Each helper switched on or off in Site settings → AI */
|
/** @description Each helper switched on or off in Site settings → AI */
|
||||||
@@ -38041,11 +38059,16 @@ export interface operations {
|
|||||||
capReached: boolean;
|
capReached: boolean;
|
||||||
/** @description false: the Hub couldn't be reached just now */
|
/** @description false: the Hub couldn't be reached just now */
|
||||||
available: boolean;
|
available: boolean;
|
||||||
/** @description The monthly allowance, in cents */
|
/** @description How much of this month's allowance is used (0–100) */
|
||||||
capCents: number;
|
|
||||||
/** @description Used this month, in cents (fractions of a cent) */
|
|
||||||
usedCents: number;
|
|
||||||
usedPercent: number;
|
usedPercent: number;
|
||||||
|
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||||
|
usedInputTokens: number | null;
|
||||||
|
/** @description Output tokens used this month */
|
||||||
|
usedOutputTokens: number | null;
|
||||||
|
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||||
|
capInputTokens: number | null;
|
||||||
|
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||||
|
capOutputTokens: number | null;
|
||||||
/** @description YYYY-MM-DD */
|
/** @description YYYY-MM-DD */
|
||||||
renewsOn: string | null;
|
renewsOn: string | null;
|
||||||
/** @description Each helper switched on or off in Site settings → AI */
|
/** @description Each helper switched on or off in Site settings → AI */
|
||||||
@@ -38127,11 +38150,16 @@ export interface operations {
|
|||||||
capReached: boolean;
|
capReached: boolean;
|
||||||
/** @description false: the Hub couldn't be reached just now */
|
/** @description false: the Hub couldn't be reached just now */
|
||||||
available: boolean;
|
available: boolean;
|
||||||
/** @description The monthly allowance, in cents */
|
/** @description How much of this month's allowance is used (0–100) */
|
||||||
capCents: number;
|
|
||||||
/** @description Used this month, in cents (fractions of a cent) */
|
|
||||||
usedCents: number;
|
|
||||||
usedPercent: number;
|
usedPercent: number;
|
||||||
|
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||||
|
usedInputTokens: number | null;
|
||||||
|
/** @description Output tokens used this month */
|
||||||
|
usedOutputTokens: number | null;
|
||||||
|
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||||
|
capInputTokens: number | null;
|
||||||
|
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||||
|
capOutputTokens: number | null;
|
||||||
/** @description YYYY-MM-DD */
|
/** @description YYYY-MM-DD */
|
||||||
renewsOn: string | null;
|
renewsOn: string | null;
|
||||||
/** @description Each helper switched on or off in Site settings → AI */
|
/** @description Each helper switched on or off in Site settings → AI */
|
||||||
@@ -38220,11 +38248,16 @@ export interface operations {
|
|||||||
capReached: boolean;
|
capReached: boolean;
|
||||||
/** @description false: the Hub couldn't be reached just now */
|
/** @description false: the Hub couldn't be reached just now */
|
||||||
available: boolean;
|
available: boolean;
|
||||||
/** @description The monthly allowance, in cents */
|
/** @description How much of this month's allowance is used (0–100) */
|
||||||
capCents: number;
|
|
||||||
/** @description Used this month, in cents (fractions of a cent) */
|
|
||||||
usedCents: number;
|
|
||||||
usedPercent: number;
|
usedPercent: number;
|
||||||
|
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||||
|
usedInputTokens: number | null;
|
||||||
|
/** @description Output tokens used this month */
|
||||||
|
usedOutputTokens: number | null;
|
||||||
|
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||||
|
capInputTokens: number | null;
|
||||||
|
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||||
|
capOutputTokens: number | null;
|
||||||
/** @description YYYY-MM-DD */
|
/** @description YYYY-MM-DD */
|
||||||
renewsOn: string | null;
|
renewsOn: string | null;
|
||||||
/** @description Each helper switched on or off in Site settings → AI */
|
/** @description Each helper switched on or off in Site settings → AI */
|
||||||
@@ -38313,11 +38346,16 @@ export interface operations {
|
|||||||
capReached: boolean;
|
capReached: boolean;
|
||||||
/** @description false: the Hub couldn't be reached just now */
|
/** @description false: the Hub couldn't be reached just now */
|
||||||
available: boolean;
|
available: boolean;
|
||||||
/** @description The monthly allowance, in cents */
|
/** @description How much of this month's allowance is used (0–100) */
|
||||||
capCents: number;
|
|
||||||
/** @description Used this month, in cents (fractions of a cent) */
|
|
||||||
usedCents: number;
|
|
||||||
usedPercent: number;
|
usedPercent: number;
|
||||||
|
/** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */
|
||||||
|
usedInputTokens: number | null;
|
||||||
|
/** @description Output tokens used this month */
|
||||||
|
usedOutputTokens: number | null;
|
||||||
|
/** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */
|
||||||
|
capInputTokens: number | null;
|
||||||
|
/** @description About how many output tokens the allowance holds, if half of it went on output */
|
||||||
|
capOutputTokens: number | null;
|
||||||
/** @description YYYY-MM-DD */
|
/** @description YYYY-MM-DD */
|
||||||
renewsOn: string | null;
|
renewsOn: string | null;
|
||||||
/** @description Each helper switched on or off in Site settings → AI */
|
/** @description Each helper switched on or off in Site settings → AI */
|
||||||
|
|||||||
@@ -72,10 +72,7 @@ export function resolveToApiOrigin(urlOrPath: string | null | undefined): string
|
|||||||
} catch {
|
} catch {
|
||||||
// fall through to relative handling
|
// fall through to relative handling
|
||||||
}
|
}
|
||||||
// Stored uploads ("/uploads/…") are served under /api/uploads (2.3.0), so they reach the
|
return API_BASE ? `${API_BASE}${raw}` : raw;
|
||||||
// backend when the site and its API share one address.
|
|
||||||
const path = raw.startsWith("/uploads/") ? `/api${raw}` : raw;
|
|
||||||
return API_BASE ? `${API_BASE}${path}` : path;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The parsed JSON body of a failed request — v1 sends `message` (some routes add a
|
// The parsed JSON body of a failed request — v1 sends `message` (some routes add a
|
||||||
|
|||||||
@@ -177,9 +177,8 @@ monorepo, listing every variable with its layer, whether it's required, and a de
|
|||||||
itself.
|
itself.
|
||||||
- **URLs are checked before and after.** Before: the form checks that the domain's DNS points at
|
- **URLs are checked before and after.** Before: the form checks that the domain's DNS points at
|
||||||
the central server and warns if not (the install still runs). After Joshua marks the proxy done:
|
the central server and warns if not (the install still runs). After Joshua marks the proxy done:
|
||||||
the Hub checks `https://<domain>/` (frontend answers), `https://<domain>/api/health` (backend
|
the Hub checks `https://<domain>/` (frontend answers), `https://<domain>/health` (backend
|
||||||
answers with the right version; `/health` before Events 2.3.0) and that it reports the
|
answers with the right version) and that `/health` reports the `FRONTEND_URL` it was given.
|
||||||
`FRONTEND_URL` it was given.
|
|
||||||
|
|
||||||
**For Joshua to set per server before the first install:** the database settings and
|
**For Joshua to set per server before the first install:** the database settings and
|
||||||
`TRUST_PROXY`. Behind frp the app sees every connection from frpc on `127.0.0.1`, and the
|
`TRUST_PROXY`. Behind frp the app sees every connection from frpc on `127.0.0.1`, and the
|
||||||
@@ -376,8 +375,7 @@ Set up in FastPanel: events.hope.co.za (Hope Family Church, Cross Events)
|
|||||||
|
|
||||||
1. Add the site events.hope.co.za.
|
1. Add the site events.hope.co.za.
|
||||||
2. Proxy:
|
2. Proxy:
|
||||||
/api → http://127.0.0.1:20011 (backend; Events 2.3.0+, older
|
/api, /uploads, /health, /docs → http://127.0.0.1:20011 (backend)
|
||||||
releases also need /uploads, /health, /docs)
|
|
||||||
everything else → http://127.0.0.1:20010 (frontend)
|
everything else → http://127.0.0.1:20010 (frontend)
|
||||||
Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https.
|
Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https.
|
||||||
Allow uploads up to 25 MB.
|
Allow uploads up to 25 MB.
|
||||||
|
|||||||
+1
-1
@@ -26,7 +26,7 @@ for each phase. They moved here from `hope-events/docs/` on 2026-11-05.
|
|||||||
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04 (`contracts@1.0.0`, `contracts@1.1.0`). Not published to a registry (decision 22): the Hub gets a packed release committed to its repo |
|
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04 (`contracts@1.0.0`, `contracts@1.1.0`). Not published to a registry (decision 22): the Hub gets a packed release committed to its repo |
|
||||||
| 1 | Hub 2.0.0 | **Released** 2026-11-05 (`events-hub` `v2.0.0`; `docs/HUB-2.0-PLAN.md` there). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first). crosscode-site's address prices are merged, **not deployed yet** |
|
| 1 | Hub 2.0.0 | **Released** 2026-11-05 (`events-hub` `v2.0.0`; `docs/HUB-2.0-PLAN.md` there). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first). crosscode-site's address prices are merged, **not deployed yet** |
|
||||||
| 1b | Cross Events 2.2.0: moves here as `apps/events`, `crosscode` script | **In progress.** Planned in [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). **Steps 1–3 done 2026-11-12** (merged into `main`): history merged in under `apps/events` (from `hope-events` `e6c9670`), workspaces and one root lockfile with versions pinned to 2.1.1, same test results as 2.1.1 (711 backend tests, typecheck, both builds). **The `crosscode` script and `adopt` (§4–5) are written** (branch `feat/crosscode-script`, 2026-11-12; shellcheck and 47 bats tests pass, not yet run on a server). **Still to do:** VM testing (§6), the version bump and `events@2.2.0` tag, adopting each install, archiving `hope-events` (§7). Until then servers keep deploying from `hope-events` `v2.1.1`, and **Events work happens here** (`hope-events` is frozen; a hotfix there as 2.1.2 is cherry-picked into `apps/events`) |
|
| 1b | Cross Events 2.2.0: moves here as `apps/events`, `crosscode` script | **In progress.** Planned in [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). **Steps 1–3 done 2026-11-12** (merged into `main`): history merged in under `apps/events` (from `hope-events` `e6c9670`), workspaces and one root lockfile with versions pinned to 2.1.1, same test results as 2.1.1 (711 backend tests, typecheck, both builds). **The `crosscode` script and `adopt` (§4–5) are written** (branch `feat/crosscode-script`, 2026-11-12; shellcheck and 47 bats tests pass, not yet run on a server). **Still to do:** VM testing (§6), the version bump and `events@2.2.0` tag, adopting each install, archiving `hope-events` (§7). Until then servers keep deploying from `hope-events` `v2.1.1`, and **Events work happens here** (`hope-events` is frozen; a hotfix there as 2.1.2 is cherry-picked into `apps/events`) |
|
||||||
| 1c | Cross Events 2.3.0: authenticator app 2FA (TOTP + recovery codes) | TOTP not started (`TwoFactorMethod` enum in Events' `prisma/schema.prisma`). **Done on branches, 2026-11-17, not merged:** AI use in tokens (`feat/ai-tokens` here, in `events-hub` as 2.0.1 and in crosscode-site) and the backend under `/api` (`feat/api-prefix`) |
|
| 1c | Cross Events 2.3.0: authenticator app 2FA (TOTP + recovery codes) | Not started (`TwoFactorMethod` enum in Events' `prisma/schema.prisma`) |
|
||||||
| 1d | Agent 1.0.0 + Hub 2.1.0 (+ contracts 1.2.0): server agent, installs / scheduled updates / uninstalls from the Hub, server stats | **Planned** 2026-11-12 in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) (ROADMAP decisions 27–37). Starts after 1b; can run alongside 1c |
|
| 1d | Agent 1.0.0 + Hub 2.1.0 (+ contracts 1.2.0): server agent, installs / scheduled updates / uninstalls from the Hub, server stats | **Planned** 2026-11-12 in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) (ROADMAP decisions 27–37). Starts after 1b; can run alongside 1c |
|
||||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | Not started. Events keeps speaking protocol 1 until then |
|
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | Not started. Events keeps speaking protocol 1 until then |
|
||||||
| 3–7 | Accounts 1.0.0 → Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started |
|
| 3–7 | Accounts 1.0.0 → Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started |
|
||||||
|
|||||||
+2
-2
@@ -614,7 +614,7 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
|
|||||||
| 0 | contracts 1.0.0 | `crosscode.event/1`, `crosscode.church/1`, `crosscode.identity/1`, Hub protocol v2: schemas, generated JSON Schema, docs, sample payloads, the monorepo set up. **Released 2026-11-04** | Everything else depends on them |
|
| 0 | contracts 1.0.0 | `crosscode.event/1`, `crosscode.church/1`, `crosscode.identity/1`, Hub protocol v2: schemas, generated JSON Schema, docs, sample payloads, the monorepo set up. **Released 2026-11-04** | Everything else depends on them |
|
||||||
| 1 | **Hub 2.0.0** | Cross Code Hub: products, licence per product, per-customer billing with bundles, protocol v2 (v1 still accepted), sibling discovery, AI usage per product, **releases per product with requirements** (§5), contracts as a committed file (§2). **Released 2026-11-05** (crosscode-site address prices merged) | Must exist before a second product is sold, and before Events releases come from the monorepo |
|
| 1 | **Hub 2.0.0** | Cross Code Hub: products, licence per product, per-customer billing with bundles, protocol v2 (v1 still accepted), sibling discovery, AI usage per product, **releases per product with requirements** (§5), contracts as a committed file (§2). **Released 2026-11-05** (crosscode-site address prices merged) | Must exist before a second product is sold, and before Events releases come from the monorepo |
|
||||||
| 1b | **Cross Events 2.2.0** | **Moves into the monorepo** as `apps/events`, with its git history (merged in, not copied); its packages become workspaces; the **`crosscode` script** (`deploy`, `status`, `install`, `adopt`; §8) replaces `scripts/deploy.sh` and `scripts/install.sh`; every install moved with `crosscode adopt`; `hope-events` archived. No feature changes, so a problem is clearly the move | Before more products, so every product is released and deployed the same way from the start |
|
| 1b | **Cross Events 2.2.0** | **Moves into the monorepo** as `apps/events`, with its git history (merged in, not copied); its packages become workspaces; the **`crosscode` script** (`deploy`, `status`, `install`, `adopt`; §8) replaces `scripts/deploy.sh` and `scripts/install.sh`; every install moved with `crosscode adopt`; `hope-events` archived. No feature changes, so a problem is clearly the move | Before more products, so every product is released and deployed the same way from the start |
|
||||||
| 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses. Also (decided 2026-11-17): **AI use shown in tokens**, never rand, outside the Hub (needs Hub 2.0.1); **everything the backend serves under `/api`**, so a site and its API share one address and one proxy rule | Independent and useful now; the Accounts migration later carries it over |
|
| 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses | Independent and useful now; the Accounts migration later carries it over |
|
||||||
| 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.2.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c |
|
| 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.2.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c |
|
||||||
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events | Small; ready for when the Website exists |
|
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events | Small; ready for when the Website exists |
|
||||||
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script | The Website is built on it from day one |
|
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script | The Website is built on it from day one |
|
||||||
@@ -637,7 +637,7 @@ At the end of each phase, update it in the same sitting and deploy it (its `DEPL
|
|||||||
| 0 contracts | Nothing |
|
| 0 contracts | Nothing |
|
||||||
| 1 Hub 2.0.0 | Bundle discounts (15% / 25%) and the address add-on (own domain R0 · Cross Code address R10 · domain included R25) in `src/data/pricing.mjs`, worded so it's clear the Website and App are still coming. Legal pages if billing terms change |
|
| 1 Hub 2.0.0 | Bundle discounts (15% / 25%) and the address add-on (own domain R0 · Cross Code address R10 · domain included R25) in `src/data/pricing.mjs`, worded so it's clear the Website and App are still coming. Legal pages if billing terms change |
|
||||||
| 1b Events 2.2.0 | Nothing (the move doesn't change what Cross Events does) |
|
| 1b Events 2.2.0 | Nothing (the move doesn't change what Cross Events does) |
|
||||||
| 1c Events 2.3.0 | Authenticator app 2FA in the Cross Events feature list (`src/data/cross-events.mjs`) and the security / POPIA wording. (The AI allowance in tokens was done ahead, on branch `feat/ai-tokens` in crosscode-site, 2026-11-17) |
|
| 1c Events 2.3.0 | Authenticator app 2FA in the Cross Events feature list (`src/data/cross-events.mjs`) and the security / POPIA wording |
|
||||||
| 1d Agent 1.0.0 + Hub 2.1.0 | Nothing (it changes how installs are run, not what churches buy) |
|
| 1d Agent 1.0.0 + Hub 2.1.0 | Nothing (it changes how installs are run, not what churches buy) |
|
||||||
| 2 Events 2.4.0 | "Works with the Church Website and App" (event feed, Linked products) on the Cross Events page, as "coming" until those ship |
|
| 2 Events 2.4.0 | "Works with the Church Website and App" (event feed, Linked products) on the Cross Events page, as "coming" until those ship |
|
||||||
| 3 Accounts 1.0.0 | "One sign-in for all your church's products" on the Products page. Accounts isn't sold, so no page or price of its own |
|
| 3 Accounts 1.0.0 | "One sign-in for all your church's products" on the Products page. Accounts isn't sold, so no page or price of its own |
|
||||||
|
|||||||
+12
-3
@@ -205,15 +205,24 @@ POST /api/installs/ai/status
|
|||||||
X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
|
X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
|
||||||
{ "protocolVersion": 1 }
|
{ "protocolVersion": 1 }
|
||||||
→ 200 { "enabled": true, "capReached": false, "capCents": 5000, "usedCents": 812.4,
|
→ 200 { "enabled": true, "capReached": false, "capCents": 5000, "usedCents": 812.4,
|
||||||
"usedPercent": 16, "renewsOn": "2026-12-01" }
|
"usedPercent": 16, "renewsOn": "2026-12-01",
|
||||||
|
"usedInputTokens": 412000, "usedOutputTokens": 61000, // Hub 2.0.1+
|
||||||
|
"capInputTokens": 3571000, "capOutputTokens": 714000 } // Hub 2.0.1+
|
||||||
```
|
```
|
||||||
|
|
||||||
- **`enabled: false`** — hide the AI buttons everywhere: the licence's cap is R0, the licence isn't
|
- **`enabled: false`** — hide the AI buttons everywhere: the licence's cap is R0, the licence isn't
|
||||||
active (suspended, revoked, or past its grace days), or the Hub's AI isn't set up.
|
active (suspended, revoked, or past its grace days), or the Hub's AI isn't set up.
|
||||||
- **`capReached: true`** — show the buttons **disabled** ("This month's AI allowance is used up — it
|
- **`capReached: true`** — show the buttons **disabled** ("This month's AI allowance is used up — it
|
||||||
renews on 1 December"). Reached means there isn't room left for even a small call.
|
renews on 1 December"). Reached means there isn't room left for even a small call.
|
||||||
- Amounts are cents (rand) as **charged** to the church, with fractions (a call costs a fraction of a
|
- **Churches see tokens, never rand** (Hub 2.0.1, Cross Events 2.3.0). `usedInputTokens` /
|
||||||
cent). The month is South African time; `renewsOn` is the 1st of the next month.
|
`usedOutputTokens` are this month's tokens over all the church's installs (input counts cached
|
||||||
|
prompt tokens). `capInputTokens` / `capOutputTokens` are an **estimate** of the allowance: what half
|
||||||
|
the cap buys as input and half as output, at the current model price, exchange rate and markup,
|
||||||
|
rounded down to a thousand. `usedPercent` is exact (it's worked out in rand). Installs show the
|
||||||
|
tokens and the percentage, and don't pass the cents on.
|
||||||
|
- `capCents` / `usedCents` are cents (rand) as **charged** to the church, with fractions (a call costs
|
||||||
|
a fraction of a cent), for the Hub and for installs before Cross Events 2.3.0. The month is South
|
||||||
|
African time; `renewsOn` is the 1st of the next month.
|
||||||
|
|
||||||
### A helper call
|
### A helper call
|
||||||
|
|
||||||
|
|||||||
@@ -65,6 +65,26 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "date",
|
"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])))$"
|
"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])))$"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
|
|||||||
@@ -25,6 +25,26 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "date",
|
"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])))$"
|
"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])))$"
|
||||||
|
},
|
||||||
|
"usedInputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"usedOutputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"capInputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
|
},
|
||||||
|
"capOutputTokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 9007199254740991
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
|
|||||||
@@ -269,6 +269,12 @@ export const aiStatusSchema = z.object({
|
|||||||
usedCents: z.number().nonnegative(),
|
usedCents: z.number().nonnegative(),
|
||||||
usedPercent: z.number().nonnegative(),
|
usedPercent: z.number().nonnegative(),
|
||||||
renewsOn: dateSchema,
|
renewsOn: dateSchema,
|
||||||
|
// Hub 2.0.1: tokens, which is what churches see (the cents are for the Hub and older installs).
|
||||||
|
// The allowance is approximate: half the cap priced as input, half as output.
|
||||||
|
usedInputTokens: count.optional(),
|
||||||
|
usedOutputTokens: count.optional(),
|
||||||
|
capInputTokens: count.optional(),
|
||||||
|
capOutputTokens: count.optional(),
|
||||||
});
|
});
|
||||||
export type AiStatus = z.infer<typeof aiStatusSchema>;
|
export type AiStatus = z.infer<typeof aiStatusSchema>;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user