Files
events-hub/backend/src/utils/licences.js
T
joshuaandClaude Opus 5.5 c6f734ab20 Hub 2.21.0: install the Church Website; Website storage bought in steps
- New install offers the Church Website: Accounts first when the church has
  none, at accounts.<its address> (www. dropped); the FastPanel email sends a
  www. site's bare domain to www. with a 301.
- Licence.extraStorageSteps (migration): the token sends a Website its limit
  (5 GB + steps, limits.storageBytes, contracts 1.17.0); invoices bill the
  steps bought instead of the storage reported. Edit popup field 0-99.
- A Website/App licence starts on its plan however it's made (New install too).
- Vendored @crosscode/contracts 1.17.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 00:03:21 +02:00

89 lines
4.6 KiB
JavaScript

/**
* Creating licences (Hub 2.0): one licence per product per customer that isn't revoked, a key
* with the product's prefix, and the free Accounts licence that comes with any other product.
*/
const { licenceKey } = require('./crypto');
const { PRODUCT_NAMES, BILLABLE, isProduct } = require('./products');
const { today, addMonths } = require('./billing/dates');
const conflict = (message, code) => Object.assign(new Error(message), { status: 409, code });
/** The customer's licence for a product that isn't revoked, or null. */
function openLicence(db, customerId, product) {
return db.licence.findFirst({ where: { customerId, product, status: { not: 'revoked' } } });
}
const productTaken = product =>
conflict(`This customer already has a ${PRODUCT_NAMES[product]} licence. Revoke it first to issue a new one (a customer has one of each product).`, 'PRODUCT_LICENCE_EXISTS');
/**
* A new licence for `product`, with a fresh key. A key collision (vanishingly rare) is retried; a
* second open licence for the product is refused with 409 PRODUCT_LICENCE_EXISTS, also when two
* requests race (the partial unique index catches the second).
*/
async function createLicence(db, { customerId, product = 'events', data = {} }) {
if (!isProduct(product)) throw Object.assign(new Error('Unknown product.'), { status: 400 });
if (await openLicence(db, customerId, product)) throw productTaken(product);
for (let attempt = 0; attempt < 5; attempt++) {
try {
return await db.licence.create({ data: { ...data, customerId, product, key: licenceKey(product) } });
} catch (e) {
if (e?.code !== 'P2002') throw e;
if (await openLicence(db, customerId, product)) throw productTaken(product);
// Otherwise the key collided: try another.
}
}
throw new Error('Could not generate a unique licence key.');
}
/**
* The customer's Accounts licence, created (free, never invoiced) if it has none that isn't
* revoked. Returns { licence, created }.
*/
async function ensureAccountsLicence(db, customerId) {
const existing = await openLicence(db, customerId, 'accounts');
if (existing) return { licence: existing, created: false };
try {
const licence = await createLicence(db, { customerId, product: 'accounts', data: { plan: 'included', status: 'active', notes: 'Comes with the church\'s other products (free).' } });
return { licence, created: true };
} catch (e) {
// Created by a request running at the same time.
if (e.code === 'PRODUCT_LICENCE_EXISTS') return { licence: await openLicence(db, customerId, 'accounts'), created: false };
throw e;
}
}
/** The plan a new licence starts on, for products with one (others: the default). */
const FIRST_PLAN = { website: 'Website', app: 'Mustard Seed' };
/**
* Generate a licence for a customer, plus its Accounts licence when this is a product other than
* Accounts and it has none yet. Returns { licence, accounts } (accounts: the licence if created now).
*/
async function generateLicence(db, { customerId, product = 'events', data = {}, now = new Date() }) {
// Hub 2.0, decision 3: a product added to a customer that's already billed gets its free month,
// then joins the customer's invoices (the days before its first full period prorated).
// Hub 2.21.0: a Website licence is on its one plan, an App licence on the first tier, however it's
// made (Generate or New install); the App's review moves it.
if (data.plan === undefined && FIRST_PLAN[product]) data = { ...data, plan: FIRST_PLAN[product] };
const customer = BILLABLE.includes(product) && data.billedFrom === undefined ? await db.customer?.findUnique({ where: { id: customerId } }) : null;
if (customer && customer.billingCycle && customer.billingCycle !== 'none') data = { ...data, billedFrom: addMonths(today(now), 1) };
const licence = await createLicence(db, { customerId, product, data });
if (product === 'accounts') return { licence, accounts: null };
const { licence: accounts, created } = await ensureAccountsLicence(db, customerId);
return { licence, accounts: created ? accounts : null };
}
/**
* Changing a licence's status back from revoked would give the customer two open licences for the
* product: refused with 409 PRODUCT_LICENCE_EXISTS.
*/
async function checkReopen(db, licence, nextStatus) {
if (licence.status !== 'revoked' || !nextStatus || nextStatus === 'revoked') return;
const other = await openLicence(db, licence.customerId, licence.product);
if (other && other.id !== licence.id) throw productTaken(licence.product);
}
module.exports = { openLicence, createLicence, ensureAccountsLicence, generateLicence, checkReopen };