oweme/packages/core/src/expense.ts
agent c2043b86bc Add core package: money math, event replay, settle-up, recurring, stats, CSV
Deterministic integer/BigInt arithmetic so every client computes identical
balances; replay validates events and supports rewind via snapshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:30:09 +00:00

117 lines
4.5 KiB
TypeScript

// Validating an expense and turning it into per-member amounts.
import { allocate, convert, isCurrencyCode, isValidRate, MAX_AMOUNT } from './money.ts';
import { CATEGORIES, type Expense, type Member } from './types.ts';
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const isInt = (n: unknown): n is number => Number.isSafeInteger(n);
export function isValidDate(d: unknown): d is string {
if (typeof d !== 'string' || !DATE_RE.test(d)) return false;
const t = Date.parse(`${d}T00:00:00Z`);
return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === d;
}
/**
* Returns null if the expense is valid for the given members, otherwise a
* short reason. Events failing this are ignored on replay, so a buggy or
* malicious client can't corrupt everyone's balances.
*/
export function validateExpense(e: Expense, members: Member[]): string | null {
const ids = new Set(members.map((m) => m.id));
if (!e || typeof e !== 'object') return 'not an object';
if (typeof e.id !== 'string' || !e.id) return 'id';
if (e.kind !== 'expense' && e.kind !== 'transfer') return 'kind';
if (typeof e.title !== 'string' || e.title.length > 200) return 'title';
if (e.category !== 'transfer' && !(CATEGORIES as readonly string[]).includes(e.category)) return 'category';
if (!isValidDate(e.date)) return 'date';
if (!isCurrencyCode(e.currency)) return 'currency';
if (!isInt(e.amount) || e.amount <= 0 || e.amount > MAX_AMOUNT) return 'amount';
if (!isValidRate(e.rate)) return 'rate';
if (typeof e.note !== 'string' || e.note.length > 2000) return 'note';
if (!Array.isArray(e.payers) || e.payers.length === 0) return 'payers';
const payerIds = new Set<string>();
let paid = 0;
for (const p of e.payers) {
if (!ids.has(p.member) || payerIds.has(p.member)) return 'payer member';
if (!isInt(p.amount) || p.amount <= 0) return 'payer amount';
payerIds.add(p.member);
paid += p.amount;
}
if (paid !== e.amount) return 'payers sum';
const { mode, entries } = e.split ?? {};
if (!Array.isArray(entries) || entries.length === 0) return 'split';
const seen = new Set<string>();
let sum = 0;
for (const s of entries) {
if (!ids.has(s.member) || seen.has(s.member)) return 'split member';
if (!isInt(s.value) || s.value < 0) return 'split value';
seen.add(s.member);
sum += s.value;
}
switch (mode) {
case 'equal':
if (entries.some((s) => s.value > 1) || sum === 0) return 'equal';
break;
case 'shares':
if (sum === 0 || sum > 1_000_000) return 'shares';
break;
case 'exact':
if (sum !== e.amount) return 'exact sum';
break;
case 'percent':
if (sum !== 10000) return 'percent sum';
break;
default:
return 'mode';
}
if (e.kind === 'transfer' && entries.filter((s) => s.value > 0).length !== 1) return 'transfer';
if (e.photo !== null) {
const p = e.photo;
if (!p || typeof p.blobId !== 'string' || typeof p.thumbBlobId !== 'string') return 'photo';
}
return null;
}
/** What each member owes, in minor units of the expense's own currency. */
export function owedOriginal(e: Expense): Record<string, number> {
const entries = e.split.entries;
const parts =
e.split.mode === 'exact'
? entries.map((s) => s.value)
: allocate(e.amount, entries.map((s) => s.value));
const out: Record<string, number> = {};
entries.forEach((s, i) => {
if (parts[i] !== 0) out[s.member] = parts[i];
});
return out;
}
export interface ExpenseInBase {
/** total in base currency minor units */
total: number;
paid: Record<string, number>;
owed: Record<string, number>;
}
/**
* Express an expense in the base currency. The total is converted once, and
* both the payer vector and the split vector are re-allocated onto it, so
* paid and owed each sum to exactly `total`.
*/
export function inBase(e: Expense, baseCurrency: string): ExpenseInBase {
const total = convert(e.amount, e.currency, baseCurrency, e.rate);
const owedOrig = owedOriginal(e);
const owedIds = Object.keys(owedOrig);
const paidIds = e.payers.map((p) => p.member);
const sameCurrency = e.currency === baseCurrency;
const paidParts = sameCurrency ? e.payers.map((p) => p.amount) : allocate(total, e.payers.map((p) => p.amount));
const owedParts = sameCurrency ? owedIds.map((id) => owedOrig[id]) : allocate(total, owedIds.map((id) => owedOrig[id]));
const paid: Record<string, number> = {};
const owed: Record<string, number> = {};
paidIds.forEach((id, i) => (paid[id] = paidParts[i]));
owedIds.forEach((id, i) => (owed[id] = owedParts[i]));
return { total, paid, owed };
}