oweme/packages/core/test/core.test.ts
agent 9981cf9a9a Several payers: clearer on phones, plus tests
The editor already supported several payers ("Several people" in Paid by);
this polishes it after checking it at 390x844 and 360x780 (Czech):

- Expense list: "Paid by 3 people" was truncated on phones; now "3 payers"
  (proper Czech plurals: plátce / plátci / plátců).
- Empty payer boxes show the unassigned remainder as a placeholder.
- A green "Adds up to the total" line confirms when the payers match.
- Tests: core balance + settle-up for a car bought by three people, a
  foreign-currency multi-payer case, and an e2e flow (remaining, over,
  validation error, save, balances).
- SPEC: describe the actual several-payers UI (no "add payer" button).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gX9UJk6BEyaJJwiWPc
2026-11-18 19:23:19 +00:00

277 lines
13 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.

import { describe, expect, it } from 'vitest';
import { ACTIVE_CURRENCIES, isActiveCurrency } from '../src/index.ts';
import {
allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence,
occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats,
type EventBody, type Expense, type GroupEvent,
} from '../src/index.ts';
let seq = 0;
function ev(body: EventBody, actor: string | null = null, id?: string): GroupEvent {
seq += 1;
return { ...body, v: 1, actor, at: `2026-10-01T00:00:${String(seq % 60).padStart(2, '0')}Z`, id: id ?? `e${seq}`, seq, deviceId: 'd' } as GroupEvent;
}
function expense(over: Partial<Expense> = {}): Expense {
return {
id: 'x1', kind: 'expense', title: 'Dinner', category: 'food', date: '2026-10-01',
currency: 'CZK', amount: 10000, rate: '1', rateSource: 'manual',
payers: [{ member: 'a', amount: 10000 }],
split: { mode: 'equal', entries: [{ member: 'a', value: 1 }, { member: 'b', value: 1 }, { member: 'c', value: 1 }] },
note: '', photo: null, ...over,
};
}
function baseGroup(): GroupEvent[] {
return [
ev({ type: 'group.created', data: { name: 'Trip', baseCurrency: 'CZK', icon: '🏔️' } }),
ev({ type: 'member.added', data: { id: 'a', name: 'Anna', color: '' } }),
ev({ type: 'member.added', data: { id: 'b', name: 'Petr', color: '' } }),
ev({ type: 'member.added', data: { id: 'c', name: 'Jana', color: '' } }),
];
}
describe('allocate', () => {
it('splits 100.00 three ways as 33.34 / 33.33 / 33.33', () => {
expect(allocate(10000, [1, 1, 1])).toEqual([3334, 3333, 3333]);
});
it('gives leftovers to the largest remainders, ties to the earlier index', () => {
expect(allocate(10, [1, 1, 1, 1])).toEqual([3, 3, 2, 2]);
expect(allocate(100, [1, 2])).toEqual([33, 67]);
});
it('always sums to the total', () => {
for (let t = 1; t < 500; t += 7) {
const w = [3, 0, 7, 1, 13];
expect(allocate(t, w).reduce((a, b) => a + b, 0)).toBe(t);
}
});
});
describe('convert', () => {
it('converts EUR to CZK with the stored rate', () => {
expect(convert(12050, 'EUR', 'CZK', '25.214')).toBe(303829); // 120.50 × 25.214 = 3038.287 → 3038.29
});
it('handles differing exponents', () => {
expect(convert(1000, 'JPY', 'CZK', '0.1567')).toBe(15670); // ¥1000 → 156.70 Kč
expect(convert(100, 'CZK', 'JPY', '6.38')).toBe(6); // 1 Kč → ¥6.38 → ¥6
});
it('rounds half to even', () => {
expect(convert(1, 'EUR', 'CZK', '0.5')).toBe(0); // 0.005 → 0.00
expect(convert(3, 'EUR', 'CZK', '0.5')).toBe(2); // 0.015 → 0.02
});
});
describe('parseAmount / toDecimalString', () => {
it('accepts comma or dot decimals and grouping', () => {
expect(parseAmount('12,5', 'CZK')).toBe(1250);
expect(parseAmount('1 234,50', 'CZK')).toBe(123450);
expect(parseAmount('1.234,5', 'EUR')).toBe(123450);
expect(parseAmount('1,234.56', 'USD')).toBe(123456);
expect(parseAmount('1.234', 'EUR')).toBe(123400);
expect(parseAmount('1.234', 'BHD')).toBe(1234);
expect(parseAmount('500', 'JPY')).toBe(500);
});
it('rejects junk, zero and too many decimals', () => {
for (const s of ['', 'abc', '0', '1.234.5', '12.3456', '-5', '1e5']) expect(parseAmount(s, 'EUR')).toBeNull();
expect(parseAmount('1.5', 'JPY')).toBeNull();
});
it('formats minor units', () => {
expect(toDecimalString(5, 'EUR')).toBe('0.05');
expect(toDecimalString(-123450, 'CZK')).toBe('-1234.50');
expect(toDecimalString(500, 'JPY')).toBe('500');
});
it('rateToString keeps 6 significant digits', () => {
expect(rateToString(25.21399999)).toBe('25.214');
expect(rateToString(0.0412345678)).toBe('0.0412346');
expect(rateToString(1)).toBe('1');
});
});
describe('inBase', () => {
it('paid and owed each sum to the converted total', () => {
const e = expense({ currency: 'EUR', amount: 1000, rate: '25.333', split: { mode: 'shares', entries: [{ member: 'a', value: 1 }, { member: 'b', value: 2 }, { member: 'c', value: 0 }] } });
const b = inBase(e, 'CZK');
expect(b.total).toBe(25333);
expect(Object.values(b.owed).reduce((x, y) => x + y)).toBe(b.total);
expect(Object.values(b.paid).reduce((x, y) => x + y)).toBe(b.total);
expect(b.owed.c).toBeUndefined();
});
it('supports exact and percent splits', () => {
expect(inBase(expense({ split: { mode: 'exact', entries: [{ member: 'a', value: 2500 }, { member: 'b', value: 7500 }] } }), 'CZK').owed).toEqual({ a: 2500, b: 7500 });
expect(inBase(expense({ split: { mode: 'percent', entries: [{ member: 'a', value: 3333 }, { member: 'b', value: 6667 }] } }), 'CZK').owed).toEqual({ a: 3333, b: 6667 });
});
});
describe('replay', () => {
it('builds members and balances that sum to zero', () => {
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense() })]);
const bal = balances(state);
expect(bal).toEqual({ a: 6666, b: -3333, c: -3333 });
expect(Object.values(bal).reduce((x, y) => x + y)).toBe(0);
});
it('credits each of several payers (three people buy a car together)', () => {
const car = expense({
amount: 30000000,
payers: [{ member: 'a', amount: 10000000 }, { member: 'b', amount: 15000000 }, { member: 'c', amount: 5000000 }],
});
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: car })]);
const bal = balances(state);
expect(bal).toEqual({ a: 0, b: 5000000, c: -5000000 });
expect(settleUp(bal, ['a', 'b', 'c'])).toEqual([{ from: 'c', to: 'b', amount: 5000000 }]);
});
it('credits several payers in a foreign currency, summing exactly to the base total', () => {
// €100.01 at 25.1 = 2510.251 Kč → 2510.25; payer and share vectors must each sum to it.
const e = expense({
currency: 'EUR', amount: 10001, rate: '25.1',
payers: [{ member: 'a', amount: 5001 }, { member: 'b', amount: 5000 }],
});
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: e })]);
const bal = balances(state);
expect(Object.values(bal).reduce((x, y) => x + y)).toBe(0);
expect(bal.a).toBeGreaterThan(0);
expect(bal.b).toBeGreaterThan(0);
expect(bal.c).toBeLessThan(0);
});
it('ignores invalid expenses (bad sums, unknown members)', () => {
const bad1 = expense({ id: 'x2', payers: [{ member: 'a', amount: 1 }] });
const bad2 = expense({ id: 'x3', split: { mode: 'equal', entries: [{ member: 'zzz', value: 1 }] } });
const r = replay([...baseGroup(), ev({ type: 'expense.created', data: bad1 }), ev({ type: 'expense.created', data: bad2 })]);
expect(Object.keys(r.state.expenses)).toEqual([]);
expect(r.activity.filter((a) => a.ignored)).toHaveLength(2);
});
it('last writer wins, and delete/restore toggle', () => {
const evs = [
...baseGroup(),
ev({ type: 'expense.created', data: expense() }),
ev({ type: 'expense.updated', data: expense({ title: 'Lunch' }) }),
ev({ type: 'expense.deleted', data: { id: 'x1' } }),
];
let { state } = replay(evs);
expect(state.expenses.x1.expense.title).toBe('Lunch');
expect(state.expenses.x1.deleted).toBe(true);
expect(balances(state)).toEqual({ a: 0, b: 0, c: 0 });
({ state } = replay([...evs, ev({ type: 'expense.restored', data: { id: 'x1' } })]));
expect(state.expenses.x1.deleted).toBe(false);
});
it('expense.created is first-wins (recurring dedupe)', () => {
const { state } = replay([
...baseGroup(),
ev({ type: 'expense.created', data: expense({ title: 'first' }) }),
ev({ type: 'expense.created', data: expense({ title: 'second' }) }),
]);
expect(state.expenses.x1.expense.title).toBe('first');
});
it('locks the base currency once there are expenses', () => {
const evs = [...baseGroup(), ev({ type: 'group.updated', data: { baseCurrency: 'EUR' } })];
expect(replay(evs).state.group!.baseCurrency).toBe('EUR');
const locked = [...baseGroup(), ev({ type: 'expense.created', data: expense() }), ev({ type: 'group.updated', data: { baseCurrency: 'EUR' } })];
expect(replay(locked).state.group!.baseCurrency).toBe('CZK');
});
it('sets a default category and ignores invalid ones', () => {
const set = [...baseGroup(), ev({ type: 'group.updated', data: { defaultCategory: 'travel' } })];
expect(replay(set).state.group!.defaultCategory).toBe('travel');
const bad = [...set, ev({ type: 'group.updated', data: { defaultCategory: 'transfer' as never, name: 'Renamed' } })];
const g = replay(bad).state.group!;
expect(g.defaultCategory).toBe('travel');
expect(g.name).not.toBe('Renamed'); // the whole invalid event is ignored
});
it('revert restores an earlier state, and can itself be reverted', () => {
const evs = [...baseGroup(), ev({ type: 'expense.created', data: expense() }, 'a', 'keep')];
evs.push(ev({ type: 'expense.updated', data: expense({ amount: 99900, payers: [{ member: 'a', amount: 99900 }] }) }, 'b', 'vandal'));
evs.push(ev({ type: 'member.added', data: { id: 'd', name: 'Dan', color: '' } }));
evs.push(ev({ type: 'revert', data: { targetId: 'keep' } }, 'a', 'rw'));
let r = replay(evs);
expect(r.state.expenses.x1.expense.amount).toBe(10000);
expect(r.state.members.map((m) => m.id)).toEqual(['a', 'b', 'c']);
expect(r.activity).toHaveLength(evs.length); // nothing erased from history
// Undo the rewind: revert to the event just before it.
const before = evs[evs.length - 2].id;
evs.push(ev({ type: 'revert', data: { targetId: before } }));
r = replay(evs);
expect(r.state.expenses.x1.expense.amount).toBe(99900);
expect(r.state.members).toHaveLength(4);
});
it('logOrder puts synced events by seq, then pending ones', () => {
const a = ev({ type: 'member.added', data: { id: 'q', name: 'Q', color: '' } });
const b = ev({ type: 'member.added', data: { id: 'r', name: 'R', color: '' } });
const p = { ...b, id: 'p1', seq: null };
expect(logOrder([b, a], [p, { ...a }]).map((e) => e.id)).toEqual([a.id, b.id, 'p1']);
});
});
describe('settleUp', () => {
it('produces transfers that zero all balances', () => {
const bal = { a: 5000, b: -2000, c: -2000, d: -1000 };
const t = settleUp(bal, ['a', 'b', 'c', 'd']);
expect(t).toEqual([
{ from: 'b', to: 'a', amount: 2000 },
{ from: 'c', to: 'a', amount: 2000 },
{ from: 'd', to: 'a', amount: 1000 },
]);
});
it('uses at most n-1 transfers', () => {
const bal = { a: 700, b: 300, c: -400, d: -600 };
const t = settleUp(bal, ['a', 'b', 'c', 'd']);
expect(t.length).toBeLessThanOrEqual(3);
const net: Record<string, number> = { ...bal };
for (const x of t) (net[x.from] += x.amount), (net[x.to] -= x.amount);
expect(Object.values(net).every((v) => v === 0)).toBe(true);
});
});
describe('recurring', () => {
it('clamps monthly occurrences to the month end', () => {
const rule = { freq: 'monthly' as const, interval: 1, start: '2026-01-31', end: null };
expect([0, 1, 2, 3].map((n) => nthOccurrence(rule, n))).toEqual(['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30']);
});
it('creates missing occurrences once, and deleted ones stay deleted', () => {
const { template: _t, ...rest } = { template: null, ...expense() };
const tpl = { ...rest } as Partial<Expense>;
delete tpl.id; delete tpl.date; delete tpl.photo;
const rec = { id: 'r1', template: tpl as any, rule: { freq: 'weekly' as const, interval: 1, start: '2026-09-01', end: null } };
const evs = [...baseGroup(), ev({ type: 'recurring.created', data: rec })];
let { state } = replay(evs);
const due = dueOccurrences(state, '2026-09-20');
expect(due.map((e) => e.date)).toEqual(['2026-09-01', '2026-09-08', '2026-09-15']);
for (const e of due) evs.push(ev({ type: 'expense.created', data: e }));
evs.push(ev({ type: 'expense.deleted', data: { id: occurrenceId('r1', '2026-09-08') } }));
({ state } = replay(evs));
expect(dueOccurrences(state, '2026-09-20')).toEqual([]);
expect(dueOccurrences(state, '2026-09-22').map((e) => e.date)).toEqual(['2026-09-22']);
});
});
describe('stats and csv', () => {
it('excludes transfers from stats', () => {
const t = expense({ id: 't1', kind: 'transfer', category: 'transfer', amount: 500, payers: [{ member: 'b', amount: 500 }], split: { mode: 'equal', entries: [{ member: 'a', value: 1 }] } });
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense() }), ev({ type: 'expense.created', data: t })]);
const st = computeStats(state, null, null);
expect(st.total).toBe(10000);
expect(st.byCategory).toEqual([{ category: 'food', amount: 10000 }]);
expect(balances(state)).toEqual({ a: 6166, b: -2833, c: -3333 });
});
it('escapes CSV and neutralises formulas', () => {
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense({ title: '=HYPERLINK("x")' }) })]);
expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`);
});
});
describe('ACTIVE_CURRENCIES', () => {
it('is sorted, unique ISO codes without replaced currencies', () => {
expect([...ACTIVE_CURRENCIES].sort()).toEqual(ACTIVE_CURRENCIES);
expect(new Set(ACTIVE_CURRENCIES).size).toBe(ACTIVE_CURRENCIES.length);
expect(ACTIVE_CURRENCIES.every((c) => /^[A-Z]{3}$/.test(c))).toBe(true);
for (const gone of ['ANG', 'BGN', 'CUC', 'HRK', 'SLL', 'ZWL', 'DEM', 'XDR']) expect(isActiveCurrency(gone)).toBe(false);
for (const c of ['ALL', 'CZK', 'EUR', 'XCG', 'ZWG']) expect(isActiveCurrency(c)).toBe(true);
});
});