// 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 { const out: Record = {}; 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, 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; }