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:
@@ -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