Billing: invoices, approval, receipts, statements, licence changes (1.7.0)
- Invoices drafted 14 days before each licence's invoice date and emailed to the alert email for approval; approved ones go out on their date from 08:00 SA time. Drafts can be edited, recalculated, sent early, put back to draft or voided; one-off invoices too. - Annual tier review from the 12-month event-income band; approving a tier change emails a notice of licence change, applied when the invoice goes out. Notices can also be sent by hand. - Founding churches (35% off as its own line), payments with receipts, statements for any dates. - Every billing email is styled HTML with a PDF (invoice / tax invoice, receipt, statement, licence change) and logged per customer. - Settings -> Billing: business and bank details, VAT (off: plain invoices; on: VAT-inclusive tax invoices), timing and numbering. - Migration 20261103111645_invoicing; pdfkit 0.17.2; tests/billing.test.js; scripts/sample-billing-pdfs.js. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -40,3 +40,24 @@ export async function api<T = unknown>(path: string, options: { method?: string;
|
||||
}
|
||||
|
||||
export const errorText = (e: unknown, fallback = "Something went wrong.") => (e instanceof Error && e.message) || fallback;
|
||||
|
||||
/** Opens a PDF from the API (which needs the session token) in a new tab. */
|
||||
export async function openPdf(path: string) {
|
||||
// Open the tab first, while the click still counts as the user's: browsers block it after an await.
|
||||
const tab = window.open("", "_blank");
|
||||
try {
|
||||
const token = getToken();
|
||||
const res = await fetch(`${API_URL}${path}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
throw new ApiError(data?.message || `Request failed (${res.status})`, res.status, data?.code);
|
||||
}
|
||||
const url = URL.createObjectURL(await res.blob());
|
||||
if (tab) tab.location.href = url;
|
||||
else window.location.href = url;
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
} catch (e) {
|
||||
tab?.close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import React from "react";
|
||||
|
||||
// Billing (1.7.0): the shapes the billing API returns, and how they're shown.
|
||||
|
||||
export type InvoiceStatus = "draft" | "approved" | "sent" | "void";
|
||||
export type InvoiceState = InvoiceStatus | "unpaid" | "part_paid" | "overdue" | "paid";
|
||||
export type BillingCycle = "none" | "monthly" | "yearly";
|
||||
export type Line = { description: string; quantity: number; unitCents: number; amountCents: number };
|
||||
export type PlanChange = { from: string; to: string; fromMonthlyCents: number | null; toMonthlyCents: number | null; band?: string | null };
|
||||
export type BillingTier = { name: string; upTo: number | null; monthly: number | null; founding: number | null };
|
||||
|
||||
export type Payment = {
|
||||
id: string; receiptNumber: string; customerId: string; invoiceId: string | null; amountCents: number; paidOn: string;
|
||||
method: string; reference: string | null; notes: string | null; receiptSentAt: string | null; createdAt: string;
|
||||
invoice?: { id: string; number: string } | null; customer?: { id: string; name: string };
|
||||
};
|
||||
|
||||
export type Invoice = {
|
||||
id: string; number: string; customerId: string; licenceId: string | null; status: InvoiceStatus; state: InvoiceState;
|
||||
issueDate: string; dueDate: string; periodStart: string | null; periodEnd: string | null; cycle: BillingCycle;
|
||||
plan: string | null; incomeBand: string | null; reviewed: boolean; founding: boolean; planChange: PlanChange | null;
|
||||
lines: Line[]; totalCents: number; vatCents: number; paidCents: number; balanceCents: number;
|
||||
notes: string | null; warnings: string[]; recipientEmail: string | null;
|
||||
approvedAt: string | null; approvalEmailedAt: string | null; sentAt: string | null; sendError: string | null; voidedAt: string | null; voidReason: string | null;
|
||||
createdAt: string; payments: Payment[];
|
||||
customer?: { id: string; name: string; founding: boolean };
|
||||
licence?: { id: string; key: string; plan: string; billingCycle: BillingCycle; installUrl: string | null } | null;
|
||||
};
|
||||
|
||||
export type LicenceChange = {
|
||||
id: string; number: string; fromPlan: string; toPlan: string; fromMonthlyCents: number | null; toMonthlyCents: number | null;
|
||||
effectiveDate: string; reason: string | null; incomeBand: string | null; appliedAt: string | null; sentAt: string | null; invoiceId: string | null; createdAt: string;
|
||||
};
|
||||
|
||||
export type BillingEmail = { id: string; kind: string; to: string; subject: string; error: string | null; sentAt: string };
|
||||
|
||||
/** R1 350.00 */
|
||||
export function money(cents: number | null | undefined) {
|
||||
if (cents == null) return "—";
|
||||
const neg = cents < 0;
|
||||
const [r, c] = (Math.abs(Math.round(cents)) / 100).toFixed(2).split(".");
|
||||
return `${neg ? "-" : ""}R${r.replace(/\B(?=(\d{3})+(?!\d))/g, " ")}.${c}`;
|
||||
}
|
||||
|
||||
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
/** "1 Dec 2026" from "2026-12-01". */
|
||||
export function day(d: string | null | undefined) {
|
||||
if (!d) return "—";
|
||||
const [y, m, dd] = d.slice(0, 10).split("-").map(Number);
|
||||
return `${dd} ${MONTHS[m - 1]} ${y}`;
|
||||
}
|
||||
/** Today in South Africa, "YYYY-MM-DD". */
|
||||
export const todayYmd = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Africa/Johannesburg", year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date());
|
||||
|
||||
export const STATE: Record<InvoiceState, { label: string; cls: string }> = {
|
||||
draft: { label: "Draft: needs approval", cls: "bg-amber-50 text-amber-800 border-amber-200" },
|
||||
approved: { label: "Approved: goes out on its date", cls: "bg-indigo-50 text-indigo-700 border-indigo-200" },
|
||||
sent: { label: "Sent", cls: "bg-slate-50 text-slate-700 border-slate-200" },
|
||||
unpaid: { label: "Unpaid", cls: "bg-sky-50 text-sky-800 border-sky-200" },
|
||||
part_paid: { label: "Part paid", cls: "bg-sky-50 text-sky-800 border-sky-200" },
|
||||
overdue: { label: "Overdue", cls: "bg-red-50 text-red-700 border-red-200" },
|
||||
paid: { label: "Paid", cls: "bg-green-50 text-green-700 border-green-200" },
|
||||
void: { label: "Void", cls: "bg-slate-100 text-slate-500 border-slate-200" },
|
||||
};
|
||||
|
||||
export function StateBadge({ state, short = false }: { state: InvoiceState; short?: boolean }) {
|
||||
const s = STATE[state];
|
||||
return <span className={`inline-block whitespace-nowrap rounded-full border px-2 py-0.5 text-xs font-medium ${s.cls}`}>{short ? s.label.split(":")[0] : s.label}</span>;
|
||||
}
|
||||
|
||||
export const CYCLE: Record<BillingCycle, string> = { none: "Not billed", monthly: "Monthly", yearly: "Yearly (2 months free)" };
|
||||
export const METHOD: Record<string, string> = { eft: "EFT", card: "Card", cash: "Cash", other: "Other" };
|
||||
export const EMAIL_KIND: Record<string, string> = { invoice: "Invoice", receipt: "Receipt", statement: "Statement", licence_change: "Licence change", approval: "Approval request (to you)", reminder: "Reminder (to you)" };
|
||||
|
||||
/** Rand typed into a form ("1350" or "1 350,50") → cents, or null. */
|
||||
export function centsFrom(v: string): number | null {
|
||||
const n = Number(String(v).replace(/[\sR]/g, "").replace(",", "."));
|
||||
return Number.isFinite(n) && String(v).trim() !== "" ? Math.round(n * 100) : null;
|
||||
}
|
||||
export const randInput = (cents: number | null | undefined) => (cents == null ? "" : (cents / 100).toFixed(2));
|
||||
Reference in New Issue
Block a user