Merge branch 'feat/hub2-ai' into release/2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+6
-1
@@ -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).
|
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
|
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.
|
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
|
### 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).
|
otherwise); the other products register with protocol v2 (step 2).
|
||||||
- Migrations `20261104132032_products`, `20261104150000_releases_per_product`,
|
- Migrations `20261104132032_products`, `20261104150000_releases_per_product`,
|
||||||
`20261104170000_billing_per_customer` (moves each billed licence's schedule to its customer,
|
`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
|
## [1.7.0] - 2026-11-03
|
||||||
|
|
||||||
|
|||||||
@@ -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";
|
||||||
@@ -62,6 +62,11 @@ model Customer {
|
|||||||
// reminded about (30 days before), so he's reminded once per renewal.
|
// reminded about (30 days before), so he's reminded once per renewal.
|
||||||
domainRenewsOn DateTime? @db.Date
|
domainRenewsOn DateTime? @db.Date
|
||||||
domainRemindedFor 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())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
licences Licence[]
|
licences Licence[]
|
||||||
@@ -102,10 +107,6 @@ model Licence {
|
|||||||
// Null = no end date.
|
// Null = no end date.
|
||||||
expiresAt DateTime?
|
expiresAt DateTime?
|
||||||
graceDays Int @default(14)
|
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?
|
notes String?
|
||||||
// Billing (Hub 2.0: the schedule is the customer's). The licence is charged from billedFrom
|
// 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
|
// (null = not charged: a trial, free, or Accounts); a product added to a customer already
|
||||||
|
|||||||
+15
-14
@@ -100,6 +100,20 @@ router.get('/customers', wrap(async (req, res) => {
|
|||||||
function customerData(body, { partial = false } = {}) {
|
function customerData(body, { partial = false } = {}) {
|
||||||
const data = {};
|
const data = {};
|
||||||
for (const f of ['name', 'contactName', 'email', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200);
|
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.');
|
if ((!partial || 'name' in data) && !data.name) throw bad('Give the customer a name.');
|
||||||
return data;
|
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.');
|
if (!Number.isInteger(n) || n < 0 || n > 90) throw bad('Grace period: 0–90 days.');
|
||||||
data.graceDays = n;
|
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 (body?.status !== undefined) {
|
||||||
if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.');
|
if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.');
|
||||||
data.status = body.status;
|
data.status = body.status;
|
||||||
@@ -224,7 +225,7 @@ router.get('/installs/:id', wrap(async (req, res) => {
|
|||||||
let licence = null;
|
let licence = null;
|
||||||
if (install.licence) {
|
if (install.licence) {
|
||||||
// What the install would be told right now, for checking.
|
// 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 target = latest[install.product] || null;
|
||||||
const behind = !!(target && install.version && compareVersions(install.version, target) < 0);
|
const behind = !!(target && install.version && compareVersions(install.version, target) < 0);
|
||||||
|
|||||||
@@ -64,9 +64,10 @@ async function releaseInfo(install, version, { v2 = false } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function tokenFor(install) {
|
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;
|
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));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+33
-21
@@ -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).
|
* 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,
|
* 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.
|
* 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) {
|
function pricing(settings, licence, hasKey) {
|
||||||
const known = findModel(settings.ai_model);
|
const known = findModel(settings.ai_model);
|
||||||
@@ -131,11 +131,14 @@ function cleanRequest(body) {
|
|||||||
|
|
||||||
// ─── Database ─────────────────────────────────────────────────────────────────
|
// ─── 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({
|
const rows = await db.aiUsage.aggregate({
|
||||||
where: {
|
where: {
|
||||||
installId, month,
|
installId: { in: installIds }, month,
|
||||||
OR: [{ status: { in: ['done', 'failed'] } }, { status: 'reserved', createdAt: { gt: new Date(now.getTime() - STALE_HOLD_MS) } }],
|
OR: [{ status: { in: ['done', 'failed'] } }, { status: 'reserved', createdAt: { gt: new Date(now.getTime() - STALE_HOLD_MS) } }],
|
||||||
},
|
},
|
||||||
_sum: { chargedMillicents: true },
|
_sum: { chargedMillicents: true },
|
||||||
@@ -143,30 +146,38 @@ async function chargedThisMonth(db, installId, month, now = new Date()) {
|
|||||||
return rows._sum.chargedMillicents || 0;
|
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) {
|
async function setup(install) {
|
||||||
const [settings, key, licence] = await Promise.all([
|
const [settings, key, licence, customer, installs] = await Promise.all([
|
||||||
getSettings(),
|
getSettings(),
|
||||||
aiApiKey(),
|
aiApiKey(),
|
||||||
install.licenceId ? prisma.licence.findUnique({ where: { id: install.licenceId } }) : null,
|
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()) {
|
async function statusFor(install, now = new Date()) {
|
||||||
const { licence, price } = await setup(install);
|
const { licence, installIds, price } = await setup(install);
|
||||||
return statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now });
|
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
|
* Hold the worst case against the cap, or refuse. One transaction with a lock per church (its
|
||||||
* calls at once can't both take the last of the allowance.
|
* 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);
|
const month = monthOf(now);
|
||||||
return prisma.$transaction(async tx => {
|
return prisma.$transaction(async tx => {
|
||||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai:${install.id}`}))`;
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai:${install.customerId || install.id}`}))`;
|
||||||
const charged = await chargedThisMonth(tx, install.id, month, now);
|
const charged = await chargedThisMonth(tx, installIds, month, now);
|
||||||
if (charged + worst > licence.aiMonthlyCapCents * 1000) return null;
|
if (charged + worst > licence.aiMonthlyCapCents * 1000) return null;
|
||||||
return tx.aiUsage.create({
|
return tx.aiUsage.create({
|
||||||
data: { installId: install.id, helper, model: price.model, month, status: 'reserved', chargedMillicents: worst, markupPercent: price.markup, usdZar: price.usdZar },
|
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()) {
|
async function complete(install, body, now = new Date()) {
|
||||||
const req = cleanRequest(body);
|
const req = cleanRequest(body);
|
||||||
const { key, licence, price } = await setup(install);
|
const { key, licence, installIds, price } = await setup(install);
|
||||||
const status = async () => statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now });
|
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 (!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() });
|
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 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() });
|
if (!hold) throw Object.assign(fail(402, 'AI_CAP_REACHED', "This month's AI allowance is used up."), { aiStatus: await status() });
|
||||||
|
|
||||||
let message;
|
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);
|
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()) {
|
async function usageForMonth(month = monthOf()) {
|
||||||
const rows = await prisma.aiUsage.groupBy({
|
const rows = await prisma.aiUsage.groupBy({
|
||||||
by: ['installId'],
|
by: ['installId'],
|
||||||
@@ -331,12 +342,13 @@ async function usageForMonth(month = monthOf()) {
|
|||||||
_sum: { realMillicents: true, chargedMillicents: true },
|
_sum: { realMillicents: true, chargedMillicents: true },
|
||||||
_count: { _all: 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]));
|
const byId = new Map(installs.map(i => [i.id, i]));
|
||||||
return rows.map(r => {
|
return rows.map(r => {
|
||||||
const i = byId.get(r.installId);
|
const i = byId.get(r.installId);
|
||||||
return {
|
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,
|
calls: r._count._all,
|
||||||
realCents: toCents(r._sum.realMillicents || 0),
|
realCents: toCents(r._sum.realMillicents || 0),
|
||||||
chargedCents: toCents(r._sum.chargedMillicents || 0),
|
chargedCents: toCents(r._sum.chargedMillicents || 0),
|
||||||
|
|||||||
@@ -2,14 +2,18 @@
|
|||||||
// mocked Claude.
|
// mocked Claude.
|
||||||
|
|
||||||
const mockRows = [];
|
const mockRows = [];
|
||||||
const mockState = { licence: null };
|
const mockState = { licence: null, installs: [{ id: 'inst_1' }] };
|
||||||
const mockDb = {
|
const mockDb = {
|
||||||
licence: { findUnique: jest.fn(async () => mockState.licence) },
|
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: {
|
aiUsage: {
|
||||||
aggregate: jest.fn(async ({ where }) => {
|
aggregate: jest.fn(async ({ where }) => {
|
||||||
const cutoff = where.OR[1].createdAt.gt;
|
const cutoff = where.OR[1].createdAt.gt;
|
||||||
const sum = mockRows
|
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)
|
.filter(r => r.status !== 'reserved' || r.createdAt > cutoff)
|
||||||
.reduce((n, r) => n + r.chargedMillicents, 0);
|
.reduce((n, r) => n + r.chargedMillicents, 0);
|
||||||
return { _sum: { chargedMillicents: sum } };
|
return { _sum: { chargedMillicents: sum } };
|
||||||
@@ -37,7 +41,7 @@ jest.mock('@anthropic-ai/sdk', () => {
|
|||||||
|
|
||||||
const ai = require('../src/utils/ai');
|
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 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 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 });
|
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(() => {
|
beforeEach(() => {
|
||||||
mockRows.length = 0;
|
mockRows.length = 0;
|
||||||
mockState.licence = { id: 'lic_1', status: 'active', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 5000, aiMarkupPercent: null };
|
mockState.licence = { id: 'lic_1', status: 'active', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 5000, aiMarkupPercent: null };
|
||||||
|
mockState.installs = [{ id: 'inst_1' }];
|
||||||
mockCreate.mockReset();
|
mockCreate.mockReset();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -201,3 +206,19 @@ describe('complete', () => {
|
|||||||
expect(mockCreate).not.toHaveBeenCalled();
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -22,8 +22,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
|||||||
plan: licence.plan,
|
plan: licence.plan,
|
||||||
expiresAt: dateInput(licence.expiresAt),
|
expiresAt: dateInput(licence.expiresAt),
|
||||||
graceDays: String(licence.graceDays),
|
graceDays: String(licence.graceDays),
|
||||||
aiRand: String(licence.aiMonthlyCapCents / 100),
|
|
||||||
aiMarkup: licence.aiMarkupPercent == null ? "" : String(licence.aiMarkupPercent),
|
|
||||||
notes: licence.notes || "",
|
notes: licence.notes || "",
|
||||||
});
|
});
|
||||||
const [busy, setBusy] = useState(false);
|
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.
|
// End of the chosen day, South African time.
|
||||||
expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null,
|
expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null,
|
||||||
graceDays: form.graceDays,
|
graceDays: form.graceDays,
|
||||||
aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100),
|
|
||||||
aiMarkupPercent: form.aiMarkup.trim() === "" ? null : form.aiMarkup,
|
|
||||||
notes: form.notes,
|
notes: form.notes,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -107,16 +103,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
|||||||
<label className="label">Grace (days)</label>
|
<label className="label">Grace (days)</label>
|
||||||
<input type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} />
|
<input type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<label className="label">AI cap (R / month)</label>
|
|
||||||
<input type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
|
|
||||||
<p className="mt-1 text-xs text-slate-500">0 = off (no AI buttons). Counted in charged rand.</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="label" htmlFor={`markup-${licence.id}`}>AI markup (%)</label>
|
|
||||||
<input id={`markup-${licence.id}`} type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
|
|
||||||
<p className="mt-1 text-xs text-slate-500">Blank uses the default (Settings → AI).</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="label">Notes</label>
|
<label className="label">Notes</label>
|
||||||
@@ -134,13 +120,16 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
|||||||
export default function CustomerPage() {
|
export default function CustomerPage() {
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
const [c, setC] = useState<Customer | null>(null);
|
const [c, setC] = useState<Customer | null>(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 [newLicence, setNewLicence] = useState<{ product: Product | ""; expiresAt: string; graceDays: string }>({ product: "", expiresAt: "", graceDays: "14" });
|
||||||
const [msg, setMsg] = useState<Msg>(null);
|
const [msg, setMsg] = useState<Msg>(null);
|
||||||
|
|
||||||
const load = useCallback(() => api<Customer>(`/api/admin/customers/${id}`).then(x => {
|
const load = useCallback(() => api<Customer>(`/api/admin/customers/${id}`).then(x => {
|
||||||
setC(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]);
|
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
|
||||||
useEffect(() => { load(); }, [load]);
|
useEffect(() => { load(); }, [load]);
|
||||||
|
|
||||||
@@ -155,8 +144,12 @@ export default function CustomerPage() {
|
|||||||
const saveDetails = async (e: React.FormEvent) => {
|
const saveDetails = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
try {
|
try {
|
||||||
await api(`/api/admin/customers/${id}`, { method: "PUT", body: form });
|
const { aiRand, aiMarkup, ...details } = form;
|
||||||
setMsg({ type: "ok", text: "Saved." });
|
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();
|
load();
|
||||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||||
};
|
};
|
||||||
@@ -191,6 +184,17 @@ export default function CustomerPage() {
|
|||||||
<div><label className="label">Email</label><input type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
|
<div><label className="label">Email</label><input type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
|
||||||
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
|
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
|
||||||
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
|
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<label className="label" htmlFor="ai-cap">AI cap (R / month)</label>
|
||||||
|
<input id="ai-cap" type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="label" htmlFor="ai-markup">AI markup (%)</label>
|
||||||
|
<input id="ai-markup" type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-slate-500">The AI allowance is the church's, shared by all its sites: 0 = off (no AI buttons). Counted in charged rand. A blank markup uses the default (Settings → AI).</p>
|
||||||
<button className="btn-secondary">Save details</button>
|
<button className="btn-secondary">Save details</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type Detail = {
|
|||||||
adminContact: { name?: string; email?: string } | null; server: { node?: string; postgres?: string; os?: string } | null;
|
adminContact: { name?: string; email?: string } | null; server: { node?: string; postgres?: string; os?: string } | null;
|
||||||
features: Record<string, unknown> | null; registeredAt: string; lastHeartbeatAt: string | null; releasedAt: string | null;
|
features: Record<string, unknown> | null; registeredAt: string; lastHeartbeatAt: string | null; releasedAt: string | null;
|
||||||
health: Health | null; stats: Stats | null;
|
health: Health | null; stats: Stats | null;
|
||||||
customer: { id: string; name: string };
|
customer: { id: string; name: string; aiMonthlyCapCents: number; aiMarkupPercent: number | null };
|
||||||
licence: (Licence & { tokenPreview: { status: string; validUntil: string; licenceExpiresAt: string | null } }) | null;
|
licence: (Licence & { tokenPreview: { status: string; validUntil: string; licenceExpiresAt: string | null } }) | null;
|
||||||
summary: InstallSummary;
|
summary: InstallSummary;
|
||||||
events: InstallEvent[];
|
events: InstallEvent[];
|
||||||
@@ -137,8 +137,8 @@ export default function InstallPage() {
|
|||||||
v={<>{tier.name} · {tierPrice(tier)}{d.licence.plan !== tier.name && d.licence.plan !== "Trial" && <span className="ml-1 text-amber-700">(plan is {d.licence.plan})</span>}</>}
|
v={<>{tier.name} · {tierPrice(tier)}{d.licence.plan !== tier.name && d.licence.plan !== "Trial" && <span className="ml-1 text-amber-700">(plan is {d.licence.plan})</span>}</>}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<Row k="AI cap" v={d.licence.aiMonthlyCapCents ? `${rand(d.licence.aiMonthlyCapCents)} / month` : "off"} />
|
<Row k="AI cap (church)" v={d.customer.aiMonthlyCapCents ? `${rand(d.customer.aiMonthlyCapCents)} / month` : "off"} />
|
||||||
<Row k="AI markup" v={d.licence.aiMarkupPercent == null ? "default" : `${d.licence.aiMarkupPercent}%`} />
|
<Row k="AI markup" v={d.customer.aiMarkupPercent == null ? "default" : `${d.customer.aiMarkupPercent}%`} />
|
||||||
<Link href={`/customers/${d.customer.id}`} className="mt-3 inline-block text-sm text-indigo-600 hover:underline">Change the licence →</Link>
|
<Link href={`/customers/${d.customer.id}`} className="mt-3 inline-block text-sm text-indigo-600 hover:underline">Change the licence →</Link>
|
||||||
</>
|
</>
|
||||||
) : <p className="text-sm text-slate-500">No licence (released).</p>}
|
) : <p className="text-sm text-slate-500">No licence (released).</p>}
|
||||||
@@ -162,7 +162,7 @@ export default function InstallPage() {
|
|||||||
<div className="card mt-6">
|
<div className="card mt-6">
|
||||||
<h2 className="mb-2 font-semibold">AI</h2>
|
<h2 className="mb-2 font-semibold">AI</h2>
|
||||||
{!d.ai.status.enabled && d.ai.months.length === 0 ? (
|
{!d.ai.status.enabled && d.ai.months.length === 0 ? (
|
||||||
<p className="text-sm text-slate-500">Off for this site{d.licence?.aiMonthlyCapCents ? " (AI isn't set up in Settings → AI, or the licence isn't active)" : " (cap R0)"}.</p>
|
<p className="text-sm text-slate-500">Off for this site{d.customer.aiMonthlyCapCents ? " (AI isn't set up in Settings → AI, or the licence isn't active)" : " (cap R0)"}.</p>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Row k="This month (charged)" v={`${randFine(d.ai.status.usedCents)} of ${rand(d.ai.status.capCents)} (${d.ai.status.usedPercent}%)${d.ai.status.capReached ? " — used up" : ""}`} />
|
<Row k="This month (charged)" v={`${randFine(d.ai.status.usedCents)} of ${rand(d.ai.status.capCents)} (${d.ai.status.usedPercent}%)${d.ai.status.capReached ? " — used up" : ""}`} />
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { matches, usePaged } from "@/lib/paging";
|
|||||||
import type { AiInstallUse } from "@/lib/types";
|
import type { AiInstallUse } from "@/lib/types";
|
||||||
import { Loading, Message, PageTitle, Pager, SearchInput, Tabs } from "@/components/ui";
|
import { Loading, Message, PageTitle, Pager, SearchInput, Tabs } from "@/components/ui";
|
||||||
import { BillingSettings } from "@/components/billing/BillingSettings";
|
import { BillingSettings } from "@/components/billing/BillingSettings";
|
||||||
|
import { PRODUCT_NAMES } from "@/lib/products";
|
||||||
|
|
||||||
type Settings = Record<string, string>;
|
type Settings = Record<string, string>;
|
||||||
type AuditRow = { id: string; action: string; target: string | null; metadata: unknown; createdAt: string; actor: { name: string } | null };
|
type AuditRow = { id: string; action: string; target: string | null; metadata: unknown; createdAt: string; actor: { name: string } | null };
|
||||||
@@ -145,11 +146,11 @@ function AiTab({ settings, models, onSaved, setMsg }: { settings: Settings; mode
|
|||||||
{!usage ? <Loading /> : usage.installs.length === 0 ? <p className="px-5 pb-5 text-sm text-slate-500">No AI use in {usage.month}.</p> : (
|
{!usage ? <Loading /> : usage.installs.length === 0 ? <p className="px-5 pb-5 text-sm text-slate-500">No AI use in {usage.month}.</p> : (
|
||||||
<div className="overflow-x-auto px-5 pb-5">
|
<div className="overflow-x-auto px-5 pb-5">
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm">
|
||||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Site</th><th>Cap</th><th>Uses</th><th className="text-right">Real cost</th><th className="text-right">Charged</th><th className="text-right">Profit</th></tr></thead>
|
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Site</th><th>Church cap</th><th>Uses</th><th className="text-right">Real cost</th><th className="text-right">Charged</th><th className="text-right">Profit</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{usage.installs.map(i => (
|
{usage.installs.map(i => (
|
||||||
<tr key={i.installId} className="border-t border-slate-100">
|
<tr key={i.installId} className="border-t border-slate-100">
|
||||||
<td className="py-1"><Link href={`/installs/${i.installId}`} className="text-indigo-700 hover:underline">{i.name}</Link></td>
|
<td className="py-1"><Link href={`/installs/${i.installId}`} className="text-indigo-700 hover:underline">{i.customer?.name || i.name}</Link> <span className="text-xs text-slate-500">{PRODUCT_NAMES[i.product]}</span></td>
|
||||||
<td>{i.capCents ? rand(i.capCents) : "off"}</td>
|
<td>{i.capCents ? rand(i.capCents) : "off"}</td>
|
||||||
<td>{i.calls}</td>
|
<td>{i.calls}</td>
|
||||||
<td className="text-right">{randFine(i.realCents)}</td>
|
<td className="text-right">{randFine(i.realCents)}</td>
|
||||||
|
|||||||
@@ -27,8 +27,6 @@ export type Licence = {
|
|||||||
status: LicenceStatus;
|
status: LicenceStatus;
|
||||||
expiresAt: string | null;
|
expiresAt: string | null;
|
||||||
graceDays: number;
|
graceDays: number;
|
||||||
aiMonthlyCapCents: number;
|
|
||||||
aiMarkupPercent: number | null;
|
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
install?: { id: string; name: string; url: string; lastHeartbeatAt: string | null } | null;
|
install?: { id: string; name: string; url: string; lastHeartbeatAt: string | null } | null;
|
||||||
@@ -42,6 +40,9 @@ export type Customer = {
|
|||||||
phone: string | null;
|
phone: string | null;
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
/** Hub 2.0: the church's AI allowance, shared by all its installs. */
|
||||||
|
aiMonthlyCapCents: number;
|
||||||
|
aiMarkupPercent: number | null;
|
||||||
licences: Licence[];
|
licences: Licence[];
|
||||||
installs: { id: string; product: Product; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
|
installs: { id: string; product: Product; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
|
||||||
};
|
};
|
||||||
@@ -75,7 +76,7 @@ export type InstallEvent = { id: string; type: string; level: Problem["level"];
|
|||||||
export type AiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string };
|
export type AiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string };
|
||||||
export type AiMonth = { month: string; calls: number; inputTokens: number; outputTokens: number; realCents: number; chargedCents: number; profitCents: number };
|
export type AiMonth = { month: string; calls: number; inputTokens: number; outputTokens: number; realCents: number; chargedCents: number; profitCents: number };
|
||||||
export type AiHelperUse = { helper: string; calls: number; chargedCents: number };
|
export type AiHelperUse = { helper: string; calls: number; chargedCents: number };
|
||||||
export type AiInstallUse = { installId: string; name: string; url: string; capCents: number; calls: number; realCents: number; chargedCents: number; profitCents: number };
|
export type AiInstallUse = { installId: string; name: string; url: string; product: Product; customer: { id: string; name: string } | null; capCents: number; calls: number; realCents: number; chargedCents: number; profitCents: number };
|
||||||
|
|
||||||
export type ReleaseRequirement = { product: Product; version: string };
|
export type ReleaseRequirement = { product: Product; version: string };
|
||||||
export type Release = { id: string; product: Product; version: string; notes: string; urgent: boolean; requires: ReleaseRequirement[]; releasedAt: string; latest: boolean; installs: number };
|
export type Release = { id: string; product: Product; version: string; notes: string; urgent: boolean; requires: ReleaseRequirement[]; releasedAt: string; latest: boolean; installs: number };
|
||||||
|
|||||||
Reference in New Issue
Block a user