oweme/packages/core/src/settle.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

47 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Balances and settle-up suggestions (SPEC.md §5.3–5.4).
import { inBase } from './expense.ts';
import type { GroupState } from './types.ts';
/** member id → balance in base minor units (positive = is owed money). */
export function balances(s: GroupState): Record<string, number> {
const out: Record<string, number> = {};
for (const m of s.members) out[m.id] = 0;
if (!s.group) return out;
for (const r of Object.values(s.expenses)) {
if (r.deleted) continue;
const b = inBase(r.expense, s.group.baseCurrency);
for (const [id, v] of Object.entries(b.paid)) out[id] = (out[id] ?? 0) + v;
for (const [id, v] of Object.entries(b.owed)) out[id] = (out[id] ?? 0) - v;
}
return out;
}
export interface Transfer {
from: string;
to: string;
amount: number;
}
/**
* Greedy settle-up: repeatedly pay the largest creditor from the largest
* debtor. At most n − 1 transfers. Ties go to the earlier member, so every
* client suggests the same transfers.
*/
export function settleUp(bal: Record<string, number>, memberOrder: string[]): Transfer[] {
const idx = new Map(memberOrder.map((id, i) => [id, i]));
const rank = (id: string) => idx.get(id) ?? Number.MAX_SAFE_INTEGER;
const debtors = Object.entries(bal).filter(([, v]) => v < 0).map(([id, v]) => ({ id, v: -v }));
const creditors = Object.entries(bal).filter(([, v]) => v > 0).map(([id, v]) => ({ id, v }));
const pick = (xs: { id: string; v: number }[]) =>
xs.reduce((best, x) => (x.v > best.v || (x.v === best.v && rank(x.id) < rank(best.id)) ? x : best));
const out: Transfer[] = [];
while (debtors.some((d) => d.v > 0) && creditors.some((c) => c.v > 0)) {
const d = pick(debtors.filter((x) => x.v > 0));
const c = pick(creditors.filter((x) => x.v > 0));
const amount = Math.min(d.v, c.v);
out.push({ from: d.id, to: c.id, amount });
d.v -= amount;
c.v -= amount;
}
return out;
}