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
This commit is contained in:
parent
747e49f46a
commit
c2043b86bc
15 changed files with 2355 additions and 0 deletions
46
packages/core/src/csv.ts
Normal file
46
packages/core/src/csv.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
// CSV export (SPEC.md §7.6). Plain decimal numbers with "." so spreadsheets
|
||||
// in any locale can import them.
|
||||
import { inBase } from './expense.ts';
|
||||
import { toDecimalString } from './money.ts';
|
||||
import { balances } from './settle.ts';
|
||||
import type { GroupState } from './types.ts';
|
||||
|
||||
function cell(v: string | number): string {
|
||||
const s = String(v);
|
||||
// Neutralise spreadsheet formula injection, then quote if needed.
|
||||
const safe = /^[=+\-@\t\r]/.test(s) && typeof v === 'string' ? `'${s}` : s;
|
||||
return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
|
||||
}
|
||||
|
||||
const row = (cells: (string | number)[]) => cells.map(cell).join(',');
|
||||
|
||||
export function expensesCsv(s: GroupState): string {
|
||||
const base = s.group?.baseCurrency ?? 'EUR';
|
||||
const name = (id: string) => s.members.find((m) => m.id === id)?.name ?? id;
|
||||
const header = [
|
||||
'date', 'title', 'type', 'category', 'currency', 'amount', 'rate', `amount_${base}`, 'paid_by', 'note',
|
||||
...s.members.map((m) => `share_${base}:${m.name}`),
|
||||
];
|
||||
const lines = [row(header)];
|
||||
const records = Object.values(s.expenses)
|
||||
.filter((r) => !r.deleted)
|
||||
.sort((a, b) => a.expense.date.localeCompare(b.expense.date));
|
||||
for (const { expense: e } of records) {
|
||||
const b = inBase(e, base);
|
||||
lines.push(row([
|
||||
e.date, e.title, e.kind, e.category, e.currency, toDecimalString(e.amount, e.currency),
|
||||
e.currency === base ? '1' : e.rate, toDecimalString(b.total, base),
|
||||
e.payers.map((p) => name(p.member)).join(' + '), e.note,
|
||||
...s.members.map((m) => toDecimalString(b.owed[m.id] ?? 0, base)),
|
||||
]));
|
||||
}
|
||||
return lines.join('\r\n') + '\r\n';
|
||||
}
|
||||
|
||||
export function balancesCsv(s: GroupState): string {
|
||||
const base = s.group?.baseCurrency ?? 'EUR';
|
||||
const bal = balances(s);
|
||||
const lines = [row(['member', `balance_${base}`])];
|
||||
for (const m of s.members) lines.push(row([m.name, toDecimalString(bal[m.id] ?? 0, base)]));
|
||||
return lines.join('\r\n') + '\r\n';
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue