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
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
.env
|
||||
deploy/.env
|
||||
test-results/
|
||||
playwright-report/
|
||||
*.log
|
||||
1241
package-lock.json
generated
Normal file
1241
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
22
package.json
Normal file
22
package.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"name": "oweme",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"workspaces": ["packages/core", "apps/web"],
|
||||
"engines": { "node": ">=24" },
|
||||
"scripts": {
|
||||
"dev": "node scripts/dev.mjs",
|
||||
"build": "npm run build -w apps/web",
|
||||
"test": "npm run test:core && npm run test:server",
|
||||
"test:core": "vitest run --root packages/core",
|
||||
"test:server": "node --test --disable-warning=ExperimentalWarning apps/server/test/",
|
||||
"test:e2e": "playwright test",
|
||||
"check": "tsc -p packages/core && tsc -p apps/server && npm run check -w apps/web"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.63.0",
|
||||
"@types/node": "24.10.1",
|
||||
"typescript": "6.0.2",
|
||||
"vitest": "5.0.2"
|
||||
}
|
||||
}
|
||||
6
packages/core/package.json
Normal file
6
packages/core/package.json
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"name": "@oweme/core",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": { ".": "./src/index.ts" }
|
||||
}
|
||||
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';
|
||||
}
|
||||
117
packages/core/src/expense.ts
Normal file
117
packages/core/src/expense.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
// Validating an expense and turning it into per-member amounts.
|
||||
import { allocate, convert, isCurrencyCode, isValidRate, MAX_AMOUNT } from './money.ts';
|
||||
import { CATEGORIES, type Expense, type Member } from './types.ts';
|
||||
|
||||
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const isInt = (n: unknown): n is number => Number.isSafeInteger(n);
|
||||
|
||||
export function isValidDate(d: unknown): d is string {
|
||||
if (typeof d !== 'string' || !DATE_RE.test(d)) return false;
|
||||
const t = Date.parse(`${d}T00:00:00Z`);
|
||||
return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === d;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns null if the expense is valid for the given members, otherwise a
|
||||
* short reason. Events failing this are ignored on replay, so a buggy or
|
||||
* malicious client can't corrupt everyone's balances.
|
||||
*/
|
||||
export function validateExpense(e: Expense, members: Member[]): string | null {
|
||||
const ids = new Set(members.map((m) => m.id));
|
||||
if (!e || typeof e !== 'object') return 'not an object';
|
||||
if (typeof e.id !== 'string' || !e.id) return 'id';
|
||||
if (e.kind !== 'expense' && e.kind !== 'transfer') return 'kind';
|
||||
if (typeof e.title !== 'string' || e.title.length > 200) return 'title';
|
||||
if (e.category !== 'transfer' && !(CATEGORIES as readonly string[]).includes(e.category)) return 'category';
|
||||
if (!isValidDate(e.date)) return 'date';
|
||||
if (!isCurrencyCode(e.currency)) return 'currency';
|
||||
if (!isInt(e.amount) || e.amount <= 0 || e.amount > MAX_AMOUNT) return 'amount';
|
||||
if (!isValidRate(e.rate)) return 'rate';
|
||||
if (typeof e.note !== 'string' || e.note.length > 2000) return 'note';
|
||||
|
||||
if (!Array.isArray(e.payers) || e.payers.length === 0) return 'payers';
|
||||
const payerIds = new Set<string>();
|
||||
let paid = 0;
|
||||
for (const p of e.payers) {
|
||||
if (!ids.has(p.member) || payerIds.has(p.member)) return 'payer member';
|
||||
if (!isInt(p.amount) || p.amount <= 0) return 'payer amount';
|
||||
payerIds.add(p.member);
|
||||
paid += p.amount;
|
||||
}
|
||||
if (paid !== e.amount) return 'payers sum';
|
||||
|
||||
const { mode, entries } = e.split ?? {};
|
||||
if (!Array.isArray(entries) || entries.length === 0) return 'split';
|
||||
const seen = new Set<string>();
|
||||
let sum = 0;
|
||||
for (const s of entries) {
|
||||
if (!ids.has(s.member) || seen.has(s.member)) return 'split member';
|
||||
if (!isInt(s.value) || s.value < 0) return 'split value';
|
||||
seen.add(s.member);
|
||||
sum += s.value;
|
||||
}
|
||||
switch (mode) {
|
||||
case 'equal':
|
||||
if (entries.some((s) => s.value > 1) || sum === 0) return 'equal';
|
||||
break;
|
||||
case 'shares':
|
||||
if (sum === 0 || sum > 1_000_000) return 'shares';
|
||||
break;
|
||||
case 'exact':
|
||||
if (sum !== e.amount) return 'exact sum';
|
||||
break;
|
||||
case 'percent':
|
||||
if (sum !== 10000) return 'percent sum';
|
||||
break;
|
||||
default:
|
||||
return 'mode';
|
||||
}
|
||||
if (e.kind === 'transfer' && entries.filter((s) => s.value > 0).length !== 1) return 'transfer';
|
||||
|
||||
if (e.photo !== null) {
|
||||
const p = e.photo;
|
||||
if (!p || typeof p.blobId !== 'string' || typeof p.thumbBlobId !== 'string') return 'photo';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What each member owes, in minor units of the expense's own currency. */
|
||||
export function owedOriginal(e: Expense): Record<string, number> {
|
||||
const entries = e.split.entries;
|
||||
const parts =
|
||||
e.split.mode === 'exact'
|
||||
? entries.map((s) => s.value)
|
||||
: allocate(e.amount, entries.map((s) => s.value));
|
||||
const out: Record<string, number> = {};
|
||||
entries.forEach((s, i) => {
|
||||
if (parts[i] !== 0) out[s.member] = parts[i];
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ExpenseInBase {
|
||||
/** total in base currency minor units */
|
||||
total: number;
|
||||
paid: Record<string, number>;
|
||||
owed: Record<string, number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Express an expense in the base currency. The total is converted once, and
|
||||
* both the payer vector and the split vector are re-allocated onto it, so
|
||||
* paid and owed each sum to exactly `total`.
|
||||
*/
|
||||
export function inBase(e: Expense, baseCurrency: string): ExpenseInBase {
|
||||
const total = convert(e.amount, e.currency, baseCurrency, e.rate);
|
||||
const owedOrig = owedOriginal(e);
|
||||
const owedIds = Object.keys(owedOrig);
|
||||
const paidIds = e.payers.map((p) => p.member);
|
||||
const sameCurrency = e.currency === baseCurrency;
|
||||
const paidParts = sameCurrency ? e.payers.map((p) => p.amount) : allocate(total, e.payers.map((p) => p.amount));
|
||||
const owedParts = sameCurrency ? owedIds.map((id) => owedOrig[id]) : allocate(total, owedIds.map((id) => owedOrig[id]));
|
||||
const paid: Record<string, number> = {};
|
||||
const owed: Record<string, number> = {};
|
||||
paidIds.forEach((id, i) => (paid[id] = paidParts[i]));
|
||||
owedIds.forEach((id, i) => (owed[id] = owedParts[i]));
|
||||
return { total, paid, owed };
|
||||
}
|
||||
8
packages/core/src/index.ts
Normal file
8
packages/core/src/index.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export * from './types.ts';
|
||||
export * from './money.ts';
|
||||
export * from './expense.ts';
|
||||
export * from './replay.ts';
|
||||
export * from './settle.ts';
|
||||
export * from './recurring.ts';
|
||||
export * from './stats.ts';
|
||||
export * from './csv.ts';
|
||||
134
packages/core/src/money.ts
Normal file
134
packages/core/src/money.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// Integer money math. Every client must produce identical numbers from the
|
||||
// same events, so nothing here uses floating point: amounts are integers in
|
||||
// minor units, rates are exact decimal strings, and intermediate values are
|
||||
// BigInt.
|
||||
|
||||
/** ISO 4217 exponents that differ from the default of 2. Hardcoded rather
|
||||
* than read from Intl, because Intl data can differ between browsers. */
|
||||
const EXPONENTS: Record<string, number> = {
|
||||
BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0,
|
||||
RWF: 0, UGX: 0, UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
|
||||
BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3,
|
||||
};
|
||||
|
||||
export const MAX_AMOUNT = 1e13; // minor units; keeps everything well inside 2^53
|
||||
|
||||
export function isCurrencyCode(code: unknown): code is string {
|
||||
return typeof code === 'string' && /^[A-Z]{3}$/.test(code);
|
||||
}
|
||||
|
||||
export function exponent(currency: string): number {
|
||||
return EXPONENTS[currency] ?? 2;
|
||||
}
|
||||
|
||||
const RATE_RE = /^(\d{1,12})(?:\.(\d{1,12}))?$/;
|
||||
|
||||
/** A rate is a positive decimal string, e.g. "25.214". */
|
||||
export function isValidRate(rate: unknown): rate is string {
|
||||
if (typeof rate !== 'string') return false;
|
||||
const m = RATE_RE.exec(rate);
|
||||
if (!m) return false;
|
||||
return BigInt(m[1] + (m[2] ?? '')) > 0n;
|
||||
}
|
||||
|
||||
function parseRate(rate: string): { num: bigint; scale: number } {
|
||||
const m = RATE_RE.exec(rate);
|
||||
if (!m) throw new Error(`invalid rate ${rate}`);
|
||||
const frac = m[2] ?? '';
|
||||
return { num: BigInt(m[1] + frac), scale: frac.length };
|
||||
}
|
||||
|
||||
/** n / d rounded half to even, for n >= 0, d > 0. */
|
||||
function divRoundHalfEven(n: bigint, d: bigint): bigint {
|
||||
const q = n / d;
|
||||
const r = n % d;
|
||||
const twice = r * 2n;
|
||||
if (twice > d || (twice === d && q % 2n === 1n)) return q + 1n;
|
||||
return q;
|
||||
}
|
||||
|
||||
/** Convert an amount (minor units of `from`) into minor units of `to`. */
|
||||
export function convert(amount: number, from: string, to: string, rate: string): number {
|
||||
if (from === to) return amount;
|
||||
const { num, scale } = parseRate(rate);
|
||||
const n = BigInt(amount) * num * 10n ** BigInt(exponent(to));
|
||||
const d = 10n ** BigInt(scale + exponent(from));
|
||||
return Number(divRoundHalfEven(n, d));
|
||||
}
|
||||
|
||||
/**
|
||||
* Split `total` into integers proportional to `weights` that sum exactly to
|
||||
* `total`. Each part is floored, then the leftover units go one at a time to
|
||||
* the largest remainders; ties go to the lower index (member order).
|
||||
*/
|
||||
export function allocate(total: number, weights: number[]): number[] {
|
||||
const W = weights.reduce((a, w) => a + BigInt(w), 0n);
|
||||
if (W <= 0n) throw new Error('allocate: weights must sum to > 0');
|
||||
const T = BigInt(total);
|
||||
const parts = weights.map((w) => {
|
||||
const raw = T * BigInt(w);
|
||||
return { q: raw / W, r: raw % W };
|
||||
});
|
||||
let leftover = T - parts.reduce((a, p) => a + p.q, 0n);
|
||||
const order = parts
|
||||
.map((p, i) => ({ r: p.r, i }))
|
||||
.sort((a, b) => (a.r === b.r ? a.i - b.i : a.r > b.r ? -1 : 1));
|
||||
for (const { i } of order) {
|
||||
if (leftover <= 0n) break;
|
||||
parts[i].q += 1n;
|
||||
leftover -= 1n;
|
||||
}
|
||||
return parts.map((p) => Number(p.q));
|
||||
}
|
||||
|
||||
/** Minor units → plain decimal string ("1234.50"), no grouping. */
|
||||
export function toDecimalString(minor: number, currency: string): string {
|
||||
const e = exponent(currency);
|
||||
const neg = minor < 0;
|
||||
const s = String(Math.abs(minor)).padStart(e + 1, '0');
|
||||
const out = e === 0 ? s : `${s.slice(0, -e)}.${s.slice(-e)}`;
|
||||
return neg ? `-${out}` : out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse user input ("1 234,5", "1234.50", "12") into minor units.
|
||||
* Returns null for anything that isn't a positive number with at most the
|
||||
* currency's number of decimals.
|
||||
*/
|
||||
export function parseAmount(input: string, currency: string): number | null {
|
||||
const e = exponent(currency);
|
||||
const s = input.replace(/[\s\u00a0\u202f']/g, '');
|
||||
let intPart: string;
|
||||
let frac = '';
|
||||
const sep = Math.max(s.lastIndexOf('.'), s.lastIndexOf(','));
|
||||
const before = s.slice(0, sep);
|
||||
const after = s.slice(sep + 1);
|
||||
if (/^\d+$/.test(s)) {
|
||||
intPart = s;
|
||||
} else if (
|
||||
sep > 0 && !before.includes(s[sep]) && after.length >= 1 && after.length <= e && /^\d+$/.test(after) &&
|
||||
/^(\d{1,3}([.,]\d{3})*|\d+)$/.test(before)
|
||||
) {
|
||||
// "12,5" / "1.234,50": the last separator is the decimal point
|
||||
intPart = before.replace(/[.,]/g, '');
|
||||
frac = after;
|
||||
} else if (/^\d{1,3}([.,]\d{3})+$/.test(s)) {
|
||||
// "1.234" in a 2-decimal currency: grouping only
|
||||
intPart = s.replace(/[.,]/g, '');
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
const minor = Number(intPart + frac.padEnd(e, '0'));
|
||||
if (!Number.isSafeInteger(minor) || minor <= 0 || minor > MAX_AMOUNT) return null;
|
||||
return minor;
|
||||
}
|
||||
|
||||
/** Turn a float rate (from the rates API) into a stored decimal string with
|
||||
* 6 significant digits. Only used to prefill; the stored string is then exact. */
|
||||
export function rateToString(rate: number): string {
|
||||
if (!(rate > 0) || !Number.isFinite(rate)) throw new Error('bad rate');
|
||||
const digits = Math.max(0, 6 - Math.floor(Math.log10(rate)) - 1);
|
||||
let s = rate.toFixed(Math.min(12, digits));
|
||||
if (s.includes('.')) s = s.replace(/0+$/, '').replace(/\.$/, '');
|
||||
return s === '0' ? rate.toFixed(12).replace(/0+$/, '') : s;
|
||||
}
|
||||
69
packages/core/src/recurring.ts
Normal file
69
packages/core/src/recurring.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// Recurring expenses (SPEC.md §7.4). There's no server-side scheduler (the
|
||||
// server can't read templates), so whichever client opens the group first
|
||||
// creates the missing occurrences. Their ids are deterministic, so two
|
||||
// clients doing it at once produce the same expense and replay keeps one.
|
||||
import type { Expense, Recurring, RecurringRule, GroupState } from './types.ts';
|
||||
|
||||
const MAX_PER_RUN = 120;
|
||||
|
||||
function parse(d: string): Date {
|
||||
return new Date(`${d}T00:00:00Z`);
|
||||
}
|
||||
function fmt(d: Date): string {
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
function daysInMonth(y: number, m: number): number {
|
||||
return new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
|
||||
}
|
||||
|
||||
/** The n-th occurrence date (n = 0 is `start`). Monthly/yearly clamp to month end. */
|
||||
export function nthOccurrence(rule: RecurringRule, n: number): string {
|
||||
const start = parse(rule.start);
|
||||
if (rule.freq === 'weekly') return fmt(new Date(start.getTime() + n * rule.interval * 7 * 864e5));
|
||||
const months = rule.freq === 'monthly' ? n * rule.interval : n * rule.interval * 12;
|
||||
const y = start.getUTCFullYear() + Math.floor((start.getUTCMonth() + months) / 12);
|
||||
const m = (start.getUTCMonth() + months) % 12;
|
||||
const day = Math.min(start.getUTCDate(), daysInMonth(y, m));
|
||||
return fmt(new Date(Date.UTC(y, m, day)));
|
||||
}
|
||||
|
||||
/** All occurrence dates from start up to and including `today`. */
|
||||
export function occurrencesUntil(rule: RecurringRule, today: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (let n = 0; out.length < 10_000; n++) {
|
||||
const d = nthOccurrence(rule, n);
|
||||
if (d > today || (rule.end && d > rule.end)) break;
|
||||
out.push(d);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function occurrenceId(recurringId: string, date: string): string {
|
||||
return `rec-${recurringId}-${date}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Occurrences that are due but don't exist yet. Deleted occurrences count
|
||||
* as existing, so deleting one doesn't make it come back.
|
||||
*/
|
||||
export function dueOccurrences(s: GroupState, today: string): Expense[] {
|
||||
const out: Expense[] = [];
|
||||
for (const r of Object.values(s.recurring) as Recurring[]) {
|
||||
for (const date of occurrencesUntil(r.rule, today)) {
|
||||
const id = occurrenceId(r.id, date);
|
||||
if (s.expenses[id]) continue;
|
||||
out.push({ ...structuredClone(r.template), id, date, photo: null, recurringId: r.id });
|
||||
if (out.length >= MAX_PER_RUN) return out;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function nextOccurrence(rule: RecurringRule, today: string): string | null {
|
||||
for (let n = 0; n < 10_000; n++) {
|
||||
const d = nthOccurrence(rule, n);
|
||||
if (rule.end && d > rule.end) return null;
|
||||
if (d > today) return d;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
197
packages/core/src/replay.ts
Normal file
197
packages/core/src/replay.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
// Rebuild a group's state from its event log. Events are applied in log
|
||||
// order (server seq, then the local outbox); for the same entity the later
|
||||
// event wins. A `revert` event replaces the state with a snapshot taken right
|
||||
// after its target event; nothing is ever erased from the log. See SPEC.md §6.
|
||||
import { validateExpense } from './expense.ts';
|
||||
import { isCurrencyCode } from './money.ts';
|
||||
import type { Activity, GroupEvent, GroupState, Recurring } from './types.ts';
|
||||
|
||||
export function emptyState(): GroupState {
|
||||
return { group: null, members: [], expenses: {}, comments: {}, recurring: {} };
|
||||
}
|
||||
|
||||
const str = (v: unknown, max: number): v is string => typeof v === 'string' && v.length > 0 && v.length <= max;
|
||||
|
||||
function validRecurring(r: Recurring, s: GroupState): boolean {
|
||||
if (!r || !str(r.id, 100) || !r.rule || !r.template) return false;
|
||||
const { freq, interval, start, end } = r.rule;
|
||||
if (!['weekly', 'monthly', 'yearly'].includes(freq)) return false;
|
||||
if (!Number.isSafeInteger(interval) || interval < 1 || interval > 52) return false;
|
||||
const probe = { ...r.template, id: r.id, date: start, photo: null };
|
||||
if (validateExpense(probe, s.members) !== null) return false;
|
||||
return end === null || (typeof end === 'string' && end >= start);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one event to `s` in place. Returns the activity entry describing it.
|
||||
* `snapshots` provides states for `revert` targets.
|
||||
*/
|
||||
function apply(s: GroupState, ev: GroupEvent, snapshots: Map<string, GroupState>): { state: GroupState; activity: Activity } {
|
||||
const act: Activity = {
|
||||
eventId: ev.id, seq: ev.seq, at: ev.at, actor: ev.actor, type: ev.type,
|
||||
entityId: null, before: null, after: null,
|
||||
};
|
||||
const ignore = () => ((act.ignored = true), { state: s, activity: act });
|
||||
const member = (id: string) => s.members.find((m) => m.id === id);
|
||||
const hasExpenses = Object.keys(s.expenses).length > 0;
|
||||
|
||||
switch (ev.type) {
|
||||
case 'group.created': {
|
||||
const d = ev.data;
|
||||
if (s.group || !str(d?.name, 100) || !isCurrencyCode(d.baseCurrency)) return ignore();
|
||||
s.group = { name: d.name, baseCurrency: d.baseCurrency, icon: typeof d.icon === 'string' ? d.icon.slice(0, 16) : '' };
|
||||
act.after = { ...s.group };
|
||||
break;
|
||||
}
|
||||
case 'group.updated': {
|
||||
if (!s.group) return ignore();
|
||||
const d = ev.data ?? {};
|
||||
act.before = { ...s.group };
|
||||
if (d.name !== undefined) {
|
||||
if (!str(d.name, 100)) return ignore();
|
||||
s.group.name = d.name;
|
||||
}
|
||||
if (typeof d.icon === 'string') s.group.icon = d.icon.slice(0, 16);
|
||||
if (d.baseCurrency !== undefined && d.baseCurrency !== s.group.baseCurrency) {
|
||||
// Locked once the group has any expense (SPEC §7.1).
|
||||
if (hasExpenses || !isCurrencyCode(d.baseCurrency)) return ignore();
|
||||
s.group.baseCurrency = d.baseCurrency;
|
||||
}
|
||||
act.after = { ...s.group };
|
||||
break;
|
||||
}
|
||||
case 'member.added': {
|
||||
const d = ev.data;
|
||||
if (!str(d?.id, 100) || !str(d.name, 60) || member(d.id)) return ignore();
|
||||
s.members.push({ id: d.id, name: d.name, color: String(d.color ?? '').slice(0, 16), archived: false });
|
||||
act.entityId = d.id;
|
||||
act.after = { name: d.name };
|
||||
break;
|
||||
}
|
||||
case 'member.updated': {
|
||||
const m = member(ev.data?.id);
|
||||
if (!m) return ignore();
|
||||
act.entityId = m.id;
|
||||
act.before = { name: m.name, color: m.color };
|
||||
if (ev.data.name !== undefined) {
|
||||
if (!str(ev.data.name, 60)) return ignore();
|
||||
m.name = ev.data.name;
|
||||
}
|
||||
if (typeof ev.data.color === 'string') m.color = ev.data.color.slice(0, 16);
|
||||
act.after = { name: m.name, color: m.color };
|
||||
break;
|
||||
}
|
||||
case 'member.archived':
|
||||
case 'member.restored': {
|
||||
const m = member(ev.data?.id);
|
||||
if (!m) return ignore();
|
||||
act.entityId = m.id;
|
||||
m.archived = ev.type === 'member.archived';
|
||||
break;
|
||||
}
|
||||
case 'expense.created':
|
||||
case 'expense.updated': {
|
||||
const e = ev.data;
|
||||
const existing = s.expenses[e?.id];
|
||||
act.entityId = e?.id ?? null;
|
||||
// Creation is idempotent (first wins): two clients generating the same
|
||||
// recurring occurrence must not clobber each other.
|
||||
if (ev.type === 'expense.created' && existing) return ignore();
|
||||
if (ev.type === 'expense.updated' && !existing) return ignore();
|
||||
if (validateExpense(e, s.members) !== null) return ignore();
|
||||
const copy = structuredClone(e);
|
||||
if (existing) {
|
||||
act.before = existing.expense;
|
||||
existing.expense = copy;
|
||||
existing.updatedAt = ev.at;
|
||||
} else {
|
||||
s.expenses[e.id] = { expense: copy, deleted: false, createdBy: ev.actor, createdAt: ev.at, updatedAt: ev.at };
|
||||
}
|
||||
act.after = copy;
|
||||
break;
|
||||
}
|
||||
case 'expense.deleted':
|
||||
case 'expense.restored': {
|
||||
const r = s.expenses[ev.data?.id];
|
||||
if (!r) return ignore();
|
||||
act.entityId = r.expense.id;
|
||||
act.before = r.expense;
|
||||
r.deleted = ev.type === 'expense.deleted';
|
||||
break;
|
||||
}
|
||||
case 'comment.added': {
|
||||
const d = ev.data;
|
||||
if (!str(d?.id, 100) || !str(d.text, 2000) || !s.expenses[d.expenseId] || s.comments[d.id]) return ignore();
|
||||
s.comments[d.id] = { id: d.id, expenseId: d.expenseId, text: d.text, author: ev.actor, at: ev.at };
|
||||
act.entityId = d.expenseId;
|
||||
act.after = { text: d.text };
|
||||
break;
|
||||
}
|
||||
case 'comment.deleted': {
|
||||
const c = s.comments[ev.data?.id];
|
||||
if (!c) return ignore();
|
||||
act.entityId = c.expenseId;
|
||||
act.before = { text: c.text };
|
||||
delete s.comments[c.id];
|
||||
break;
|
||||
}
|
||||
case 'recurring.created':
|
||||
case 'recurring.updated': {
|
||||
const r = ev.data;
|
||||
const existing = s.recurring[r?.id];
|
||||
if ((ev.type === 'recurring.created') === !!existing) return ignore();
|
||||
if (!validRecurring(r, s)) return ignore();
|
||||
act.entityId = r.id;
|
||||
act.before = existing ?? null;
|
||||
s.recurring[r.id] = structuredClone(r);
|
||||
act.after = s.recurring[r.id];
|
||||
break;
|
||||
}
|
||||
case 'recurring.deleted': {
|
||||
const r = s.recurring[ev.data?.id];
|
||||
if (!r) return ignore();
|
||||
act.entityId = r.id;
|
||||
act.before = r;
|
||||
delete s.recurring[r.id];
|
||||
break;
|
||||
}
|
||||
case 'revert': {
|
||||
const snap = snapshots.get(ev.data?.targetId);
|
||||
if (!snap) return ignore();
|
||||
act.entityId = ev.data.targetId;
|
||||
return { state: structuredClone(snap), activity: act };
|
||||
}
|
||||
default:
|
||||
return ignore();
|
||||
}
|
||||
return { state: s, activity: act };
|
||||
}
|
||||
|
||||
export interface ReplayResult {
|
||||
state: GroupState;
|
||||
/** oldest first, one entry per event */
|
||||
activity: Activity[];
|
||||
}
|
||||
|
||||
/** Replay events (already in log order) into a state. */
|
||||
export function replay(events: GroupEvent[]): ReplayResult {
|
||||
const targets = new Set<string>();
|
||||
for (const ev of events) if (ev.type === 'revert' && typeof ev.data?.targetId === 'string') targets.add(ev.data.targetId);
|
||||
|
||||
const snapshots = new Map<string, GroupState>();
|
||||
const activity: Activity[] = [];
|
||||
let state = emptyState();
|
||||
for (const ev of events) {
|
||||
const r = apply(state, ev, snapshots);
|
||||
state = r.state;
|
||||
activity.push(r.activity);
|
||||
if (targets.has(ev.id) && !snapshots.has(ev.id)) snapshots.set(ev.id, structuredClone(state));
|
||||
}
|
||||
return { state, activity };
|
||||
}
|
||||
|
||||
/** Sort events into log order: synced by seq, then pending in outbox order. */
|
||||
export function logOrder(synced: GroupEvent[], pending: GroupEvent[]): GroupEvent[] {
|
||||
const ids = new Set(synced.map((e) => e.id));
|
||||
return [...synced].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)).concat(pending.filter((e) => !ids.has(e.id)));
|
||||
}
|
||||
47
packages/core/src/settle.ts
Normal file
47
packages/core/src/settle.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// 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;
|
||||
}
|
||||
53
packages/core/src/stats.ts
Normal file
53
packages/core/src/stats.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// Spending statistics (SPEC.md §7.5). Transfers are not spending, so they
|
||||
// are left out of every figure here.
|
||||
import { inBase } from './expense.ts';
|
||||
import type { GroupState } from './types.ts';
|
||||
|
||||
export interface Stats {
|
||||
total: number;
|
||||
byCategory: { category: string; amount: number }[];
|
||||
/** YYYY-MM → amount, ascending, months with no spending included */
|
||||
byMonth: { month: string; amount: number }[];
|
||||
/** paid = put money in; consumed = their share of the spending */
|
||||
perMember: { member: string; paid: number; consumed: number }[];
|
||||
}
|
||||
|
||||
export function computeStats(s: GroupState, from: string | null, to: string | null): Stats {
|
||||
const base = s.group?.baseCurrency ?? 'EUR';
|
||||
const cat = new Map<string, number>();
|
||||
const month = new Map<string, number>();
|
||||
const paid = new Map<string, number>();
|
||||
const consumed = new Map<string, number>();
|
||||
let total = 0;
|
||||
for (const r of Object.values(s.expenses)) {
|
||||
const e = r.expense;
|
||||
if (r.deleted || e.kind === 'transfer') continue;
|
||||
if ((from && e.date < from) || (to && e.date > to)) continue;
|
||||
const b = inBase(e, base);
|
||||
total += b.total;
|
||||
cat.set(e.category, (cat.get(e.category) ?? 0) + b.total);
|
||||
const mk = e.date.slice(0, 7);
|
||||
month.set(mk, (month.get(mk) ?? 0) + b.total);
|
||||
for (const [id, v] of Object.entries(b.paid)) paid.set(id, (paid.get(id) ?? 0) + v);
|
||||
for (const [id, v] of Object.entries(b.owed)) consumed.set(id, (consumed.get(id) ?? 0) + v);
|
||||
}
|
||||
const months = [...month.keys()].sort();
|
||||
const byMonth: Stats['byMonth'] = [];
|
||||
if (months.length) {
|
||||
let [y, m] = months[0].split('-').map(Number);
|
||||
const last = months[months.length - 1];
|
||||
for (;;) {
|
||||
const k = `${y}-${String(m).padStart(2, '0')}`;
|
||||
byMonth.push({ month: k, amount: month.get(k) ?? 0 });
|
||||
if (k >= last) break;
|
||||
m += 1;
|
||||
if (m > 12) (m = 1), (y += 1);
|
||||
}
|
||||
}
|
||||
return {
|
||||
total,
|
||||
byCategory: [...cat].map(([category, amount]) => ({ category, amount })).sort((a, b) => b.amount - a.amount),
|
||||
byMonth,
|
||||
perMember: s.members.map((m) => ({ member: m.id, paid: paid.get(m.id) ?? 0, consumed: consumed.get(m.id) ?? 0 })),
|
||||
};
|
||||
}
|
||||
161
packages/core/src/types.ts
Normal file
161
packages/core/src/types.ts
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
// Event schema (decrypted plaintext) and the state derived by replaying it.
|
||||
// See SPEC.md §4.
|
||||
|
||||
export const SCHEMA_VERSION = 1;
|
||||
|
||||
export type SplitMode = 'equal' | 'shares' | 'exact' | 'percent';
|
||||
export type ExpenseKind = 'expense' | 'transfer';
|
||||
|
||||
export const CATEGORIES = [
|
||||
'food', 'groceries', 'transport', 'accommodation', 'entertainment',
|
||||
'shopping', 'utilities', 'rent', 'travel', 'gifts', 'health', 'other',
|
||||
] as const;
|
||||
export type Category = (typeof CATEGORIES)[number] | 'transfer';
|
||||
|
||||
export interface Member {
|
||||
id: string;
|
||||
name: string;
|
||||
color: string;
|
||||
archived: boolean;
|
||||
}
|
||||
|
||||
export interface SplitEntry {
|
||||
member: string;
|
||||
/** equal: 1/0 · shares: weight · exact: minor units · percent: basis points */
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface Payer {
|
||||
member: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export interface Photo {
|
||||
blobId: string;
|
||||
thumbBlobId: string;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
export interface Expense {
|
||||
id: string;
|
||||
kind: ExpenseKind;
|
||||
title: string;
|
||||
category: Category;
|
||||
/** YYYY-MM-DD */
|
||||
date: string;
|
||||
currency: string;
|
||||
/** minor units of `currency` */
|
||||
amount: number;
|
||||
/** decimal string: 1 `currency` = rate × base currency */
|
||||
rate: string;
|
||||
rateSource: string;
|
||||
payers: Payer[];
|
||||
split: { mode: SplitMode; entries: SplitEntry[] };
|
||||
note: string;
|
||||
photo: Photo | null;
|
||||
/** set on occurrences generated from a recurring template */
|
||||
recurringId?: string;
|
||||
}
|
||||
|
||||
export type Freq = 'weekly' | 'monthly' | 'yearly';
|
||||
|
||||
export interface RecurringRule {
|
||||
freq: Freq;
|
||||
interval: number;
|
||||
/** YYYY-MM-DD, first occurrence */
|
||||
start: string;
|
||||
/** YYYY-MM-DD inclusive, or null */
|
||||
end: string | null;
|
||||
}
|
||||
|
||||
export type ExpenseTemplate = Omit<Expense, 'id' | 'date' | 'recurringId' | 'photo'>;
|
||||
|
||||
export interface Recurring {
|
||||
id: string;
|
||||
template: ExpenseTemplate;
|
||||
rule: RecurringRule;
|
||||
}
|
||||
|
||||
export interface GroupInfo {
|
||||
name: string;
|
||||
baseCurrency: string;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
export type EventBody =
|
||||
| { type: 'group.created'; data: GroupInfo }
|
||||
| { type: 'group.updated'; data: Partial<GroupInfo> }
|
||||
| { type: 'member.added'; data: { id: string; name: string; color: string } }
|
||||
| { type: 'member.updated'; data: { id: string; name?: string; color?: string } }
|
||||
| { type: 'member.archived'; data: { id: string } }
|
||||
| { type: 'member.restored'; data: { id: string } }
|
||||
| { type: 'expense.created'; data: Expense }
|
||||
| { type: 'expense.updated'; data: Expense }
|
||||
| { type: 'expense.deleted'; data: { id: string } }
|
||||
| { type: 'expense.restored'; data: { id: string } }
|
||||
| { type: 'comment.added'; data: { id: string; expenseId: string; text: string } }
|
||||
| { type: 'comment.deleted'; data: { id: string } }
|
||||
| { type: 'recurring.created'; data: Recurring }
|
||||
| { type: 'recurring.updated'; data: Recurring }
|
||||
| { type: 'recurring.deleted'; data: { id: string } }
|
||||
| { type: 'revert'; data: { targetId: string } };
|
||||
|
||||
export type EventType = EventBody['type'];
|
||||
|
||||
/** What gets encrypted into an event's ciphertext. */
|
||||
export type EventPlaintext = EventBody & {
|
||||
v: number;
|
||||
/** member id of whoever made the change, if they picked an identity */
|
||||
actor: string | null;
|
||||
/** client clock, ISO 8601 */
|
||||
at: string;
|
||||
};
|
||||
|
||||
/** A decrypted event as the client holds it. */
|
||||
export type GroupEvent = EventPlaintext & {
|
||||
id: string;
|
||||
/** server-assigned; null while still in the local outbox */
|
||||
seq: number | null;
|
||||
deviceId: string;
|
||||
};
|
||||
|
||||
export interface ExpenseRecord {
|
||||
expense: Expense;
|
||||
deleted: boolean;
|
||||
createdBy: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
id: string;
|
||||
expenseId: string;
|
||||
text: string;
|
||||
author: string | null;
|
||||
at: string;
|
||||
}
|
||||
|
||||
export interface GroupState {
|
||||
group: GroupInfo | null;
|
||||
/** in order of addition; order breaks rounding ties */
|
||||
members: Member[];
|
||||
expenses: Record<string, ExpenseRecord>;
|
||||
comments: Record<string, Comment>;
|
||||
recurring: Record<string, Recurring>;
|
||||
}
|
||||
|
||||
/** One line of the group's activity feed. Not affected by rewinds. */
|
||||
export interface Activity {
|
||||
eventId: string;
|
||||
seq: number | null;
|
||||
at: string;
|
||||
actor: string | null;
|
||||
type: EventType;
|
||||
/** id of the entity concerned (expense, member, comment, …) */
|
||||
entityId: string | null;
|
||||
before: unknown;
|
||||
after: unknown;
|
||||
/** set when the event was ignored as invalid or as a no-op */
|
||||
ignored?: boolean;
|
||||
}
|
||||
232
packages/core/test/core.test.ts
Normal file
232
packages/core/test/core.test.ts
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
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('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('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"")"`);
|
||||
});
|
||||
});
|
||||
14
packages/core/tsconfig.json
Normal file
14
packages/core/tsconfig.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue