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>
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
-- Hub 2.0: billing per customer. The schedule (cycle, start, next invoice, review) moves from the
|
||||
-- licence to the customer, so one invoice covers all of a customer's products; each licence keeps
|
||||
-- when it's charged from (billedFrom) and up to which day it has been invoiced (billedUntil).
|
||||
-- Existing billing carries on unchanged: each billed licence's schedule becomes its customer's.
|
||||
|
||||
-- AlterTable: the customer's schedule, and the invoice's basis.
|
||||
ALTER TABLE "Customer" ADD COLUMN "billingCycle" "BillingCycle" NOT NULL DEFAULT 'none',
|
||||
ADD COLUMN "billingStart" DATE,
|
||||
ADD COLUMN "nextInvoiceDate" DATE,
|
||||
ADD COLUMN "reviewDate" DATE;
|
||||
|
||||
ALTER TABLE "Invoice" ADD COLUMN "basis" JSONB;
|
||||
|
||||
ALTER TABLE "Licence" ADD COLUMN "billedFrom" DATE,
|
||||
ADD COLUMN "billedUntil" DATE;
|
||||
|
||||
-- Copy: a customer takes the schedule of its billed licence (Hub 1.7 billed one Events licence per
|
||||
-- customer; if there were several, the one invoiced next).
|
||||
UPDATE "Customer" c
|
||||
SET "billingCycle" = l."billingCycle", "billingStart" = l."billingStart", "nextInvoiceDate" = l."nextInvoiceDate", "reviewDate" = l."reviewDate"
|
||||
FROM (
|
||||
SELECT DISTINCT ON ("customerId") "customerId", "billingCycle", "billingStart", "nextInvoiceDate", "reviewDate"
|
||||
FROM "Licence"
|
||||
WHERE "billingCycle" <> 'none' AND status <> 'revoked'
|
||||
ORDER BY "customerId", "nextInvoiceDate" ASC NULLS LAST, "createdAt" ASC
|
||||
) l
|
||||
WHERE c.id = l."customerId";
|
||||
|
||||
-- A billed licence is charged from when its billing started, and has been invoiced up to the day
|
||||
-- before its next invoice.
|
||||
UPDATE "Licence"
|
||||
SET "billedFrom" = COALESCE("billingStart", "nextInvoiceDate"),
|
||||
"billedUntil" = CASE WHEN "nextInvoiceDate" IS NOT NULL THEN "nextInvoiceDate" - 1 END
|
||||
WHERE "billingCycle" <> 'none';
|
||||
|
||||
-- The licence's own schedule is gone.
|
||||
ALTER TABLE "Licence" DROP COLUMN "billingCycle",
|
||||
DROP COLUMN "billingStart",
|
||||
DROP COLUMN "nextInvoiceDate",
|
||||
DROP COLUMN "reviewDate";
|
||||
|
||||
-- Invoices: one per licence and period before 2.0 (kept as history); one per customer and period
|
||||
-- from 2.0 (licenceId null), not counting void ones.
|
||||
DROP INDEX "Invoice_licenceId_periodStart_key";
|
||||
CREATE INDEX "Invoice_licenceId_periodStart_idx" ON "Invoice"("licenceId", "periodStart");
|
||||
CREATE UNIQUE INDEX "Invoice_customerId_periodStart_open_key" ON "Invoice"("customerId", "periodStart")
|
||||
WHERE "licenceId" IS NULL AND "periodStart" IS NOT NULL AND status <> 'void';
|
||||
@@ -40,6 +40,16 @@ model Customer {
|
||||
founding Boolean @default(false)
|
||||
foundingSince DateTime? @db.Date
|
||||
foundingNote String?
|
||||
// Hub 2.0: one invoice per customer per period for all its products (moved from Licence).
|
||||
// none = not invoiced. Invoices are in advance: each covers the period starting on its date.
|
||||
billingCycle BillingCycle @default(none)
|
||||
// The day billing started; its day of the month is the billing day.
|
||||
billingStart DateTime? @db.Date
|
||||
// The start of the next period to invoice (the draft is made 14 days before).
|
||||
nextInvoiceDate DateTime? @db.Date
|
||||
// The next annual tier review: the first invoice for a period starting on or after it uses
|
||||
// what each product reports (Events: 12-month event income; App: active members).
|
||||
reviewDate DateTime? @db.Date
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
licences Licence[]
|
||||
@@ -85,16 +95,12 @@ model Licence {
|
||||
// Markup on the real AI cost, in %. Null = the Hub default (Settings → AI).
|
||||
aiMarkupPercent Int?
|
||||
notes String?
|
||||
// Billing (1.7.0). none = not invoiced (trial, free). Invoices are in advance: each covers
|
||||
// the period starting on its date.
|
||||
billingCycle BillingCycle @default(none)
|
||||
// The day billing started; its day of the month is the billing day.
|
||||
billingStart DateTime? @db.Date
|
||||
// The start of the next period to invoice (the draft is made 14 days before).
|
||||
nextInvoiceDate DateTime? @db.Date
|
||||
// The next annual tier review: the first invoice for a period starting on or after it
|
||||
// uses the last 12 months' event income.
|
||||
reviewDate DateTime? @db.Date
|
||||
// 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
|
||||
// billed starts after its free month. billedUntil is the last day an invoice has covered, so a
|
||||
// product that starts mid-period gets a prorated line on the next invoice.
|
||||
billedFrom DateTime? @db.Date
|
||||
billedUntil DateTime? @db.Date
|
||||
// A price per month instead of the tier's (e.g. the Network tier), in cents.
|
||||
customMonthlyCents Int?
|
||||
createdAt DateTime @default(now())
|
||||
@@ -318,7 +324,9 @@ model Invoice {
|
||||
incomeBand String?
|
||||
reviewed Boolean @default(false)
|
||||
founding Boolean @default(false)
|
||||
// A tier change that comes with this invoice: { from, to, fromMonthlyCents, toMonthlyCents }.
|
||||
// Tier changes that come with this invoice. Hub 2.0: a list, one per product,
|
||||
// [{ licenceId, product, from, to, fromMonthlyCents, toMonthlyCents, band }]; before 2.0 one
|
||||
// object { from, to, … } (read with compute.planChangesOf).
|
||||
planChange Json?
|
||||
// [{ description, quantity, unitCents, amountCents }]
|
||||
lines Json
|
||||
@@ -330,6 +338,9 @@ model Invoice {
|
||||
// Things Joshua should check before approving (e.g. no income band reported).
|
||||
warnings String[] @default([])
|
||||
recipientEmail String?
|
||||
// Hub 2.0: what a customer invoice was worked out from, so a draft can be recalculated:
|
||||
// { licences: [{ id, billedUntil }], planChangeDropped }.
|
||||
basis Json?
|
||||
approvedAt DateTime?
|
||||
approvedById String?
|
||||
approvalEmailedAt DateTime?
|
||||
@@ -344,7 +355,10 @@ model Invoice {
|
||||
payments Payment[]
|
||||
licenceChanges LicenceChange[]
|
||||
|
||||
@@unique([licenceId, periodStart])
|
||||
// Before Hub 2.0 an invoice was for one licence's period. From 2.0 it's for the customer's
|
||||
// period (licenceId null): one per customer per period that isn't void, enforced by the partial
|
||||
// unique index "Invoice_customerId_periodStart_open_key" (migration …_billing_per_customer).
|
||||
@@index([licenceId, periodStart])
|
||||
@@index([status, issueDate])
|
||||
@@index([customerId])
|
||||
}
|
||||
|
||||
@@ -7,17 +7,26 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { DEFAULTS } = require('../src/utils/settings');
|
||||
const pdf = require('../src/utils/billing/pdf');
|
||||
const { draftInvoice, invoiceState, statement } = require('../src/utils/billing/compute');
|
||||
const { draftCustomerInvoice, invoiceState, statement } = require('../src/utils/billing/compute');
|
||||
|
||||
const out = path.resolve(process.argv[2] || 'billing-samples');
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const settings = { ...DEFAULTS, bank_name: 'Sample Bank', bank_account_name: 'Cross Code', bank_account_number: '1234 567 890', bank_branch_code: '250655', bank_account_type: 'Cheque' };
|
||||
const customer = { id: 'c1', name: 'Cedarwood Community Church', contactName: 'Thandi Nkosi', billingAddress: '12 Oak Street, Meyerton, 1961', email: 'office@cedarwood.example', founding: true };
|
||||
const install = { adminContact: { email: 'admin@cedarwood.example' }, stats: { income: { eventIncome12m: 'R250 001–R400 000' } } };
|
||||
const licence = { id: 'l1', plan: 'Sprout', billingCycle: 'monthly', billingStart: new Date('2026-01-01'), nextInvoiceDate: new Date('2027-01-01'), reviewDate: new Date('2027-01-01'), customMonthlyCents: null };
|
||||
// A founding church with all three products at its annual review: Events moves up a tier, the App
|
||||
// joined part-way through December, and the website uses 7 GB.
|
||||
const customer = {
|
||||
id: 'c1', name: 'Cedarwood Community Church', contactName: 'Thandi Nkosi', billingAddress: '12 Oak Street, Meyerton, 1961', email: 'office@cedarwood.example', founding: true,
|
||||
billingCycle: 'monthly', billingStart: new Date('2026-01-01'), nextInvoiceDate: new Date('2027-01-01'), reviewDate: new Date('2027-01-01'),
|
||||
};
|
||||
const GB = 1024 ** 3;
|
||||
const licences = [
|
||||
{ id: 'l1', product: 'events', status: 'active', plan: 'Sprout', customMonthlyCents: null, billedFrom: new Date('2026-01-01'), billedUntil: new Date('2026-12-31'), install: { product: 'events', adminContact: { email: 'admin@cedarwood.example' }, stats: { income: { eventIncome12m: 'R250 001–R400 000' } } } },
|
||||
{ id: 'l2', product: 'website', status: 'active', plan: 'Website', customMonthlyCents: null, billedFrom: new Date('2026-06-01'), billedUntil: new Date('2026-12-31'), install: { product: 'website', stats: { storage: { usedBytes: 7 * GB, includedBytes: 5 * GB } } } },
|
||||
{ id: 'l3', product: 'app', status: 'active', plan: 'Mustard Seed', customMonthlyCents: null, billedFrom: new Date('2026-12-15'), billedUntil: null, install: { product: 'app', stats: { activeMembers90d: '0–100' } } },
|
||||
];
|
||||
|
||||
(async () => {
|
||||
const { invoice: draft } = draftInvoice({ licence, customer, install, settings });
|
||||
const { invoice: draft } = draftCustomerInvoice({ customer, licences, settings });
|
||||
const invoice = { ...draft, id: 'i1', number: 'INV-2027-0001', status: 'sent', notes: null };
|
||||
const payment = { id: 'p1', receiptNumber: 'REC-2027-0001', amountCents: 30000, paidOn: new Date('2027-01-05'), method: 'eft', reference: 'INV-2027-0001' };
|
||||
const state = invoiceState({ ...invoice, payments: [payment] }, '2027-01-06');
|
||||
@@ -28,6 +37,6 @@ const licence = { id: 'l1', plan: 'Sprout', billingCycle: 'monthly', billingStar
|
||||
const st = statement({ invoices: [older, { ...invoice, payments: [payment] }], payments: [{ ...payment, invoice }], from: '2026-12-15', to: '2027-01-31' });
|
||||
fs.writeFileSync(path.join(out, 'statement.pdf'), await pdf.statementPdf({ statement: st, customer, settings, recipientEmail: invoice.recipientEmail }));
|
||||
const change = { number: 'LC-2026-0001', fromPlan: 'Sprout', toPlan: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, effectiveDate: new Date('2027-01-01'), incomeBand: 'R250 001–R400 000', createdAt: new Date('2026-12-18') };
|
||||
fs.writeFileSync(path.join(out, 'licence-change.pdf'), await pdf.licenceChangePdf({ change, customer, settings, founding: true, recipientEmail: invoice.recipientEmail, cycle: 'monthly' }));
|
||||
fs.writeFileSync(path.join(out, 'licence-change.pdf'), await pdf.licenceChangePdf({ change, customer, settings, founding: true, recipientEmail: invoice.recipientEmail, cycle: 'monthly', product: 'events' }));
|
||||
console.log(`samples in ${out}`);
|
||||
})();
|
||||
|
||||
@@ -166,7 +166,9 @@ router.post('/customers/:id/licences', wrap(async (req, res) => {
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
const product = req.body?.product ?? 'events';
|
||||
if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.');
|
||||
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data: licenceData(req.body) });
|
||||
// A new Website licence is on its one plan, an App licence on the first tier (the review moves it).
|
||||
const data = { ...(product === 'website' ? { plan: 'Website' } : product === 'app' ? { plan: 'Mustard Seed' } : {}), ...licenceData(req.body) };
|
||||
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data });
|
||||
await audit(req, 'licence_generated', licence.id, { customer: customer.name, product, expiresAt: licence.expiresAt });
|
||||
if (accounts) await audit(req, 'licence_generated', accounts.id, { customer: customer.name, product: 'accounts', automatic: true });
|
||||
res.status(201).json({ ...licence, accountsLicence: accounts });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Billing API (1.7.0, admin login required): invoices, payments, statements, licence changes,
|
||||
* founding churches and each licence's billing set-up. The work is in utils/billing/.
|
||||
* founding churches, each customer's billing schedule and each licence's billing (Hub 2.0: one
|
||||
* invoice per customer for all its products). The work is in utils/billing/.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
@@ -11,7 +12,8 @@ const { audit } = require('../utils/audit');
|
||||
const billing = require('../utils/billing');
|
||||
const compute = require('../utils/billing/compute');
|
||||
const { ymd, day, today } = require('../utils/billing/dates');
|
||||
const { TIERS } = require('../utils/billing/tiers');
|
||||
const { TIERS, PLANS, BUNDLE_PERCENT, STORAGE } = require('../utils/billing/tiers');
|
||||
const { addMonths } = require('../utils/billing/dates');
|
||||
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -43,7 +45,8 @@ function invoiceRow(invoice, todayYmd = ymd(today())) {
|
||||
periodStart: ymd(invoice.periodStart), periodEnd: ymd(invoice.periodEnd),
|
||||
customer: invoice.customer ? { id: invoice.customer.id, name: invoice.customer.name, founding: invoice.customer.founding } : undefined,
|
||||
payments: (invoice.payments || []).map(p => ({ ...p, paidOn: ymd(p.paidOn) })),
|
||||
licence: licence ? { id: licence.id, key: licence.key, plan: licence.plan, billingCycle: licence.billingCycle, installUrl: licence.install?.url || null } : null,
|
||||
licence: licence ? { id: licence.id, key: licence.key, product: licence.product, plan: licence.plan, installUrl: licence.install?.url || null } : null,
|
||||
planChanges: compute.planChangesOf(invoice),
|
||||
...compute.invoiceState(invoice, todayYmd),
|
||||
};
|
||||
}
|
||||
@@ -68,6 +71,7 @@ router.get('/overview', wrap(async (req, res) => {
|
||||
overdue: rows.filter(i => i.state === 'overdue').length,
|
||||
receivedThisMonthCents: payments.reduce((s, p) => s + p.amountCents, 0),
|
||||
tiers: TIERS,
|
||||
plans: PLANS,
|
||||
});
|
||||
}));
|
||||
|
||||
@@ -103,7 +107,7 @@ router.get('/invoices/:id', wrap(async (req, res) => {
|
||||
prisma.licenceChange.findMany({ where: { invoiceId: invoice.id }, orderBy: { createdAt: 'desc' } }),
|
||||
prisma.billingEmail.findMany({ where: { refId: invoice.id }, orderBy: { sentAt: 'desc' } }),
|
||||
]);
|
||||
res.json({ ...invoiceRow(invoice), licenceChanges: changes.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })), emails, tiers: TIERS });
|
||||
res.json({ ...invoiceRow(invoice), licenceChanges: changes.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })), emails, tiers: TIERS, plans: PLANS });
|
||||
}));
|
||||
|
||||
router.put('/invoices/:id', wrap(async (req, res) => {
|
||||
@@ -174,7 +178,26 @@ router.get('/payments/:id/pdf', wrap(async (req, res) => sendPdf(res, await bill
|
||||
|
||||
// ─── Customers: founding, billing details, statements ─────────────────────────
|
||||
|
||||
/** Every customer's billing at a glance: founding, licences' plans and next invoice, balance. */
|
||||
/** What a licence's product reports that its price depends on, for the billing screens. */
|
||||
function reported(l) {
|
||||
const stats = l.install?.stats || {};
|
||||
if (l.product === 'events') return { incomeBand: stats.income?.eventIncome12m || null };
|
||||
if (l.product === 'app') return { activeMembers: stats.activeMembers90d || null };
|
||||
if (l.product === 'website') return { storage: stats.storage || null };
|
||||
return {};
|
||||
}
|
||||
|
||||
/** A licence for the billing screens. */
|
||||
const billingLicence = l => ({
|
||||
id: l.id, key: l.key, product: l.product, plan: l.plan, status: l.status, customMonthlyCents: l.customMonthlyCents,
|
||||
billedFrom: ymd(l.billedFrom), billedUntil: ymd(l.billedUntil), billable: BILLABLE.includes(l.product),
|
||||
url: l.install?.url || null, ...reported(l),
|
||||
});
|
||||
|
||||
/** A customer's schedule for the billing screens. */
|
||||
const schedule = c => ({ billingCycle: c.billingCycle, billingStart: ymd(c.billingStart), nextInvoiceDate: ymd(c.nextInvoiceDate), reviewDate: ymd(c.reviewDate) });
|
||||
|
||||
/** Every customer's billing at a glance: founding, schedule, licences' plans, balance. */
|
||||
router.get('/customers', wrap(async (req, res) => {
|
||||
const t = ymd(today());
|
||||
const customers = await prisma.customer.findMany({
|
||||
@@ -185,9 +208,10 @@ router.get('/customers', wrap(async (req, res) => {
|
||||
const states = c.invoices.map(i => compute.invoiceState(i, t));
|
||||
return {
|
||||
id: c.id, name: c.name, founding: c.founding, foundingSince: ymd(c.foundingSince), foundingNote: c.foundingNote, billingEmail: c.billingEmail,
|
||||
...schedule(c),
|
||||
balanceCents: states.reduce((s, x) => s + Math.max(0, x.balanceCents), 0),
|
||||
overdue: states.filter(x => x.state === 'overdue').length,
|
||||
licences: c.licences.map(l => ({ id: l.id, key: l.key, plan: l.plan, status: l.status, billingCycle: l.billingCycle, nextInvoiceDate: ymd(l.nextInvoiceDate), reviewDate: ymd(l.reviewDate), customMonthlyCents: l.customMonthlyCents, url: l.install?.url || null })),
|
||||
licences: c.licences.map(billingLicence),
|
||||
};
|
||||
}));
|
||||
}));
|
||||
@@ -206,23 +230,35 @@ router.get('/customers/:id', wrap(async (req, res) => {
|
||||
});
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
const invoices = customer.invoices.map(i => invoiceRow(i, t));
|
||||
const install = customer.licences.find(l => l.install && !l.install.releasedAt)?.install || null;
|
||||
res.json({
|
||||
id: customer.id, name: customer.name, contactName: customer.contactName, email: customer.email,
|
||||
billingEmail: customer.billingEmail, billingAddress: customer.billingAddress,
|
||||
founding: customer.founding, foundingSince: ymd(customer.foundingSince), foundingNote: customer.foundingNote,
|
||||
sendsTo: compute.recipientFor(customer, install),
|
||||
...schedule(customer),
|
||||
sendsTo: compute.recipientFor(customer, compute.contactInstall(customer.licences)),
|
||||
balanceCents: invoices.filter(i => i.status === 'sent').reduce((s, i) => s + Math.max(0, i.balanceCents), 0),
|
||||
licences: customer.licences.map(l => ({
|
||||
id: l.id, key: l.key, plan: l.plan, status: l.status, billingCycle: l.billingCycle, billingStart: ymd(l.billingStart),
|
||||
nextInvoiceDate: ymd(l.nextInvoiceDate), reviewDate: ymd(l.reviewDate), customMonthlyCents: l.customMonthlyCents,
|
||||
url: l.install?.url || null, incomeBand: l.install?.stats?.income?.eventIncome12m || null,
|
||||
})),
|
||||
licences: customer.licences.map(billingLicence),
|
||||
invoices,
|
||||
payments: customer.payments.map(p => ({ ...p, paidOn: ymd(p.paidOn) })),
|
||||
licenceChanges: customer.licenceChanges.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })),
|
||||
emails: customer.billingEmails,
|
||||
tiers: TIERS,
|
||||
plans: PLANS,
|
||||
bundlePercent: BUNDLE_PERCENT,
|
||||
storage: STORAGE,
|
||||
});
|
||||
}));
|
||||
|
||||
// The next invoice as it would be drafted now (nothing is saved): its lines, discounts and total.
|
||||
router.get('/customers/:id/preview', wrap(async (req, res) => {
|
||||
const { getSettings } = require('../utils/settings');
|
||||
const customer = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: { include: { install: true } } } });
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
if (customer.billingCycle === 'none' || !customer.nextInvoiceDate) return res.json({ billed: false });
|
||||
const { invoice, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings: await getSettings() });
|
||||
res.json({
|
||||
billed: true, empty,
|
||||
invoice: { ...invoice, issueDate: ymd(invoice.issueDate), dueDate: ymd(invoice.dueDate), periodStart: ymd(invoice.periodStart), periodEnd: ymd(invoice.periodEnd), planChanges: invoice.planChange || [] },
|
||||
});
|
||||
}));
|
||||
|
||||
@@ -241,8 +277,29 @@ router.put('/customers/:id', wrap(async (req, res) => {
|
||||
if (e && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) throw bad('That email address doesn\'t look right.');
|
||||
data.billingEmail = e;
|
||||
}
|
||||
const customer = await prisma.customer.update({ where: { id: req.params.id }, data }).catch(() => { throw bad('Customer not found', 404); });
|
||||
await audit(req, 'customer_billing_updated', customer.id, { changed: Object.keys(data), founding: customer.founding });
|
||||
// The schedule (Hub 2.0: per customer, for all its products).
|
||||
if (b.billingCycle !== undefined) {
|
||||
if (!['none', 'monthly', 'yearly'].includes(b.billingCycle)) throw bad('Choose monthly, yearly or not billed.');
|
||||
data.billingCycle = b.billingCycle;
|
||||
}
|
||||
for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]);
|
||||
const existing = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: true } });
|
||||
if (!existing) throw bad('Customer not found', 404);
|
||||
const merged = { ...existing, ...data };
|
||||
if (merged.billingCycle !== 'none') {
|
||||
if (!merged.billingStart) throw bad('Set the date billing starts.');
|
||||
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
|
||||
// The first review is a year after billing starts.
|
||||
if (!merged.reviewDate && b.reviewDate === undefined) data.reviewDate = addMonths(merged.billingStart, 12);
|
||||
}
|
||||
// Starting billing: the products not charged yet are charged from the billing start.
|
||||
const start = existing.billingCycle === 'none' && merged.billingCycle !== 'none' ? merged.billingStart : null;
|
||||
const startLicences = start ? existing.licences.filter(l => BILLABLE.includes(l.product) && l.status === 'active' && !l.billedFrom) : [];
|
||||
const [customer] = await prisma.$transaction([
|
||||
prisma.customer.update({ where: { id: existing.id }, data }),
|
||||
...startLicences.map(l => prisma.licence.update({ where: { id: l.id }, data: { billedFrom: day(start) } })),
|
||||
]);
|
||||
await audit(req, 'customer_billing_updated', customer.id, { changed: Object.keys(data), founding: customer.founding, billingCycle: customer.billingCycle, licencesStarted: startLicences.length });
|
||||
res.json({ ok: true });
|
||||
}));
|
||||
|
||||
@@ -261,16 +318,20 @@ router.post('/customers/:id/statement/email', emailLimiter, wrap(async (req, res
|
||||
|
||||
// ─── Licence billing set-up ───────────────────────────────────────────────────
|
||||
|
||||
// Hub 2.0: when a licence is charged from (blank = not charged), and an optional custom price.
|
||||
// The schedule is the customer's.
|
||||
router.put('/licences/:id', wrap(async (req, res) => {
|
||||
const b = req.body || {};
|
||||
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
|
||||
if (!existing) throw bad('Licence not found', 404);
|
||||
const data = {};
|
||||
if (b.billingCycle !== undefined) {
|
||||
if (!['none', 'monthly', 'yearly'].includes(b.billingCycle)) throw bad('Choose monthly, yearly or not billed.');
|
||||
data.billingCycle = b.billingCycle;
|
||||
if (b.billedFrom !== undefined) {
|
||||
data.billedFrom = dayOrNull(b.billedFrom);
|
||||
if (data.billedFrom && !BILLABLE.includes(existing.product)) throw bad(`${PRODUCT_NAMES[existing.product]} is free: it's never invoiced.`);
|
||||
if (data.billedFrom && existing.billedUntil && ymd(data.billedFrom) <= ymd(existing.billedUntil)) {
|
||||
throw bad(`It's invoiced up to ${ymd(existing.billedUntil)} already: choose a later date, or correct the invoices by hand.`);
|
||||
}
|
||||
}
|
||||
for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]);
|
||||
if (b.customMonthlyCents !== undefined) {
|
||||
if (b.customMonthlyCents === null || b.customMonthlyCents === '') data.customMonthlyCents = null;
|
||||
else {
|
||||
@@ -279,19 +340,8 @@ router.put('/licences/:id', wrap(async (req, res) => {
|
||||
data.customMonthlyCents = n;
|
||||
}
|
||||
}
|
||||
const merged = { ...existing, ...data };
|
||||
// Until billing per customer (Hub 2.0 step 4) only Events has prices; Accounts is never invoiced.
|
||||
if (merged.billingCycle !== 'none' && !BILLABLE.includes(existing.product)) {
|
||||
throw bad(`${PRODUCT_NAMES[existing.product]} licences can't be invoiced yet.`);
|
||||
}
|
||||
if (merged.billingCycle !== 'none') {
|
||||
if (!merged.billingStart) throw bad('Set the date billing starts.');
|
||||
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
|
||||
// The first review is a year after billing starts.
|
||||
if (!merged.reviewDate && b.reviewDate === undefined) data.reviewDate = require('../utils/billing/dates').addMonths(merged.billingStart, 12);
|
||||
}
|
||||
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
|
||||
await audit(req, 'licence_billing_updated', licence.id, { changed: Object.keys(data), billingCycle: licence.billingCycle });
|
||||
await audit(req, 'licence_billing_updated', licence.id, { changed: Object.keys(data), billedFrom: ymd(licence.billedFrom) });
|
||||
res.json({ ok: true });
|
||||
}));
|
||||
|
||||
|
||||
@@ -2,19 +2,34 @@
|
||||
* Billing calculations, pure (no database): what an invoice for a period contains, totals and
|
||||
* VAT, where an invoice stands with its payments, and a statement.
|
||||
*
|
||||
* Rules (decided 2026-11-03):
|
||||
* - Invoices are in advance: the invoice dated the 1st covers the period starting that day.
|
||||
* - The tier is reviewed once a year: the first invoice for a period starting on or after the
|
||||
* licence's reviewDate uses the 12-month event-income band; invoices in between keep the tier.
|
||||
* Rules (decided 2026-11-03 and 2026-11-04, Hub 2.0):
|
||||
* - One invoice per customer per period, for all its products. Invoices are in advance: the
|
||||
* invoice dated the 1st covers the period starting that day.
|
||||
* - Each product is priced on its own plan (prices in tiers.js). Tiers are reviewed once a year:
|
||||
* the first invoice for a period starting on or after the customer's reviewDate uses what each
|
||||
* product reports (Events: 12-month event income; App: active members); invoices in between keep
|
||||
* the tier.
|
||||
* - Yearly billing is 10 months' price for 12 months. Founding churches pay the founding price.
|
||||
* - Bundles: 15% off two products, 25% off three, on the products after founding (Accounts is free
|
||||
* and never counts).
|
||||
* - Add-ons (extra website storage) are never discounted: no founding, bundle or yearly discount.
|
||||
* - A product that starts part-way through a period (after its free month, decision 3) is charged
|
||||
* by the day for the days before its first full period: on the invoice for the period it starts
|
||||
* in, or the next one if that was already invoiced.
|
||||
* - Not VAT registered: no VAT. Once registered, prices are VAT-inclusive (totals unchanged).
|
||||
*/
|
||||
|
||||
const { tierNamed, tierForBand, planPrice, YEARLY_MONTHS, FOUNDING_PERCENT } = require('./tiers');
|
||||
const { ymd, day, addDays, addMonths, periodLabel } = require('./dates');
|
||||
const {
|
||||
tierNamed, reviewTier, planPrice, extraStorageBlocks, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
|
||||
} = require('./tiers');
|
||||
const { ymd, day, addDays, addMonths, periodLabel, shortDate } = require('./dates');
|
||||
const { PRODUCTS, PRODUCT_NAMES, BILLABLE } = require('../products');
|
||||
|
||||
const anchorDayOf = licence => day(licence.billingStart || licence.nextInvoiceDate).getUTCDate();
|
||||
const anchorDayOf = schedule => day(schedule.billingStart || schedule.nextInvoiceDate).getUTCDate();
|
||||
const monthsIn = cycle => (cycle === 'yearly' ? 12 : 1);
|
||||
const DAY = 864e5;
|
||||
const daysBetween = (a, b) => Math.round((day(b) - day(a)) / DAY) + 1;
|
||||
const later = (a, b) => (ymd(a) >= ymd(b) ? day(a) : day(b));
|
||||
|
||||
/** Who an invoice goes to: the customer's billing email, the site's admin contact, the customer's email. */
|
||||
function recipientFor(customer, install) {
|
||||
@@ -22,6 +37,12 @@ function recipientFor(customer, install) {
|
||||
return customer?.billingEmail || contact || customer?.email || null;
|
||||
}
|
||||
|
||||
/** The install whose admin contact invoices fall back on: Events first, then any in use. */
|
||||
function contactInstall(licences) {
|
||||
const installs = licences.map(l => l.install).filter(i => i && !i.releasedAt);
|
||||
return installs.find(i => i.product === 'events' && i.adminContact?.email) || installs.find(i => i.adminContact?.email) || installs[0] || null;
|
||||
}
|
||||
|
||||
/** Cleans invoice lines from the form: [{ description, quantity, unitCents, amountCents }]. */
|
||||
function cleanLines(lines) {
|
||||
if (!Array.isArray(lines)) throw Object.assign(new Error('Lines must be a list.'), { status: 400 });
|
||||
@@ -48,8 +69,8 @@ function totals(lines, settings = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The lines for a plan over a period: the tier's price (×10 for a year) and, for a founding
|
||||
* church, the founding discount as its own line. Returns { lines, warning? }.
|
||||
* Before Hub 2.0: the lines for one Cross Events licence's plan over a period. Kept to recalculate
|
||||
* drafts made by Hub 1.7 (licenceId set). Returns { lines, warning? }.
|
||||
*/
|
||||
function planLines({ plan, customMonthlyCents, cycle, periodStart, periodEnd, founding }) {
|
||||
const price = planPrice(plan, customMonthlyCents);
|
||||
@@ -70,73 +91,198 @@ function planLines({ plan, customMonthlyCents, cycle, periodStart, periodEnd, fo
|
||||
return { lines };
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft invoice for a licence's next period (licence.nextInvoiceDate), and how the licence
|
||||
* moves on. `install` gives the income band (stats.income.eventIncome12m) and admin contact.
|
||||
* Returns { invoice, licenceUpdate }.
|
||||
*/
|
||||
function draftInvoice({ licence, customer, install, settings = {} }) {
|
||||
const cycle = licence.billingCycle;
|
||||
if (cycle !== 'monthly' && cycle !== 'yearly') throw new Error('This licence isn\'t billed.');
|
||||
const anchor = anchorDayOf(licence);
|
||||
const periodStart = day(licence.nextInvoiceDate);
|
||||
const nextStart = addMonths(periodStart, monthsIn(cycle), anchor);
|
||||
const periodEnd = addDays(nextStart, -1);
|
||||
const warnings = [];
|
||||
/** "Cross Events, Grow tier" · "Church Website" · "Church App, Small Group tier". */
|
||||
function productLabel(product, plan) {
|
||||
const name = PRODUCT_NAMES[product];
|
||||
if (product === 'website' && tierNamed(plan, 'website')) return name;
|
||||
const tier = tierNamed(plan, product);
|
||||
return `${name}, ${tier ? `${tier.name} tier` : plan}`;
|
||||
}
|
||||
|
||||
// The yearly review: the first period starting on or after reviewDate.
|
||||
const reviewed = !!licence.reviewDate && ymd(periodStart) >= ymd(licence.reviewDate);
|
||||
const band = install?.stats?.income?.eventIncome12m || null;
|
||||
let plan = licence.plan;
|
||||
let planChange = null;
|
||||
if (reviewed) {
|
||||
const tier = tierForBand(band);
|
||||
if (!tier) {
|
||||
warnings.push(band
|
||||
? `The site reports its income as "${band}", which can't be placed in a tier (Cross Events before 2.0.2). The tier stays ${plan}.`
|
||||
: `The site hasn't reported its 12-month event income (it needs Cross Events 2.0.2 or later). The tier stays ${plan}.`);
|
||||
} else if (licence.customMonthlyCents != null) {
|
||||
if (tier.name !== plan) warnings.push(`Its income (${band}) is in the ${tier.name} tier, but the licence has a custom price, so it's kept. Change it by hand if needed.`);
|
||||
} else if (tier.name !== plan) {
|
||||
const from = planPrice(plan);
|
||||
const to = planPrice(tier.name);
|
||||
planChange = { from: plan, to: tier.name, fromMonthlyCents: from?.monthlyCents ?? null, toMonthlyCents: to?.monthlyCents ?? null, band };
|
||||
plan = tier.name;
|
||||
/** The tier review for one licence: { plan, planChange, warning }. */
|
||||
function reviewLicence(licence, product) {
|
||||
const { tier, band } = reviewTier(product, licence.install);
|
||||
const plan = licence.plan;
|
||||
if (tier === undefined) return { plan, planChange: null, warning: null, band };
|
||||
const what = product === 'events' ? '12-month event income' : 'active members (last 90 days)';
|
||||
if (!tier) {
|
||||
const needs = product === 'events' ? ' (it needs Cross Events 2.0.2 or later)' : '';
|
||||
return {
|
||||
plan, planChange: null, band,
|
||||
warning: band
|
||||
? `${PRODUCT_NAMES[product]} reports its ${what} as "${band}", which can't be placed in a tier. The tier stays ${plan}.`
|
||||
: `${PRODUCT_NAMES[product]} hasn't reported its ${what}${needs}. The tier stays ${plan}.`,
|
||||
};
|
||||
}
|
||||
if (licence.customMonthlyCents != null) {
|
||||
return { plan, planChange: null, band, warning: tier.name !== plan ? `${PRODUCT_NAMES[product]}: its ${what} (${band}) is in the ${tier.name} tier, but the licence has a custom price, so it's kept. Change it by hand if needed.` : null };
|
||||
}
|
||||
if (tier.name === plan) return { plan, planChange: null, warning: null, band };
|
||||
const from = planPrice(plan, null, product);
|
||||
const to = planPrice(tier.name, null, product);
|
||||
return {
|
||||
plan: tier.name, band, warning: null,
|
||||
planChange: { licenceId: licence.id, product, from: plan, to: tier.name, fromMonthlyCents: from?.monthlyCents ?? null, toMonthlyCents: to?.monthlyCents ?? null, band },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A customer's invoice lines for a period: each billed product (with a prorated line for days
|
||||
* owed before the period), its founding discount, the bundle discount, then add-ons. Pure.
|
||||
*
|
||||
* `licences` are the customer's licences with their install (`billedUntil` as it was before this
|
||||
* period was invoiced). Returns { lines, plan, planChanges, warnings, licenceUpdates, products,
|
||||
* eventsBand }.
|
||||
*/
|
||||
function customerInvoiceLines({ customer, licences, period, reviewed }) {
|
||||
const { start, end, cycle } = period;
|
||||
const months = cycle === 'yearly' ? YEARLY_MONTHS : 1;
|
||||
// By the day: a year's price over 365 days (10 months' for yearly billing).
|
||||
const perDay = cents => (cents * (cycle === 'yearly' ? YEARLY_MONTHS : 12)) / 365;
|
||||
const founding = !!customer.founding;
|
||||
|
||||
const productLines = [];
|
||||
const addOns = [];
|
||||
const warnings = [];
|
||||
const planChanges = [];
|
||||
const licenceUpdates = [];
|
||||
const products = [];
|
||||
const plans = [];
|
||||
let eventsBand = null;
|
||||
|
||||
const billed = licences
|
||||
.filter(l => l.status === 'active' && BILLABLE.includes(l.product) && l.billedFrom && ymd(l.billedFrom) <= ymd(end))
|
||||
.sort((a, b) => PRODUCTS.indexOf(a.product) - PRODUCTS.indexOf(b.product));
|
||||
|
||||
for (const licence of billed) {
|
||||
const product = licence.product;
|
||||
let plan = licence.plan;
|
||||
if (reviewed) {
|
||||
const r = reviewLicence(licence, product);
|
||||
plan = r.plan;
|
||||
if (r.warning) warnings.push(r.warning);
|
||||
if (r.planChange) planChanges.push(r.planChange);
|
||||
if (product === 'events') eventsBand = r.band;
|
||||
}
|
||||
const price = planPrice(plan, licence.customMonthlyCents, product);
|
||||
if (!price) {
|
||||
warnings.push(`${PRODUCT_NAMES[product]}: there's no price for the "${plan}" plan. Set a custom monthly price on the licence, or add the lines yourself.`);
|
||||
continue;
|
||||
}
|
||||
const label = productLabel(product, plan);
|
||||
const off = founding && price.foundingCents < price.monthlyCents ? price.foundingCents - price.monthlyCents : 0;
|
||||
const add = (description, quantity, unitCents) => {
|
||||
productLines.push({ description, quantity, unitCents, amountCents: Math.round(quantity * unitCents) });
|
||||
if (off) {
|
||||
const unitOff = unitCents === price.monthlyCents ? off : Math.round((unitCents * off) / price.monthlyCents);
|
||||
productLines.push({ description: `Founding church discount (${FOUNDING_PERCENT}%)`, quantity, unitCents: unitOff, amountCents: Math.round(quantity * unitOff) });
|
||||
}
|
||||
};
|
||||
|
||||
// Days owed from before this period: it started after the last invoice was made.
|
||||
const owedFrom = licence.billedUntil ? later(licence.billedFrom, addDays(licence.billedUntil, 1)) : day(licence.billedFrom);
|
||||
if (ymd(owedFrom) < ymd(start)) {
|
||||
const to = addDays(start, -1);
|
||||
const days = daysBetween(owedFrom, to);
|
||||
add(`${label}, ${shortDate(owedFrom)} – ${shortDate(to)} (${days} day${days === 1 ? '' : 's'} before this period)`, 1, Math.round(perDay(price.monthlyCents) * days));
|
||||
}
|
||||
// This period: all of it, or from the day it starts.
|
||||
if (ymd(licence.billedFrom) <= ymd(start)) {
|
||||
const range = periodLabel(start, end);
|
||||
add(cycle === 'yearly' ? `${label}, 12 months (${range}), paid yearly: 2 months free` : `${label}, ${range}`, months, price.monthlyCents);
|
||||
} else {
|
||||
const days = daysBetween(licence.billedFrom, end);
|
||||
add(`${label}, ${shortDate(licence.billedFrom)} – ${shortDate(end)} (${days} day${days === 1 ? '' : 's'}, from its start)`, 1, Math.round(perDay(price.monthlyCents) * days));
|
||||
}
|
||||
|
||||
// Add-ons for the whole period only (measured now), never discounted.
|
||||
if (product === 'website' && ymd(licence.billedFrom) <= ymd(start)) {
|
||||
const blocks = extraStorageBlocks(licence.install?.stats?.storage);
|
||||
if (blocks) {
|
||||
const m = monthsIn(cycle);
|
||||
addOns.push({
|
||||
description: `Extra website storage: ${blocks} × 5 GB, ${m === 12 ? '12 months' : periodLabel(start, end)}`,
|
||||
quantity: blocks * m, unitCents: STORAGE.monthly * 100, amountCents: blocks * m * STORAGE.monthly * 100,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
products.push(product);
|
||||
plans.push({ product, plan });
|
||||
licenceUpdates.push({ id: licence.id, data: { billedUntil: day(end) } });
|
||||
}
|
||||
|
||||
const { lines, warning } = planLines({ plan, customMonthlyCents: licence.customMonthlyCents, cycle, periodStart, periodEnd, founding: !!customer.founding });
|
||||
if (warning) warnings.push(warning);
|
||||
const recipientEmail = recipientFor(customer, install);
|
||||
const lines = [...productLines];
|
||||
const pct = BUNDLE_PERCENT[Math.min(products.length, 3)];
|
||||
if (pct) {
|
||||
const base = productLines.reduce((s, l) => s + l.amountCents, 0);
|
||||
const cut = -Math.round((base * pct) / 100);
|
||||
lines.push({ description: `Bundle discount (${pct}%: ${products.map(p => PRODUCT_NAMES[p]).join(', ').replace(/, ([^,]*)$/, ' and $1')})`, quantity: 1, unitCents: cut, amountCents: cut });
|
||||
}
|
||||
lines.push(...addOns);
|
||||
|
||||
const plan = plans.length === 1 && plans[0].product === 'events'
|
||||
? plans[0].plan
|
||||
: plans.map(p => (p.product === 'website' ? PRODUCT_NAMES.website : `${PRODUCT_NAMES[p.product]} ${p.plan}`)).join(' · ') || null;
|
||||
return { lines, plan, planChanges, warnings, licenceUpdates, products, eventsBand };
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft invoice for a customer's next period (customer.nextInvoiceDate), and how the
|
||||
* customer and its licences move on. Returns { invoice, customerUpdate, licenceUpdates, empty }:
|
||||
* `empty` when no product was billed and there's nothing to warn about (no invoice is made).
|
||||
*/
|
||||
function draftCustomerInvoice({ customer, licences, settings = {} }) {
|
||||
const cycle = customer.billingCycle;
|
||||
if (cycle !== 'monthly' && cycle !== 'yearly') throw new Error('This customer isn\'t billed.');
|
||||
const anchor = anchorDayOf(customer);
|
||||
const periodStart = day(customer.nextInvoiceDate);
|
||||
const nextStart = addMonths(periodStart, monthsIn(cycle), anchor);
|
||||
const periodEnd = addDays(nextStart, -1);
|
||||
const reviewed = !!customer.reviewDate && ymd(periodStart) >= ymd(customer.reviewDate);
|
||||
|
||||
const r = customerInvoiceLines({ customer, licences, period: { start: periodStart, end: periodEnd, cycle }, reviewed });
|
||||
const warnings = [...r.warnings];
|
||||
const recipientEmail = recipientFor(customer, contactInstall(licences));
|
||||
if (!recipientEmail) warnings.push('No email address to send it to: add a billing email on the customer.');
|
||||
const terms = parseInt(settings.payment_terms_days, 10);
|
||||
|
||||
let reviewDate = licence.reviewDate ? day(licence.reviewDate) : null;
|
||||
let reviewDate = customer.reviewDate ? day(customer.reviewDate) : null;
|
||||
if (reviewed) while (ymd(reviewDate) <= ymd(periodStart)) reviewDate = addMonths(reviewDate, 12);
|
||||
|
||||
return {
|
||||
empty: r.products.length === 0 && r.warnings.length === 0,
|
||||
invoice: {
|
||||
customerId: customer.id,
|
||||
licenceId: licence.id,
|
||||
licenceId: null,
|
||||
issueDate: periodStart,
|
||||
dueDate: addDays(periodStart, Number.isFinite(terms) && terms >= 0 ? terms : 7),
|
||||
periodStart,
|
||||
periodEnd,
|
||||
cycle,
|
||||
plan,
|
||||
incomeBand: reviewed ? band : null,
|
||||
plan: r.plan,
|
||||
incomeBand: reviewed ? r.eventsBand : null,
|
||||
reviewed,
|
||||
founding: !!customer.founding,
|
||||
planChange,
|
||||
lines,
|
||||
...totals(lines, settings),
|
||||
planChange: r.planChanges.length ? r.planChanges : null,
|
||||
lines: r.lines,
|
||||
...totals(r.lines, settings),
|
||||
warnings,
|
||||
recipientEmail,
|
||||
basis: { licences: licences.map(l => ({ id: l.id, billedUntil: ymd(l.billedUntil) })), planChangeDropped: false },
|
||||
},
|
||||
licenceUpdate: { nextInvoiceDate: nextStart, reviewDate },
|
||||
customerUpdate: { nextInvoiceDate: nextStart, reviewDate },
|
||||
licenceUpdates: r.licenceUpdates,
|
||||
};
|
||||
}
|
||||
|
||||
/** An invoice's tier changes as a list (Hub 1.7 stored one object). */
|
||||
function planChangesOf(invoice) {
|
||||
const pc = invoice?.planChange;
|
||||
if (!pc) return [];
|
||||
return Array.isArray(pc) ? pc : [{ licenceId: invoice.licenceId || null, product: 'events', ...pc }];
|
||||
}
|
||||
|
||||
/** What's been paid on an invoice and where it stands. `todayYmd` decides "overdue". */
|
||||
function invoiceState(invoice, todayYmd) {
|
||||
const paidCents = (invoice.payments || []).reduce((s, p) => s + p.amountCents, 0);
|
||||
@@ -151,7 +297,7 @@ function invoiceState(invoice, todayYmd) {
|
||||
}
|
||||
|
||||
function invoiceDescription(invoice) {
|
||||
if (invoice.periodStart && invoice.periodEnd) return `Cross Events licence, ${periodLabel(invoice.periodStart, invoice.periodEnd)}`;
|
||||
if (invoice.periodStart && invoice.periodEnd) return `${invoice.licenceId ? 'Cross Events licence' : 'Licences'}, ${periodLabel(invoice.periodStart, invoice.periodEnd)}`;
|
||||
return (invoice.lines?.[0]?.description || 'Invoice').slice(0, 80);
|
||||
}
|
||||
|
||||
@@ -187,4 +333,7 @@ function statement({ invoices, payments, from, to }) {
|
||||
return { from: f, to: t, openingCents: opening, entries, closingCents: balance, outstanding };
|
||||
}
|
||||
|
||||
module.exports = { recipientFor, cleanLines, totals, planLines, draftInvoice, invoiceState, statement, invoiceDescription, anchorDayOf };
|
||||
module.exports = {
|
||||
recipientFor, contactInstall, cleanLines, totals, planLines, productLabel, customerInvoiceLines, draftCustomerInvoice,
|
||||
planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn,
|
||||
};
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
* PDFs in pdf.js, emails in email.js.
|
||||
*
|
||||
* The job (runBilling, every 15 minutes):
|
||||
* 1. Drafts: for each billed, active licence whose next period starts within billing_draft_days,
|
||||
* make the draft invoice and email it to alert_email for approval (the licence moves on to
|
||||
* the next period at once, so a period is drafted once).
|
||||
* 1. Drafts: for each billed customer whose next period starts within billing_draft_days, make
|
||||
* the draft invoice for all its products (Hub 2.0) and email it to alert_email for approval
|
||||
* (the customer moves on to the next period at once, so a period is drafted once).
|
||||
* 2. Sends approved invoices on their date, from billing_send_hour (South African time).
|
||||
* 3. Emails Joshua once when an invoice's date has come and it still isn't approved.
|
||||
* 4. Applies tier changes on their effective date (the licence's plan).
|
||||
@@ -21,9 +21,11 @@ const pdf = require('./pdf');
|
||||
const { layout, sendBillingEmail } = require('./email');
|
||||
const { ymd, day, today, saHour, addDays, longDate, periodLabel, money } = require('./dates');
|
||||
const { planPrice, tierNamed } = require('./tiers');
|
||||
const { BILLABLE } = require('../products');
|
||||
const { PRODUCT_NAMES } = require('../products');
|
||||
|
||||
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
/** The install whose admin contact a customer's documents fall back on (Events first). */
|
||||
const contactOf = customer => compute.contactInstall((customer.installs || []).map(install => ({ install })));
|
||||
const hubLink = p => `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}${p}`;
|
||||
const EDITABLE = ['draft', 'approved'];
|
||||
|
||||
@@ -50,17 +52,33 @@ async function invoicePdfFor(invoice, settings) {
|
||||
|
||||
// ─── Drafting ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Makes the draft for one licence's next period. Returns the invoice, or null if it already exists. */
|
||||
async function draftForLicence(licenceId, settings) {
|
||||
/** The products on a customer invoice, by name ("Cross Events and Church Website"). */
|
||||
function productsText(invoice) {
|
||||
const products = invoice.basis?.products || (invoice.licenceId ? ['events'] : []);
|
||||
const names = products.map(p => PRODUCT_NAMES[p]);
|
||||
return names.length ? names.join(', ').replace(/, ([^,]*)$/, ' and $1') : 'Cross Code';
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the draft for one customer's next period (Hub 2.0: all its products on one invoice).
|
||||
* Returns the invoice, `{ empty: true }` when nothing was billed (the customer still moves on), or
|
||||
* null if the period was invoiced already.
|
||||
*/
|
||||
async function draftForCustomer(customerId, settings) {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const licence = await tx.licence.findUnique({ where: { id: licenceId }, include: { customer: true, install: true } });
|
||||
if (!licence || !licence.nextInvoiceDate) return null;
|
||||
const { invoice, licenceUpdate } = compute.draftInvoice({ licence, customer: licence.customer, install: licence.install, settings });
|
||||
await tx.licence.update({ where: { id: licence.id }, data: licenceUpdate });
|
||||
const exists = await tx.invoice.findFirst({ where: { licenceId: licence.id, periodStart: invoice.periodStart } });
|
||||
// Lock the customer row: two runs never draft the same period.
|
||||
await tx.$executeRaw`SELECT 1 FROM "Customer" WHERE id = ${customerId} FOR UPDATE`;
|
||||
const customer = await tx.customer.findUnique({ where: { id: customerId }, include: { licences: { include: { install: true } } } });
|
||||
if (!customer || customer.billingCycle === 'none' || !customer.nextInvoiceDate) return null;
|
||||
const { invoice, customerUpdate, licenceUpdates, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings });
|
||||
await tx.customer.update({ where: { id: customer.id }, data: customerUpdate });
|
||||
if (empty) return { empty: true };
|
||||
const exists = await tx.invoice.findFirst({ where: { customerId: customer.id, licenceId: null, periodStart: invoice.periodStart, status: { not: 'void' } } });
|
||||
if (exists) return null;
|
||||
for (const u of licenceUpdates) await tx.licence.update({ where: { id: u.id }, data: u.data });
|
||||
const products = [...new Set(licenceUpdates.map(u => customer.licences.find(l => l.id === u.id)?.product).filter(Boolean))];
|
||||
const number = await nextNumber(settings.invoice_prefix || 'INV', invoice.issueDate, tx);
|
||||
return tx.invoice.create({ data: { ...invoice, number, planChange: invoice.planChange ?? undefined }, include: invoiceInclude });
|
||||
return tx.invoice.create({ data: { ...invoice, basis: { ...invoice.basis, products }, number, planChange: invoice.planChange ?? undefined }, include: invoiceInclude });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -75,9 +93,9 @@ async function emailApproval(invoice, settings) {
|
||||
],
|
||||
rows: [
|
||||
['Church', invoice.customer.name],
|
||||
['Tier', `${invoice.plan || '—'}${invoice.founding ? ' (founding)' : ''}`],
|
||||
['Products', `${invoice.plan || '—'}${invoice.founding ? ' (founding)' : ''}`],
|
||||
...(invoice.reviewed ? [['12-month event income', invoice.incomeBand || 'not reported']] : []),
|
||||
...(invoice.planChange ? [['Tier change', `${invoice.planChange.from} → ${invoice.planChange.to}`, true]] : []),
|
||||
...compute.planChangesOf(invoice).map(pc => [`Tier change (${PRODUCT_NAMES[pc.product] || 'Cross Events'})`, `${pc.from} → ${pc.to}`, true]),
|
||||
['Total', money(invoice.totalCents), true],
|
||||
['Goes out', longDate(invoice.issueDate)],
|
||||
],
|
||||
@@ -97,20 +115,22 @@ async function emailApproval(invoice, settings) {
|
||||
async function createDueDrafts(now, settings) {
|
||||
const days = parseInt(settings.billing_draft_days, 10) || 14;
|
||||
const horizon = addDays(today(now), days);
|
||||
const licences = await prisma.licence.findMany({
|
||||
where: { status: 'active', product: { in: BILLABLE }, billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
|
||||
const customers = await prisma.customer.findMany({
|
||||
where: { billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
|
||||
select: { id: true },
|
||||
});
|
||||
let made = 0;
|
||||
for (const { id } of licences) {
|
||||
// Catch up a licence that's behind (at most a year's worth in one run).
|
||||
for (const { id } of customers) {
|
||||
// Catch up a customer that's behind (at most a year's worth in one run).
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const invoice = await draftForLicence(id, settings);
|
||||
const invoice = await draftForCustomer(id, settings);
|
||||
if (!invoice) break;
|
||||
made += 1;
|
||||
await emailApproval(invoice, settings).catch(e => console.warn('[billing] approval email failed:', e?.message || e));
|
||||
const lic = await prisma.licence.findUnique({ where: { id }, select: { nextInvoiceDate: true } });
|
||||
if (!lic?.nextInvoiceDate || ymd(lic.nextInvoiceDate) > ymd(horizon)) break;
|
||||
if (!invoice.empty) {
|
||||
made += 1;
|
||||
await emailApproval(invoice, settings).catch(e => console.warn('[billing] approval email failed:', e?.message || e));
|
||||
}
|
||||
const c = await prisma.customer.findUnique({ where: { id }, select: { nextInvoiceDate: true } });
|
||||
if (!c?.nextInvoiceDate || ymd(c.nextInvoiceDate) > ymd(horizon)) break;
|
||||
}
|
||||
}
|
||||
return made;
|
||||
@@ -118,6 +138,18 @@ async function createDueDrafts(now, settings) {
|
||||
|
||||
// ─── Sending ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The email note for an invoice's tier changes, or null. */
|
||||
function tierChangeNote(invoice) {
|
||||
const changes = compute.planChangesOf(invoice);
|
||||
if (!changes.length) return null;
|
||||
const why = pc => (pc.product === 'app' ? 'your active members over the last 90 days' : 'your event income over the last 12 months');
|
||||
const one = pc => `${PRODUCT_NAMES[pc.product] || 'Cross Events'} moves from the ${pc.from} tier to the ${pc.to} tier, based on ${why(pc)}.`;
|
||||
return {
|
||||
title: changes.length === 1 ? `Your ${PRODUCT_NAMES[changes[0].product] || 'Cross Events'} tier is now ${changes[0].to}` : 'Your tiers have changed',
|
||||
text: `At your annual review: ${changes.map(one).join(' ')}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
|
||||
const state = compute.invoiceState(invoice, ymd(today()));
|
||||
const tax = String(settings.vat_registered) === 'true';
|
||||
@@ -127,7 +159,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
|
||||
heading: `${title} ${invoice.number}${copy ? ' (copy)' : ''}`,
|
||||
greeting: `Hi ${invoice.customer.contactName || invoice.customer.name},`,
|
||||
paragraphs: [
|
||||
`Here is your ${title.toLowerCase()} for Cross Events${invoice.periodStart ? `, ${periodLabel(invoice.periodStart, invoice.periodEnd)}` : ''}. The PDF is attached.`,
|
||||
`Here is your ${title.toLowerCase()} for ${productsText(invoice)}${invoice.periodStart ? `, ${periodLabel(invoice.periodStart, invoice.periodEnd)}` : ''}. The PDF is attached.`,
|
||||
'Please pay by EFT using the invoice number as the reference. The banking details are on the invoice.',
|
||||
],
|
||||
rows: [
|
||||
@@ -137,7 +169,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
|
||||
[state.paidCents ? 'Balance due' : 'Amount due', money(state.balanceCents), true],
|
||||
['Due by', longDate(invoice.dueDate), true],
|
||||
],
|
||||
note: invoice.planChange ? { title: `Your tier is now ${invoice.planChange.to}`, text: `Your annual review moved your licence from the ${invoice.planChange.from} tier to the ${invoice.planChange.to} tier, based on your event income over the last 12 months.` } : null,
|
||||
note: tierChangeNote(invoice),
|
||||
});
|
||||
return sendBillingEmail(settings, {
|
||||
kind: 'invoice', customerId: invoice.customerId, refId: invoice.id, to: invoice.recipientEmail,
|
||||
@@ -202,9 +234,10 @@ async function remindUnapproved(now, settings) {
|
||||
async function applyDueLicenceChanges(now = new Date()) {
|
||||
const due = await prisma.licenceChange.findMany({
|
||||
where: { appliedAt: null, effectiveDate: { lte: today(now) }, licenceId: { not: null }, OR: [{ invoiceId: null }, { invoice: { is: { status: 'sent' } } }] },
|
||||
include: { licence: { select: { product: true } } },
|
||||
});
|
||||
for (const c of due) {
|
||||
const tier = tierNamed(c.toPlan);
|
||||
const tier = tierNamed(c.toPlan, c.licence?.product || 'events');
|
||||
const data = { plan: c.toPlan };
|
||||
// A custom price comes with a change to an unpriced plan; a priced tier uses its own price.
|
||||
if (tier?.monthly != null) data.customMonthlyCents = null;
|
||||
@@ -238,20 +271,20 @@ async function approveInvoice(id, actorId) {
|
||||
if (!invoice.recipientEmail) throw bad('Add an email address to send it to first.', 409);
|
||||
if (!invoice.lines?.length) throw bad('Add at least one line first.', 409);
|
||||
await prisma.invoice.update({ where: { id }, data: { status: 'approved', approvedAt: new Date(), approvedById: actorId || null } });
|
||||
let notice = null;
|
||||
if (invoice.planChange && invoice.licenceId) {
|
||||
const existing = await prisma.licenceChange.findFirst({ where: { invoiceId: id } });
|
||||
if (!existing) {
|
||||
const pc = invoice.planChange;
|
||||
notice = await createLicenceChange({
|
||||
customerId: invoice.customerId, licenceId: invoice.licenceId, invoiceId: id,
|
||||
fromPlan: pc.from, toPlan: pc.to, fromMonthlyCents: pc.fromMonthlyCents, toMonthlyCents: pc.toMonthlyCents,
|
||||
effectiveDate: invoice.periodStart || invoice.issueDate, incomeBand: pc.band || invoice.incomeBand,
|
||||
reason: 'Your annual tier review.',
|
||||
}, settings);
|
||||
}
|
||||
// One notice per tier change (Hub 2.0: per product), unless it was made already.
|
||||
const notices = [];
|
||||
for (const pc of compute.planChangesOf(invoice)) {
|
||||
if (!pc.licenceId) continue;
|
||||
const existing = await prisma.licenceChange.findFirst({ where: { invoiceId: id, licenceId: pc.licenceId } });
|
||||
if (existing) continue;
|
||||
notices.push(await createLicenceChange({
|
||||
customerId: invoice.customerId, licenceId: pc.licenceId, invoiceId: id,
|
||||
fromPlan: pc.from, toPlan: pc.to, fromMonthlyCents: pc.fromMonthlyCents, toMonthlyCents: pc.toMonthlyCents,
|
||||
effectiveDate: invoice.periodStart || invoice.issueDate, incomeBand: pc.band || (pc.product === 'events' ? invoice.incomeBand : null),
|
||||
reason: 'Your annual tier review.',
|
||||
}, settings));
|
||||
}
|
||||
return { invoice: await loadInvoice(id), notice };
|
||||
return { invoice: await loadInvoice(id), notice: notices[0] || null, notices };
|
||||
}
|
||||
|
||||
async function unapproveInvoice(id) {
|
||||
@@ -281,23 +314,33 @@ async function updateInvoice(id, body) {
|
||||
if (e && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) throw bad('That email address doesn\'t look right.');
|
||||
data.recipientEmail = e || null;
|
||||
}
|
||||
let reprice = false;
|
||||
if (body.dropPlanChange === true) {
|
||||
if (await prisma.licenceChange.findFirst({ where: { invoiceId: id, sentAt: { not: null } } })) throw bad('The church has already been sent the notice of this tier change.', 409);
|
||||
data.planChange = Prisma.DbNull;
|
||||
data.plan = invoice.licence?.plan || invoice.plan;
|
||||
if (invoice.licenceId) data.plan = invoice.licence?.plan || invoice.plan;
|
||||
else {
|
||||
// A customer invoice keeps the tiers it had: a draft is repriced at them below.
|
||||
data.basis = { ...(invoice.basis || {}), planChangeDropped: true };
|
||||
reprice = invoice.status === 'draft' && body.lines === undefined;
|
||||
}
|
||||
}
|
||||
// Editing an approved invoice keeps it approved; editing clears the "waiting" reminder.
|
||||
data.overdueEmailedAt = null;
|
||||
await prisma.invoice.update({ where: { id }, data });
|
||||
return loadInvoice(id);
|
||||
return reprice ? recalculateInvoice(id) : loadInvoice(id);
|
||||
}
|
||||
|
||||
/** Rebuilds a draft's lines from the licence as it is now (e.g. after changing founding or the price). */
|
||||
/**
|
||||
* Rebuilds a draft's lines from the customer and its licences as they are now (e.g. after changing
|
||||
* founding, a price or a product's start), for the same period.
|
||||
*/
|
||||
async function recalculateInvoice(id) {
|
||||
const settings = await getSettings();
|
||||
const invoice = await loadInvoice(id);
|
||||
if (invoice.status !== 'draft') throw bad('Only a draft can be recalculated.', 409);
|
||||
if (!invoice.licence || !invoice.periodStart) throw bad('Only an invoice for a licence\'s period can be recalculated.', 409);
|
||||
if (!invoice.licenceId && invoice.periodStart && invoice.cycle !== 'none') return recalculateCustomerInvoice(invoice, settings);
|
||||
if (!invoice.licence || !invoice.periodStart) throw bad('Only an invoice for a period can be recalculated.', 409);
|
||||
const plan = invoice.planChange?.to || invoice.plan || invoice.licence.plan;
|
||||
const { lines, warning } = compute.planLines({
|
||||
plan, customMonthlyCents: invoice.licence.customMonthlyCents, cycle: invoice.cycle,
|
||||
@@ -311,6 +354,32 @@ async function recalculateInvoice(id) {
|
||||
return loadInvoice(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hub 2.0 customer invoice: the lines worked out again for its period, from each licence's
|
||||
* billedUntil as it was before the draft (invoice.basis), so days owed are counted once.
|
||||
*/
|
||||
async function recalculateCustomerInvoice(invoice, settings) {
|
||||
const customer = await prisma.customer.findUnique({ where: { id: invoice.customerId }, include: { licences: { include: { install: true } } } });
|
||||
const before = new Map((invoice.basis?.licences || []).map(l => [l.id, l.billedUntil]));
|
||||
const licences = customer.licences.map(l => (before.has(l.id) ? { ...l, billedUntil: before.get(l.id) ? day(before.get(l.id)) : null } : l));
|
||||
const reviewed = invoice.reviewed && !invoice.basis?.planChangeDropped;
|
||||
const r = compute.customerInvoiceLines({ customer, licences, period: { start: invoice.periodStart, end: invoice.periodEnd, cycle: invoice.cycle }, reviewed });
|
||||
const recipientEmail = invoice.recipientEmail || compute.recipientFor(customer, compute.contactInstall(customer.licences));
|
||||
await prisma.$transaction([
|
||||
prisma.invoice.update({
|
||||
where: { id: invoice.id },
|
||||
data: {
|
||||
lines: r.lines, ...compute.totals(r.lines, settings), founding: !!customer.founding, plan: r.plan, recipientEmail, warnings: r.warnings,
|
||||
planChange: r.planChanges.length ? r.planChanges : Prisma.DbNull,
|
||||
basis: { ...(invoice.basis || {}), products: r.products },
|
||||
},
|
||||
}),
|
||||
// A product added or started since the draft was made is now covered up to the period's end.
|
||||
...r.licenceUpdates.map(u => prisma.licence.update({ where: { id: u.id }, data: u.data })),
|
||||
]);
|
||||
return loadInvoice(invoice.id);
|
||||
}
|
||||
|
||||
async function voidInvoice(id, reason) {
|
||||
const invoice = await loadInvoice(id);
|
||||
if (invoice.status === 'void') throw bad('It\'s already void.', 409);
|
||||
@@ -333,7 +402,7 @@ async function resendInvoice(id) {
|
||||
/** A one-off invoice (e.g. standby support), as a draft. */
|
||||
async function createManualInvoice(body) {
|
||||
const settings = await getSettings();
|
||||
const customer = await prisma.customer.findUnique({ where: { id: String(body.customerId || '') }, include: { installs: { where: { releasedAt: null }, take: 1 } } });
|
||||
const customer = await prisma.customer.findUnique({ where: { id: String(body.customerId || '') }, include: { installs: { where: { releasedAt: null } } } });
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
const lines = compute.cleanLines(body.lines || []);
|
||||
if (!lines.length) throw bad('Add at least one line.');
|
||||
@@ -345,7 +414,7 @@ async function createManualInvoice(body) {
|
||||
data: {
|
||||
number, customerId: customer.id, licenceId: body.licenceId || null, status: 'draft', issueDate, dueDate,
|
||||
cycle: 'none', lines, ...compute.totals(lines, settings), notes: body.notes || null, founding: customer.founding,
|
||||
recipientEmail: body.recipientEmail || compute.recipientFor(customer, customer.installs[0]),
|
||||
recipientEmail: body.recipientEmail || compute.recipientFor(customer, contactOf(customer)),
|
||||
},
|
||||
include: invoiceInclude,
|
||||
});
|
||||
@@ -354,9 +423,9 @@ async function createManualInvoice(body) {
|
||||
// ─── Payments and receipts ───────────────────────────────────────────────────
|
||||
|
||||
async function sendReceipt(paymentId, settings) {
|
||||
const payment = await prisma.payment.findUnique({ where: { id: paymentId }, include: { customer: { include: { installs: { where: { releasedAt: null }, take: 1 } } }, invoice: { include: { payments: true } } } });
|
||||
const payment = await prisma.payment.findUnique({ where: { id: paymentId }, include: { customer: { include: { installs: { where: { releasedAt: null } } } }, invoice: { include: { payments: true } } } });
|
||||
if (!payment) throw bad('Payment not found', 404);
|
||||
const to = payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, payment.customer.installs[0]);
|
||||
const to = payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, contactOf(payment.customer));
|
||||
const state = payment.invoice ? compute.invoiceState(payment.invoice, ymd(today())) : null;
|
||||
const content = layout(settings, {
|
||||
preheader: `We received ${money(payment.amountCents)}. Thank you!`,
|
||||
@@ -419,16 +488,16 @@ async function resendReceipt(id) {
|
||||
|
||||
async function receiptPdfFor(id) {
|
||||
const settings = await getSettings();
|
||||
const payment = await prisma.payment.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null }, take: 1 } } }, invoice: { include: { payments: true } } } });
|
||||
const payment = await prisma.payment.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null } } } }, invoice: { include: { payments: true } } } });
|
||||
if (!payment) throw bad('Payment not found', 404);
|
||||
const state = payment.invoice ? compute.invoiceState(payment.invoice, ymd(today())) : null;
|
||||
return { filename: `${payment.receiptNumber}.pdf`, content: await pdf.receiptPdf({ payment, customer: payment.customer, invoice: payment.invoice, state, settings, recipientEmail: payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, payment.customer.installs[0]) }) };
|
||||
return { filename: `${payment.receiptNumber}.pdf`, content: await pdf.receiptPdf({ payment, customer: payment.customer, invoice: payment.invoice, state, settings, recipientEmail: payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, contactOf(payment.customer)) }) };
|
||||
}
|
||||
|
||||
// ─── Statements ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function customerStatement(customerId, from, to) {
|
||||
const customer = await prisma.customer.findUnique({ where: { id: customerId }, include: { installs: { where: { releasedAt: null }, take: 1 } } });
|
||||
const customer = await prisma.customer.findUnique({ where: { id: customerId }, include: { installs: { where: { releasedAt: null } } } });
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
const t = to ? day(to) : today();
|
||||
const f = from ? day(from) : addDays(t, -365);
|
||||
@@ -437,7 +506,7 @@ async function customerStatement(customerId, from, to) {
|
||||
prisma.invoice.findMany({ where: { customerId, status: 'sent' }, include: { payments: true } }),
|
||||
prisma.payment.findMany({ where: { customerId }, include: { invoice: { select: { number: true } } } }),
|
||||
]);
|
||||
return { customer, recipientEmail: compute.recipientFor(customer, customer.installs[0]), statement: compute.statement({ invoices, payments, from: f, to: t }) };
|
||||
return { customer, recipientEmail: compute.recipientFor(customer, contactOf(customer)), statement: compute.statement({ invoices, payments, from: f, to: t }) };
|
||||
}
|
||||
|
||||
async function statementPdfFor(customerId, from, to) {
|
||||
@@ -452,7 +521,7 @@ async function emailStatement(customerId, { from, to, email } = {}) {
|
||||
const sendTo = email || recipientEmail;
|
||||
const content = layout(settings, {
|
||||
preheader: `Balance ${money(statement.closingCents)} on ${longDate(statement.to)}`,
|
||||
heading: 'Your Cross Events statement',
|
||||
heading: 'Your Cross Code statement',
|
||||
greeting: `Hi ${customer.contactName || customer.name},`,
|
||||
paragraphs: [`Here is your statement from ${longDate(statement.from)} to ${longDate(statement.to)}. The PDF is attached.`],
|
||||
rows: [
|
||||
@@ -474,30 +543,32 @@ async function emailStatement(customerId, { from, to, email } = {}) {
|
||||
// ─── Licence changes ─────────────────────────────────────────────────────────
|
||||
|
||||
async function sendLicenceChange(change, settings) {
|
||||
const customer = await prisma.customer.findUnique({ where: { id: change.customerId }, include: { installs: { where: { releasedAt: null }, take: 1 } } });
|
||||
const customer = await prisma.customer.findUnique({ where: { id: change.customerId }, include: { installs: { where: { releasedAt: null } } } });
|
||||
const licence = change.licenceId ? await prisma.licence.findUnique({ where: { id: change.licenceId } }) : null;
|
||||
const to = compute.recipientFor(customer, customer.installs[0]);
|
||||
const product = licence?.product || 'events';
|
||||
const name = PRODUCT_NAMES[product];
|
||||
const to = compute.recipientFor(customer, contactOf(customer));
|
||||
const up = change.fromMonthlyCents != null && change.toMonthlyCents != null ? change.toMonthlyCents > change.fromMonthlyCents : null;
|
||||
const content = layout(settings, {
|
||||
preheader: `From ${longDate(change.effectiveDate)}: the ${change.toPlan} tier`,
|
||||
heading: up === false ? `Good news: your tier moves down to ${change.toPlan}` : `Your Cross Events tier changes to ${change.toPlan}`,
|
||||
heading: up === false ? `Good news: your ${name} tier moves down to ${change.toPlan}` : `Your ${name} tier changes to ${change.toPlan}`,
|
||||
greeting: `Hi ${customer.contactName || customer.name},`,
|
||||
paragraphs: [
|
||||
`From ${longDate(change.effectiveDate)}, your Cross Events licence moves from the ${change.fromPlan} tier to the ${change.toPlan} tier. The notice is attached.`,
|
||||
`From ${longDate(change.effectiveDate)}, your ${name} licence moves from the ${change.fromPlan} tier to the ${change.toPlan} tier. The notice is attached.`,
|
||||
...(change.reason ? [change.reason] : []),
|
||||
'Every feature stays included, whatever your tier. If you have any questions, just reply to this email.',
|
||||
],
|
||||
rows: [
|
||||
['Now', `${change.fromPlan}${change.fromMonthlyCents != null ? `, ${money(change.fromMonthlyCents)} a month` : ''}`],
|
||||
[`From ${longDate(change.effectiveDate)}`, `${change.toPlan}${change.toMonthlyCents != null ? `, ${money(change.toMonthlyCents)} a month` : ''}`, true],
|
||||
...(change.incomeBand ? [['12-month event income', change.incomeBand]] : []),
|
||||
...(change.incomeBand ? [[product === 'app' ? 'Active members (90 days)' : '12-month event income', change.incomeBand]] : []),
|
||||
],
|
||||
note: customer.founding ? { title: 'Founding church', text: 'Your 35% founding discount carries on in your new tier.' } : null,
|
||||
});
|
||||
const res = await sendBillingEmail(settings, {
|
||||
kind: 'licence_change', customerId: customer.id, refId: change.id, to,
|
||||
subject: `Notice of licence change: ${change.fromPlan} to ${change.toPlan} from ${longDate(change.effectiveDate)}`,
|
||||
content, pdfs: [{ filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer, settings, founding: customer.founding, recipientEmail: to, cycle: licence?.billingCycle }) }],
|
||||
content, pdfs: [{ filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer, settings, founding: customer.founding, recipientEmail: to, cycle: customer.billingCycle, product }) }],
|
||||
});
|
||||
if (res.ok) await prisma.licenceChange.update({ where: { id: change.id }, data: { sentAt: new Date() } });
|
||||
return res;
|
||||
@@ -509,14 +580,14 @@ async function sendLicenceChange(change, settings) {
|
||||
*/
|
||||
async function createLicenceChange(body, settings = null, { send = true } = {}) {
|
||||
settings = settings || await getSettings();
|
||||
const licence = await prisma.licence.findUnique({ where: { id: String(body.licenceId || '') } });
|
||||
const licence = await prisma.licence.findUnique({ where: { id: String(body.licenceId || '') }, include: { customer: true } });
|
||||
if (!licence) throw bad('Licence not found', 404);
|
||||
const toPlan = String(body.toPlan || '').trim();
|
||||
if (!toPlan) throw bad('Choose the new tier.');
|
||||
const fromPlan = body.fromPlan || licence.plan;
|
||||
if (toPlan === fromPlan && body.toMonthlyCents == null) throw bad('That\'s the tier it\'s on already.');
|
||||
const priceOf = (plan, custom) => (custom != null ? Math.round(Number(custom)) : planPrice(plan)?.monthlyCents ?? null);
|
||||
const effectiveDate = body.effectiveDate ? day(body.effectiveDate) : licence.nextInvoiceDate ? day(licence.nextInvoiceDate) : today();
|
||||
const priceOf = (plan, custom) => (custom != null ? Math.round(Number(custom)) : planPrice(plan, null, licence.product)?.monthlyCents ?? null);
|
||||
const effectiveDate = body.effectiveDate ? day(body.effectiveDate) : licence.customer.nextInvoiceDate ? day(licence.customer.nextInvoiceDate) : today();
|
||||
const number = await nextNumber(settings.change_prefix || 'LC', new Date());
|
||||
const change = await prisma.licenceChange.create({
|
||||
data: {
|
||||
@@ -543,13 +614,14 @@ async function resendLicenceChange(id) {
|
||||
|
||||
async function licenceChangePdfFor(id) {
|
||||
const settings = await getSettings();
|
||||
const change = await prisma.licenceChange.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null }, take: 1 } } }, licence: true } });
|
||||
const change = await prisma.licenceChange.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null } } } }, licence: true } });
|
||||
if (change) change.product = change.licence?.product || 'events';
|
||||
if (!change) throw bad('Notice not found', 404);
|
||||
return { filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer: change.customer, settings, founding: change.customer.founding, recipientEmail: compute.recipientFor(change.customer, change.customer.installs[0]), cycle: change.licence?.billingCycle }) };
|
||||
return { filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer: change.customer, settings, founding: change.customer.founding, recipientEmail: compute.recipientFor(change.customer, contactOf(change.customer)), cycle: change.customer.billingCycle, product: change.product }) };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
nextNumber, loadInvoice, invoicePdfFor, draftForLicence, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
|
||||
nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
|
||||
applyDueLicenceChanges, runBilling, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice,
|
||||
resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement,
|
||||
statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval,
|
||||
|
||||
@@ -9,6 +9,14 @@ const path = require('path');
|
||||
const PDFDocument = require('pdfkit');
|
||||
const { longDate, shortDate, money, periodLabel } = require('./dates');
|
||||
const { planPrice, FOUNDING_PERCENT } = require('./tiers');
|
||||
const { PRODUCT_NAMES } = require('../products');
|
||||
|
||||
/** An invoice's tier changes as a list (Hub 1.7 stored one object). Same as compute.planChangesOf. */
|
||||
const planChangesOf = invoice => {
|
||||
const pc = invoice?.planChange;
|
||||
if (!pc) return [];
|
||||
return Array.isArray(pc) ? pc : [{ product: 'events', ...pc }];
|
||||
};
|
||||
|
||||
const LOGO = path.join(__dirname, '..', '..', '..', 'assets', 'logo.png');
|
||||
const C = { navy: '#11111f', sky: '#62b5e5', skyDark: '#1d6a9c', skyPale: '#e8f4fb', text: '#2b3044', muted: '#6b7184', line: '#e1e5ee', surface: '#f5f7fb', green: '#12734a', red: '#b42318' };
|
||||
@@ -199,11 +207,14 @@ function invoicePdf({ invoice, customer, settings: s, state }) {
|
||||
...(paid ? [['Total', money(invoice.totalCents)], ['Paid', money(-paid), { color: C.green }]] : []),
|
||||
[paid ? 'Balance due' : 'Total due', money(paid ? state.balanceCents : invoice.totalCents), { big: true }],
|
||||
]);
|
||||
if (invoice.planChange) {
|
||||
const pc = invoice.planChange;
|
||||
y = box(doc, y, `Your tier changes to ${pc.to}`, [
|
||||
`From this period your licence moves from the ${pc.from} tier to the ${pc.to} tier${pc.band ? `, based on your event income over the last 12 months (${pc.band})` : ''}.`,
|
||||
'Tiers are reviewed once a year. Donations and sponsored places are never counted.',
|
||||
const changes = planChangesOf(invoice);
|
||||
if (changes.length) {
|
||||
const basis = pc => (pc.product === 'app'
|
||||
? `, based on your active members over the last 90 days (${pc.band})`
|
||||
: `, based on your event income over the last 12 months (${pc.band})`);
|
||||
y = box(doc, y, changes.length === 1 ? `Your ${PRODUCT_NAMES[changes[0].product] || 'Cross Events'} tier changes to ${changes[0].to}` : 'Your tiers change', [
|
||||
...changes.map(pc => `From this period ${PRODUCT_NAMES[pc.product] || 'Cross Events'} moves from the ${pc.from} tier to the ${pc.to} tier${pc.band ? basis(pc) : ''}.`),
|
||||
`Tiers are reviewed once a year.${changes.some(pc => pc.product !== 'app') ? ' Donations and sponsored places are never counted.' : ''}`,
|
||||
], { tone: 'sky' });
|
||||
}
|
||||
if (invoice.status !== 'void') y = box(doc, y, 'How to pay', paymentLines(s, invoice.number));
|
||||
@@ -270,13 +281,14 @@ function statementPdf({ statement: st, customer, settings: s, recipientEmail })
|
||||
}
|
||||
|
||||
/** A notice of licence change (tier up or down). */
|
||||
function licenceChangePdf({ change, customer, settings: s, founding, recipientEmail, cycle }) {
|
||||
function licenceChangePdf({ change, customer, settings: s, founding, recipientEmail, cycle, product = 'events' }) {
|
||||
const name = PRODUCT_NAMES[product] || 'Cross Events';
|
||||
const up = change.fromMonthlyCents != null && change.toMonthlyCents != null ? change.toMonthlyCents > change.fromMonthlyCents : null;
|
||||
// The monthly price, and for a founding church its founding price (the tier's, or 35% off).
|
||||
const priceText = (plan, cents) => {
|
||||
if (cents == null) return 'priced for your church';
|
||||
if (!founding) return `${money(cents)} a month`;
|
||||
const p = planPrice(plan);
|
||||
const p = planPrice(plan, null, product);
|
||||
const f = p && p.monthlyCents === cents ? p.foundingCents : Math.round((cents * (100 - FOUNDING_PERCENT)) / 100);
|
||||
return `${money(f)} a month (founding price; normally ${money(cents)})`;
|
||||
};
|
||||
@@ -288,7 +300,7 @@ function licenceChangePdf({ change, customer, settings: s, founding, recipientEm
|
||||
]);
|
||||
y = party(doc, y, 'Notice to', customer, recipientEmail);
|
||||
doc.font('Helvetica-Bold').fontSize(14).fillColor(C.navy).text(
|
||||
up == null ? `Your Cross Events tier changes to ${change.toPlan}` : up ? `Your Cross Events tier moves up to ${change.toPlan}` : `Good news: your Cross Events tier moves down to ${change.toPlan}`, M, y, { width: W });
|
||||
up == null ? `Your ${name} tier changes to ${change.toPlan}` : up ? `Your ${name} tier moves up to ${change.toPlan}` : `Good news: your ${name} tier moves down to ${change.toPlan}`, M, y, { width: W });
|
||||
y = doc.y + 10;
|
||||
y = table(doc, y, [
|
||||
{ label: '', width: 150 },
|
||||
@@ -300,7 +312,8 @@ function licenceChangePdf({ change, customer, settings: s, founding, recipientEm
|
||||
]);
|
||||
const why = [];
|
||||
if (change.reason) why.push(change.reason);
|
||||
if (change.incomeBand) why.push(`Your event income over the last 12 months was in the range ${change.incomeBand}. Tiers are based on ticket sales and other payments through Cross Events, less refunds; donations and sponsored places are never counted.`);
|
||||
if (change.incomeBand && product === 'app') why.push(`Your church had ${change.incomeBand} active members over the last 90 days (people who used the app; visitors who don't sign in never count).`);
|
||||
else if (change.incomeBand) why.push(`Your event income over the last 12 months was in the range ${change.incomeBand}. Tiers are based on ticket sales and other payments through Cross Events, less refunds; donations and sponsored places are never counted.`);
|
||||
why.push('We review tiers once a year when your licence renews, never in the middle of the year.');
|
||||
if (founding) why.push('As a founding church, your 35% founding discount carries on in your new tier.');
|
||||
if (cycle === 'yearly') why.push('You pay yearly, so you still get two months free on the new price.');
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
/**
|
||||
* Cross Events licence tiers, billed on a site's event income over the last 12 months
|
||||
* (`income.eventIncome12m`, Cross Events 2.0.2+). The same tiers are in
|
||||
* frontend/src/lib/tiers.ts (a test checks they match) and the public prices in crosscode-site
|
||||
* src/data/pricing.mjs. Prices are rand per month.
|
||||
* Prices per product (Hub 2.0, ROADMAP-v3 §10), rand per month. The same prices are in
|
||||
* frontend/src/lib/tiers.ts (a test checks they match) and the public ones in crosscode-site
|
||||
* src/data/pricing.mjs.
|
||||
*
|
||||
* - Cross Events: tiers on a site's event income over the last 12 months (`income.eventIncome12m`,
|
||||
* Cross Events 2.0.2+).
|
||||
* - Church Website: one price, 5 GB of uploads included; extra storage is an add-on.
|
||||
* - Church App: tiers on active members in the last 90 days (`activeMembers90d`, a band).
|
||||
* - Accounts: free, never invoiced.
|
||||
*
|
||||
* The same rules for every product: yearly billing is 10 months' price, founding churches pay the
|
||||
* founding price, bundles take 15% off two products and 25% off three, and add-ons are never
|
||||
* discounted (compute.js).
|
||||
*/
|
||||
|
||||
const TIERS = [
|
||||
@@ -16,12 +25,34 @@ const TIERS = [
|
||||
{ name: 'Network', upTo: null, monthly: null, founding: null }, // priced per church, from R7 500
|
||||
];
|
||||
|
||||
/** Yearly billing: this many months' price for 12 months (two months free). */
|
||||
/** Church Website: one plan. */
|
||||
const WEBSITE_PLANS = [{ name: 'Website', monthly: 99, founding: 64 }];
|
||||
|
||||
/** Church App tiers, one per active-member band (contracts ACTIVE_MEMBER_BANDS, in order). */
|
||||
const APP_TIERS = [
|
||||
{ name: 'Mustard Seed', band: '0–100', monthly: 99, founding: 64 },
|
||||
{ name: 'Small Group', band: '101–300', monthly: 249, founding: 162 },
|
||||
{ name: 'Congregation', band: '301–750', monthly: 399, founding: 259 },
|
||||
{ name: 'Gathering', band: '751–2 000', monthly: 649, founding: 422 },
|
||||
{ name: 'Multitude', band: '2 001–5 000', monthly: 999, founding: 649 },
|
||||
{ name: 'Network', band: 'over 5 000', monthly: null, founding: null }, // from R1 500, priced per church
|
||||
];
|
||||
|
||||
/** Extra website storage: R20 a month per 5 GB above the 5 GB included. */
|
||||
const STORAGE = { includedBytes: 5 * 1024 ** 3, stepBytes: 5 * 1024 ** 3, monthly: 20 };
|
||||
|
||||
/** Bundles: % off the products (not the add-ons) by how many are billed. Accounts doesn't count. */
|
||||
const BUNDLE_PERCENT = { 2: 15, 3: 25 };
|
||||
|
||||
/** Yearly billing: this many months' price for 12 months (two months free). Products only. */
|
||||
const YEARLY_MONTHS = 10;
|
||||
/** Founding churches: this much off a price that has no published founding price. */
|
||||
const FOUNDING_PERCENT = 35;
|
||||
|
||||
const tierNamed = name => TIERS.find(t => t.name.toLowerCase() === String(name || '').toLowerCase()) || null;
|
||||
const PLANS = { events: TIERS, website: WEBSITE_PLANS, app: APP_TIERS, accounts: [] };
|
||||
|
||||
const tierNamed = (name, product = 'events') =>
|
||||
(PLANS[product] || []).find(t => t.name.toLowerCase() === String(name || '').toLowerCase()) || null;
|
||||
|
||||
/** The highest rand amount in a band label ("R100 001–R150 000" → 150000; "over R10 000 000" → Infinity). */
|
||||
function bandTop(band) {
|
||||
@@ -32,7 +63,7 @@ function bandTop(band) {
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/** The tier a band falls in, or null (no band, or an old install's "over R100 000"). */
|
||||
/** The Cross Events tier an income band falls in, or null (no band, or an old install's "over R100 000"). */
|
||||
function tierForBand(band) {
|
||||
if (!band || band === 'over R100 000') return null;
|
||||
const top = bandTop(band);
|
||||
@@ -40,12 +71,31 @@ function tierForBand(band) {
|
||||
return TIERS.find(t => t.upTo == null || top <= t.upTo) || null;
|
||||
}
|
||||
|
||||
/** The Church App tier for an active-member band, or null. */
|
||||
const appTierForBand = band => APP_TIERS.find(t => t.band === band) || null;
|
||||
|
||||
/**
|
||||
* The monthly price of a plan in cents, normal and founding: { monthlyCents, foundingCents },
|
||||
* The tier a product's install should be on from what it reports: { tier, band }. `tier` is
|
||||
* undefined for a product without tiers (Website), null when it can't tell (no band reported).
|
||||
*/
|
||||
function reviewTier(product, install) {
|
||||
if (product === 'events') {
|
||||
const band = install?.stats?.income?.eventIncome12m || null;
|
||||
return { tier: tierForBand(band), band };
|
||||
}
|
||||
if (product === 'app') {
|
||||
const band = install?.stats?.activeMembers90d || null;
|
||||
return { tier: appTierForBand(band), band };
|
||||
}
|
||||
return { tier: undefined, band: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* The monthly price of a plan in cents, normal and founding: { monthlyCents, foundingCents, custom },
|
||||
* or null when the plan has no price (Network, Trial, an old "standard") and no custom price.
|
||||
*/
|
||||
function planPrice(plan, customMonthlyCents = null) {
|
||||
const tier = tierNamed(plan);
|
||||
function planPrice(plan, customMonthlyCents = null, product = 'events') {
|
||||
const tier = tierNamed(plan, product);
|
||||
if (customMonthlyCents != null && customMonthlyCents >= 0) {
|
||||
return { monthlyCents: customMonthlyCents, foundingCents: Math.round((customMonthlyCents * (100 - FOUNDING_PERCENT)) / 100), custom: true };
|
||||
}
|
||||
@@ -53,4 +103,15 @@ function planPrice(plan, customMonthlyCents = null) {
|
||||
return { monthlyCents: tier.monthly * 100, foundingCents: tier.founding * 100, custom: false };
|
||||
}
|
||||
|
||||
module.exports = { TIERS, YEARLY_MONTHS, FOUNDING_PERCENT, tierNamed, tierForBand, planPrice };
|
||||
/** How many extra 5 GB blocks a website uses (from its heartbeat's `storage`). */
|
||||
function extraStorageBlocks(storage) {
|
||||
const used = Number(storage?.usedBytes);
|
||||
if (!Number.isFinite(used) || used <= 0) return 0;
|
||||
const included = Number(storage?.includedBytes) > 0 ? Number(storage.includedBytes) : STORAGE.includedBytes;
|
||||
return Math.max(0, Math.ceil((used - included) / STORAGE.stepBytes));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TIERS, WEBSITE_PLANS, APP_TIERS, PLANS, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
|
||||
tierNamed, tierForBand, appTierForBand, reviewTier, planPrice, extraStorageBlocks,
|
||||
};
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
*/
|
||||
|
||||
const { licenceKey } = require('./crypto');
|
||||
const { PRODUCT_NAMES, isProduct } = require('./products');
|
||||
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 });
|
||||
|
||||
@@ -57,7 +58,11 @@ async function ensureAccountsLicence(db, customerId) {
|
||||
* 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 = {} }) {
|
||||
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);
|
||||
|
||||
@@ -31,10 +31,7 @@ function productOfKey(key) {
|
||||
|
||||
const isProduct = p => PRODUCTS.includes(p);
|
||||
|
||||
/**
|
||||
* Products that can be invoiced. Until billing per customer (Hub 2.0 step 4) only Events has
|
||||
* prices; Accounts is never invoiced.
|
||||
*/
|
||||
const BILLABLE = ['events'];
|
||||
/** Products that are invoiced (Accounts is free and never invoiced). */
|
||||
const BILLABLE = ['events', 'website', 'app'];
|
||||
|
||||
module.exports = { PRODUCTS, PRODUCT_NAMES, KEY_PREFIXES, BILLABLE, productOfKey, isProduct };
|
||||
|
||||
+188
-40
@@ -2,24 +2,48 @@ jest.mock('../src/config/db', () => ({}));
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { TIERS, tierForBand, planPrice } = require('../src/utils/billing/tiers');
|
||||
const { hub } = require('@crosscode/contracts');
|
||||
const { TIERS, WEBSITE_PLANS, APP_TIERS, tierForBand, appTierForBand, planPrice, extraStorageBlocks } = require('../src/utils/billing/tiers');
|
||||
const { day, ymd, addMonths, addDays, today, saHour, periodLabel, money } = require('../src/utils/billing/dates');
|
||||
const { draftInvoice, cleanLines, totals, invoiceState, statement, recipientFor } = require('../src/utils/billing/compute');
|
||||
const { draftCustomerInvoice, customerInvoiceLines, planChangesOf, cleanLines, totals, invoiceState, statement, recipientFor } = require('../src/utils/billing/compute');
|
||||
|
||||
const customer = (extra = {}) => ({ id: 'c1', name: 'Hope Church', email: 'office@hope.example', founding: false, ...extra });
|
||||
const install = (band, email = 'admin@hope.example') => ({ adminContact: { email }, stats: band ? { income: { eventIncome12m: band } } : {} });
|
||||
const licence = (extra = {}) => ({
|
||||
id: 'l1', plan: 'Sprout', billingCycle: 'monthly', billingStart: day('2026-01-01'), nextInvoiceDate: day('2026-12-01'),
|
||||
reviewDate: day('2027-01-01'), customMonthlyCents: null, ...extra,
|
||||
const GB = 1024 ** 3;
|
||||
const customer = (extra = {}) => ({
|
||||
id: 'c1', name: 'Hope Church', email: 'office@hope.example', founding: false,
|
||||
billingCycle: 'monthly', billingStart: day('2026-01-01'), nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-01-01'), ...extra,
|
||||
});
|
||||
const install = (band, email = 'admin@hope.example') => ({ product: 'events', adminContact: { email }, stats: band ? { income: { eventIncome12m: band } } : {} });
|
||||
const events = (extra = {}) => ({
|
||||
id: 'l1', product: 'events', status: 'active', plan: 'Sprout', customMonthlyCents: null,
|
||||
billedFrom: day('2026-01-01'), billedUntil: day('2026-11-30'), install: install('R100 001–R150 000'), ...extra,
|
||||
});
|
||||
const website = (extra = {}) => ({
|
||||
id: 'l2', product: 'website', status: 'active', plan: 'Website', customMonthlyCents: null,
|
||||
billedFrom: day('2026-06-01'), billedUntil: day('2026-11-30'), install: { product: 'website', stats: {} }, ...extra,
|
||||
});
|
||||
const app = (extra = {}) => ({
|
||||
id: 'l3', product: 'app', status: 'active', plan: 'Mustard Seed', customMonthlyCents: null,
|
||||
billedFrom: day('2026-06-01'), billedUntil: day('2026-11-30'), install: { product: 'app', stats: { activeMembers90d: '0–100' } }, ...extra,
|
||||
});
|
||||
const accounts = () => ({ id: 'l4', product: 'accounts', status: 'active', plan: 'included', billedFrom: null, billedUntil: null, install: null });
|
||||
const settings = { payment_terms_days: '7' };
|
||||
const draft = (c, licences) => draftCustomerInvoice({ customer: c, licences, settings });
|
||||
const amounts = invoice => invoice.lines.map(l => [l.description, l.amountCents]);
|
||||
|
||||
describe('tiers', () => {
|
||||
test('the server and the Hub screens have the same tiers', () => {
|
||||
const ts = fs.readFileSync(path.join(__dirname, '..', '..', 'frontend', 'src', 'lib', 'tiers.ts'), 'utf8');
|
||||
const front = [...ts.matchAll(/\{ name: "(\w+)", upTo: ([\d_]+|null), monthly: (\d+|null), founding: (\d+|null) \}/g)]
|
||||
.map(m => [m[1], m[2] === 'null' ? null : Number(m[2].replace(/_/g, '')), m[3] === 'null' ? null : Number(m[3]), m[4] === 'null' ? null : Number(m[4])]);
|
||||
expect(front).toEqual(TIERS.map(t => [t.name, t.upTo, t.monthly, t.founding]));
|
||||
const front = fs.readFileSync(path.join(__dirname, '..', '..', 'frontend', 'src', 'lib', 'tiers.ts'), 'utf8');
|
||||
const num = v => (v === 'null' ? null : Number(v.replace(/_/g, '')));
|
||||
|
||||
test('the server and the Hub screens have the same Cross Events tiers', () => {
|
||||
const rows = [...front.matchAll(/\{ name: "(\w+)", upTo: ([\d_]+|null), monthly: (\d+|null), founding: (\d+|null) \}/g)].map(m => [m[1], num(m[2]), num(m[3]), num(m[4])]);
|
||||
expect(rows).toEqual(TIERS.map(t => [t.name, t.upTo, t.monthly, t.founding]));
|
||||
});
|
||||
|
||||
test('...and the same Church App tiers and Website price', () => {
|
||||
const appRows = [...front.matchAll(/\{ name: "([\w ]+)", band: "([^"]+)", monthly: (\d+|null), founding: (\d+|null) \}/g)].map(m => [m[1], m[2], num(m[3]), num(m[4])]);
|
||||
expect(appRows).toEqual(APP_TIERS.map(t => [t.name, t.band, t.monthly, t.founding]));
|
||||
const site = /WEBSITE_PLAN = \{ name: "Website", monthly: (\d+), founding: (\d+) \}/.exec(front);
|
||||
expect([num(site[1]), num(site[2])]).toEqual([WEBSITE_PLANS[0].monthly, WEBSITE_PLANS[0].founding]);
|
||||
});
|
||||
|
||||
test('a band falls in the tier whose top it fits under', () => {
|
||||
@@ -32,11 +56,27 @@ describe('tiers', () => {
|
||||
expect(tierForBand(null)).toBeNull();
|
||||
});
|
||||
|
||||
test('every App active-member band (contracts) has a tier', () => {
|
||||
expect(APP_TIERS.map(t => t.band)).toEqual([...hub.ACTIVE_MEMBER_BANDS]);
|
||||
expect(appTierForBand('101–300').name).toBe('Small Group');
|
||||
expect(appTierForBand(null)).toBeNull();
|
||||
});
|
||||
|
||||
test('prices: the tier\'s, or a custom one with 35% off for founding', () => {
|
||||
expect(planPrice('Grow')).toEqual({ monthlyCents: 85000, foundingCents: 55000, custom: false });
|
||||
expect(planPrice('Network')).toBeNull();
|
||||
expect(planPrice('Network', 750000)).toEqual({ monthlyCents: 750000, foundingCents: 487500, custom: true });
|
||||
expect(planPrice('standard')).toBeNull();
|
||||
expect(planPrice('Website', null, 'website')).toEqual({ monthlyCents: 9900, foundingCents: 6400, custom: false });
|
||||
expect(planPrice('Small Group', null, 'app')).toEqual({ monthlyCents: 24900, foundingCents: 16200, custom: false });
|
||||
expect(planPrice('Grow', null, 'app')).toBeNull(); // another product's tier
|
||||
});
|
||||
|
||||
test('extra storage: whole 5 GB blocks above what is included', () => {
|
||||
expect(extraStorageBlocks({ usedBytes: 4 * GB, includedBytes: 5 * GB })).toBe(0);
|
||||
expect(extraStorageBlocks({ usedBytes: 5 * GB + 1, includedBytes: 5 * GB })).toBe(1);
|
||||
expect(extraStorageBlocks({ usedBytes: 11 * GB })).toBe(2);
|
||||
expect(extraStorageBlocks(null)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,82 +103,190 @@ describe('dates', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('drafting an invoice', () => {
|
||||
describe('drafting an invoice (one product, as before Hub 2.0)', () => {
|
||||
test('monthly, in advance: the period starting on its date, due after the payment terms', () => {
|
||||
const { invoice, licenceUpdate } = draftInvoice({ licence: licence(), customer: customer(), install: install('R100 001–R150 000'), settings });
|
||||
const { invoice, customerUpdate, licenceUpdates } = draft(customer(), [events(), accounts()]);
|
||||
expect(ymd(invoice.issueDate)).toBe('2026-12-01');
|
||||
expect(ymd(invoice.dueDate)).toBe('2026-12-08');
|
||||
expect([ymd(invoice.periodStart), ymd(invoice.periodEnd)]).toEqual(['2026-12-01', '2026-12-31']);
|
||||
expect(invoice.lines).toEqual([{ description: 'Cross Events licence: Sprout tier, December 2026', quantity: 1, unitCents: 55000, amountCents: 55000 }]);
|
||||
expect(invoice).toMatchObject({ totalCents: 55000, vatCents: 0, reviewed: false, planChange: null, recipientEmail: 'admin@hope.example', warnings: [] });
|
||||
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-01-01');
|
||||
expect(ymd(licenceUpdate.reviewDate)).toBe('2027-01-01'); // not reviewed yet
|
||||
expect(invoice.lines).toEqual([{ description: 'Cross Events, Sprout tier, December 2026', quantity: 1, unitCents: 55000, amountCents: 55000 }]);
|
||||
expect(invoice).toMatchObject({ licenceId: null, plan: 'Sprout', totalCents: 55000, vatCents: 0, reviewed: false, planChange: null, recipientEmail: 'admin@hope.example', warnings: [] });
|
||||
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-01-01');
|
||||
expect(ymd(customerUpdate.reviewDate)).toBe('2027-01-01'); // not reviewed yet
|
||||
expect(licenceUpdates.map(u => [u.id, ymd(u.data.billedUntil)])).toEqual([['l1', '2026-12-31']]);
|
||||
expect(invoice.basis.licences).toEqual([{ id: 'l1', billedUntil: '2026-11-30' }, { id: 'l4', billedUntil: null }]);
|
||||
});
|
||||
|
||||
test('between reviews the tier stays, whatever the income', () => {
|
||||
const { invoice } = draftInvoice({ licence: licence(), customer: customer(), install: install('R1 000 001–R2 500 000'), settings });
|
||||
const { invoice } = draft(customer(), [events({ install: install('R1 000 001–R2 500 000') })]);
|
||||
expect(invoice.plan).toBe('Sprout');
|
||||
expect(invoice.incomeBand).toBeNull();
|
||||
});
|
||||
|
||||
test('at the yearly review the income moves the tier up, and the next review is a year on', () => {
|
||||
const { invoice, licenceUpdate } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install('R250 001–R400 000'), settings });
|
||||
const { invoice, customerUpdate } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install('R250 001–R400 000') })]);
|
||||
expect(invoice).toMatchObject({ reviewed: true, plan: 'Grow', incomeBand: 'R250 001–R400 000', totalCents: 85000 });
|
||||
expect(invoice.planChange).toEqual({ from: 'Sprout', to: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, band: 'R250 001–R400 000' });
|
||||
expect(ymd(licenceUpdate.reviewDate)).toBe('2028-01-01');
|
||||
expect(invoice.planChange).toEqual([{ licenceId: 'l1', product: 'events', from: 'Sprout', to: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, band: 'R250 001–R400 000' }]);
|
||||
expect(ymd(customerUpdate.reviewDate)).toBe('2028-01-01');
|
||||
});
|
||||
|
||||
test('...or down', () => {
|
||||
const { invoice } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install('R5 001–R20 000'), settings });
|
||||
expect(invoice.planChange).toMatchObject({ from: 'Sprout', to: 'Seed' });
|
||||
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install('R5 001–R20 000') })]);
|
||||
expect(invoice.planChange[0]).toMatchObject({ from: 'Sprout', to: 'Seed' });
|
||||
expect(invoice.totalCents).toBe(35000);
|
||||
});
|
||||
|
||||
test('no band at the review: the tier stays and Joshua is warned', () => {
|
||||
const { invoice } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install(null), settings });
|
||||
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install(null) })]);
|
||||
expect(invoice.plan).toBe('Sprout');
|
||||
expect(invoice.planChange).toBeNull();
|
||||
expect(invoice.warnings[0]).toMatch(/hasn't reported its 12-month event income/);
|
||||
});
|
||||
|
||||
test('a founding church gets the founding price as its own line', () => {
|
||||
const { invoice } = draftInvoice({ licence: licence(), customer: customer({ founding: true }), install: install(null), settings });
|
||||
const { invoice } = draft(customer({ founding: true }), [events()]);
|
||||
expect(invoice.lines[1]).toEqual({ description: 'Founding church discount (35%)', quantity: 1, unitCents: -19000, amountCents: -19000 });
|
||||
expect(invoice.totalCents).toBe(36000);
|
||||
expect(invoice.founding).toBe(true);
|
||||
});
|
||||
|
||||
test('yearly: 10 months\' price for 12 months, founding on all of it', () => {
|
||||
const { invoice, licenceUpdate } = draftInvoice({
|
||||
licence: licence({ plan: 'Grow', billingCycle: 'yearly', nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-12-01') }),
|
||||
customer: customer({ founding: true }), install: install(null), settings,
|
||||
});
|
||||
const { invoice, customerUpdate } = draft(
|
||||
customer({ founding: true, billingCycle: 'yearly', nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-12-01') }),
|
||||
[events({ plan: 'Grow' })],
|
||||
);
|
||||
expect([ymd(invoice.periodStart), ymd(invoice.periodEnd)]).toEqual(['2026-12-01', '2027-11-30']);
|
||||
expect(invoice.lines.map(l => [l.quantity, l.unitCents, l.amountCents])).toEqual([[10, 85000, 850000], [10, -30000, -300000]]);
|
||||
expect(invoice.lines[0].description).toBe('Cross Events licence: Grow tier, 12 months (1 December 2026 – 30 November 2027), paid yearly: 2 months free');
|
||||
expect(invoice.lines[0].description).toBe('Cross Events, Grow tier, 12 months (1 December 2026 – 30 November 2027), paid yearly: 2 months free');
|
||||
expect(invoice.totalCents).toBe(550000);
|
||||
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-12-01');
|
||||
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-12-01');
|
||||
});
|
||||
|
||||
test('a custom price is kept at the review, with a note if the income points elsewhere', () => {
|
||||
const { invoice } = draftInvoice({
|
||||
licence: licence({ plan: 'Network', customMonthlyCents: 750000, nextInvoiceDate: day('2027-01-01') }),
|
||||
customer: customer(), install: install('R5 000 001–R10 000 000'), settings,
|
||||
});
|
||||
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ plan: 'Network', customMonthlyCents: 750000, billedUntil: day('2026-12-31'), install: install('R5 000 001–R10 000 000') })]);
|
||||
expect(invoice).toMatchObject({ plan: 'Network', totalCents: 750000, planChange: null });
|
||||
expect(invoice.warnings[0]).toMatch(/Movement tier, but the licence has a custom price/);
|
||||
});
|
||||
|
||||
test('an unpriced plan makes an empty draft with a warning', () => {
|
||||
const { invoice } = draftInvoice({ licence: licence({ plan: 'standard' }), customer: customer(), install: install(null), settings });
|
||||
test('an unpriced plan makes an empty draft with a warning (so it isn\'t skipped)', () => {
|
||||
const { invoice, empty } = draft(customer(), [events({ plan: 'standard' })]);
|
||||
expect(invoice.lines).toEqual([]);
|
||||
expect(invoice.warnings[0]).toMatch(/no price for the "standard" plan/);
|
||||
expect(empty).toBe(false);
|
||||
});
|
||||
|
||||
test('month-end billing day stays on the last day', () => {
|
||||
const { invoice, licenceUpdate } = draftInvoice({ licence: licence({ billingStart: day('2026-01-31'), nextInvoiceDate: day('2027-01-31'), reviewDate: day('2028-01-31') }), customer: customer(), install: install(null), settings });
|
||||
const { invoice, customerUpdate } = draft(customer({ billingStart: day('2026-01-31'), nextInvoiceDate: day('2027-01-31'), reviewDate: day('2028-01-31') }), [events({ billedUntil: day('2027-01-30') })]);
|
||||
expect(ymd(invoice.periodEnd)).toBe('2027-02-27');
|
||||
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-02-28');
|
||||
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-02-28');
|
||||
});
|
||||
|
||||
test('nothing billed (only Accounts, a trial or a suspended licence): no invoice, the customer still moves on', () => {
|
||||
for (const licences of [[accounts()], [events({ billedFrom: null })], [events({ status: 'suspended' })], []]) {
|
||||
const { empty, customerUpdate } = draft(customer(), licences);
|
||||
expect(empty).toBe(true);
|
||||
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-01-01');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('drafting an invoice (several products, Hub 2.0)', () => {
|
||||
test('two products: each at its price, then 15% off them', () => {
|
||||
const { invoice } = draft(customer(), [events(), website(), accounts()]);
|
||||
expect(amounts(invoice)).toEqual([
|
||||
['Cross Events, Sprout tier, December 2026', 55000],
|
||||
['Church Website, December 2026', 9900],
|
||||
['Bundle discount (15%: Cross Events and Church Website)', -9735],
|
||||
]);
|
||||
expect(invoice.totalCents).toBe(55165);
|
||||
expect(invoice.plan).toBe('Cross Events Sprout · Church Website');
|
||||
});
|
||||
|
||||
test('three products: 25% off, after the founding prices (decision 1)', () => {
|
||||
const { invoice } = draft(customer({ founding: true }), [events(), website(), app()]);
|
||||
// Founding: 360 + 64 + 64 = R488, less 25% = R366.
|
||||
expect(invoice.totalCents).toBe(36600);
|
||||
expect(invoice.lines.at(-1)).toMatchObject({ description: 'Bundle discount (25%: Cross Events, Church Website and Church App)', amountCents: -12200 });
|
||||
});
|
||||
|
||||
test('Accounts never counts towards a bundle, and is never on the invoice', () => {
|
||||
const { invoice } = draft(customer(), [events(), accounts()]);
|
||||
expect(invoice.lines.some(l => /Bundle|Accounts/.test(l.description))).toBe(false);
|
||||
});
|
||||
|
||||
test('extra website storage: R20 per 5 GB a month, never discounted', () => {
|
||||
const { invoice } = draft(customer({ founding: true }), [events(), website({ install: { product: 'website', stats: { storage: { usedBytes: 12 * GB, includedBytes: 5 * GB } } } })]);
|
||||
expect(invoice.lines.at(-1)).toEqual({ description: 'Extra website storage: 2 × 5 GB, December 2026', quantity: 2, unitCents: 2000, amountCents: 4000 });
|
||||
// The bundle comes off the products only: (360 + 64) × 15% = R63.60.
|
||||
expect(invoice.lines.find(l => /Bundle/.test(l.description)).amountCents).toBe(-6360);
|
||||
});
|
||||
|
||||
test('yearly: add-ons are 12 months\' price (decision 2), products 10', () => {
|
||||
const { invoice } = draft(customer({ billingCycle: 'yearly', reviewDate: day('2027-12-01') }), [website({ install: { product: 'website', stats: { storage: { usedBytes: 8 * GB } } } })]);
|
||||
expect(invoice.lines.map(l => [l.quantity, l.unitCents])).toEqual([[10, 9900], [12, 2000]]);
|
||||
});
|
||||
|
||||
test('the App is reviewed on its active members', () => {
|
||||
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [app({ billedUntil: day('2026-12-31'), install: { product: 'app', stats: { activeMembers90d: '301–750' } } })]);
|
||||
expect(invoice.planChange).toEqual([expect.objectContaining({ licenceId: 'l3', product: 'app', from: 'Mustard Seed', to: 'Congregation', toMonthlyCents: 39900, band: '301–750' })]);
|
||||
expect(invoice.totalCents).toBe(39900);
|
||||
});
|
||||
|
||||
test('several tier changes at one review: one per product', () => {
|
||||
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [
|
||||
events({ billedUntil: day('2026-12-31'), install: install('R250 001–R400 000') }),
|
||||
app({ billedUntil: day('2026-12-31'), install: { product: 'app', stats: { activeMembers90d: '101–300' } } }),
|
||||
]);
|
||||
expect(invoice.planChange.map(pc => `${pc.product}:${pc.to}`)).toEqual(['events:Grow', 'app:Small Group']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a product added part-way (decision 3)', () => {
|
||||
test('starting inside the period being drafted: charged from its first day', () => {
|
||||
const { invoice, licenceUpdates } = draft(customer(), [events(), website({ billedFrom: day('2026-12-20'), billedUntil: null })]);
|
||||
// R99 a month = R1 188 a year; 12 days of it.
|
||||
expect(amounts(invoice)[1]).toEqual(['Church Website, 20 Dec 2026 – 31 Dec 2026 (12 days, from its start)', Math.round((9900 * 12 / 365) * 12)]);
|
||||
expect(licenceUpdates.find(u => u.id === 'l2').data.billedUntil).toEqual(day('2026-12-31'));
|
||||
// It counts for the bundle in that period.
|
||||
expect(invoice.lines.some(l => /Bundle discount \(15%/.test(l.description))).toBe(true);
|
||||
});
|
||||
|
||||
test('starting in a period invoiced already: those days on the next invoice, then the full period', () => {
|
||||
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01'), reviewDate: day('2027-06-01') }), [
|
||||
events({ billedUntil: day('2026-12-31') }),
|
||||
app({ billedFrom: day('2026-12-15'), billedUntil: null }),
|
||||
]);
|
||||
expect(amounts(invoice).slice(1, 3)).toEqual([
|
||||
['Church App, Mustard Seed tier, 15 Dec 2026 – 31 Dec 2026 (17 days before this period)', Math.round((9900 * 12 / 365) * 17)],
|
||||
['Church App, Mustard Seed tier, January 2027', 9900],
|
||||
]);
|
||||
});
|
||||
|
||||
test('starting after the period: not on this invoice', () => {
|
||||
const { invoice } = draft(customer(), [events(), website({ billedFrom: day('2027-01-05'), billedUntil: null })]);
|
||||
expect(invoice.lines.map(l => l.description)).toEqual(['Cross Events, Sprout tier, December 2026']);
|
||||
});
|
||||
|
||||
test('days are never charged twice', () => {
|
||||
// Invoiced up to the end of December already: nothing owed from before January.
|
||||
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01'), reviewDate: day('2027-06-01') }), [app({ billedFrom: day('2026-12-15'), billedUntil: day('2026-12-31') })]);
|
||||
expect(invoice.lines.map(l => l.description)).toEqual(['Church App, Mustard Seed tier, January 2027']);
|
||||
});
|
||||
|
||||
test('a founding church\'s founding price is prorated the same way', () => {
|
||||
const { lines } = customerInvoiceLines({
|
||||
customer: customer({ founding: true }), licences: [website({ billedFrom: day('2026-12-20'), billedUntil: null })],
|
||||
period: { start: day('2026-12-01'), end: day('2026-12-31'), cycle: 'monthly' }, reviewed: false,
|
||||
});
|
||||
const full = Math.round((9900 * 12 / 365) * 12);
|
||||
expect(lines.map(l => l.amountCents)).toEqual([full, Math.round((full * -3500) / 9900)]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tier changes stored before Hub 2.0', () => {
|
||||
test('one object reads as a list of one Cross Events change', () => {
|
||||
expect(planChangesOf({ licenceId: 'l1', planChange: { from: 'Seed', to: 'Sprout' } })).toEqual([{ licenceId: 'l1', product: 'events', from: 'Seed', to: 'Sprout' }]);
|
||||
expect(planChangesOf({ planChange: null })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -110,6 +110,28 @@ describe('licences', () => {
|
||||
await expect(checkReopen(mockDb, old, 'revoked')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('a product added to a customer that is billed already starts after its free month', async () => {
|
||||
mockDb.customer = { findUnique: jest.fn(async () => ({ id: 'c1', billingCycle: 'monthly' })) };
|
||||
try {
|
||||
const { licence, accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'app', data: {}, now: new Date('2026-11-04T10:00:00Z') });
|
||||
expect(licence.billedFrom.toISOString().slice(0, 10)).toBe('2026-12-04');
|
||||
// Accounts is free: never charged.
|
||||
expect(accounts.billedFrom).toBeUndefined();
|
||||
} finally {
|
||||
delete mockDb.customer;
|
||||
}
|
||||
});
|
||||
|
||||
test('a customer not billed yet: the product waits until billing is set up', async () => {
|
||||
mockDb.customer = { findUnique: jest.fn(async () => ({ id: 'c1', billingCycle: 'none' })) };
|
||||
try {
|
||||
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
expect(licence.billedFrom).toBeUndefined();
|
||||
} finally {
|
||||
delete mockDb.customer;
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown products are refused', async () => {
|
||||
await expect(createLicence(mockDb, { customerId: 'c1', product: 'shop' })).rejects.toMatchObject({ status: 400 });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user