add money tracker
All checks were successful
Test and deploy staging / staging (push) Successful in 1m46s
All checks were successful
Test and deploy staging / staging (push) Successful in 1m46s
This commit is contained in:
151
src/lib/money-tracker/MoneyChart.svelte
Normal file
151
src/lib/money-tracker/MoneyChart.svelte
Normal 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>
|
||||
62
src/lib/money-tracker/charts.test.ts
Normal file
62
src/lib/money-tracker/charts.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
89
src/lib/money-tracker/charts.ts
Normal file
89
src/lib/money-tracker/charts.ts
Normal 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
|
||||
};
|
||||
}
|
||||
@@ -6,3 +6,4 @@ export * from './progress';
|
||||
export * from './catch-em-all';
|
||||
export * from './animaldex';
|
||||
export * from './lists';
|
||||
export * from './money-tracker';
|
||||
|
||||
130
src/lib/server/db/schema/money-tracker.ts
Normal file
130
src/lib/server/db/schema/money-tracker.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { date, index, integer, numeric, pgTable, text, unique } from 'drizzle-orm/pg-core';
|
||||
import { id, timestamps } from './helpers';
|
||||
import { user } from './auth';
|
||||
|
||||
export const moneyAccounts = pgTable(
|
||||
'money_accounts',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
openingBalanceCents: integer('opening_balance_cents').notNull().default(0),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [unique().on(table.userId, table.name), index().on(table.userId)]
|
||||
);
|
||||
|
||||
export const moneyTransactions = pgTable(
|
||||
'money_transactions',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
accountId: integer('account_id')
|
||||
.notNull()
|
||||
.references(() => moneyAccounts.id),
|
||||
date: date('date', { mode: 'string' }).notNull(),
|
||||
description: text('description').notNull(),
|
||||
amountCents: integer('amount_cents').notNull(),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [index().on(table.userId, table.date, table.id), index().on(table.accountId)]
|
||||
);
|
||||
|
||||
export const moneyRecurring = pgTable(
|
||||
'money_recurring',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
amountCents: integer('amount_cents').notNull(),
|
||||
cadence: text('cadence').notNull(),
|
||||
accountId: integer('account_id').references(() => moneyAccounts.id, { onDelete: 'set null' }),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [index().on(table.userId)]
|
||||
);
|
||||
|
||||
export const moneyForecasts = pgTable(
|
||||
'money_forecasts',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
date: date('date', { mode: 'string' }).notNull(),
|
||||
description: text('description').notNull(),
|
||||
amountCents: integer('amount_cents').notNull(),
|
||||
accountId: integer('account_id').references(() => moneyAccounts.id, { onDelete: 'set null' }),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [index().on(table.userId, table.date)]
|
||||
);
|
||||
|
||||
export const moneyUtilitySettings = pgTable(
|
||||
'money_utility_settings',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
kind: text('kind').notNull(),
|
||||
ratePerUnit: numeric('rate_per_unit', { precision: 12, scale: 4 }).notNull().default('0'),
|
||||
monthlyAdvanceCents: integer('monthly_advance_cents').notNull().default(0),
|
||||
billingStart: date('billing_start', { mode: 'string' }),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [unique().on(table.userId, table.kind)]
|
||||
);
|
||||
|
||||
export const moneyUtilityReadings = pgTable(
|
||||
'money_utility_readings',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
kind: text('kind').notNull(),
|
||||
date: date('date', { mode: 'string' }).notNull(),
|
||||
reading: numeric('reading', { precision: 12, scale: 3 }).notNull(),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [index().on(table.userId, table.kind, table.date)]
|
||||
);
|
||||
|
||||
export const moneyWishlist = pgTable(
|
||||
'money_wishlist',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
estimatedCents: integer('estimated_cents'),
|
||||
notes: text('notes'),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [index().on(table.userId)]
|
||||
);
|
||||
|
||||
export const moneyInsurances = pgTable(
|
||||
'money_insurances',
|
||||
{
|
||||
id: id(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
provider: text('provider'),
|
||||
coverage: text('coverage'),
|
||||
premiumCents: integer('premium_cents'),
|
||||
cadence: text('cadence').notNull().default('monthly'),
|
||||
...timestamps
|
||||
},
|
||||
(table) => [index().on(table.userId)]
|
||||
);
|
||||
20
src/lib/server/money-tracker.test.ts
Normal file
20
src/lib/server/money-tracker.test.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { cents, csvDate, parseCsv } from './money-tracker';
|
||||
|
||||
describe('transaction import parsing', () => {
|
||||
it('handles quoted commas and semicolon-separated European amounts', () => {
|
||||
expect(
|
||||
parseCsv('date;account;description;amount\n23/09/2026;Cash;"Food; drinks";-12,50')[1]
|
||||
).toEqual(['23/09/2026', 'Cash', 'Food; drinks', '-12,50']);
|
||||
expect(
|
||||
parseCsv('date,account,description,amount\n2026-09-23,Cash,"Food, drinks",-12.50')[1][2]
|
||||
).toBe('Food, drinks');
|
||||
expect(csvDate('23/09/2026')).toBe('2026-09-23');
|
||||
expect(cents('-12,50')).toBe(-1250);
|
||||
});
|
||||
|
||||
it('rejects invalid dates and amounts rather than altering them', () => {
|
||||
expect(csvDate('31/02/2026')).toBeNull();
|
||||
expect(cents('1.234,56')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
87
src/lib/server/money-tracker.ts
Normal file
87
src/lib/server/money-tracker.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { fail } from '@sveltejs/kit';
|
||||
|
||||
export const utilityKinds = ['electricity', 'gas', 'water'] as const;
|
||||
export const cadences = ['weekly', 'monthly', 'yearly'] as const;
|
||||
|
||||
export function textField(form: FormData, key: string, max = 200) {
|
||||
const value = String(form.get(key) ?? '').trim();
|
||||
return value.length > 0 && value.length <= max ? value : null;
|
||||
}
|
||||
|
||||
export function optionalText(form: FormData, key: string, max = 2000) {
|
||||
const value = String(form.get(key) ?? '').trim();
|
||||
return value.length <= max ? value || null : undefined;
|
||||
}
|
||||
|
||||
export function cents(value: unknown, optional = false): number | null | undefined {
|
||||
const raw = String(value ?? '')
|
||||
.trim()
|
||||
.replace(',', '.');
|
||||
if (optional && !raw) return null;
|
||||
if (!/^-?\d{1,9}(?:\.\d{1,2})?$/.test(raw)) return undefined;
|
||||
const amount = Math.round(Number(raw) * 100);
|
||||
return Number.isSafeInteger(amount) && Math.abs(amount) <= 1_000_000_000 ? amount : undefined;
|
||||
}
|
||||
|
||||
export function validDate(value: unknown): string | null {
|
||||
const raw = String(value ?? '').trim();
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;
|
||||
const d = new Date(`${raw}T12:00:00Z`);
|
||||
return !Number.isNaN(d.valueOf()) && d.toISOString().slice(0, 10) === raw ? raw : null;
|
||||
}
|
||||
|
||||
export function positiveId(value: unknown): number | null {
|
||||
const id = Number(value);
|
||||
return Number.isSafeInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
export function cadence(value: unknown): (typeof cadences)[number] | null {
|
||||
return cadences.find((item) => item === value) ?? null;
|
||||
}
|
||||
|
||||
export function utilityKind(value: unknown): (typeof utilityKinds)[number] | null {
|
||||
return utilityKinds.find((item) => item === value) ?? null;
|
||||
}
|
||||
|
||||
export function invalid(message: string) {
|
||||
return fail(400, { message });
|
||||
}
|
||||
|
||||
export function parseCsv(input: string): string[][] {
|
||||
const rows: string[][] = [];
|
||||
const delimiter = input.split(/\r?\n/, 1)[0].includes(';') ? ';' : ',';
|
||||
let row: string[] = [];
|
||||
let field = '';
|
||||
let quoted = false;
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const character = input[i];
|
||||
if (character === '"') {
|
||||
if (quoted && input[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else quoted = !quoted;
|
||||
} else if (character === delimiter && !quoted) {
|
||||
row.push(field.trim());
|
||||
field = '';
|
||||
} else if ((character === '\n' || character === '\r') && !quoted) {
|
||||
if (character === '\r' && input[i + 1] === '\n') i++;
|
||||
row.push(field.trim());
|
||||
if (row.some(Boolean)) rows.push(row);
|
||||
row = [];
|
||||
field = '';
|
||||
} else field += character;
|
||||
}
|
||||
if (quoted) throw new Error('CSV has an unclosed quoted field.');
|
||||
row.push(field.trim());
|
||||
if (row.some(Boolean)) rows.push(row);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function csvDate(value: string): string | null {
|
||||
const raw = value.trim();
|
||||
if (validDate(raw)) return raw;
|
||||
const match = /^(\d{1,2})[/-](\d{1,2})[/-](\d{4})$/.exec(raw);
|
||||
return match
|
||||
? validDate(`${match[3]}-${match[2].padStart(2, '0')}-${match[1].padStart(2, '0')}`)
|
||||
: null;
|
||||
}
|
||||
Reference in New Issue
Block a user