// 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'; }