diff --git a/CHANGELOG.md b/CHANGELOG.md index fa34420..3dcb307 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,10 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`). as a custom price). Charged once per invoice and never discounted (12 months' price when yearly). For a domain included: its renewal date, an email to the alert address 30 days before (once per renewal), and **Renewed** on the customer page to move it on a year. +- **AI per church** (step 6): the monthly AI cap and markup are the church's (customer page → + Details), shared by all its sites: a call from any of them counts what all of them used this month, + under one lock so two calls at once can't both take the last of it. The licence token carries the + church's cap. Settings → AI shows each site's use with its product and the church's cap. ### Changed @@ -70,7 +74,8 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`). otherwise); the other products register with protocol v2 (step 2). - Migrations `20261104132032_products`, `20261104150000_releases_per_product`, `20261104170000_billing_per_customer` (moves each billed licence's schedule to its customer, - so billing carries on unchanged), `20261104190000_customer_address`. + so billing carries on unchanged), `20261104190000_customer_address`, + `20261105080000_ai_per_customer` (each church takes its licence's AI cap and markup). ## [1.7.0] - 2026-11-03 diff --git a/backend/prisma/migrations/20261105080000_ai_per_customer/migration.sql b/backend/prisma/migrations/20261105080000_ai_per_customer/migration.sql new file mode 100644 index 0000000..fbe675a --- /dev/null +++ b/backend/prisma/migrations/20261105080000_ai_per_customer/migration.sql @@ -0,0 +1,19 @@ +-- Hub 2.0: the AI cap and markup are the church's (counted over all its installs), moved from the +-- licence. Each church takes the cap of its open licence with the highest cap, and that licence's +-- markup override (Hub 1.7 had one Events licence per church, so this is that licence's). + +ALTER TABLE "Customer" ADD COLUMN "aiMarkupPercent" INTEGER, +ADD COLUMN "aiMonthlyCapCents" INTEGER NOT NULL DEFAULT 0; + +UPDATE "Customer" c +SET "aiMonthlyCapCents" = l."aiMonthlyCapCents", "aiMarkupPercent" = l."aiMarkupPercent" +FROM ( + SELECT DISTINCT ON ("customerId") "customerId", "aiMonthlyCapCents", "aiMarkupPercent" + FROM "Licence" + WHERE status <> 'revoked' + ORDER BY "customerId", "aiMonthlyCapCents" DESC, "createdAt" ASC +) l +WHERE c.id = l."customerId"; + +ALTER TABLE "Licence" DROP COLUMN "aiMarkupPercent", +DROP COLUMN "aiMonthlyCapCents"; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 5173041..208909f 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -62,6 +62,11 @@ model Customer { // reminded about (30 days before), so he's reminded once per renewal. domainRenewsOn DateTime? @db.Date domainRemindedFor DateTime? @db.Date + // Hub 2.0 (moved from Licence): the monthly AI spend cap in cents (rand), counted in charged + // rand over all the church's installs. 0 = AI off. And the markup on the real cost, in %; null = + // the Hub default (Settings → AI). + aiMonthlyCapCents Int @default(0) + aiMarkupPercent Int? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt licences Licence[] @@ -102,10 +107,6 @@ model Licence { // Null = no end date. expiresAt DateTime? graceDays Int @default(14) - // Cross Events 2.0: monthly AI spend cap (in cents, rand), counted in charged rand. 0 = AI off. - aiMonthlyCapCents Int @default(0) - // Markup on the real AI cost, in %. Null = the Hub default (Settings → AI). - aiMarkupPercent Int? notes String? // Billing (Hub 2.0: the schedule is the customer's). The licence is charged from billedFrom // (null = not charged: a trial, free, or Accounts); a product added to a customer already diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index 9f090d1..37aacee 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -100,6 +100,20 @@ router.get('/customers', wrap(async (req, res) => { function customerData(body, { partial = false } = {}) { const data = {}; for (const f of ['name', 'contactName', 'email', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200); + // AI (Hub 2.0: the church's, for all its installs): the monthly cap and an optional markup. + if (body?.aiMonthlyCapCents !== undefined) { + const n = parseInt(body.aiMonthlyCapCents, 10); + if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.'); + data.aiMonthlyCapCents = n; + } + if (body?.aiMarkupPercent !== undefined) { + if (body.aiMarkupPercent === null || body.aiMarkupPercent === '') data.aiMarkupPercent = null; + else { + const n = parseInt(body.aiMarkupPercent, 10); + if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The AI markup is 0–500 %, or blank for the default.'); + data.aiMarkupPercent = n; + } + } if ((!partial || 'name' in data) && !data.name) throw bad('Give the customer a name.'); return data; } @@ -136,19 +150,6 @@ function licenceData(body, { partial = false } = {}) { if (!Number.isInteger(n) || n < 0 || n > 90) throw bad('Grace period: 0–90 days.'); data.graceDays = n; } - if (body?.aiMonthlyCapCents !== undefined) { - const n = parseInt(body.aiMonthlyCapCents, 10); - if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.'); - data.aiMonthlyCapCents = n; - } - if (body?.aiMarkupPercent !== undefined) { - if (body.aiMarkupPercent === null || body.aiMarkupPercent === '') data.aiMarkupPercent = null; - else { - const n = parseInt(body.aiMarkupPercent, 10); - if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The AI markup is 0–500 %, or blank for the default.'); - data.aiMarkupPercent = n; - } - } if (body?.status !== undefined) { if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.'); data.status = body.status; @@ -224,7 +225,7 @@ router.get('/installs/:id', wrap(async (req, res) => { let licence = null; if (install.licence) { // What the install would be told right now, for checking. - licence = { ...install.licence, tokenPreview: licenceToken.buildPayload(install.licence, install, install.customer.name) }; + licence = { ...install.licence, tokenPreview: licenceToken.buildPayload({ ...install.licence, aiMonthlyCapCents: install.customer.aiMonthlyCapCents }, install, install.customer.name) }; } const target = latest[install.product] || null; const behind = !!(target && install.version && compareVersions(install.version, target) < 0); diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index 7448504..599fa99 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -64,9 +64,10 @@ async function releaseInfo(install, version, { v2 = false } = {}) { } async function tokenFor(install) { - const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true } } } }) : null; + const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true, aiMonthlyCapCents: true } } } }) : null; if (!licence) return null; - return licenceToken.sign(licenceToken.buildPayload(licence, install, licence.customer.name)); + // The AI cap in the token is the church's (Hub 2.0). + return licenceToken.sign(licenceToken.buildPayload({ ...licence, aiMonthlyCapCents: licence.customer.aiMonthlyCapCents }, install, licence.customer.name)); } /** diff --git a/backend/src/utils/ai.js b/backend/src/utils/ai.js index 9ea79af..f6ba007 100644 --- a/backend/src/utils/ai.js +++ b/backend/src/utils/ai.js @@ -50,7 +50,7 @@ function renewsOn(date = new Date()) { * Prices for a call, or null when the Hub's AI isn't set up (no key or no exchange rate). * Blank prices use the built-in ones for the model (utils/aiModels.js); cache reads always do, * falling back to 0.1× the input price for a model the Hub doesn't know. - * `licence.aiMarkupPercent` overrides the Hub's default markup. + * `allowance.aiMarkupPercent` (the church's, Hub 2.0) overrides the Hub's default markup. */ function pricing(settings, licence, hasKey) { const known = findModel(settings.ai_model); @@ -131,11 +131,14 @@ function cleanRequest(body) { // ─── Database ───────────────────────────────────────────────────────────────── -/** Charged so far this month (millicents): finished calls, and holds for calls still running. */ -async function chargedThisMonth(db, installId, month, now = new Date()) { +/** + * Charged so far this month (millicents) over the church's installs (Hub 2.0: the cap is the + * church's): finished calls, and holds for calls still running. + */ +async function chargedThisMonth(db, installIds, month, now = new Date()) { const rows = await db.aiUsage.aggregate({ where: { - installId, month, + installId: { in: installIds }, month, OR: [{ status: { in: ['done', 'failed'] } }, { status: 'reserved', createdAt: { gt: new Date(now.getTime() - STALE_HOLD_MS) } }], }, _sum: { chargedMillicents: true }, @@ -143,30 +146,38 @@ async function chargedThisMonth(db, installId, month, now = new Date()) { return rows._sum.chargedMillicents || 0; } +/** + * What a call is checked against: the install's licence (active, not expired) with the church's + * cap and markup (Hub 2.0), and the church's installs whose use counts towards the cap. + */ async function setup(install) { - const [settings, key, licence] = await Promise.all([ + const [settings, key, licence, customer, installs] = await Promise.all([ getSettings(), aiApiKey(), install.licenceId ? prisma.licence.findUnique({ where: { id: install.licenceId } }) : null, + install.customerId ? prisma.customer.findUnique({ where: { id: install.customerId }, select: { aiMonthlyCapCents: true, aiMarkupPercent: true } }) : null, + install.customerId ? prisma.install.findMany({ where: { customerId: install.customerId }, select: { id: true } }) : [], ]); - return { settings, key, licence, price: pricing(settings, licence, !!key) }; + const allowance = licence ? { ...licence, aiMonthlyCapCents: customer?.aiMonthlyCapCents || 0, aiMarkupPercent: customer?.aiMarkupPercent ?? null } : null; + const installIds = [...new Set([install.id, ...installs.map(i => i.id)])]; + return { settings, key, licence: allowance, installIds, price: pricing(settings, allowance, !!key) }; } -/** Status for one install (§3b). */ +/** Status for one install (§3b): the church's allowance, used by all its installs. */ async function statusFor(install, now = new Date()) { - const { licence, price } = await setup(install); - return statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now }); + const { licence, installIds, price } = await setup(install); + return statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, installIds, monthOf(now), now), now }); } /** - * Hold the worst case against the cap, or refuse. One transaction with a lock per install, so two - * calls at once can't both take the last of the allowance. + * Hold the worst case against the cap, or refuse. One transaction with a lock per church (its + * installs share the cap), so two calls at once can't both take the last of the allowance. */ -async function reserve({ install, licence, price, helper, worst, now }) { +async function reserve({ install, installIds, licence, price, helper, worst, now }) { const month = monthOf(now); return prisma.$transaction(async tx => { - await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai:${install.id}`}))`; - const charged = await chargedThisMonth(tx, install.id, month, now); + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai:${install.customerId || install.id}`}))`; + const charged = await chargedThisMonth(tx, installIds, month, now); if (charged + worst > licence.aiMonthlyCapCents * 1000) return null; return tx.aiUsage.create({ data: { installId: install.id, helper, model: price.model, month, status: 'reserved', chargedMillicents: worst, markupPercent: price.markup, usdZar: price.usdZar }, @@ -231,15 +242,15 @@ function claudeError(e) { */ async function complete(install, body, now = new Date()) { const req = cleanRequest(body); - const { key, licence, price } = await setup(install); - const status = async () => statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now }); + const { key, licence, installIds, price } = await setup(install); + const status = async () => statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, installIds, monthOf(now), now), now }); if (!price) throw Object.assign(fail(503, 'AI_NOT_CONFIGURED', 'AI is not available.'), { aiStatus: await status() }); - if (!licence || licence.aiMonthlyCapCents <= 0) throw Object.assign(fail(403, 'AI_OFF', 'AI is not part of this licence.'), { aiStatus: await status() }); + if (!licence || licence.aiMonthlyCapCents <= 0) throw Object.assign(fail(403, 'AI_OFF', 'AI is not part of this church\'s plan.'), { aiStatus: await status() }); if (!licenceAllows(licence, now)) throw Object.assign(fail(403, 'LICENCE_INACTIVE', 'AI needs an active licence.'), { aiStatus: await status() }); const worst = worstCase(req.inputTokens, req.maxTokens, price); - const hold = await reserve({ install, licence, price, helper: req.helper, worst, now }); + const hold = await reserve({ install, installIds, licence, price, helper: req.helper, worst, now }); if (!hold) throw Object.assign(fail(402, 'AI_CAP_REACHED', "This month's AI allowance is used up."), { aiStatus: await status() }); let message; @@ -323,7 +334,7 @@ async function usageByHelper(installId, month = monthOf()) { return rows.map(r => ({ helper: r.helper, calls: r._count._all, chargedCents: toCents(r._sum.chargedMillicents || 0) })).sort((a, b) => b.chargedCents - a.chargedCents); } -/** Every install's use in a month, for the Settings → AI overview. */ +/** Every install's use in a month, for the Settings → AI overview (with its product and the church's cap). */ async function usageForMonth(month = monthOf()) { const rows = await prisma.aiUsage.groupBy({ by: ['installId'], @@ -331,12 +342,13 @@ async function usageForMonth(month = monthOf()) { _sum: { realMillicents: true, chargedMillicents: true }, _count: { _all: true }, }); - const installs = await prisma.install.findMany({ where: { id: { in: rows.map(r => r.installId) } }, select: { id: true, name: true, url: true, licence: { select: { aiMonthlyCapCents: true } } } }); + const installs = await prisma.install.findMany({ where: { id: { in: rows.map(r => r.installId) } }, select: { id: true, name: true, url: true, product: true, customer: { select: { id: true, name: true, aiMonthlyCapCents: true } } } }); const byId = new Map(installs.map(i => [i.id, i])); return rows.map(r => { const i = byId.get(r.installId); return { - installId: r.installId, name: i?.name || '?', url: i?.url || '', capCents: i?.licence?.aiMonthlyCapCents || 0, + installId: r.installId, name: i?.name || '?', url: i?.url || '', product: i?.product || 'events', + customer: i?.customer ? { id: i.customer.id, name: i.customer.name } : null, capCents: i?.customer?.aiMonthlyCapCents || 0, calls: r._count._all, realCents: toCents(r._sum.realMillicents || 0), chargedCents: toCents(r._sum.chargedMillicents || 0), diff --git a/backend/tests/ai.test.js b/backend/tests/ai.test.js index c6bca86..16b9333 100644 --- a/backend/tests/ai.test.js +++ b/backend/tests/ai.test.js @@ -2,14 +2,18 @@ // mocked Claude. const mockRows = []; -const mockState = { licence: null }; +const mockState = { licence: null, installs: [{ id: 'inst_1' }] }; const mockDb = { licence: { findUnique: jest.fn(async () => mockState.licence) }, + // Hub 2.0: the cap and markup are the church's (kept on mockState.licence here for the tests), and + // its installs share the cap. + customer: { findUnique: jest.fn(async () => ({ aiMonthlyCapCents: mockState.licence.aiMonthlyCapCents, aiMarkupPercent: mockState.licence.aiMarkupPercent })) }, + install: { findMany: jest.fn(async () => mockState.installs) }, aiUsage: { aggregate: jest.fn(async ({ where }) => { const cutoff = where.OR[1].createdAt.gt; const sum = mockRows - .filter(r => r.installId === where.installId && r.month === where.month) + .filter(r => where.installId.in.includes(r.installId) && r.month === where.month) .filter(r => r.status !== 'reserved' || r.createdAt > cutoff) .reduce((n, r) => n + r.chargedMillicents, 0); return { _sum: { chargedMillicents: sum } }; @@ -37,7 +41,7 @@ jest.mock('@anthropic-ai/sdk', () => { const ai = require('../src/utils/ai'); -const install = { id: 'inst_1', licenceId: 'lic_1' }; +const install = { id: 'inst_1', licenceId: 'lic_1', customerId: 'c1' }; const price = { model: 'claude-haiku-5-5', inUsd: 0.1, outUsd: 0.5, cacheReadUsd: 0.01, usdZar: 20, markup: 40 }; const body = { protocolVersion: 1, helper: 'draft_message', system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 1000 }; const reply = (usage, extra = {}) => ({ model: 'claude-haiku-5-5', stop_reason: 'end_turn', content: [{ type: 'text', text: 'Hi all!' }], usage, ...extra }); @@ -45,6 +49,7 @@ const reply = (usage, extra = {}) => ({ model: 'claude-haiku-5-5', stop_reason: beforeEach(() => { mockRows.length = 0; mockState.licence = { id: 'lic_1', status: 'active', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 5000, aiMarkupPercent: null }; + mockState.installs = [{ id: 'inst_1' }]; mockCreate.mockReset(); }); @@ -201,3 +206,19 @@ describe('complete', () => { expect(mockCreate).not.toHaveBeenCalled(); }); }); + +describe('the cap is the church\'s (Hub 2.0)', () => { + test('what its other installs used this month counts against it', async () => { + mockState.installs = [{ id: 'inst_1' }, { id: 'inst_website' }]; + mockRows.push({ id: 'w1', installId: 'inst_website', month: ai.monthOf(), status: 'done', chargedMillicents: 4999 * 1000, createdAt: new Date() }); + const status = await ai.statusFor(install); + expect(status).toMatchObject({ enabled: true, capReached: true, usedCents: 4999 }); + await expect(ai.complete(install, body)).rejects.toMatchObject({ code: 'AI_CAP_REACHED' }); + expect(mockCreate).not.toHaveBeenCalled(); + }); + + test('another church\'s use doesn\'t count', async () => { + mockRows.push({ id: 'o1', installId: 'inst_other_church', month: ai.monthOf(), status: 'done', chargedMillicents: 4999 * 1000, createdAt: new Date() }); + expect((await ai.statusFor(install)).usedCents).toBe(0); + }); +}); diff --git a/frontend/src/app/(hub)/customers/[id]/page.tsx b/frontend/src/app/(hub)/customers/[id]/page.tsx index 2a1b643..1742cf8 100644 --- a/frontend/src/app/(hub)/customers/[id]/page.tsx +++ b/frontend/src/app/(hub)/customers/[id]/page.tsx @@ -22,8 +22,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: plan: licence.plan, expiresAt: dateInput(licence.expiresAt), graceDays: String(licence.graceDays), - aiRand: String(licence.aiMonthlyCapCents / 100), - aiMarkup: licence.aiMarkupPercent == null ? "" : String(licence.aiMarkupPercent), notes: licence.notes || "", }); const [busy, setBusy] = useState(false); @@ -40,8 +38,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: // End of the chosen day, South African time. expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null, graceDays: form.graceDays, - aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100), - aiMarkupPercent: form.aiMarkup.trim() === "" ? null : form.aiMarkup, notes: form.notes, }, }); @@ -107,16 +103,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: setForm({ ...form, graceDays: e.target.value })} /> -
- - setForm({ ...form, aiRand: e.target.value })} /> -

0 = off (no AI buttons). Counted in charged rand.

-
-
- - setForm({ ...form, aiMarkup: e.target.value })} /> -

Blank uses the default (Settings → AI).

-
@@ -134,13 +120,16 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: export default function CustomerPage() { const { id } = useParams<{ id: string }>(); const [c, setC] = useState(null); - const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "" }); + const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "", aiRand: "0", aiMarkup: "" }); const [newLicence, setNewLicence] = useState<{ product: Product | ""; expiresAt: string; graceDays: string }>({ product: "", expiresAt: "", graceDays: "14" }); const [msg, setMsg] = useState(null); const load = useCallback(() => api(`/api/admin/customers/${id}`).then(x => { setC(x); - setForm({ name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "" }); + setForm({ + name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "", + aiRand: String(x.aiMonthlyCapCents / 100), aiMarkup: x.aiMarkupPercent == null ? "" : String(x.aiMarkupPercent), + }); }).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]); useEffect(() => { load(); }, [load]); @@ -155,8 +144,12 @@ export default function CustomerPage() { const saveDetails = async (e: React.FormEvent) => { e.preventDefault(); try { - await api(`/api/admin/customers/${id}`, { method: "PUT", body: form }); - setMsg({ type: "ok", text: "Saved." }); + const { aiRand, aiMarkup, ...details } = form; + await api(`/api/admin/customers/${id}`, { + method: "PUT", + body: { ...details, aiMonthlyCapCents: Math.round((parseFloat(aiRand) || 0) * 100), aiMarkupPercent: aiMarkup.trim() === "" ? null : aiMarkup }, + }); + setMsg({ type: "ok", text: "Saved. The church's sites pick up an AI change with their next heartbeat (within 15 minutes)." }); load(); } catch (err) { setMsg({ type: "err", text: errorText(err) }); } }; @@ -191,6 +184,17 @@ export default function CustomerPage() {
setForm({ ...form, email: e.target.value })} />
setForm({ ...form, phone: e.target.value })} />