/** * 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 };