Hub 2.0 step 6: AI cap and markup per church

The cap and markup move from the licence to the customer (migrated), use
is counted over all the church's installs under one lock per church, and
the licence token carries the church's cap. Settings → AI shows product.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 08:55:43 +02:00
co-authored by Claude Opus 5.5
parent 6e51780103
commit 59e6b9f03c
11 changed files with 138 additions and 72 deletions
+33 -21
View File
@@ -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),