add money tracker
All checks were successful
Test and deploy staging / staging (push) Successful in 1m46s

This commit is contained in:
2026-09-23 17:02:32 +00:00
parent 753b2e5d6a
commit 0638ead87f
15 changed files with 2532 additions and 3 deletions

View File

@@ -0,0 +1,151 @@
<script lang="ts">
import type { ChartSeries } from './charts';
let {
series,
title,
unit = '€'
}: { series: ChartSeries[]; title: string; unit?: string } = $props();
const width = 800;
const height = 260;
const plot = { left: 72, right: 18, top: 14, bottom: 38 };
let values = $derived(series.flatMap((item) => item.points.map((point) => point.value)));
let dates = $derived(
series.flatMap((item) => item.points.map((point) => Date.parse(`${point.date}T12:00:00Z`)))
);
let min = $derived(Math.min(0, ...values));
let max = $derived(Math.max(0, ...values));
let span = $derived(max - min || 1);
let from = $derived(Math.min(...dates));
let until = $derived(Math.max(...dates));
let dateSpan = $derived(until - from || 1);
const money = new Intl.NumberFormat('en-NL', { maximumFractionDigits: 0 });
function x(date: string) {
return (
plot.left +
((Date.parse(`${date}T12:00:00Z`) - from) / dateSpan) * (width - plot.left - plot.right)
);
}
function y(value: number) {
return plot.top + (1 - (value - min) / span) * (height - plot.top - plot.bottom);
}
function path(points: ChartSeries['points']) {
return points
.map(
(point, index) =>
`${index ? 'L' : 'M'}${x(point.date).toFixed(2)},${y(point.value).toFixed(2)}`
)
.join(' ');
}
function dateLabel(value: number) {
return new Date(value).toLocaleDateString('en-NL', {
month: 'short',
year: 'numeric',
timeZone: 'UTC'
});
}
</script>
<figure class="chart">
{#if values.length}
<!-- svelte-ignore a11y_no_noninteractive_tabindex: the chart viewport scrolls horizontally on narrow screens -->
<div class="chart-scroll" role="region" tabindex="0" aria-label={title}>
<svg
viewBox={`0 0 ${width} ${height}`}
role="img"
aria-label={title}
preserveAspectRatio="xMidYMid meet"
>
{#each [0, 0.5, 1] as fraction (fraction)}
{@const value = max - span * fraction}
<line
x1={plot.left}
x2={width - plot.right}
y1={y(value)}
y2={y(value)}
stroke="var(--site-border)"
stroke-width="1"
/>
<text
x={plot.left - 12}
y={y(value) + 4}
text-anchor="end"
fill="var(--site-muted)"
font-size="11">{unit}{money.format(value / (unit === '€' ? 100 : 1))}</text
>
{/each}
{#each series as item (item.label)}
{#if item.points.length}
<path
d={path(item.points)}
fill="none"
stroke={item.color}
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
vector-effect="non-scaling-stroke"
/>
{/if}
{/each}
<text x={plot.left} y={height - 8} fill="var(--site-muted)" font-size="11"
>{dateLabel(from)}</text
>
<text
x={width - plot.right}
y={height - 8}
text-anchor="end"
fill="var(--site-muted)"
font-size="11">{dateLabel(until)}</text
>
</svg>
</div>
{#if series.length > 1}
<figcaption class="legend">
{#each series as item (item.label)}
<span><span class="swatch" style={`background:${item.color}`}></span>{item.label}</span>
{/each}
</figcaption>
{/if}
{:else}
<p class="empty">Add entries to see a chart.</p>
{/if}
</figure>
<style>
.chart {
min-width: 0;
}
.chart-scroll {
overflow-x: auto;
}
svg {
display: block;
width: 100%;
min-width: 540px;
height: auto;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 18px;
padding-top: 12px;
color: var(--site-muted);
font-size: 12px;
}
.legend > span {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
}
.empty {
padding: 70px 0;
text-align: center;
color: var(--site-muted);
}
</style>

View File

@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest';
import { accountBalances, balanceSeries, forecastSeries, utilityEstimate } from './charts';
describe('money tracker calculations', () => {
it('keeps balances separate across accounts and preserves transaction order', () => {
const accounts = [
{ id: 1, name: 'Cash', openingBalanceCents: 10000 },
{ id: 2, name: 'Bank', openingBalanceCents: 20000 }
];
const transactions = [
{ accountId: 1, date: '2026-01-01', amountCents: -2500 },
{ accountId: 2, date: '2026-01-02', amountCents: 5000 },
{ accountId: 1, date: '2026-01-03', amountCents: 1000 }
];
expect([...accountBalances(accounts, transactions).values()]).toEqual([8500, 25000]);
expect(balanceSeries(accounts, transactions)[0].points.map((point) => point.value)).toEqual([
10000, 7500, 8500
]);
});
it('projects only future estimates from the current balance', () => {
expect(
forecastSeries(
10000,
[
{ date: '2026-01-01', amountCents: -9999 },
{ date: '2026-10-01', amountCents: -2500 },
{ date: '2026-11-01', amountCents: 5000 }
],
'2026-09-23'
)[0].points.map((point) => point.value)
).toEqual([10000, 7500, 12500]);
});
it('compares estimated usage cost with prorated advances', () => {
const result = utilityEstimate(
[
{ kind: 'gas', date: '2026-01-01', reading: '100' },
{ kind: 'gas', date: '2026-04-01', reading: '130' }
],
'gas',
'1.2500',
2000
);
expect(result?.usage).toBe(30);
expect(result?.estimatedCents).toBe(3750);
expect(result?.advancesCents).toBeGreaterThan(5800);
expect(
utilityEstimate(
[
{ kind: 'gas', date: '2025-01-01', reading: '0' },
{ kind: 'gas', date: '2026-01-01', reading: '100' },
{ kind: 'gas', date: '2026-04-01', reading: '130' }
],
'gas',
'1.2500',
2000,
'2026-01-01'
)?.usage
).toBe(30);
});
});

View File

@@ -0,0 +1,89 @@
export type ChartPoint = { date: string; value: number };
export type ChartSeries = { label: string; color: string; points: ChartPoint[] };
export function balanceSeries(
accounts: { id: number; name: string; openingBalanceCents: number }[],
transactions: { accountId: number; date: string; amountCents: number }[]
): ChartSeries[] {
const palette = ['#0070f3', '#e5484d', '#46a758', '#ad7f00', '#8e4ec6', '#0091ad', '#e56910'];
const lastDate = transactions.at(-1)?.date;
return accounts.map((account, index) => {
let balance = account.openingBalanceCents;
const entries = transactions.filter((transaction) => transaction.accountId === account.id);
const points: ChartPoint[] = [];
if (entries.length) points.push({ date: entries[0].date, value: balance });
for (const entry of entries) {
balance += entry.amountCents;
points.push({ date: entry.date, value: balance });
}
if (lastDate && entries.length && lastDate > entries.at(-1)!.date)
points.push({ date: lastDate, value: balance });
return { label: account.name, color: palette[index % palette.length], points };
});
}
export function accountBalances(
accounts: { id: number; openingBalanceCents: number }[],
transactions: { accountId: number; amountCents: number }[]
): Map<number, number> {
const balances = new Map(accounts.map((account) => [account.id, account.openingBalanceCents]));
for (const transaction of transactions)
balances.set(
transaction.accountId,
(balances.get(transaction.accountId) ?? 0) + transaction.amountCents
);
return balances;
}
export function monthlyCents(amountCents: number, cadence: string): number {
return cadence === 'weekly'
? (amountCents * 52) / 12
: cadence === 'yearly'
? amountCents / 12
: amountCents;
}
export function forecastSeries(
currentCents: number,
forecasts: { date: string; amountCents: number }[],
today: string
): ChartSeries[] {
let projected = currentCents;
const points: ChartPoint[] = [{ date: today, value: currentCents }];
for (const item of forecasts
.filter((entry) => entry.date >= today)
.sort((a, b) => a.date.localeCompare(b.date))) {
projected += item.amountCents;
points.push({ date: item.date, value: projected });
}
return [{ label: 'Projected total', color: '#0070f3', points }];
}
export function utilityEstimate(
readings: { date: string; reading: string; kind: string }[],
kind: string,
ratePerUnit: string,
monthlyAdvanceCents: number,
billingStart?: string | null
) {
const byKind = readings.filter(
(reading) => reading.kind === kind && (!billingStart || reading.date >= billingStart)
);
if (byKind.length < 2) return null;
const first = byKind[0];
const last = byKind.at(-1)!;
const usage = Number(last.reading) - Number(first.reading);
const months =
(Date.parse(`${last.date}T12:00:00Z`) - Date.parse(`${first.date}T12:00:00Z`)) /
((365.25 / 12) * 86_400_000);
if (months <= 0 || usage < 0) return null;
const estimatedCents = Math.round(usage * Number(ratePerUnit) * 100);
const advancesCents = Math.round(months * monthlyAdvanceCents);
return {
usage,
months,
estimatedCents,
advancesCents,
differenceCents: advancesCents - estimatedCents
};
}