staging-org / ocean-landing-serve / src/ lib/ invoices.ts

import { rates } from './billing-plans.js';
import { type Member } from './org-types.js';
import { org } from './live/org.svelte.js';
import { orgBilling, teamPlan, type PastCycle } from './live/org-settings.svelte.js';
import type { PaymentMethod } from './payment.js';

export type InvoiceLine = { label: string; detail: string; cents: number };

export type Invoice = PastCycle & {
	end: string;
	issued: string;
	due: string;
	seats: Member[];
	joined: Member[];
	includedGiB: number;
	lines: InvoiceLine[];
	cents: number;
	method: PaymentMethod | null;
};

export type InvoiceStatus = 'paid' | 'open' | 'overdue';

const ms = (date: string) => Date.parse(`${date}T00:00:00Z`);
const iso = (t: number) => new Date(t).toISOString().slice(0, 10);
export const addDays = (date: string, days: number) => iso(ms(date) + days * 86_400_000);
const addMonth = (date: string) => {
	const d = new Date(ms(date));
	d.setUTCMonth(d.getUTCMonth() + 1);
	return iso(d.getTime());
};

const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
export const dollars = (cents: number) => money.format(cents / 100);

const build = (cycle: PastCycle): Invoice => {
	const issued = addMonth(cycle.start);
	const end = addDays(issued, -1);
	// Seats are counted when the cycle ends, as the plan page says.
	const seats = org.members.filter((m) => m.joined <= end);
	const joined = seats.filter((m) => m.joined >= cycle.start);
	const includedGiB = seats.length * teamPlan.storageGiBPerSeat;
	const storageOver = Math.max(0, cycle.storageGiB - includedGiB);
	const method = orgBilling.methods.find((m) => m.id === (cycle.paid?.by ?? orgBilling.methods.find((x) => x.default)?.id)) ?? null;
	const terms = method?.kind === 'invoice' ? method.terms : 0;
	const lines: InvoiceLine[] = [
		{
			label: `${teamPlan.label} plan, ${seats.length} ${seats.length === 1 ? 'seat' : 'seats'}`,
			detail: `${dollars(teamPlan.centsPerSeat)} a seat`,
			cents: seats.length * teamPlan.centsPerSeat
		},
		{
			label: 'Storage',
			detail: `${cycle.storageGiB} GiB of ${includedGiB} GiB included${storageOver > 0 ? `, ${storageOver} GiB over at ${dollars(rates.centsPerGiB)} each` : ''}`,
			cents: Math.ceil(storageOver * rates.centsPerGiB)
		}
	];
	return {
		...cycle,
		end,
		issued,
		due: addDays(issued, terms),
		seats,
		joined,
		includedGiB,
		lines,
		cents: lines.reduce((sum, l) => sum + l.cents, 0),
		method
	};
};

export const invoices = orgBilling.history.map(build).reverse();

export const invoiceStatus = (inv: Invoice, now = Date.now()): InvoiceStatus =>
	inv.paid ? 'paid' : now >= ms(addDays(inv.due, 1)) ? 'overdue' : 'open';

export const invoiceCsv = (list: Invoice[], now = Date.now()) => {
	const rows = [
		['Invoice', 'Period start', 'Period end', 'Issued', 'Due', 'Seats', 'Storage GiB', 'Amount USD', 'Status', 'Paid on', 'Reference'],
		...list.map((i) => [
			i.number,
			i.start,
			i.end,
			i.issued,
			i.due,
			String(i.seats.length),
			String(i.storageGiB),
			`${Math.floor(i.cents / 100)}.${String(i.cents % 100).padStart(2, '0')}`,
			invoiceStatus(i, now),
			i.paid?.on ?? '',
			i.paid?.reference ?? ''
		])
	];
	return rows.map((r) => r.map((v) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v)).join(',')).join('\n');
};