Files
events-hub/frontend/src/lib/api.ts
T
joshuaandClaude Opus 5.5 6fce0fe90e 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>
2026-11-03 13:42:45 +02:00

64 lines
2.5 KiB
TypeScript

export const API_URL = (process.env.NEXT_PUBLIC_API_URL || "http://localhost:5200").replace(/\/$/, "");
const TOKEN_KEY = "events_hub_token";
export class ApiError extends Error {
constructor(message: string, public status: number, public code?: string) {
super(message);
}
}
export function getToken(): string | null {
try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }
}
export function setToken(token: string | null) {
try {
if (token) localStorage.setItem(TOKEN_KEY, token);
else localStorage.removeItem(TOKEN_KEY);
} catch { /* private window */ }
}
/** Call the Hub API. Logged-in calls send the session token; a 401 signs out. */
export async function api<T = unknown>(path: string, options: { method?: string; body?: unknown; auth?: boolean } = {}): Promise<T> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
const token = getToken();
if (options.auth !== false && token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(`${API_URL}${path}`, {
method: options.method || "GET",
headers,
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
const data = await res.json().catch(() => null);
if (!res.ok) {
if (res.status === 401 && options.auth !== false) {
setToken(null);
if (typeof window !== "undefined" && !window.location.pathname.startsWith("/login")) window.location.href = "/login";
}
throw new ApiError(data?.message || `Request failed (${res.status})`, res.status, data?.code);
}
return data as T;
}
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;
}
}