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:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user