openvibers/openvibe.finance Commits
Budgets: a monthly limit per category (v0.4) (#4)
Changes
@@@ -10,7 +10,7 @@ to connect.- **No money moves.** It reads and plans; it never pays, transfers or cancels anything.- **Yours to take.** Download everything as one JSON file, or delete everything, at `/data`.--## What it does today (v0.3)++## What it does today (v0.4)- Accounts (checking, savings, credit card, cash, loan, investments) with an opening balance and a running balance.- Transactions typed in, or imported from a bank's CSV export: the columns are read from the header (date; amount, or@@@ -20,11 +20,13 @@ to connect.- Category rules: tick **Always** on a transaction's category and every transaction whose payee contains its wordsgoes there, past and future imports (never one you categorised yourself). `/rules` lists and removes them.- The month: money in, money out, and spending by category (transfers between your accounts left out).++- Budgets: a monthly limit per category of spending; the month shows each against its limit (left, or over) and the++ rest of the spending beside them.- Recurring: bills, subscriptions and regular income found in your own transactions (the same payee and a similaramount at a steady rhythm, three times or more): what each costs a month, when the next is due, and which stopped.- A JSON API for all of it (`/api/v1/…`), for the person signed in.--Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: budgets, goals, OFX/QFX, the Link plugin++Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: goals, OFX/QFX, the Link pluginfor local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.## Runningnnew file mode 100644@@@ -0,0 +1,11 @@++-- phase: expand++-- Budgets (plan §L.2: "budgets (envelope, category, flex, paycheck, none)"), the category kind first: a monthly limit++-- for a category of spending, the same every month until changed. The month page sets the limit against what the++-- category spent. A person with no budgets has none (the "none" kind): nothing nags.++CREATE TABLE finance_budgets (++ owner text COLLATE "C" NOT NULL,++ category text NOT NULL,++ monthly_cents bigint NOT NULL CHECK (monthly_cents > 0),++ updated_at timestamptz NOT NULL DEFAULT now(),++ PRIMARY KEY (owner, category)++);@@@ -1,12 +1,12 @@{"name": "openvibe-finance",-- "version": "0.3.0",++ "version": "0.4.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openvibe-finance",-- "version": "0.3.0",++ "version": "0.4.0","license": "AGPL-3.0-only","dependencies": {"@electric-sql/pglite": "^0.5.8",@@@ -1,6 +1,6 @@{"name": "openvibe-finance",-- "version": "0.3.0",++ "version": "0.4.0","private": true,"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you","main": "server/index.js",@@@ -105,3 +105,9 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco.fin-bill-when { display: grid; justify-items: end; gap: 2px; white-space: nowrap; font-variant-numeric: tabular-nums; }.fin-bill-when small { color: var(--text-secondary, #9aa4b2); font-size: 12px; }.fin-bill.is-late .fin-bill-when small { color: var(--warning, #f59e0b); }++/* Budgets (v0.4): the bar's budget mark, what is left or over. */++.fin-bar { position: relative; }++.fin-bars li.is-over .fin-bar > span { background: var(--danger, #ef4444); }++.fin-bar-sum { display: grid; justify-items: end; gap: 1px; }++.fin-bar-sum small { color: var(--text-secondary, #9aa4b2); font-size: 12px; }++.fin-budget-sum { margin: 0 0 10px; color: var(--text-secondary, #9aa4b2); font-variant-numeric: tabular-nums; }@@@ -64,6 +64,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowconst said = (q) => {if (q.imported) { const [a, s] = String(q.imported).split(','); return `Imported ${Number(a) || 0} new transaction${Number(a) === 1 ? '' : 's'}${Number(s) ? `; ${Number(s)} already here` : ''}.`; }if (q.ruled != null) return `Rule made. It also put ${Number(q.ruled) || 0} earlier transaction${Number(q.ruled) === 1 ? '' : 's'} in that category.`;++ if (q.budgeted) return 'Budget saved.';++ if (q.unbudgeted) return 'Budget removed.';if (q.added) return 'Added.';if (q.removed) return 'Rule removed. What it categorised stays as it is.';if (q.deleted) return 'Everything is deleted.';@@@ -127,7 +129,7 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowapp.get('/month', handle(async (req, res) => {const me = who(req);if (!me) return signIn(req, res);-- res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)) }));++ res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)), budgets: await store.budgets(me), o: { said: said(req.query) } }));}));app.get('/bills', handle(async (req, res) => {const me = who(req);@@@ -147,6 +149,17 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowawait store.removeRule(me, req.params.id);res.redirect(303, '/rules?removed=1');}));++ app.post('/budgets', form, handle(async (req, res) => {++ const me = who(req);++ if (!me) return signIn(req, res);++ if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');++ const text = String(req.body.amount || '').trim();++ const cents = text ? readAmount(text) : null;++ if (text && cents == null) throw new FinanceError(422, 'finance.budget.amount', 'The budget is not a number.');++ await store.setBudget(me, req.body.category, cents == null ? null : Math.abs(cents));++ const back = /^\d{4}-(0[1-9]|1[0-2])$/.test(String(req.body.back || '')) ? String(req.body.back) : thisMonth();++ res.redirect(303, `/month?m=${back}&${cents ? 'budgeted' : 'unbudgeted'}=1`);++ }));app.get('/data', handle(async (req, res) => {if (!who(req)) return signIn(req, res);res.send(v.dataPage({ o: { said: said(req.query) } }));@@@ -183,6 +196,11 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now}));api.get('/months/:m', handle(async (req, res) => res.json(await store.month(who(req), req.params.m))));api.get('/rules', handle(async (req, res) => res.json({ rules: await store.rules(who(req)) })));++ api.get('/budgets', handle(async (req, res) => res.json({ budgets: await store.budgets(who(req)) })));++ api.put('/budgets/:category', express.json({ limit: '2kb' }), handle(async (req, res) => {++ const cents = req.body && req.body.monthly_cents;++ res.json({ budget: await store.setBudget(who(req), decodeURIComponent(req.params.category), cents == null ? null : Number(cents)) });++ }));api.get('/recurring', handle(async (req, res) => res.json({ recurring: findRecurring(await store.recent(who(req)), { today: now().toISOString().slice(0, 10) }).map(({ key, ...r }) => r) })));api.post('/rules', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addRule(who(req), req.body || {}))));api.delete('/rules/:id', handle(async (req, res) => { await store.removeRule(who(req), req.params.id); res.status(204).end(); }));@@@ -17,6 +17,8 @@* rules(owner) → [{ id, match, category }] (longest words first)* addRule(owner, { match, category }) the same words again replace the category; applied to the past* removeRule(owner, id)++ * budgets(owner) → [{ category, monthly_cents }]++ * setBudget(owner, category, cents|null) a monthly limit for a category; null or 0 removes it* exportAll(owner) → everything, opened (the person's own copy)* removeAll(owner) → everything of theirs deleted*/@@@ -233,6 +235,25 @@ function createStore({ db, vault }) {await db.exec('DELETE FROM finance_rules WHERE id = $1 AND owner = $2', [String(id || ''), owner]);}++ async function budgets(owner) {++ own(owner);++ const rows = await db.many('SELECT category, monthly_cents FROM finance_budgets WHERE owner = $1 ORDER BY category', [owner]);++ return rows.map((r) => ({ category: r.category, monthly_cents: Number(r.monthly_cents) }));++ }++++ async function setBudget(owner, category, cents) {++ own(owner);++ const c = cleanCategory(category);++ if (c === 'Uncategorized' || c === 'Income' || c === 'Transfers') fail(422, 'finance.budget.category', `A budget is for a category of spending, not ${c}.`);++ if (cents == null || cents === 0) { await db.exec('DELETE FROM finance_budgets WHERE owner = $1 AND category = $2', [owner, c]); return null; }++ if (!Number.isSafeInteger(cents) || cents < 0 || cents > 1e11) fail(422, 'finance.budget.amount', 'A budget is an amount of money a month.');++ const count = Number(await db.value('SELECT count(*) FROM finance_budgets WHERE owner = $1', [owner]));++ if (count >= 100) fail(422, 'finance.budget.limit', 'A hundred budgets is the most for now.');++ await db.exec(`INSERT INTO finance_budgets (owner, category, monthly_cents) VALUES ($1, $2, $3)++ ON CONFLICT (owner, category) DO UPDATE SET monthly_cents = EXCLUDED.monthly_cents, updated_at = now()`, [owner, c, cents]);++ return { category: c, monthly_cents: cents };++ }++async function exportAll(owner) {own(owner);const accs = await db.many('SELECT id, name, kind, currency, opening_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);@@@ -242,6 +263,7 @@ function createStore({ db, vault }) {accounts: accs.map((a) => ({ ...a, opening_cents: Number(a.opening_cents) })),transactions: txns.map((r) => open(owner, r)),rules: (await rules(owner)).map((r) => ({ match: r.match, category: r.category })),++ budgets: await budgets(owner),};}@@@ -251,11 +273,12 @@ function createStore({ db, vault }) {await t.exec('DELETE FROM finance_transactions WHERE owner = $1', [owner]);await t.exec('DELETE FROM finance_imports WHERE owner = $1', [owner]);await t.exec('DELETE FROM finance_rules WHERE owner = $1', [owner]);++ await t.exec('DELETE FROM finance_budgets WHERE owner = $1', [owner]);await t.exec('DELETE FROM finance_accounts WHERE owner = $1', [owner]);});}-- return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, exportAll, removeAll };++ return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, exportAll, removeAll };}module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };@@@ -142,9 +142,30 @@ ${notice(o)}${cats}${txns.length ? [...groups.values()].map((list) => `<ul class="fin-txns">${list.map(row).join('')}</ul>`).join('') : `<p class="fin-empty">Nothing in ${esc(monthName(month))}. Add a transaction, or import a CSV.</p>`}` });}--function monthPage({ m, o = {} }) {-- const spent = m.by_category.filter((c) => c.out_cents > 0);-- const most = Math.max(1, ...spent.map((c) => c.out_cents));++function monthPage({ m, budgets = [], o = {} }) {++ const limit = new Map(budgets.map((b) => [b.category, b.monthly_cents]));++ const spentBy = new Map(m.by_category.filter((c) => c.out_cents > 0).map((c) => [c.category, c]));++ // Budgeted categories with nothing spent yet still show: what is left is the whole budget.++ for (const b of budgets) if (!spentBy.has(b.category)) spentBy.set(b.category, { category: b.category, out_cents: 0, count: 0 });++ const spent = [...spentBy.values()].sort((a, b) => b.out_cents - a.out_cents);++ // Budgets read against their own limit (a full bar is the budget, red once over); the rest against the largest.++ const withBudget = spent.filter((c) => limit.has(c.category));++ const without = spent.filter((c) => !limit.has(c.category));++ const most = Math.max(1, ...without.map((c) => c.out_cents));++ const budgeted = budgets.reduce((n, b) => n + b.monthly_cents, 0);++ // What the budgeted categories really spent (an overspend is counted, not capped at its budget).++ const usedOfBudgets = withBudget.reduce((n, c) => n + c.out_cents, 0);++ const cats = `<datalist id="fin-cats">${CATEGORIES.filter((c) => !['Income', 'Transfers', 'Uncategorized'].includes(c)).map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;++ const budgetBar = (c) => {++ const cap = limit.get(c.category);++ const over = c.out_cents > cap;++ const left = cap - c.out_cents;++ return `<li class="${over ? 'is-over' : ''}"><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span>++<span class="fin-bar fin-bar--budget"><span style="--w:${Math.min(100, Math.round((c.out_cents / cap) * 100))}%"></span></span>++<span class="fin-bar-sum">${esc(money(c.out_cents))}<small class="${over ? 'is-neg' : ''}">of ${esc(money(cap))} · ${over ? `${esc(money(-left))} over` : `${esc(money(left))} left`}</small></span></li>`;++ };++ const bar = (c) => `<li><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span>++<span class="fin-bar"><span style="--w:${Math.max(2, Math.round((c.out_cents / most) * 100))}%"></span></span><span class="fin-bar-sum">${esc(money(c.out_cents))}</span></li>`;return page({title: `${monthName(m.month)}`, path: '/month', body: `<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>${esc(monthName(m.month))}</h1></header>@@@ -152,9 +173,16 @@ ${notice(o)}<nav class="fin-monthnav" aria-label="Month"><a href="/month?m=${shiftMonth(m.month, -1)}">${esc(monthName(shiftMonth(m.month, -1)))}</a><b>${esc(monthName(m.month))}</b><a href="/month?m=${shiftMonth(m.month, 1)}">${esc(monthName(shiftMonth(m.month, 1)))}</a></nav><div class="fin-sums"><p><span>In</span><b class="fin-in">${esc(money(m.income_cents))}</b></p><p><span>Out</span><b class="fin-out">${esc(money(m.spent_cents))}</b></p><p><span>Left</span><b class="${m.income_cents - m.spent_cents < 0 ? 'is-neg' : ''}">${esc(money(m.income_cents - m.spent_cents))}</b></p></div>--${spent.length ? `<ul class="fin-bars">${spent.map((c) => `<li><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span>--<span class="fin-bar"><span style="--w:${Math.max(2, Math.round((c.out_cents / most) * 100))}%"></span></span><span class="fin-bar-sum">${esc(money(c.out_cents))}</span></li>`).join('')}</ul>`-- : '<p class="fin-empty">No spending this month.</p>'}++${withBudget.length ? `<section class="fin-sec"><h2>Budgets</h2><p class="fin-budget-sum">${esc(money(usedOfBudgets))} of ${esc(money(budgeted))} spent</p>++<ul class="fin-bars">${withBudget.map(budgetBar).join('')}</ul></section>` : ''}++${without.length ? `<section class="fin-sec">${withBudget.length ? '<h2>Everything else</h2>' : ''}<ul class="fin-bars">${without.map(bar).join('')}</ul></section>` : (withBudget.length ? '' : '<p class="fin-empty">No spending this month.</p>')}++<details class="fin-fold"><summary>${budgets.length ? 'Change a budget' : 'Set a monthly budget for a category'}</summary>++<form class="fin-form" method="post" action="/budgets">${cats}++<div class="fin-row"><label class="fin-field"><span>Category</span><input name="category" list="fin-cats" required maxlength="60" placeholder="Eating out" autocomplete="off"></label>++<label class="fin-field"><span>A month</span><input name="amount" inputmode="decimal" placeholder="300.00 (empty removes it)" autocomplete="off"></label></div>++<input type="hidden" name="back" value="${esc(m.month)}">++<p><button class="fin-btn fin-btn--primary" type="submit">Save the budget</button></p>++</form></details><p class="fin-note">Transfers between your own accounts are left out. Amounts in other currencies are added as they are.</p>` });}nnew file mode 100644@@@ -0,0 +1,81 @@++'use strict';++/**++ * Budgets (migrations/0003_budgets.sql): a monthly limit for a category of spending, set from the month page; the month++ * shows what is left or how much over, budgeted categories with nothing spent yet included; income, transfers and++ * Uncategorized take no budget; an empty amount removes one; another person sees none; export carries them and delete++ * removes them.++ */++const assert = require('assert');++const path = require('node:path');++const crypto = require('node:crypto');++const { createTestDb } = require('openvibe-sdk/testing');++const { createVault } = require('../server/crypto');++const { createStore } = require('../server/store');++const { createApp } = require('../server/app');++++const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';++const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';++++(async () => {++ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });++ const vault = createVault(crypto.randomBytes(32).toString('base64'));++ const store = createStore({ db, vault });++ const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => { const u = req.get('x-test-user'); if (u) req.user = { subject_id: u }; next(); } };++ const server = createApp({ db, vault, auth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');++ await new Promise((r) => server.once('listening', r));++ const base = `http://127.0.0.1:${server.address().port}`;++ const post = (p, form, as = ADA) => fetch(base + p, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': as, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString() })++ .then(async (r) => ({ status: r.status, location: r.headers.get('location'), text: await r.text() }));++ const page = (p, as = ADA) => fetch(base + p, { headers: { 'x-test-user': as } }).then((r) => r.text());++ try {++ const acc = await store.addAccount(ADA, { name: 'Checking' });++ await store.importRows(ADA, acc.id, [++ { posted_on: '2026-11-02', amount_cents: -24000, payee: 'Thai Garden', category: 'Eating out' },++ { posted_on: '2026-11-09', amount_cents: -9000, payee: 'Pizza Place', category: 'Eating out' },++ { posted_on: '2026-11-03', amount_cents: -12000, payee: 'Corner Grocer', category: 'Groceries' },++ ]);++++ let r = await post('/budgets', { category: 'Eating out', amount: '300', back: '2026-11' });++ assert.strictEqual(r.status, 303, r.text);++ assert.strictEqual(r.location, '/month?m=2026-11&budgeted=1');++ r = await post('/budgets', { category: 'Groceries', amount: '$400.00', back: '2026-11' });++ r = await post('/budgets', { category: 'Health', amount: '50', back: '2026-11' });++ assert.deepStrictEqual(await store.budgets(ADA), [++ { category: 'Eating out', monthly_cents: 30000 }, { category: 'Groceries', monthly_cents: 40000 }, { category: 'Health', monthly_cents: 5000 }]);++++ let html = await page('/month?m=2026-11');++ assert.match(html, /\$30\.00 over/, 'Eating out: $330 of $300');++ assert.match(html, /\$280\.00 left/, 'Groceries: $120 of $400');++ assert.match(html, /\$50\.00 left/, 'Health: nothing spent yet, still shown');++ assert.match(html, /\$450\.00 of \$750\.00 spent/, '$330 + $120 + $0, the overspend counted');++ assert.match(html, /class="is-over"/);++++ r = await post('/budgets', { category: 'Eating out', amount: '400', back: '2026-11' });++ assert.strictEqual((await store.budgets(ADA))[0].monthly_cents, 40000, 'the same category again replaces it');++ r = await post('/budgets', { category: 'Health', amount: '', back: '2026-11' });++ assert.strictEqual(r.location, '/month?m=2026-11&unbudgeted=1');++ assert.ok(!(await store.budgets(ADA)).some((b) => b.category === 'Health'), 'an empty amount removes it');++++ for (const category of ['Income', 'Transfers', 'Uncategorized']) {++ r = await post('/budgets', { category, amount: '100' });++ assert.strictEqual(r.status, 422, category);++ }++ r = await post('/budgets', { category: 'Fees', amount: 'lots' });++ assert.strictEqual(r.status, 422);++ r = await fetch(`${base}/budgets`, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'cross-site', 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: 'category=Fees&amount=5' });++ assert.strictEqual(r.status, 403);++++ assert.deepStrictEqual((await fetch(`${base}/api/v1/budgets`, { headers: { 'x-test-user': BO } }).then((x) => x.json())).budgets, [], 'nobody sees another person\'s');++ const put = await fetch(`${base}/api/v1/budgets/${encodeURIComponent('Shopping')}`, { method: 'PUT', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': ADA, 'content-type': 'application/json' }, body: JSON.stringify({ monthly_cents: 10000 }) });++ assert.strictEqual(put.status, 200);++ assert.ok((await store.budgets(ADA)).some((b) => b.category === 'Shopping'));++++ assert.strictEqual((await store.exportAll(ADA)).budgets.length, 3);++ await store.removeAll(ADA);++ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_budgets WHERE owner = $1', [ADA])), 0);++ } finally {++ server.close();++ await close();++ }++ console.log('budgets: set, replaced and removed; left and over on the month; refused where they mean nothing; exported and deleted');++})().catch((err) => { console.error(err); process.exit(1); });@@@ -37,6 +37,9 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';`;await store.importRows(ADA, checking.id, readCsv(csv).rows);await store.importRows(ADA, card.id, readCsv('Date,Payee,Amount\n2026-11-07,Airline Tickets,-412.20\n2026-11-10,Hotel Downtown,-268.00\n').rows);++ await store.setBudget(ADA, 'Eating out', 4000);++ await store.setBudget(ADA, 'Groceries', 40000);++ await store.setBudget(ADA, 'Health', 5000);const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => { if (!req.get('x-guest')) req.user = { subject_id: ADA }; next(); } };const app = createApp({ db, vault, auth, baseUrl: 'http://127.0.0.1', now: () => new Date('2026-11-18T12:00:00Z') });const server = app.listen(Number(process.argv[2] || 0), '127.0.0.1', () => console.log(`port ${server.address().port} account ${checking.id}`));
@@ -10,7 +10,7 @@ to connect.
@@ -10,7 +10,7 @@ to connect.
- **No money moves.** It reads and plans; it never pays, transfers or cancels anything.
- **No money moves.** It reads and plans; it never pays, transfers or cancels anything.
- **Yours to take.** Download everything as one JSON file, or delete everything, at `/data`.
- **Yours to take.** Download everything as one JSON file, or delete everything, at `/data`.
-## What it does today (v0.3)
+## What it does today (v0.4)
- Accounts (checking, savings, credit card, cash, loan, investments) with an opening balance and a running balance.
- Accounts (checking, savings, credit card, cash, loan, investments) with an opening balance and a running balance.
- Transactions typed in, or imported from a bank's CSV export: the columns are read from the header (date; amount, or
- Transactions typed in, or imported from a bank's CSV export: the columns are read from the header (date; amount, or
@@ -20,11 +20,13 @@ to connect.
@@ -20,11 +20,13 @@ to connect.
- Category rules: tick **Always** on a transaction's category and every transaction whose payee contains its words
- Category rules: tick **Always** on a transaction's category and every transaction whose payee contains its words
goes there, past and future imports (never one you categorised yourself). `/rules` lists and removes them.
goes there, past and future imports (never one you categorised yourself). `/rules` lists and removes them.
- The month: money in, money out, and spending by category (transfers between your accounts left out).
- The month: money in, money out, and spending by category (transfers between your accounts left out).
+- Budgets: a monthly limit per category of spending; the month shows each against its limit (left, or over) and the
+ rest of the spending beside them.
- Recurring: bills, subscriptions and regular income found in your own transactions (the same payee and a similar
- Recurring: bills, subscriptions and regular income found in your own transactions (the same payee and a similar
amount at a steady rhythm, three times or more): what each costs a month, when the next is due, and which stopped.
amount at a steady rhythm, three times or more): what each costs a month, when the next is due, and which stopped.
- A JSON API for all of it (`/api/v1/…`), for the person signed in.
- A JSON API for all of it (`/api/v1/…`), for the person signed in.
-Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: budgets, goals, OFX/QFX, the Link plugin
+Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: goals, OFX/QFX, the Link plugin
for local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.
for local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.
## Running
## Running
new file mode 100644
new file mode 100644
@@ -0,0 +1,11 @@
@@ -0,0 +1,11 @@
+-- phase: expand
+-- Budgets (plan §L.2: "budgets (envelope, category, flex, paycheck, none)"), the category kind first: a monthly limit
+-- for a category of spending, the same every month until changed. The month page sets the limit against what the
+-- category spent. A person with no budgets has none (the "none" kind): nothing nags.
+CREATE TABLE finance_budgets (
+ owner text COLLATE "C" NOT NULL,
+ category text NOT NULL,
+ monthly_cents bigint NOT NULL CHECK (monthly_cents > 0),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (owner, category)
+);
@@ -1,12 +1,12 @@
@@ -1,12 +1,12 @@
{
{
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.3.0",
+ "version": "0.4.0",
"lockfileVersion": 3,
"lockfileVersion": 3,
"requires": true,
"requires": true,
"packages": {
"packages": {
"": {
"": {
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.3.0",
+ "version": "0.4.0",
"license": "AGPL-3.0-only",
"license": "AGPL-3.0-only",
"dependencies": {
"dependencies": {
"@electric-sql/pglite": "^0.5.8",
"@electric-sql/pglite": "^0.5.8",
@@ -1,6 +1,6 @@
@@ -1,6 +1,6 @@
{
{
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.3.0",
+ "version": "0.4.0",
"private": true,
"private": true,
"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you",
"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you",
"main": "server/index.js",
"main": "server/index.js",
@@ -105,3 +105,9 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
@@ -105,3 +105,9 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
.fin-bill-when { display: grid; justify-items: end; gap: 2px; white-space: nowrap; font-variant-numeric: tabular-nums; }
.fin-bill-when { display: grid; justify-items: end; gap: 2px; white-space: nowrap; font-variant-numeric: tabular-nums; }
.fin-bill-when small { color: var(--text-secondary, #9aa4b2); font-size: 12px; }
.fin-bill-when small { color: var(--text-secondary, #9aa4b2); font-size: 12px; }
.fin-bill.is-late .fin-bill-when small { color: var(--warning, #f59e0b); }
.fin-bill.is-late .fin-bill-when small { color: var(--warning, #f59e0b); }
+/* Budgets (v0.4): the bar's budget mark, what is left or over. */
+.fin-bar { position: relative; }
+.fin-bars li.is-over .fin-bar > span { background: var(--danger, #ef4444); }
+.fin-bar-sum { display: grid; justify-items: end; gap: 1px; }
+.fin-bar-sum small { color: var(--text-secondary, #9aa4b2); font-size: 12px; }
+.fin-budget-sum { margin: 0 0 10px; color: var(--text-secondary, #9aa4b2); font-variant-numeric: tabular-nums; }
@@ -64,6 +64,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -64,6 +64,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
const said = (q) => {
const said = (q) => {
if (q.imported) { const [a, s] = String(q.imported).split(','); return `Imported ${Number(a) || 0} new transaction${Number(a) === 1 ? '' : 's'}${Number(s) ? `; ${Number(s)} already here` : ''}.`; }
if (q.imported) { const [a, s] = String(q.imported).split(','); return `Imported ${Number(a) || 0} new transaction${Number(a) === 1 ? '' : 's'}${Number(s) ? `; ${Number(s)} already here` : ''}.`; }
if (q.ruled != null) return `Rule made. It also put ${Number(q.ruled) || 0} earlier transaction${Number(q.ruled) === 1 ? '' : 's'} in that category.`;
if (q.ruled != null) return `Rule made. It also put ${Number(q.ruled) || 0} earlier transaction${Number(q.ruled) === 1 ? '' : 's'} in that category.`;
+ if (q.budgeted) return 'Budget saved.';
+ if (q.unbudgeted) return 'Budget removed.';
if (q.added) return 'Added.';
if (q.added) return 'Added.';
if (q.removed) return 'Rule removed. What it categorised stays as it is.';
if (q.removed) return 'Rule removed. What it categorised stays as it is.';
if (q.deleted) return 'Everything is deleted.';
if (q.deleted) return 'Everything is deleted.';
@@ -127,7 +129,7 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -127,7 +129,7 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
app.get('/month', handle(async (req, res) => {
app.get('/month', handle(async (req, res) => {
const me = who(req);
const me = who(req);
if (!me) return signIn(req, res);
if (!me) return signIn(req, res);
- res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)) }));
+ res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)), budgets: await store.budgets(me), o: { said: said(req.query) } }));
}));
}));
app.get('/bills', handle(async (req, res) => {
app.get('/bills', handle(async (req, res) => {
const me = who(req);
const me = who(req);
@@ -147,6 +149,17 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -147,6 +149,17 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
await store.removeRule(me, req.params.id);
await store.removeRule(me, req.params.id);
res.redirect(303, '/rules?removed=1');
res.redirect(303, '/rules?removed=1');
}));
}));
+ app.post('/budgets', form, handle(async (req, res) => {
+ const me = who(req);
+ if (!me) return signIn(req, res);
+ if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
+ const text = String(req.body.amount || '').trim();
+ const cents = text ? readAmount(text) : null;
+ if (text && cents == null) throw new FinanceError(422, 'finance.budget.amount', 'The budget is not a number.');
+ await store.setBudget(me, req.body.category, cents == null ? null : Math.abs(cents));
+ const back = /^\d{4}-(0[1-9]|1[0-2])$/.test(String(req.body.back || '')) ? String(req.body.back) : thisMonth();
+ res.redirect(303, `/month?m=${back}&${cents ? 'budgeted' : 'unbudgeted'}=1`);
+ }));
app.get('/data', handle(async (req, res) => {
app.get('/data', handle(async (req, res) => {
if (!who(req)) return signIn(req, res);
if (!who(req)) return signIn(req, res);
res.send(v.dataPage({ o: { said: said(req.query) } }));
res.send(v.dataPage({ o: { said: said(req.query) } }));
@@ -183,6 +196,11 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -183,6 +196,11 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
}));
}));
api.get('/months/:m', handle(async (req, res) => res.json(await store.month(who(req), req.params.m))));
api.get('/months/:m', handle(async (req, res) => res.json(await store.month(who(req), req.params.m))));
api.get('/rules', handle(async (req, res) => res.json({ rules: await store.rules(who(req)) })));
api.get('/rules', handle(async (req, res) => res.json({ rules: await store.rules(who(req)) })));
+ api.get('/budgets', handle(async (req, res) => res.json({ budgets: await store.budgets(who(req)) })));
+ api.put('/budgets/:category', express.json({ limit: '2kb' }), handle(async (req, res) => {
+ const cents = req.body && req.body.monthly_cents;
+ res.json({ budget: await store.setBudget(who(req), decodeURIComponent(req.params.category), cents == null ? null : Number(cents)) });
+ }));
api.get('/recurring', handle(async (req, res) => res.json({ recurring: findRecurring(await store.recent(who(req)), { today: now().toISOString().slice(0, 10) }).map(({ key, ...r }) => r) })));
api.get('/recurring', handle(async (req, res) => res.json({ recurring: findRecurring(await store.recent(who(req)), { today: now().toISOString().slice(0, 10) }).map(({ key, ...r }) => r) })));
api.post('/rules', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addRule(who(req), req.body || {}))));
api.post('/rules', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addRule(who(req), req.body || {}))));
api.delete('/rules/:id', handle(async (req, res) => { await store.removeRule(who(req), req.params.id); res.status(204).end(); }));
api.delete('/rules/:id', handle(async (req, res) => { await store.removeRule(who(req), req.params.id); res.status(204).end(); }));
@@ -17,6 +17,8 @@
@@ -17,6 +17,8 @@
* rules(owner) → [{ id, match, category }] (longest words first)
* rules(owner) → [{ id, match, category }] (longest words first)
* addRule(owner, { match, category }) the same words again replace the category; applied to the past
* addRule(owner, { match, category }) the same words again replace the category; applied to the past
* removeRule(owner, id)
* removeRule(owner, id)
+ * budgets(owner) → [{ category, monthly_cents }]
+ * setBudget(owner, category, cents|null) a monthly limit for a category; null or 0 removes it
* exportAll(owner) → everything, opened (the person's own copy)
* exportAll(owner) → everything, opened (the person's own copy)
* removeAll(owner) → everything of theirs deleted
* removeAll(owner) → everything of theirs deleted
*/
*/
@@ -233,6 +235,25 @@ function createStore({ db, vault }) {
@@ -233,6 +235,25 @@ function createStore({ db, vault }) {
await db.exec('DELETE FROM finance_rules WHERE id = $1 AND owner = $2', [String(id || ''), owner]);
await db.exec('DELETE FROM finance_rules WHERE id = $1 AND owner = $2', [String(id || ''), owner]);
}
}
+ async function budgets(owner) {
+ own(owner);
+ const rows = await db.many('SELECT category, monthly_cents FROM finance_budgets WHERE owner = $1 ORDER BY category', [owner]);
+ return rows.map((r) => ({ category: r.category, monthly_cents: Number(r.monthly_cents) }));
+ }
+
+ async function setBudget(owner, category, cents) {
+ own(owner);
+ const c = cleanCategory(category);
+ if (c === 'Uncategorized' || c === 'Income' || c === 'Transfers') fail(422, 'finance.budget.category', `A budget is for a category of spending, not ${c}.`);
+ if (cents == null || cents === 0) { await db.exec('DELETE FROM finance_budgets WHERE owner = $1 AND category = $2', [owner, c]); return null; }
+ if (!Number.isSafeInteger(cents) || cents < 0 || cents > 1e11) fail(422, 'finance.budget.amount', 'A budget is an amount of money a month.');
+ const count = Number(await db.value('SELECT count(*) FROM finance_budgets WHERE owner = $1', [owner]));
+ if (count >= 100) fail(422, 'finance.budget.limit', 'A hundred budgets is the most for now.');
+ await db.exec(`INSERT INTO finance_budgets (owner, category, monthly_cents) VALUES ($1, $2, $3)
+ ON CONFLICT (owner, category) DO UPDATE SET monthly_cents = EXCLUDED.monthly_cents, updated_at = now()`, [owner, c, cents]);
+ return { category: c, monthly_cents: cents };
+ }
+
async function exportAll(owner) {
async function exportAll(owner) {
own(owner);
own(owner);
const accs = await db.many('SELECT id, name, kind, currency, opening_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);
const accs = await db.many('SELECT id, name, kind, currency, opening_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);
@@ -242,6 +263,7 @@ function createStore({ db, vault }) {
@@ -242,6 +263,7 @@ function createStore({ db, vault }) {
accounts: accs.map((a) => ({ ...a, opening_cents: Number(a.opening_cents) })),
accounts: accs.map((a) => ({ ...a, opening_cents: Number(a.opening_cents) })),
transactions: txns.map((r) => open(owner, r)),
transactions: txns.map((r) => open(owner, r)),
rules: (await rules(owner)).map((r) => ({ match: r.match, category: r.category })),
rules: (await rules(owner)).map((r) => ({ match: r.match, category: r.category })),
+ budgets: await budgets(owner),
};
};
}
}
@@ -251,11 +273,12 @@ function createStore({ db, vault }) {
@@ -251,11 +273,12 @@ function createStore({ db, vault }) {
await t.exec('DELETE FROM finance_transactions WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_transactions WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_imports WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_imports WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_rules WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_rules WHERE owner = $1', [owner]);
+ await t.exec('DELETE FROM finance_budgets WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_accounts WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_accounts WHERE owner = $1', [owner]);
});
});
}
}
- return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, exportAll, removeAll };
+ return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, exportAll, removeAll };
}
}
module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
@@ -142,9 +142,30 @@ ${notice(o)}${cats}
@@ -142,9 +142,30 @@ ${notice(o)}${cats}
${txns.length ? [...groups.values()].map((list) => `<ul class="fin-txns">${list.map(row).join('')}</ul>`).join('') : `<p class="fin-empty">Nothing in ${esc(monthName(month))}. Add a transaction, or import a CSV.</p>`}` });
${txns.length ? [...groups.values()].map((list) => `<ul class="fin-txns">${list.map(row).join('')}</ul>`).join('') : `<p class="fin-empty">Nothing in ${esc(monthName(month))}. Add a transaction, or import a CSV.</p>`}` });
}
}
-function monthPage({ m, o = {} }) {
- const spent = m.by_category.filter((c) => c.out_cents > 0);
- const most = Math.max(1, ...spent.map((c) => c.out_cents));
+function monthPage({ m, budgets = [], o = {} }) {
+ const limit = new Map(budgets.map((b) => [b.category, b.monthly_cents]));
+ const spentBy = new Map(m.by_category.filter((c) => c.out_cents > 0).map((c) => [c.category, c]));
+ // Budgeted categories with nothing spent yet still show: what is left is the whole budget.
+ for (const b of budgets) if (!spentBy.has(b.category)) spentBy.set(b.category, { category: b.category, out_cents: 0, count: 0 });
+ const spent = [...spentBy.values()].sort((a, b) => b.out_cents - a.out_cents);
+ // Budgets read against their own limit (a full bar is the budget, red once over); the rest against the largest.
+ const withBudget = spent.filter((c) => limit.has(c.category));
+ const without = spent.filter((c) => !limit.has(c.category));
+ const most = Math.max(1, ...without.map((c) => c.out_cents));
+ const budgeted = budgets.reduce((n, b) => n + b.monthly_cents, 0);
+ // What the budgeted categories really spent (an overspend is counted, not capped at its budget).
+ const usedOfBudgets = withBudget.reduce((n, c) => n + c.out_cents, 0);
+ const cats = `<datalist id="fin-cats">${CATEGORIES.filter((c) => !['Income', 'Transfers', 'Uncategorized'].includes(c)).map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;
+ const budgetBar = (c) => {
+ const cap = limit.get(c.category);
+ const over = c.out_cents > cap;
+ const left = cap - c.out_cents;
+ return `<li class="${over ? 'is-over' : ''}"><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span>
+<span class="fin-bar fin-bar--budget"><span style="--w:${Math.min(100, Math.round((c.out_cents / cap) * 100))}%"></span></span>
+<span class="fin-bar-sum">${esc(money(c.out_cents))}<small class="${over ? 'is-neg' : ''}">of ${esc(money(cap))} · ${over ? `${esc(money(-left))} over` : `${esc(money(left))} left`}</small></span></li>`;
+ };
+ const bar = (c) => `<li><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span>
+<span class="fin-bar"><span style="--w:${Math.max(2, Math.round((c.out_cents / most) * 100))}%"></span></span><span class="fin-bar-sum">${esc(money(c.out_cents))}</span></li>`;
return page({
return page({
title: `${monthName(m.month)}`, path: '/month', body: `
title: `${monthName(m.month)}`, path: '/month', body: `
<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>${esc(monthName(m.month))}</h1></header>
<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>${esc(monthName(m.month))}</h1></header>
@@ -152,9 +173,16 @@ ${notice(o)}
@@ -152,9 +173,16 @@ ${notice(o)}
<nav class="fin-monthnav" aria-label="Month"><a href="/month?m=${shiftMonth(m.month, -1)}">${esc(monthName(shiftMonth(m.month, -1)))}</a><b>${esc(monthName(m.month))}</b><a href="/month?m=${shiftMonth(m.month, 1)}">${esc(monthName(shiftMonth(m.month, 1)))}</a></nav>
<nav class="fin-monthnav" aria-label="Month"><a href="/month?m=${shiftMonth(m.month, -1)}">${esc(monthName(shiftMonth(m.month, -1)))}</a><b>${esc(monthName(m.month))}</b><a href="/month?m=${shiftMonth(m.month, 1)}">${esc(monthName(shiftMonth(m.month, 1)))}</a></nav>
<div class="fin-sums"><p><span>In</span><b class="fin-in">${esc(money(m.income_cents))}</b></p><p><span>Out</span><b class="fin-out">${esc(money(m.spent_cents))}</b></p>
<div class="fin-sums"><p><span>In</span><b class="fin-in">${esc(money(m.income_cents))}</b></p><p><span>Out</span><b class="fin-out">${esc(money(m.spent_cents))}</b></p>
<p><span>Left</span><b class="${m.income_cents - m.spent_cents < 0 ? 'is-neg' : ''}">${esc(money(m.income_cents - m.spent_cents))}</b></p></div>
<p><span>Left</span><b class="${m.income_cents - m.spent_cents < 0 ? 'is-neg' : ''}">${esc(money(m.income_cents - m.spent_cents))}</b></p></div>
-${spent.length ? `<ul class="fin-bars">${spent.map((c) => `<li><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span>
-<span class="fin-bar"><span style="--w:${Math.max(2, Math.round((c.out_cents / most) * 100))}%"></span></span><span class="fin-bar-sum">${esc(money(c.out_cents))}</span></li>`).join('')}</ul>`
- : '<p class="fin-empty">No spending this month.</p>'}
+${withBudget.length ? `<section class="fin-sec"><h2>Budgets</h2><p class="fin-budget-sum">${esc(money(usedOfBudgets))} of ${esc(money(budgeted))} spent</p>
+<ul class="fin-bars">${withBudget.map(budgetBar).join('')}</ul></section>` : ''}
+${without.length ? `<section class="fin-sec">${withBudget.length ? '<h2>Everything else</h2>' : ''}<ul class="fin-bars">${without.map(bar).join('')}</ul></section>` : (withBudget.length ? '' : '<p class="fin-empty">No spending this month.</p>')}
+<details class="fin-fold"><summary>${budgets.length ? 'Change a budget' : 'Set a monthly budget for a category'}</summary>
+<form class="fin-form" method="post" action="/budgets">${cats}
+<div class="fin-row"><label class="fin-field"><span>Category</span><input name="category" list="fin-cats" required maxlength="60" placeholder="Eating out" autocomplete="off"></label>
+<label class="fin-field"><span>A month</span><input name="amount" inputmode="decimal" placeholder="300.00 (empty removes it)" autocomplete="off"></label></div>
+<input type="hidden" name="back" value="${esc(m.month)}">
+<p><button class="fin-btn fin-btn--primary" type="submit">Save the budget</button></p>
+</form></details>
<p class="fin-note">Transfers between your own accounts are left out. Amounts in other currencies are added as they are.</p>` });
<p class="fin-note">Transfers between your own accounts are left out. Amounts in other currencies are added as they are.</p>` });
}
}
new file mode 100644
new file mode 100644
@@ -0,0 +1,81 @@
@@ -0,0 +1,81 @@
+'use strict';
+/**
+ * Budgets (migrations/0003_budgets.sql): a monthly limit for a category of spending, set from the month page; the month
+ * shows what is left or how much over, budgeted categories with nothing spent yet included; income, transfers and
+ * Uncategorized take no budget; an empty amount removes one; another person sees none; export carries them and delete
+ * removes them.
+ */
+const assert = require('assert');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const { createTestDb } = require('openvibe-sdk/testing');
+const { createVault } = require('../server/crypto');
+const { createStore } = require('../server/store');
+const { createApp } = require('../server/app');
+
+const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
+const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
+
+(async () => {
+ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
+ const vault = createVault(crypto.randomBytes(32).toString('base64'));
+ const store = createStore({ db, vault });
+ const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => { const u = req.get('x-test-user'); if (u) req.user = { subject_id: u }; next(); } };
+ const server = createApp({ db, vault, auth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
+ await new Promise((r) => server.once('listening', r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ const post = (p, form, as = ADA) => fetch(base + p, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': as, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString() })
+ .then(async (r) => ({ status: r.status, location: r.headers.get('location'), text: await r.text() }));
+ const page = (p, as = ADA) => fetch(base + p, { headers: { 'x-test-user': as } }).then((r) => r.text());
+ try {
+ const acc = await store.addAccount(ADA, { name: 'Checking' });
+ await store.importRows(ADA, acc.id, [
+ { posted_on: '2026-11-02', amount_cents: -24000, payee: 'Thai Garden', category: 'Eating out' },
+ { posted_on: '2026-11-09', amount_cents: -9000, payee: 'Pizza Place', category: 'Eating out' },
+ { posted_on: '2026-11-03', amount_cents: -12000, payee: 'Corner Grocer', category: 'Groceries' },
+ ]);
+
+ let r = await post('/budgets', { category: 'Eating out', amount: '300', back: '2026-11' });
+ assert.strictEqual(r.status, 303, r.text);
+ assert.strictEqual(r.location, '/month?m=2026-11&budgeted=1');
+ r = await post('/budgets', { category: 'Groceries', amount: '$400.00', back: '2026-11' });
+ r = await post('/budgets', { category: 'Health', amount: '50', back: '2026-11' });
+ assert.deepStrictEqual(await store.budgets(ADA), [
+ { category: 'Eating out', monthly_cents: 30000 }, { category: 'Groceries', monthly_cents: 40000 }, { category: 'Health', monthly_cents: 5000 }]);
+
+ let html = await page('/month?m=2026-11');
+ assert.match(html, /\$30\.00 over/, 'Eating out: $330 of $300');
+ assert.match(html, /\$280\.00 left/, 'Groceries: $120 of $400');
+ assert.match(html, /\$50\.00 left/, 'Health: nothing spent yet, still shown');
+ assert.match(html, /\$450\.00 of \$750\.00 spent/, '$330 + $120 + $0, the overspend counted');
+ assert.match(html, /class="is-over"/);
+
+ r = await post('/budgets', { category: 'Eating out', amount: '400', back: '2026-11' });
+ assert.strictEqual((await store.budgets(ADA))[0].monthly_cents, 40000, 'the same category again replaces it');
+ r = await post('/budgets', { category: 'Health', amount: '', back: '2026-11' });
+ assert.strictEqual(r.location, '/month?m=2026-11&unbudgeted=1');
+ assert.ok(!(await store.budgets(ADA)).some((b) => b.category === 'Health'), 'an empty amount removes it');
+
+ for (const category of ['Income', 'Transfers', 'Uncategorized']) {
+ r = await post('/budgets', { category, amount: '100' });
+ assert.strictEqual(r.status, 422, category);
+ }
+ r = await post('/budgets', { category: 'Fees', amount: 'lots' });
+ assert.strictEqual(r.status, 422);
+ r = await fetch(`${base}/budgets`, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'cross-site', 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: 'category=Fees&amount=5' });
+ assert.strictEqual(r.status, 403);
+
+ assert.deepStrictEqual((await fetch(`${base}/api/v1/budgets`, { headers: { 'x-test-user': BO } }).then((x) => x.json())).budgets, [], 'nobody sees another person\'s');
+ const put = await fetch(`${base}/api/v1/budgets/${encodeURIComponent('Shopping')}`, { method: 'PUT', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': ADA, 'content-type': 'application/json' }, body: JSON.stringify({ monthly_cents: 10000 }) });
+ assert.strictEqual(put.status, 200);
+ assert.ok((await store.budgets(ADA)).some((b) => b.category === 'Shopping'));
+
+ assert.strictEqual((await store.exportAll(ADA)).budgets.length, 3);
+ await store.removeAll(ADA);
+ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_budgets WHERE owner = $1', [ADA])), 0);
+ } finally {
+ server.close();
+ await close();
+ }
+ console.log('budgets: set, replaced and removed; left and over on the month; refused where they mean nothing; exported and deleted');
+})().catch((err) => { console.error(err); process.exit(1); });
@@ -37,6 +37,9 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
@@ -37,6 +37,9 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
`;
`;
await store.importRows(ADA, checking.id, readCsv(csv).rows);
await store.importRows(ADA, checking.id, readCsv(csv).rows);
await store.importRows(ADA, card.id, readCsv('Date,Payee,Amount\n2026-11-07,Airline Tickets,-412.20\n2026-11-10,Hotel Downtown,-268.00\n').rows);
await store.importRows(ADA, card.id, readCsv('Date,Payee,Amount\n2026-11-07,Airline Tickets,-412.20\n2026-11-10,Hotel Downtown,-268.00\n').rows);
+ await store.setBudget(ADA, 'Eating out', 4000);
+ await store.setBudget(ADA, 'Groceries', 40000);
+ await store.setBudget(ADA, 'Health', 5000);
const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => { if (!req.get('x-guest')) req.user = { subject_id: ADA }; next(); } };
const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => { if (!req.get('x-guest')) req.user = { subject_id: ADA }; next(); } };
const app = createApp({ db, vault, auth, baseUrl: 'http://127.0.0.1', now: () => new Date('2026-11-18T12:00:00Z') });
const app = createApp({ db, vault, auth, baseUrl: 'http://127.0.0.1', now: () => new Date('2026-11-18T12:00:00Z') });
const server = app.listen(Number(process.argv[2] || 0), '127.0.0.1', () => console.log(`port ${server.address().port} account ${checking.id}`));
const server = app.listen(Number(process.argv[2] || 0), '127.0.0.1', () => console.log(`port ${server.address().port} account ${checking.id}`));