Files
events-hub/backend/src/utils/licences.js
T
joshuaandClaude Opus 5.5 7478e84e9d Hub 2.0 step 4: billing per customer
- One invoice per customer per period for all its products; the schedule
  moves from Licence to Customer (migration copies it, so billing carries
  on unchanged); licences get billedFrom / billedUntil
- Website (R99, 5 GB) and App (on active members) prices next to the
  Events tiers; founding prices per product, then bundles (15% two, 25%
  three); extra website storage R20 per 5 GB, never discounted
- A product added to a billed customer starts after its free month; days
  before its first full period are prorated, never charged twice
- Annual review per product (Events income, App members), one notice of
  licence change per product; invoices, PDFs and emails name products
- Customer page: schedule, per-product billing, next-invoice preview
- Invoices from before 2.0 kept as they were (still recalculable)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 16:18:23 +02:00

83 lines
4.2 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;
}
}
/**
* 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).
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 };