Files
budget2.0/src/domain/views.ts
T
Lucas WintherandClaude Opus 5 cdece63c68 feat: user-defined currencies, and amounts that carry their own currency
Two requests. The second is small; the first changed the money layer.

TYPING THE CURRENCY. The purchase total field now reads "30$" as thirty
dollars, "€25,50" as EUR 25.50, "250 kr" as DKK, "1.234,56 usd" as USD
1234.56, and sets the currency selector from what was typed. Entry speed is a
stated product feature and a second control per amount works against it.

The field is type="text", not type="number": a number input silently discards
anything non-numeric, so "30$" would never reach the parser. It keeps its own
text so a half-typed "30." stays as typed and only commits when it parses.

Separator handling is where parseMoneyInput earns its 26 tests. With both "."
and "," present the LAST is the decimal point, which covers "1.234,56" and
"1,234.56" without knowing a locale. With one, it groups thousands if exactly
three digits follow and is a decimal point otherwise — so "1,500" is fifteen
hundred and "1,5" is one and a half. Spaces group thousands only in
three-digit groups, because "30 40" is two amounts typed by mistake and
committing it as 3040 would be worse than rejecting it. An unrecognised
currency returns null rather than falling back: reading "30 GBP" as 30 DKK
would book money at the wrong currency.

USER-DEFINED CURRENCIES. `Currency` was a closed union and decimal places were
a module constant, so "add a currency" was a code change. Both now live in the
dataset: `Dataset.currencies` is the authority on which codes are valid, what
they are called, their symbol, and how many decimals they round to. Settings
grows a table to add, edit and remove them.

That forced the money layer open. `roundMoney` takes a DIGIT COUNT, not a
currency code, and every one of its ~29 call sites resolves digits from the
dataset via `digitsFor`. Making digits a required number rather than an
optional one with a default of 2 is the whole safety argument: every site
became a compile error the type checker enumerated for me, where a default
would have left each one silently correct for DKK/USD/EUR and silently wrong
for the first zero-decimal currency the owner adds.

Because every existing currency uses two decimals, a broken version of this
refactor would still pass all 356 previous tests. src/domain/currencyDigits.test.ts
is the oracle that cannot lie: a JPY-style zero-decimal currency driven through
roundMoney, both FX directions, both split modes, finance-plan division, the
fold, and the month view, asserting no figure has a fractional yen in it.

Guards that come with it, all tested:
- Codes are identity — they key the FX table and every stored Money — so they
  are normalised (" jpy " -> "JPY") and cannot be edited, only added/removed.
- A currency in use cannot be removed, and the refusal names what refers to
  it. The same reasoning as posts being archived rather than deleted: stored
  Money carries the code, and dangling references would make the import
  validator refuse the owner's own exported file. Removing an unused one takes
  its exchange rate with it, leaving no orphan row.
- The import validator now checks the currency table itself — codes, duplicate
  codes, integer decimals 0-4 — and validates every Money against it. That
  boundary check replaces the compile-time safety the closed union provided.
- parseFxResponse takes the accepted codes instead of a global constant, so a
  rate service returning dozens cannot put unreachable rows in the table.

Migration v2 -> v3 seeds the currency table. Behaviour-preserving by
construction: every currency that existed had two decimal places and the
seeded table records two, so not one stored amount can round differently than
it did before. An existing `currencies` field is kept rather than overwritten,
since a hand-edited file could already carry currencies the owner added.

Verified in the browser, not just in tests: JPY added through the real Settings
form with 0 decimals, and the five inputs above typed into the real purchase
field, each setting the right currency.

Two obsolete test helpers went away. plans.test.ts and actions.test.ts used to
monkey-patch the CURRENCY_DIGITS constant to prove the table was consulted;
digits are an argument now, so those tests just ask for zero decimals.
types.test.ts no longer asserts "the supported currencies are exactly DKK,
USD, EUR" — that stopped being a property of the code.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 15:52:11 +02:00

206 lines
5.5 KiB
TypeScript

import { incomeFor, isOverridden } from "./allocation.ts";
import { digitsFor } from "./currencies.ts";
import { figuresFor, foldBalances, type Fold, type PostMonthFigures } from "./fold.ts";
import { roundMoney } from "./money.ts";
import { compareMonths, monthOf, monthRange, monthsOfYear } from "./months.ts";
import type { Dataset, MonthId, Post } from "./types.ts";
export interface MonthPostRow {
post: Post;
figures: PostMonthFigures;
overridden: boolean;
}
export interface MonthViewModel {
monthId: MonthId;
income: number;
totalAllocation: number;
totalCharges: number;
/** income - totalAllocation. Negative when allocations exceed income. */
unallocated: number;
rows: MonthPostRow[];
}
function hasActivity(figures: PostMonthFigures): boolean {
return (
figures.carriedIn !== 0 || figures.allocation !== 0 || figures.charges !== 0
);
}
function visiblePosts(dataset: Dataset): Post[] {
return [...dataset.posts].sort((a, b) => a.order - b.order);
}
export function monthView(dataset: Dataset, monthId: MonthId): MonthViewModel {
const fold = foldBalances(dataset, monthId);
const month = dataset.months.find((m) => m.id === monthId);
const income = incomeFor(dataset, monthId);
const rows: MonthPostRow[] = [];
for (const post of visiblePosts(dataset)) {
const figures = figuresFor(fold, post.id, monthId);
// Archived posts stay visible only while they still have activity.
if (post.archived && !hasActivity(figures)) continue;
rows.push({ post, figures, overridden: isOverridden(month, post.id) });
}
const base = dataset.settings.baseCurrency;
const baseDigits = digitsFor(dataset.currencies, base);
const totalAllocation = roundMoney(
rows.reduce((sum, r) => sum + r.figures.allocation, 0),
baseDigits,
);
const totalCharges = roundMoney(
rows.reduce((sum, r) => sum + r.figures.charges, 0),
baseDigits,
);
return {
monthId,
income,
totalAllocation,
totalCharges,
unallocated: roundMoney(income - totalAllocation, baseDigits),
rows,
};
}
export interface YearPostRow {
post: Post;
/** Twelve entries, January to December. */
byMonth: PostMonthFigures[];
totalAllocation: number;
totalCharges: number;
/** December's remaining balance. */
closingBalance: number;
}
export interface YearViewModel {
year: number;
months: MonthId[];
incomeByMonth: number[];
totalIncome: number;
totalCharges: number;
rows: YearPostRow[];
}
export function yearView(dataset: Dataset, year: number): YearViewModel {
const months = monthsOfYear(year);
const fold = foldBalances(dataset, months[11]!);
const base = dataset.settings.baseCurrency;
const baseDigits = digitsFor(dataset.currencies, base);
const incomeByMonth = months.map((m) => incomeFor(dataset, m));
const rows: YearPostRow[] = visiblePosts(dataset).map((post) => {
const byMonth = months.map((m) => figuresFor(fold, post.id, m));
return {
post,
byMonth,
totalAllocation: roundMoney(
byMonth.reduce((sum, f) => sum + f.allocation, 0),
baseDigits,
),
totalCharges: roundMoney(
byMonth.reduce((sum, f) => sum + f.charges, 0),
baseDigits,
),
closingBalance: byMonth[11]!.remaining,
};
});
return {
year,
months,
incomeByMonth,
totalIncome: roundMoney(
incomeByMonth.reduce((a, b) => a + b, 0),
baseDigits,
),
totalCharges: roundMoney(
rows.reduce((sum, r) => sum + r.totalCharges, 0),
baseDigits,
),
rows,
};
}
export interface SummaryViewModel {
from: MonthId;
to: MonthId;
byPost: { post: Post; charges: number }[];
byMonth: { monthId: MonthId; charges: number }[];
totalCharges: number;
totalIncome: number;
}
export function summaryView(
dataset: Dataset,
from: MonthId,
to: MonthId,
): SummaryViewModel {
const months = monthRange(from, to);
const base = dataset.settings.baseCurrency;
const baseDigits = digitsFor(dataset.currencies, base);
const fold: Fold =
months.length > 0 ? foldBalances(dataset, months[months.length - 1]!) : new Map();
const byPost = visiblePosts(dataset).map((post) => ({
post,
charges: roundMoney(
months.reduce((sum, m) => sum + figuresFor(fold, post.id, m).charges, 0),
baseDigits,
),
}));
const byMonth = months.map((monthId) => ({
monthId,
charges: roundMoney(
dataset.posts.reduce(
(sum, p) => sum + figuresFor(fold, p.id, monthId).charges,
0,
),
baseDigits,
),
}));
return {
from,
to,
byPost,
byMonth,
totalCharges: roundMoney(
byMonth.reduce((sum, m) => sum + m.charges, 0),
baseDigits,
),
totalIncome: roundMoney(
months.reduce((sum, m) => sum + incomeFor(dataset, m), 0),
baseDigits,
),
};
}
/**
* The months worth rendering: from the fold start to the latest month touched
* by any month record or purchase slice, including future finance-plan slices.
*/
export function datasetMonthSpan(dataset: Dataset): { from: MonthId; to: MonthId } {
const from = dataset.settings.foldStartMonth;
let to = from;
const consider = (candidate: MonthId) => {
if (compareMonths(candidate, to) > 0) to = candidate;
};
for (const month of dataset.months) consider(month.id);
for (const purchase of dataset.purchases) {
if (purchase.schedule) {
for (const slice of purchase.schedule.slices) consider(slice.month);
} else {
consider(monthOf(purchase.date));
}
}
return { from, to };
}