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

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

86 lines
5.4 KiB
TypeScript

import React from "react";
import type { Product } from "./products";
// 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 };
/** A tier change at the annual review (Hub 2.0: one per product). */
export type PlanChange = { licenceId?: string | null; product?: Product; 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;
/** The tier changes on this invoice (the API reads Hub 1.7's single change as a list of one). */
planChanges: PlanChange[];
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 };
/** Before Hub 2.0 an invoice was for one licence; from 2.0 it's for the customer (null). */
licence?: { id: string; key: string; product: Product; plan: string; 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));