openvibers/openvibe.finance Commits
Goals and debt (v0.6) (#6)
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.5)++## What it does today (v0.6)- 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 download:@@@ -23,13 +23,17 @@ 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).++- Goals: an amount to reach, by a date or not, tracking a savings account or an amount kept by hand; the page says++ what a month reaches it in time.++- Debt: a loan's or card's yearly rate and monthly payment give when it is paid off, the interest it costs, and what++ paying a little more saves.- Budgets: a monthly limit per category of spending; the month shows each against its limit (left, or over) and therest 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: goals and debt, scenarios, the Link plugin++Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: scenarios, the Link pluginfor local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.## Runningnnew file mode 100644@@@ -0,0 +1,21 @@++-- phase: expand++-- Goals and debt (plan §L.2: "goals and debt").++-- * A goal: an amount to reach, by a date or not; its progress is an account's balance (a savings account set aside++-- for it) or an amount the person keeps up to date by hand.++-- * Debt: a loan or a card account may say its yearly interest rate (basis points: 2499 is 24.99%) and the payment++-- made each month; the page works out when it is paid off and what the interest costs.++CREATE TABLE finance_goals (++ id text COLLATE "C" PRIMARY KEY,++ owner text COLLATE "C" NOT NULL,++ name text NOT NULL,++ target_cents bigint NOT NULL CHECK (target_cents > 0),++ target_on date,++ account_id text COLLATE "C" REFERENCES finance_accounts (id) ON DELETE SET NULL,++ saved_cents bigint NOT NULL DEFAULT 0,++ created_at timestamptz NOT NULL DEFAULT now(),++ updated_at timestamptz NOT NULL DEFAULT now()++);++CREATE INDEX finance_goals_owner ON finance_goals (owner, created_at);++++ALTER TABLE finance_accounts ADD COLUMN IF NOT EXISTS apr_bps integer CHECK (apr_bps IS NULL OR (apr_bps >= 0 AND apr_bps <= 10000));++ALTER TABLE finance_accounts ADD COLUMN IF NOT EXISTS payment_cents bigint CHECK (payment_cents IS NULL OR payment_cents > 0);@@@ -1,12 +1,12 @@{"name": "openvibe-finance",-- "version": "0.5.0",++ "version": "0.6.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openvibe-finance",-- "version": "0.5.0",++ "version": "0.6.0","license": "AGPL-3.0-only","dependencies": {"@electric-sql/pglite": "^0.5.8",@@@ -1,6 +1,6 @@{"name": "openvibe-finance",-- "version": "0.5.0",++ "version": "0.6.0","private": true,"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you","main": "server/index.js",@@@ -111,3 +111,22 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco.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; }++/* Goals and debt (v0.6). */++.fin-goals { list-style: none; padding: 0; margin: 0 0 10px; display: grid; gap: 10px; }++.fin-goal { display: grid; gap: 8px; padding: 12px 14px; border-radius: 14px; border: 1px solid var(--border, #1f2937); }++.fin-goal-top { display: flex; justify-content: space-between; gap: 10px; align-items: baseline; flex-wrap: wrap; }++.fin-goal-top span { font-variant-numeric: tabular-nums; color: var(--text-secondary, #9aa4b2); }++.fin-goal-top a { color: inherit; }++.fin-goal.is-done .fin-bar > span { background: var(--success, #22c55e); }++.fin-goal-note { margin: 0; color: var(--text-secondary, #9aa4b2); font-size: 14px; line-height: 1.45; }++.fin-goal-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }++.fin-goal-tools .fin-mini, .fin-goal-tools input { min-height: 44px; }++.fin-goal-remove { margin-left: auto; }++.fin-mini--quiet { border-color: transparent; }++.fin-saved { display: flex; align-items: center; gap: 8px; color: var(--text-secondary, #9aa4b2); font-size: 14px; }++.fin-saved input { width: 7.5em; font-variant-numeric: tabular-nums; }++.fin-goal-tip { margin: 0; padding: 8px 12px; border-radius: 10px; background: color-mix(in srgb, var(--success, #22c55e) 10%, transparent); color: var(--text, #e8ecf3); font-size: 14px; line-height: 1.45; }++.fin-fold--quiet { margin: 0; border: 0; padding: 0; background: none; }++.fin-fold--quiet > summary { min-height: 44px; display: flex; align-items: center; padding: 0; font-weight: 500; color: var(--text-secondary, #9aa4b2); font-size: 14px; }++.fin-debt { align-items: end; }++.fin-debt p { margin: 0; }@@@ -67,6 +67,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.goal) return 'Goal added.';++ if (q.debt) return 'Saved.';if (q.budgeted) return 'Budget saved.';if (q.unbudgeted) return 'Budget removed.';if (q.added) return 'Added.';@@@ -140,6 +142,31 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowconst today = now().toISOString().slice(0, 10);res.send(v.billsPage({ found: findRecurring(await store.recent(me), { today }), today }));}));++ app.get('/goals', handle(async (req, res) => {++ const me = who(req);++ if (!me) return signIn(req, res);++ res.send(v.goalsPage({ goals: await store.goals(me), accounts: await store.accounts(me), today: now().toISOString().slice(0, 10), o: { said: said(req.query) } }));++ }));++ const writer = (fn) => [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.');++ await fn(me, req, res);++ })];++ const cents = (text, what) => { const c = readAmount(text); if (c == null) throw new FinanceError(422, 'finance.amount', `${what} is not a number.`); return Math.abs(c); };++ app.post('/goals', ...writer(async (me, req, res) => {++ await store.addGoal(me, { name: req.body.name, target_cents: cents(req.body.target, 'The amount'), target_on: req.body.target_on || null, account_id: req.body.account || null });++ res.redirect(303, '/goals?goal=1');++ }));++ app.post('/goals/:id/saved', ...writer(async (me, req, res) => { await store.setGoalSaved(me, req.params.id, cents(req.body.saved, 'Saved so far')); res.redirect(303, '/goals'); }));++ app.post('/goals/:id/delete', ...writer(async (me, req, res) => { await store.removeGoal(me, req.params.id); res.redirect(303, '/goals'); }));++ app.post('/accounts/:id/debt', ...writer(async (me, req, res) => {++ const aprText = String(req.body.apr || '').trim(), payText = String(req.body.payment || '').trim();++ const apr = aprText ? Math.round(Number(aprText.replace('%', '')) * 100) : null;++ if (aprText && !Number.isFinite(apr)) throw new FinanceError(422, 'finance.debt.rate', 'The rate is not a number.');++ await store.setDebt(me, req.params.id, { apr_bps: apr, payment_cents: payText ? cents(payText, 'The payment') : null });++ res.redirect(303, '/goals?debt=1');++ }));app.get('/rules', handle(async (req, res) => {const me = who(req);if (!me) return signIn(req, res);@@@ -200,6 +227,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowapi.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.get('/goals', handle(async (req, res) => res.json({ goals: await store.goals(who(req)) })));++ api.post('/goals', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addGoal(who(req), req.body || {}))));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)) });nnew file mode 100644@@@ -0,0 +1,47 @@++'use strict';++/**++ * The arithmetic of goals and debt (plan §L.2), on whole cents, with no rounding drift that matters to a person.++ *++ * payoff({ owed_cents, apr_bps, payment_cents }) → { months, interest_cents, never } (never: the payment does not++ * cover the interest, so the balance never falls)++ * faster({ owed_cents, apr_bps, payment_cents }, extra_cents) → { months_sooner, interest_saved_cents }++ * perMonth({ target_cents, have_cents, target_on, today }) → cents a month to reach it by then (0 when reached,++ * null without a date or when the date has passed)++ */++++function payoff({ owed_cents, apr_bps = 0, payment_cents }) {++ let owed = Math.max(0, Math.round(owed_cents));++ if (!owed) return { months: 0, interest_cents: 0, never: false };++ if (!payment_cents || payment_cents <= 0) return { months: null, interest_cents: null, never: true };++ const rate = Math.max(0, apr_bps) / 10000 / 12;++ let months = 0, interest = 0;++ while (owed > 0 && months < 1200) {++ const charge = Math.round(owed * rate);++ if (payment_cents <= charge) return { months: null, interest_cents: null, never: true };++ interest += charge;++ owed = owed + charge - payment_cents;++ months++;++ }++ return months >= 1200 ? { months: null, interest_cents: null, never: true } : { months, interest_cents: interest, never: false };++}++++function faster(debt, extra_cents) {++ const now = payoff(debt);++ const more = payoff({ ...debt, payment_cents: (debt.payment_cents || 0) + extra_cents });++ if (more.never) return null;++ if (now.never) return { months_sooner: null, interest_saved_cents: null, months: more.months };++ return { months_sooner: now.months - more.months, interest_saved_cents: now.interest_cents - more.interest_cents, months: more.months };++}++++function perMonth({ target_cents, have_cents, target_on, today = new Date().toISOString().slice(0, 10) }) {++ const left = target_cents - Math.max(0, have_cents);++ if (left <= 0) return 0;++ if (!target_on) return null;++ const [ty, tm] = target_on.split('-').map(Number);++ const [ny, nm] = today.split('-').map(Number);++ const months = (ty - ny) * 12 + (tm - nm);++ if (months <= 0) return null;++ return Math.ceil(left / months);++}++++module.exports = { payoff, faster, perMonth };@@@ -19,6 +19,9 @@* removeRule(owner, id)* budgets(owner) → [{ category, monthly_cents }]* setBudget(owner, category, cents|null) a monthly limit for a category; null or 0 removes it++ * goals(owner) → [{ id, name, target_cents, target_on, account_id, saved_cents, have_cents }]++ * addGoal(owner, { name, target_cents, target_on, account_id, saved_cents }) / setGoalSaved(owner, id, cents) / removeGoal++ * setDebt(owner, accountId, { apr_bps, payment_cents }) a loan's or card's rate and monthly payment* exportAll(owner) → everything, opened (the person's own copy)* removeAll(owner) → everything of theirs deleted*/@@@ -54,11 +57,12 @@ function createStore({ db, vault }) {async function accounts(owner) {own(owner);-- const rows = await db.many(`SELECT a.id, a.name, a.kind, a.currency, a.opening_cents,++ const rows = await db.many(`SELECT a.id, a.name, a.kind, a.currency, a.opening_cents, a.apr_bps, a.payment_cents,COALESCE(SUM(t.amount_cents), 0)::bigint AS moved, COUNT(t.id)::int AS count, MAX(t.posted_on) AS last_onFROM finance_accounts a LEFT JOIN finance_transactions t ON t.account_id = a.idWHERE a.owner = $1 AND a.archived_at IS NULL GROUP BY a.id ORDER BY a.created_at, a.id`, [owner]);-- return rows.map((r) => ({ id: r.id, name: r.name, kind: r.kind, currency: r.currency, balance_cents: Number(r.opening_cents) + Number(r.moved), count: r.count, last_on: r.last_on || null }));++ return rows.map((r) => ({ id: r.id, name: r.name, kind: r.kind, currency: r.currency, balance_cents: Number(r.opening_cents) + Number(r.moved), count: r.count, last_on: r.last_on || null,++ apr_bps: r.apr_bps == null ? null : Number(r.apr_bps), payment_cents: r.payment_cents == null ? null : Number(r.payment_cents) }));}/** Every transaction of the person from the last `days` days, across their accounts, opened (recurring, scenarios). */@@@ -257,9 +261,57 @@ function createStore({ db, vault }) {return { category: c, monthly_cents: cents };}++ async function goals(owner) {++ own(owner);++ const rows = await db.many('SELECT * FROM finance_goals WHERE owner = $1 ORDER BY created_at, id', [owner]);++ const balances = new Map((await accounts(owner)).map((a) => [a.id, a.balance_cents]));++ return rows.map((g) => ({++ id: g.id, name: g.name, target_cents: Number(g.target_cents), target_on: g.target_on || null, account_id: g.account_id || null,++ saved_cents: Number(g.saved_cents), have_cents: g.account_id && balances.has(g.account_id) ? balances.get(g.account_id) : Number(g.saved_cents),++ }));++ }++++ async function addGoal(owner, input = {}) {++ own(owner);++ const name = String(input.name || '').replace(/\s+/g, ' ').trim().slice(0, 80);++ if (!name) fail(422, 'finance.goal.name', 'Give the goal a name.');++ if (!Number.isSafeInteger(input.target_cents) || input.target_cents <= 0) fail(422, 'finance.goal.target', 'A goal is an amount to reach.');++ const on = input.target_on ? String(input.target_on) : null;++ if (on && (!DAY.test(on) || Number.isNaN(Date.parse(`${on}T00:00:00Z`)))) fail(422, 'finance.goal.date', 'A date is YYYY-MM-DD.');++ let accountId = input.account_id ? String(input.account_id) : null;++ if (accountId && !(await account(owner, accountId))) fail(404, 'finance.account.not_found', 'No such account of yours.');++ const saved = Number.isSafeInteger(input.saved_cents) && input.saved_cents > 0 ? input.saved_cents : 0;++ if (Number(await db.value('SELECT count(*) FROM finance_goals WHERE owner = $1', [owner])) >= 50) fail(422, 'finance.goal.limit', 'Fifty goals is the most for now.');++ const id = newId('gol');++ await db.exec('INSERT INTO finance_goals (id, owner, name, target_cents, target_on, account_id, saved_cents) VALUES ($1, $2, $3, $4, $5, $6, $7)', [id, owner, name, input.target_cents, on, accountId, saved]);++ return (await goals(owner)).find((g) => g.id === id);++ }++++ async function setGoalSaved(owner, id, cents) {++ own(owner);++ if (!Number.isSafeInteger(cents) || cents < 0) fail(422, 'finance.goal.saved', 'An amount saved is a number.');++ const n = await db.exec('UPDATE finance_goals SET saved_cents = $3, updated_at = now() WHERE id = $1 AND owner = $2', [String(id || ''), owner, cents]);++ if (!n) fail(404, 'finance.goal.not_found', 'No such goal of yours.');++ }++++ async function removeGoal(owner, id) {++ own(owner);++ await db.exec('DELETE FROM finance_goals WHERE id = $1 AND owner = $2', [String(id || ''), owner]);++ }++++ async function setDebt(owner, accountId, { apr_bps = null, payment_cents = null } = {}) {++ own(owner);++ const acc = await db.maybe('SELECT id, kind FROM finance_accounts WHERE id = $1 AND owner = $2 AND archived_at IS NULL', [String(accountId || ''), owner]);++ if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.');++ if (!['loan', 'credit'].includes(acc.kind)) fail(422, 'finance.debt.kind', 'Only a loan or a credit card has a rate and a payment.');++ if (apr_bps != null && (!Number.isInteger(apr_bps) || apr_bps < 0 || apr_bps > 10000)) fail(422, 'finance.debt.rate', 'A yearly rate is between 0% and 100%.');++ if (payment_cents != null && (!Number.isSafeInteger(payment_cents) || payment_cents <= 0)) fail(422, 'finance.debt.payment', 'A monthly payment is an amount of money.');++ await db.exec('UPDATE finance_accounts SET apr_bps = $3, payment_cents = $4, updated_at = now() WHERE id = $1 AND owner = $2', [acc.id, owner, apr_bps, payment_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]);++ const accs = await db.many('SELECT id, name, kind, currency, opening_cents, apr_bps, payment_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);const txns = await db.many('SELECT * FROM finance_transactions WHERE owner = $1 ORDER BY posted_on, created_at', [owner]);return {exported_at: new Date().toISOString(), format: 'openvibe.finance.export@1',@@@ -267,6 +319,7 @@ function createStore({ db, vault }) {transactions: txns.map((r) => open(owner, r)),rules: (await rules(owner)).map((r) => ({ match: r.match, category: r.category })),budgets: await budgets(owner),++ goals: (await goals(owner)).map(({ have_cents, ...g }) => g),};}@@@ -277,11 +330,12 @@ function createStore({ db, vault }) {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_goals 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, budgets, setBudget, exportAll, removeAll };++ return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, goals, addGoal, setGoalSaved, removeGoal, setDebt, exportAll, removeAll };}module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };@@@ -7,6 +7,7 @@const shell = require('openvibe-shared/shell');const serve = require('openvibe-shared/serve');const { CATEGORIES, KINDS } = require('./store');++const { payoff, faster, perMonth } = require('./plan');const SITE = 'https://openvibe.finance';const esc = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));@@@ -21,7 +22,7 @@ const KIND_WORDS = { checking: 'Checking', savings: 'Savings', credit: 'Credit cfunction page({ title, body, path = '/', description = 'Your money, your rules, your data: accounts, imports and a monthly picture, private to you.', robots = 'noindex, nofollow' }) {return shell.page({name: 'OpenVibe.Finance', siteName: 'OpenVibe.Finance', title, description, canonical: `${SITE}${path}`, robots,-- navbar: { service: 'finance', apiBase: 'https://openvibe.network', links: [{ label: 'Money', href: '/' }, { label: 'This month', href: '/month' }, { label: 'Recurring', href: '/bills' }] },++ navbar: { service: 'finance', apiBase: 'https://openvibe.network', links: [{ label: 'Money', href: '/' }, { label: 'This month', href: '/month' }, { label: 'Recurring', href: '/bills' }, { label: 'Goals', href: '/goals' }] },footer: { service: 'finance', variant: 'full', mount: '#ov-footer' },head: `<link rel="stylesheet" href="${serve.url('kit.css')}"><link rel="stylesheet" href="/finance.css"><script src="/finance.js" defer></script>`,body: `<div id="navbar-mount"></div><main id="main" class="ovk-page fin">${body}</main>`,@@@ -69,7 +70,7 @@ ${accounts.length ? `<section class="fin-month-card" aria-label="${esc(monthName<label class="fin-field"><span>Balance before the first transaction</span><input name="opening" inputmode="decimal" placeholder="0.00" autocomplete="off"></label></div><p><button class="fin-btn fin-btn--primary" type="submit">Add the account</button></p></form></details>--<p class="fin-foot"><a href="/bills">Recurring bills</a> · <a href="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });++<p class="fin-foot"><a href="/goals">Goals and debt</a> · <a href="/bills">Recurring bills</a> · <a href="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });}const CADENCE_WORDS = { weekly: 'Every week', 'every two weeks': 'Every two weeks', monthly: 'Every month', quarterly: 'Every three months', yearly: 'Every year' };@@@ -94,6 +95,64 @@ ${soon.length ? `<section class="fin-sec"><h2>The next 31 days</h2><ul class="fi${income.length ? `<section class="fin-sec"><h2>Money that comes in regularly</h2><ul class="fin-bills">${income.map(row).join('')}</ul></section>` : ''}` });}++const monthsWords = (n) => (n < 12 ? `${n} month${n === 1 ? '' : 's'}` : `${Math.floor(n / 12)} year${n >= 24 ? 's' : ''}${n % 12 ? ` ${n % 12} month${n % 12 === 1 ? '' : 's'}` : ''}`);++const pct = (bps) => `${(bps / 100).toFixed(2).replace(/\.?0+$/, '')}%`;++++function goalsPage({ goals, accounts, today, o = {} }) {++ const debts = accounts.filter((a) => (a.kind === 'loan' || a.kind === 'credit'));++ const savings = accounts.filter((a) => a.kind !== 'loan' && a.kind !== 'credit');++ const goalRow = (g) => {++ const have = Math.max(0, g.have_cents);++ const done = have >= g.target_cents;++ const need = perMonth({ target_cents: g.target_cents, have_cents: have, target_on: g.target_on, today });++ const tracked = g.account_id ? accounts.find((a) => a.id === g.account_id) : null;++ return `<li class="fin-goal${done ? ' is-done' : ''}"><div class="fin-goal-top"><b>${esc(g.name)}</b><span>${esc(money(have))} of ${esc(money(g.target_cents))}</span></div>++<span class="fin-bar fin-bar--budget"><span style="--w:${Math.min(100, Math.round((have / g.target_cents) * 100))}%"></span></span>++<p class="fin-goal-note">${done ? 'Reached.' : need ? `${esc(money(need))} a month reaches it by ${esc(monthName(g.target_on.slice(0, 7)))}.` : g.target_on ? `The date (${esc(monthName(g.target_on.slice(0, 7)))}) has passed.` : 'No date: it is there when it is there.'}++${tracked ? ` Tracks <a href="/accounts/${esc(tracked.id)}">${esc(tracked.name)}</a>.` : ''}</p>++<div class="fin-goal-tools">${tracked ? '' : `<form method="post" action="/goals/${esc(g.id)}/saved" class="fin-cat"><label class="fin-saved"><span>Saved</span><input name="saved" inputmode="decimal" value="${(g.saved_cents / 100).toFixed(2)}" autocomplete="off"></label><button type="submit" class="fin-mini">Update</button></form>`}++<form method="post" action="/goals/${esc(g.id)}/delete" class="fin-goal-remove"><button type="submit" class="fin-mini fin-mini--quiet">Remove</button></form></div></li>`;++ };++ const debtRow = (a) => {++ const owed = Math.max(0, -a.balance_cents);++ const terms = a.apr_bps != null && a.payment_cents;++ let said = 'Add its yearly rate and your monthly payment to see when it is paid off.';++ let tip = '';++ if (!owed) said = 'Nothing owed.';++ else if (terms) {++ const p = payoff({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents });++ if (p.never) said = `At ${esc(money(a.payment_cents))} a month it never gets paid off: that does not cover the ${esc(pct(a.apr_bps))} interest.`;++ else {++ const extra = Math.max(2500, Math.round(a.payment_cents * 0.25 / 500) * 500);++ const f = faster({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents }, extra);++ said = `Paid off in <b>${esc(monthsWords(p.months))}</b> at ${esc(money(a.payment_cents))} a month, ${esc(money(p.interest_cents))} of it interest (${esc(pct(a.apr_bps))} a year).`;++ if (f && f.months_sooner) tip = `${esc(money(extra))} more a month: ${esc(monthsWords(f.months_sooner))} sooner and ${esc(money(f.interest_saved_cents))} less interest.`;++ }++ }++ return `<li class="fin-goal"><div class="fin-goal-top"><b><a href="/accounts/${esc(a.id)}">${esc(a.name)}</a></b><span>${esc(money(owed, a.currency))} owed</span></div>++<p class="fin-goal-note">${said}</p>${tip ? `<p class="fin-goal-tip">${tip}</p>` : ''}++${terms ? '<details class="fin-fold fin-fold--quiet"><summary>Change the rate or payment</summary>' : ''}<form class="fin-row fin-debt" method="post" action="/accounts/${esc(a.id)}/debt">++<label class="fin-field"><span>Yearly rate (%)</span><input name="apr" inputmode="decimal" value="${a.apr_bps != null ? (a.apr_bps / 100).toFixed(2) : ''}" placeholder="24.99" autocomplete="off"></label>++<label class="fin-field"><span>Monthly payment</span><input name="payment" inputmode="decimal" value="${a.payment_cents ? (a.payment_cents / 100).toFixed(2) : ''}" placeholder="150.00" autocomplete="off"></label>++<p><button class="fin-btn" type="submit">Save</button></p></form>${terms ? '</details>' : ''}</li>`;++ };++ const accountChips = savings.map((a) => `<label class="fin-chip"><input type="radio" name="account" value="${esc(a.id)}"><span>${esc(a.name)}</span></label>`).join('');++ return page({++ title: 'Goals and debt', path: '/goals', body: `++<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Goals and debt</h1></header>++${notice(o)}++<section class="fin-sec"><h2>Goals</h2>${goals.length ? `<ul class="fin-goals">${goals.map(goalRow).join('')}</ul>` : '<p class="fin-empty">No goals yet: an emergency fund, a trip, a deposit.</p>'}++<details class="fin-fold"><summary>Add a goal</summary>++<form class="fin-form" method="post" action="/goals">++<label class="fin-field"><span>Name</span><input name="name" maxlength="80" required placeholder="Emergency fund" autocomplete="off"></label>++<div class="fin-row"><label class="fin-field"><span>Amount</span><input name="target" inputmode="decimal" required placeholder="5000" autocomplete="off"></label>++<label class="fin-field"><span>By (optional)</span><input type="date" name="target_on"></label></div>++${savings.length ? `<fieldset class="fin-chips"><legend>Its progress is (optional)</legend><label class="fin-chip"><input type="radio" name="account" value="" checked><span>What I enter</span></label>${accountChips}</fieldset>` : ''}++<p><button class="fin-btn fin-btn--primary" type="submit">Add the goal</button></p>++</form></details></section>++<section class="fin-sec"><h2>Debt</h2>${debts.length ? `<ul class="fin-goals">${debts.map(debtRow).join('')}</ul>` : '<p class="fin-empty">No loans or credit cards. Add one as an account (its kind: Loan or Credit card) to plan paying it off.</p>'}</section>` });++}++function rulesPage({ rules, o = {} }) {return page({title: 'Your category rules', path: '/rules', body: `@@@ -198,4 +257,4 @@ ${notice(o)}<p><button class="fin-btn fin-btn--danger" type="submit">Delete everything</button></p></form></section>` });}--module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, money, esc, monthName };++module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, money, esc, monthName };nnew file mode 100644@@@ -0,0 +1,84 @@++'use strict';++/**++ * Goals and debt (migrations/0004, server/plan.js): payoff months and interest, a payment that never covers the++ * interest, paying more; a goal's amount a month to reach it by its date; goals tracking an account or a hand-kept++ * amount; a card's rate and payment from the page; only loans and cards take them; export and delete carry them.++ */++const assert = require('assert');++const path = require('node:path');++const crypto = require('node:crypto');++const { payoff, faster, perMonth } = require('../server/plan');++++assert.deepStrictEqual(payoff({ owed_cents: 500000, apr_bps: 0, payment_cents: 15000 }), { months: 34, interest_cents: 0, never: false }, '$5,000 at 0%, $150 a month');++const card = payoff({ owed_cents: 500000, apr_bps: 2499, payment_cents: 15000 });++// The standard amortisation: n = -ln(1 - rP/A) / ln(1 + r) = 57.5 months, about $3,622 of interest.++assert.deepStrictEqual(card, { months: 58, interest_cents: 362226, never: false }, '$5,000 at 24.99%, $150 a month');++assert.strictEqual(payoff({ owed_cents: 500000, apr_bps: 2499, payment_cents: 10000 }).never, true, '$100 a month never covers $104 of interest');++assert.deepStrictEqual(payoff({ owed_cents: 0, apr_bps: 2499, payment_cents: 15000 }), { months: 0, interest_cents: 0, never: false });++const more = faster({ owed_cents: 500000, apr_bps: 2499, payment_cents: 15000 }, 5000);++assert.ok(more.months_sooner > 0 && more.interest_saved_cents > 0, 'paying more is sooner and cheaper');++assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: '2027-11-01', today: '2026-11-18' }), 50000, '$6,000 in 12 months');++assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 600000, target_on: '2027-11-01', today: '2026-11-18' }), 0, 'reached');++assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: null, today: '2026-11-18' }), null, 'no date');++assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: '2026-10-01', today: '2026-11-18' }), null, 'past');++++(async () => {++ const { createTestDb } = require('openvibe-sdk/testing');++ const { createVault } = require('../server/crypto');++ const { createStore } = require('../server/store');++ const { createApp } = require('../server/app');++ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });++ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';++ 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, site = 'same-origin') => fetch(base + p, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': site, 'x-test-user': ADA, '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() }));++ try {++ const savings = await store.addAccount(ADA, { name: 'Rainy day', kind: 'savings', opening_cents: 120000 });++ const visa = await store.addAccount(ADA, { name: 'Visa', kind: 'credit', opening_cents: -500000 });++ const checking = await store.addAccount(ADA, { name: 'Checking', kind: 'checking' });++++ let r = await post('/goals', { name: 'Emergency fund', target: '6,000', target_on: '2027-11-01', account: savings.id });++ assert.strictEqual(r.status, 303, r.text);++ r = await post('/goals', { name: 'Trip to Lisbon', target: '1500', account: '' });++ let goals = await store.goals(ADA);++ assert.deepStrictEqual(goals.map((g) => [g.name, g.target_cents, g.have_cents]), [['Emergency fund', 600000, 120000], ['Trip to Lisbon', 150000, 0]]);++ r = await post(`/goals/${goals[1].id}/saved`, { saved: '400' });++ assert.strictEqual((await store.goals(ADA))[1].have_cents, 40000, 'a hand-kept amount');++++ r = await post(`/accounts/${visa.id}/debt`, { apr: '24.99', payment: '150' });++ assert.strictEqual(r.status, 303, r.text);++ const acc = (await store.accounts(ADA)).find((a) => a.id === visa.id);++ assert.deepStrictEqual([acc.apr_bps, acc.payment_cents], [2499, 15000]);++ r = await post(`/accounts/${checking.id}/debt`, { apr: '5', payment: '10' });++ assert.strictEqual(r.status, 422, 'a checking account has no rate');++ assert.match(r.text, /Only a loan or a credit card/);++ r = await post('/goals', { name: 'x', target: '5' }, 'cross-site');++ assert.strictEqual(r.status, 403);++++ const html = await fetch(`${base}/goals`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());++ assert.match(html, /\$1,200\.00 of \$6,000\.00/);++ assert.match(html, /\$400\.00 a month reaches it by November 2027/, '$4,800 left over 12 months');++ assert.match(html, /Tracks <a href="\/accounts\//);++ assert.match(html, /\$5,000\.00 owed/);++ assert.match(html, /Paid off in <b>\d+ (months|years?)/);++ assert.match(html, /more a month: .* sooner and .* less interest/);++ assert.match(html, /Change the rate or payment/, 'set terms fold away');++++ const ex = await store.exportAll(ADA);++ assert.strictEqual(ex.goals.length, 2);++ assert.strictEqual(ex.accounts.find((a) => a.id === visa.id).apr_bps, 2499);++ await post(`/goals/${goals[1].id}/delete`, {});++ assert.strictEqual((await store.goals(ADA)).length, 1);++ await store.removeAll(ADA);++ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_goals WHERE owner = $1', [ADA])), 0);++ } finally {++ server.close();++ await close();++ }++ console.log('goals and debt: payoff and interest, never, paying more, a month to reach a goal, the page, export and delete');++})().catch((err) => { console.error(err); process.exit(1); });@@@ -40,6 +40,10 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';await store.setBudget(ADA, 'Eating out', 4000);await store.setBudget(ADA, 'Groceries', 40000);await store.setBudget(ADA, 'Health', 5000);++ const rainy = (await store.accounts(ADA)).find((x) => x.name === 'Rainy day');++ await store.addGoal(ADA, { name: 'Emergency fund', target_cents: 1000000, target_on: '2027-11-01', account_id: rainy.id });++ await store.addGoal(ADA, { name: 'Trip to Lisbon', target_cents: 150000, saved_cents: 40000 });++ await store.setDebt(ADA, card.id, { apr_bps: 2499, payment_cents: 15000 });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.5)
+## What it does today (v0.6)
- 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 download:
- Transactions typed in, or imported from a bank's download:
@@ -23,13 +23,17 @@ to connect.
@@ -23,13 +23,17 @@ 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).
+- Goals: an amount to reach, by a date or not, tracking a savings account or an amount kept by hand; the page says
+ what a month reaches it in time.
+- Debt: a loan's or card's yearly rate and monthly payment give when it is paid off, the interest it costs, and what
+ paying a little more saves.
- Budgets: a monthly limit per category of spending; the month shows each against its limit (left, or over) and the
- 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.
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: goals and debt, scenarios, the Link plugin
+Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: scenarios, 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,21 @@
@@ -0,0 +1,21 @@
+-- phase: expand
+-- Goals and debt (plan §L.2: "goals and debt").
+-- * A goal: an amount to reach, by a date or not; its progress is an account's balance (a savings account set aside
+-- for it) or an amount the person keeps up to date by hand.
+-- * Debt: a loan or a card account may say its yearly interest rate (basis points: 2499 is 24.99%) and the payment
+-- made each month; the page works out when it is paid off and what the interest costs.
+CREATE TABLE finance_goals (
+ id text COLLATE "C" PRIMARY KEY,
+ owner text COLLATE "C" NOT NULL,
+ name text NOT NULL,
+ target_cents bigint NOT NULL CHECK (target_cents > 0),
+ target_on date,
+ account_id text COLLATE "C" REFERENCES finance_accounts (id) ON DELETE SET NULL,
+ saved_cents bigint NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX finance_goals_owner ON finance_goals (owner, created_at);
+
+ALTER TABLE finance_accounts ADD COLUMN IF NOT EXISTS apr_bps integer CHECK (apr_bps IS NULL OR (apr_bps >= 0 AND apr_bps <= 10000));
+ALTER TABLE finance_accounts ADD COLUMN IF NOT EXISTS payment_cents bigint CHECK (payment_cents IS NULL OR payment_cents > 0);
@@ -1,12 +1,12 @@
@@ -1,12 +1,12 @@
{
{
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.5.0",
+ "version": "0.6.0",
"lockfileVersion": 3,
"lockfileVersion": 3,
"requires": true,
"requires": true,
"packages": {
"packages": {
"": {
"": {
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.5.0",
+ "version": "0.6.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.5.0",
+ "version": "0.6.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",
@@ -111,3 +111,22 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
@@ -111,3 +111,22 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
.fin-bar-sum { display: grid; justify-items: end; gap: 1px; }
.fin-bar-sum { display: grid; justify-items: end; gap: 1px; }
.fin-bar-sum small { color: var(--text-secondary, #9aa4b2); font-size: 12px; }
.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; }
.fin-budget-sum { margin: 0 0 10px; color: var(--text-secondary, #9aa4b2); font-variant-numeric: tabular-nums; }
+/* Goals and debt (v0.6). */
+.fin-goals { list-style: none; padding: 0; margin: 0 0 10px; display: grid; gap: 10px; }
+.fin-goal { display: grid; gap: 8px; padding: 12px 14px; border-radius: 14px; border: 1px solid var(--border, #1f2937); }
+.fin-goal-top { display: flex; justify-content: space-between; gap: 10px; align-items: baseline; flex-wrap: wrap; }
+.fin-goal-top span { font-variant-numeric: tabular-nums; color: var(--text-secondary, #9aa4b2); }
+.fin-goal-top a { color: inherit; }
+.fin-goal.is-done .fin-bar > span { background: var(--success, #22c55e); }
+.fin-goal-note { margin: 0; color: var(--text-secondary, #9aa4b2); font-size: 14px; line-height: 1.45; }
+.fin-goal-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+.fin-goal-tools .fin-mini, .fin-goal-tools input { min-height: 44px; }
+.fin-goal-remove { margin-left: auto; }
+.fin-mini--quiet { border-color: transparent; }
+.fin-saved { display: flex; align-items: center; gap: 8px; color: var(--text-secondary, #9aa4b2); font-size: 14px; }
+.fin-saved input { width: 7.5em; font-variant-numeric: tabular-nums; }
+.fin-goal-tip { margin: 0; padding: 8px 12px; border-radius: 10px; background: color-mix(in srgb, var(--success, #22c55e) 10%, transparent); color: var(--text, #e8ecf3); font-size: 14px; line-height: 1.45; }
+.fin-fold--quiet { margin: 0; border: 0; padding: 0; background: none; }
+.fin-fold--quiet > summary { min-height: 44px; display: flex; align-items: center; padding: 0; font-weight: 500; color: var(--text-secondary, #9aa4b2); font-size: 14px; }
+.fin-debt { align-items: end; }
+.fin-debt p { margin: 0; }
@@ -67,6 +67,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -67,6 +67,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.goal) return 'Goal added.';
+ if (q.debt) return 'Saved.';
if (q.budgeted) return 'Budget saved.';
if (q.budgeted) return 'Budget saved.';
if (q.unbudgeted) return 'Budget removed.';
if (q.unbudgeted) return 'Budget removed.';
if (q.added) return 'Added.';
if (q.added) return 'Added.';
@@ -140,6 +142,31 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -140,6 +142,31 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
const today = now().toISOString().slice(0, 10);
const today = now().toISOString().slice(0, 10);
res.send(v.billsPage({ found: findRecurring(await store.recent(me), { today }), today }));
res.send(v.billsPage({ found: findRecurring(await store.recent(me), { today }), today }));
}));
}));
+ app.get('/goals', handle(async (req, res) => {
+ const me = who(req);
+ if (!me) return signIn(req, res);
+ res.send(v.goalsPage({ goals: await store.goals(me), accounts: await store.accounts(me), today: now().toISOString().slice(0, 10), o: { said: said(req.query) } }));
+ }));
+ const writer = (fn) => [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.');
+ await fn(me, req, res);
+ })];
+ const cents = (text, what) => { const c = readAmount(text); if (c == null) throw new FinanceError(422, 'finance.amount', `${what} is not a number.`); return Math.abs(c); };
+ app.post('/goals', ...writer(async (me, req, res) => {
+ await store.addGoal(me, { name: req.body.name, target_cents: cents(req.body.target, 'The amount'), target_on: req.body.target_on || null, account_id: req.body.account || null });
+ res.redirect(303, '/goals?goal=1');
+ }));
+ app.post('/goals/:id/saved', ...writer(async (me, req, res) => { await store.setGoalSaved(me, req.params.id, cents(req.body.saved, 'Saved so far')); res.redirect(303, '/goals'); }));
+ app.post('/goals/:id/delete', ...writer(async (me, req, res) => { await store.removeGoal(me, req.params.id); res.redirect(303, '/goals'); }));
+ app.post('/accounts/:id/debt', ...writer(async (me, req, res) => {
+ const aprText = String(req.body.apr || '').trim(), payText = String(req.body.payment || '').trim();
+ const apr = aprText ? Math.round(Number(aprText.replace('%', '')) * 100) : null;
+ if (aprText && !Number.isFinite(apr)) throw new FinanceError(422, 'finance.debt.rate', 'The rate is not a number.');
+ await store.setDebt(me, req.params.id, { apr_bps: apr, payment_cents: payText ? cents(payText, 'The payment') : null });
+ res.redirect(303, '/goals?debt=1');
+ }));
app.get('/rules', handle(async (req, res) => {
app.get('/rules', handle(async (req, res) => {
const me = who(req);
const me = who(req);
if (!me) return signIn(req, res);
if (!me) return signIn(req, res);
@@ -200,6 +227,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -200,6 +227,8 @@ 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.get('/budgets', handle(async (req, res) => res.json({ budgets: await store.budgets(who(req)) })));
+ api.get('/goals', handle(async (req, res) => res.json({ goals: await store.goals(who(req)) })));
+ api.post('/goals', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addGoal(who(req), req.body || {}))));
api.put('/budgets/:category', express.json({ limit: '2kb' }), handle(async (req, res) => {
api.put('/budgets/:category', express.json({ limit: '2kb' }), handle(async (req, res) => {
const cents = req.body && req.body.monthly_cents;
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)) });
res.json({ budget: await store.setBudget(who(req), decodeURIComponent(req.params.category), cents == null ? null : Number(cents)) });
new file mode 100644
new file mode 100644
@@ -0,0 +1,47 @@
@@ -0,0 +1,47 @@
+'use strict';
+/**
+ * The arithmetic of goals and debt (plan §L.2), on whole cents, with no rounding drift that matters to a person.
+ *
+ * payoff({ owed_cents, apr_bps, payment_cents }) → { months, interest_cents, never } (never: the payment does not
+ * cover the interest, so the balance never falls)
+ * faster({ owed_cents, apr_bps, payment_cents }, extra_cents) → { months_sooner, interest_saved_cents }
+ * perMonth({ target_cents, have_cents, target_on, today }) → cents a month to reach it by then (0 when reached,
+ * null without a date or when the date has passed)
+ */
+
+function payoff({ owed_cents, apr_bps = 0, payment_cents }) {
+ let owed = Math.max(0, Math.round(owed_cents));
+ if (!owed) return { months: 0, interest_cents: 0, never: false };
+ if (!payment_cents || payment_cents <= 0) return { months: null, interest_cents: null, never: true };
+ const rate = Math.max(0, apr_bps) / 10000 / 12;
+ let months = 0, interest = 0;
+ while (owed > 0 && months < 1200) {
+ const charge = Math.round(owed * rate);
+ if (payment_cents <= charge) return { months: null, interest_cents: null, never: true };
+ interest += charge;
+ owed = owed + charge - payment_cents;
+ months++;
+ }
+ return months >= 1200 ? { months: null, interest_cents: null, never: true } : { months, interest_cents: interest, never: false };
+}
+
+function faster(debt, extra_cents) {
+ const now = payoff(debt);
+ const more = payoff({ ...debt, payment_cents: (debt.payment_cents || 0) + extra_cents });
+ if (more.never) return null;
+ if (now.never) return { months_sooner: null, interest_saved_cents: null, months: more.months };
+ return { months_sooner: now.months - more.months, interest_saved_cents: now.interest_cents - more.interest_cents, months: more.months };
+}
+
+function perMonth({ target_cents, have_cents, target_on, today = new Date().toISOString().slice(0, 10) }) {
+ const left = target_cents - Math.max(0, have_cents);
+ if (left <= 0) return 0;
+ if (!target_on) return null;
+ const [ty, tm] = target_on.split('-').map(Number);
+ const [ny, nm] = today.split('-').map(Number);
+ const months = (ty - ny) * 12 + (tm - nm);
+ if (months <= 0) return null;
+ return Math.ceil(left / months);
+}
+
+module.exports = { payoff, faster, perMonth };
@@ -19,6 +19,9 @@
@@ -19,6 +19,9 @@
* removeRule(owner, id)
* removeRule(owner, id)
* budgets(owner) → [{ category, monthly_cents }]
* budgets(owner) → [{ category, monthly_cents }]
* setBudget(owner, category, cents|null) a monthly limit for a category; null or 0 removes it
* setBudget(owner, category, cents|null) a monthly limit for a category; null or 0 removes it
+ * goals(owner) → [{ id, name, target_cents, target_on, account_id, saved_cents, have_cents }]
+ * addGoal(owner, { name, target_cents, target_on, account_id, saved_cents }) / setGoalSaved(owner, id, cents) / removeGoal
+ * setDebt(owner, accountId, { apr_bps, payment_cents }) a loan's or card's rate and monthly payment
* 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
*/
*/
@@ -54,11 +57,12 @@ function createStore({ db, vault }) {
@@ -54,11 +57,12 @@ function createStore({ db, vault }) {
async function accounts(owner) {
async function accounts(owner) {
own(owner);
own(owner);
- const rows = await db.many(`SELECT a.id, a.name, a.kind, a.currency, a.opening_cents,
+ const rows = await db.many(`SELECT a.id, a.name, a.kind, a.currency, a.opening_cents, a.apr_bps, a.payment_cents,
COALESCE(SUM(t.amount_cents), 0)::bigint AS moved, COUNT(t.id)::int AS count, MAX(t.posted_on) AS last_on
COALESCE(SUM(t.amount_cents), 0)::bigint AS moved, COUNT(t.id)::int AS count, MAX(t.posted_on) AS last_on
FROM finance_accounts a LEFT JOIN finance_transactions t ON t.account_id = a.id
FROM finance_accounts a LEFT JOIN finance_transactions t ON t.account_id = a.id
WHERE a.owner = $1 AND a.archived_at IS NULL GROUP BY a.id ORDER BY a.created_at, a.id`, [owner]);
WHERE a.owner = $1 AND a.archived_at IS NULL GROUP BY a.id ORDER BY a.created_at, a.id`, [owner]);
- return rows.map((r) => ({ id: r.id, name: r.name, kind: r.kind, currency: r.currency, balance_cents: Number(r.opening_cents) + Number(r.moved), count: r.count, last_on: r.last_on || null }));
+ return rows.map((r) => ({ id: r.id, name: r.name, kind: r.kind, currency: r.currency, balance_cents: Number(r.opening_cents) + Number(r.moved), count: r.count, last_on: r.last_on || null,
+ apr_bps: r.apr_bps == null ? null : Number(r.apr_bps), payment_cents: r.payment_cents == null ? null : Number(r.payment_cents) }));
}
}
/** Every transaction of the person from the last `days` days, across their accounts, opened (recurring, scenarios). */
/** Every transaction of the person from the last `days` days, across their accounts, opened (recurring, scenarios). */
@@ -257,9 +261,57 @@ function createStore({ db, vault }) {
@@ -257,9 +261,57 @@ function createStore({ db, vault }) {
return { category: c, monthly_cents: cents };
return { category: c, monthly_cents: cents };
}
}
+ async function goals(owner) {
+ own(owner);
+ const rows = await db.many('SELECT * FROM finance_goals WHERE owner = $1 ORDER BY created_at, id', [owner]);
+ const balances = new Map((await accounts(owner)).map((a) => [a.id, a.balance_cents]));
+ return rows.map((g) => ({
+ id: g.id, name: g.name, target_cents: Number(g.target_cents), target_on: g.target_on || null, account_id: g.account_id || null,
+ saved_cents: Number(g.saved_cents), have_cents: g.account_id && balances.has(g.account_id) ? balances.get(g.account_id) : Number(g.saved_cents),
+ }));
+ }
+
+ async function addGoal(owner, input = {}) {
+ own(owner);
+ const name = String(input.name || '').replace(/\s+/g, ' ').trim().slice(0, 80);
+ if (!name) fail(422, 'finance.goal.name', 'Give the goal a name.');
+ if (!Number.isSafeInteger(input.target_cents) || input.target_cents <= 0) fail(422, 'finance.goal.target', 'A goal is an amount to reach.');
+ const on = input.target_on ? String(input.target_on) : null;
+ if (on && (!DAY.test(on) || Number.isNaN(Date.parse(`${on}T00:00:00Z`)))) fail(422, 'finance.goal.date', 'A date is YYYY-MM-DD.');
+ let accountId = input.account_id ? String(input.account_id) : null;
+ if (accountId && !(await account(owner, accountId))) fail(404, 'finance.account.not_found', 'No such account of yours.');
+ const saved = Number.isSafeInteger(input.saved_cents) && input.saved_cents > 0 ? input.saved_cents : 0;
+ if (Number(await db.value('SELECT count(*) FROM finance_goals WHERE owner = $1', [owner])) >= 50) fail(422, 'finance.goal.limit', 'Fifty goals is the most for now.');
+ const id = newId('gol');
+ await db.exec('INSERT INTO finance_goals (id, owner, name, target_cents, target_on, account_id, saved_cents) VALUES ($1, $2, $3, $4, $5, $6, $7)', [id, owner, name, input.target_cents, on, accountId, saved]);
+ return (await goals(owner)).find((g) => g.id === id);
+ }
+
+ async function setGoalSaved(owner, id, cents) {
+ own(owner);
+ if (!Number.isSafeInteger(cents) || cents < 0) fail(422, 'finance.goal.saved', 'An amount saved is a number.');
+ const n = await db.exec('UPDATE finance_goals SET saved_cents = $3, updated_at = now() WHERE id = $1 AND owner = $2', [String(id || ''), owner, cents]);
+ if (!n) fail(404, 'finance.goal.not_found', 'No such goal of yours.');
+ }
+
+ async function removeGoal(owner, id) {
+ own(owner);
+ await db.exec('DELETE FROM finance_goals WHERE id = $1 AND owner = $2', [String(id || ''), owner]);
+ }
+
+ async function setDebt(owner, accountId, { apr_bps = null, payment_cents = null } = {}) {
+ own(owner);
+ const acc = await db.maybe('SELECT id, kind FROM finance_accounts WHERE id = $1 AND owner = $2 AND archived_at IS NULL', [String(accountId || ''), owner]);
+ if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.');
+ if (!['loan', 'credit'].includes(acc.kind)) fail(422, 'finance.debt.kind', 'Only a loan or a credit card has a rate and a payment.');
+ if (apr_bps != null && (!Number.isInteger(apr_bps) || apr_bps < 0 || apr_bps > 10000)) fail(422, 'finance.debt.rate', 'A yearly rate is between 0% and 100%.');
+ if (payment_cents != null && (!Number.isSafeInteger(payment_cents) || payment_cents <= 0)) fail(422, 'finance.debt.payment', 'A monthly payment is an amount of money.');
+ await db.exec('UPDATE finance_accounts SET apr_bps = $3, payment_cents = $4, updated_at = now() WHERE id = $1 AND owner = $2', [acc.id, owner, apr_bps, payment_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, apr_bps, payment_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);
const txns = await db.many('SELECT * FROM finance_transactions WHERE owner = $1 ORDER BY posted_on, created_at', [owner]);
const txns = await db.many('SELECT * FROM finance_transactions WHERE owner = $1 ORDER BY posted_on, created_at', [owner]);
return {
return {
exported_at: new Date().toISOString(), format: 'openvibe.finance.export@1',
exported_at: new Date().toISOString(), format: 'openvibe.finance.export@1',
@@ -267,6 +319,7 @@ function createStore({ db, vault }) {
@@ -267,6 +319,7 @@ function createStore({ db, vault }) {
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),
budgets: await budgets(owner),
+ goals: (await goals(owner)).map(({ have_cents, ...g }) => g),
};
};
}
}
@@ -277,11 +330,12 @@ function createStore({ db, vault }) {
@@ -277,11 +330,12 @@ function createStore({ db, vault }) {
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_budgets WHERE owner = $1', [owner]);
+ await t.exec('DELETE FROM finance_goals 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, budgets, setBudget, exportAll, removeAll };
+ return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, goals, addGoal, setGoalSaved, removeGoal, setDebt, exportAll, removeAll };
}
}
module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
@@ -7,6 +7,7 @@
@@ -7,6 +7,7 @@
const shell = require('openvibe-shared/shell');
const shell = require('openvibe-shared/shell');
const serve = require('openvibe-shared/serve');
const serve = require('openvibe-shared/serve');
const { CATEGORIES, KINDS } = require('./store');
const { CATEGORIES, KINDS } = require('./store');
+const { payoff, faster, perMonth } = require('./plan');
const SITE = 'https://openvibe.finance';
const SITE = 'https://openvibe.finance';
const esc = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const esc = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
@@ -21,7 +22,7 @@ const KIND_WORDS = { checking: 'Checking', savings: 'Savings', credit: 'Credit c
@@ -21,7 +22,7 @@ const KIND_WORDS = { checking: 'Checking', savings: 'Savings', credit: 'Credit c
function page({ title, body, path = '/', description = 'Your money, your rules, your data: accounts, imports and a monthly picture, private to you.', robots = 'noindex, nofollow' }) {
function page({ title, body, path = '/', description = 'Your money, your rules, your data: accounts, imports and a monthly picture, private to you.', robots = 'noindex, nofollow' }) {
return shell.page({
return shell.page({
name: 'OpenVibe.Finance', siteName: 'OpenVibe.Finance', title, description, canonical: `${SITE}${path}`, robots,
name: 'OpenVibe.Finance', siteName: 'OpenVibe.Finance', title, description, canonical: `${SITE}${path}`, robots,
- navbar: { service: 'finance', apiBase: 'https://openvibe.network', links: [{ label: 'Money', href: '/' }, { label: 'This month', href: '/month' }, { label: 'Recurring', href: '/bills' }] },
+ navbar: { service: 'finance', apiBase: 'https://openvibe.network', links: [{ label: 'Money', href: '/' }, { label: 'This month', href: '/month' }, { label: 'Recurring', href: '/bills' }, { label: 'Goals', href: '/goals' }] },
footer: { service: 'finance', variant: 'full', mount: '#ov-footer' },
footer: { service: 'finance', variant: 'full', mount: '#ov-footer' },
head: `<link rel="stylesheet" href="${serve.url('kit.css')}"><link rel="stylesheet" href="/finance.css"><script src="/finance.js" defer></script>`,
head: `<link rel="stylesheet" href="${serve.url('kit.css')}"><link rel="stylesheet" href="/finance.css"><script src="/finance.js" defer></script>`,
body: `<div id="navbar-mount"></div><main id="main" class="ovk-page fin">${body}</main>`,
body: `<div id="navbar-mount"></div><main id="main" class="ovk-page fin">${body}</main>`,
@@ -69,7 +70,7 @@ ${accounts.length ? `<section class="fin-month-card" aria-label="${esc(monthName
@@ -69,7 +70,7 @@ ${accounts.length ? `<section class="fin-month-card" aria-label="${esc(monthName
<label class="fin-field"><span>Balance before the first transaction</span><input name="opening" inputmode="decimal" placeholder="0.00" autocomplete="off"></label></div>
<label class="fin-field"><span>Balance before the first transaction</span><input name="opening" inputmode="decimal" placeholder="0.00" autocomplete="off"></label></div>
<p><button class="fin-btn fin-btn--primary" type="submit">Add the account</button></p>
<p><button class="fin-btn fin-btn--primary" type="submit">Add the account</button></p>
</form></details>
</form></details>
-<p class="fin-foot"><a href="/bills">Recurring bills</a> · <a href="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });
+<p class="fin-foot"><a href="/goals">Goals and debt</a> · <a href="/bills">Recurring bills</a> · <a href="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });
}
}
const CADENCE_WORDS = { weekly: 'Every week', 'every two weeks': 'Every two weeks', monthly: 'Every month', quarterly: 'Every three months', yearly: 'Every year' };
const CADENCE_WORDS = { weekly: 'Every week', 'every two weeks': 'Every two weeks', monthly: 'Every month', quarterly: 'Every three months', yearly: 'Every year' };
@@ -94,6 +95,64 @@ ${soon.length ? `<section class="fin-sec"><h2>The next 31 days</h2><ul class="fi
@@ -94,6 +95,64 @@ ${soon.length ? `<section class="fin-sec"><h2>The next 31 days</h2><ul class="fi
${income.length ? `<section class="fin-sec"><h2>Money that comes in regularly</h2><ul class="fin-bills">${income.map(row).join('')}</ul></section>` : ''}` });
${income.length ? `<section class="fin-sec"><h2>Money that comes in regularly</h2><ul class="fin-bills">${income.map(row).join('')}</ul></section>` : ''}` });
}
}
+const monthsWords = (n) => (n < 12 ? `${n} month${n === 1 ? '' : 's'}` : `${Math.floor(n / 12)} year${n >= 24 ? 's' : ''}${n % 12 ? ` ${n % 12} month${n % 12 === 1 ? '' : 's'}` : ''}`);
+const pct = (bps) => `${(bps / 100).toFixed(2).replace(/\.?0+$/, '')}%`;
+
+function goalsPage({ goals, accounts, today, o = {} }) {
+ const debts = accounts.filter((a) => (a.kind === 'loan' || a.kind === 'credit'));
+ const savings = accounts.filter((a) => a.kind !== 'loan' && a.kind !== 'credit');
+ const goalRow = (g) => {
+ const have = Math.max(0, g.have_cents);
+ const done = have >= g.target_cents;
+ const need = perMonth({ target_cents: g.target_cents, have_cents: have, target_on: g.target_on, today });
+ const tracked = g.account_id ? accounts.find((a) => a.id === g.account_id) : null;
+ return `<li class="fin-goal${done ? ' is-done' : ''}"><div class="fin-goal-top"><b>${esc(g.name)}</b><span>${esc(money(have))} of ${esc(money(g.target_cents))}</span></div>
+<span class="fin-bar fin-bar--budget"><span style="--w:${Math.min(100, Math.round((have / g.target_cents) * 100))}%"></span></span>
+<p class="fin-goal-note">${done ? 'Reached.' : need ? `${esc(money(need))} a month reaches it by ${esc(monthName(g.target_on.slice(0, 7)))}.` : g.target_on ? `The date (${esc(monthName(g.target_on.slice(0, 7)))}) has passed.` : 'No date: it is there when it is there.'}
+${tracked ? ` Tracks <a href="/accounts/${esc(tracked.id)}">${esc(tracked.name)}</a>.` : ''}</p>
+<div class="fin-goal-tools">${tracked ? '' : `<form method="post" action="/goals/${esc(g.id)}/saved" class="fin-cat"><label class="fin-saved"><span>Saved</span><input name="saved" inputmode="decimal" value="${(g.saved_cents / 100).toFixed(2)}" autocomplete="off"></label><button type="submit" class="fin-mini">Update</button></form>`}
+<form method="post" action="/goals/${esc(g.id)}/delete" class="fin-goal-remove"><button type="submit" class="fin-mini fin-mini--quiet">Remove</button></form></div></li>`;
+ };
+ const debtRow = (a) => {
+ const owed = Math.max(0, -a.balance_cents);
+ const terms = a.apr_bps != null && a.payment_cents;
+ let said = 'Add its yearly rate and your monthly payment to see when it is paid off.';
+ let tip = '';
+ if (!owed) said = 'Nothing owed.';
+ else if (terms) {
+ const p = payoff({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents });
+ if (p.never) said = `At ${esc(money(a.payment_cents))} a month it never gets paid off: that does not cover the ${esc(pct(a.apr_bps))} interest.`;
+ else {
+ const extra = Math.max(2500, Math.round(a.payment_cents * 0.25 / 500) * 500);
+ const f = faster({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents }, extra);
+ said = `Paid off in <b>${esc(monthsWords(p.months))}</b> at ${esc(money(a.payment_cents))} a month, ${esc(money(p.interest_cents))} of it interest (${esc(pct(a.apr_bps))} a year).`;
+ if (f && f.months_sooner) tip = `${esc(money(extra))} more a month: ${esc(monthsWords(f.months_sooner))} sooner and ${esc(money(f.interest_saved_cents))} less interest.`;
+ }
+ }
+ return `<li class="fin-goal"><div class="fin-goal-top"><b><a href="/accounts/${esc(a.id)}">${esc(a.name)}</a></b><span>${esc(money(owed, a.currency))} owed</span></div>
+<p class="fin-goal-note">${said}</p>${tip ? `<p class="fin-goal-tip">${tip}</p>` : ''}
+${terms ? '<details class="fin-fold fin-fold--quiet"><summary>Change the rate or payment</summary>' : ''}<form class="fin-row fin-debt" method="post" action="/accounts/${esc(a.id)}/debt">
+<label class="fin-field"><span>Yearly rate (%)</span><input name="apr" inputmode="decimal" value="${a.apr_bps != null ? (a.apr_bps / 100).toFixed(2) : ''}" placeholder="24.99" autocomplete="off"></label>
+<label class="fin-field"><span>Monthly payment</span><input name="payment" inputmode="decimal" value="${a.payment_cents ? (a.payment_cents / 100).toFixed(2) : ''}" placeholder="150.00" autocomplete="off"></label>
+<p><button class="fin-btn" type="submit">Save</button></p></form>${terms ? '</details>' : ''}</li>`;
+ };
+ const accountChips = savings.map((a) => `<label class="fin-chip"><input type="radio" name="account" value="${esc(a.id)}"><span>${esc(a.name)}</span></label>`).join('');
+ return page({
+ title: 'Goals and debt', path: '/goals', body: `
+<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Goals and debt</h1></header>
+${notice(o)}
+<section class="fin-sec"><h2>Goals</h2>${goals.length ? `<ul class="fin-goals">${goals.map(goalRow).join('')}</ul>` : '<p class="fin-empty">No goals yet: an emergency fund, a trip, a deposit.</p>'}
+<details class="fin-fold"><summary>Add a goal</summary>
+<form class="fin-form" method="post" action="/goals">
+<label class="fin-field"><span>Name</span><input name="name" maxlength="80" required placeholder="Emergency fund" autocomplete="off"></label>
+<div class="fin-row"><label class="fin-field"><span>Amount</span><input name="target" inputmode="decimal" required placeholder="5000" autocomplete="off"></label>
+<label class="fin-field"><span>By (optional)</span><input type="date" name="target_on"></label></div>
+${savings.length ? `<fieldset class="fin-chips"><legend>Its progress is (optional)</legend><label class="fin-chip"><input type="radio" name="account" value="" checked><span>What I enter</span></label>${accountChips}</fieldset>` : ''}
+<p><button class="fin-btn fin-btn--primary" type="submit">Add the goal</button></p>
+</form></details></section>
+<section class="fin-sec"><h2>Debt</h2>${debts.length ? `<ul class="fin-goals">${debts.map(debtRow).join('')}</ul>` : '<p class="fin-empty">No loans or credit cards. Add one as an account (its kind: Loan or Credit card) to plan paying it off.</p>'}</section>` });
+}
+
function rulesPage({ rules, o = {} }) {
function rulesPage({ rules, o = {} }) {
return page({
return page({
title: 'Your category rules', path: '/rules', body: `
title: 'Your category rules', path: '/rules', body: `
@@ -198,4 +257,4 @@ ${notice(o)}
@@ -198,4 +257,4 @@ ${notice(o)}
<p><button class="fin-btn fin-btn--danger" type="submit">Delete everything</button></p></form></section>` });
<p><button class="fin-btn fin-btn--danger" type="submit">Delete everything</button></p></form></section>` });
}
}
-module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, money, esc, monthName };
+module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, money, esc, monthName };
new file mode 100644
new file mode 100644
@@ -0,0 +1,84 @@
@@ -0,0 +1,84 @@
+'use strict';
+/**
+ * Goals and debt (migrations/0004, server/plan.js): payoff months and interest, a payment that never covers the
+ * interest, paying more; a goal's amount a month to reach it by its date; goals tracking an account or a hand-kept
+ * amount; a card's rate and payment from the page; only loans and cards take them; export and delete carry them.
+ */
+const assert = require('assert');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const { payoff, faster, perMonth } = require('../server/plan');
+
+assert.deepStrictEqual(payoff({ owed_cents: 500000, apr_bps: 0, payment_cents: 15000 }), { months: 34, interest_cents: 0, never: false }, '$5,000 at 0%, $150 a month');
+const card = payoff({ owed_cents: 500000, apr_bps: 2499, payment_cents: 15000 });
+// The standard amortisation: n = -ln(1 - rP/A) / ln(1 + r) = 57.5 months, about $3,622 of interest.
+assert.deepStrictEqual(card, { months: 58, interest_cents: 362226, never: false }, '$5,000 at 24.99%, $150 a month');
+assert.strictEqual(payoff({ owed_cents: 500000, apr_bps: 2499, payment_cents: 10000 }).never, true, '$100 a month never covers $104 of interest');
+assert.deepStrictEqual(payoff({ owed_cents: 0, apr_bps: 2499, payment_cents: 15000 }), { months: 0, interest_cents: 0, never: false });
+const more = faster({ owed_cents: 500000, apr_bps: 2499, payment_cents: 15000 }, 5000);
+assert.ok(more.months_sooner > 0 && more.interest_saved_cents > 0, 'paying more is sooner and cheaper');
+assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: '2027-11-01', today: '2026-11-18' }), 50000, '$6,000 in 12 months');
+assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 600000, target_on: '2027-11-01', today: '2026-11-18' }), 0, 'reached');
+assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: null, today: '2026-11-18' }), null, 'no date');
+assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: '2026-10-01', today: '2026-11-18' }), null, 'past');
+
+(async () => {
+ const { createTestDb } = require('openvibe-sdk/testing');
+ const { createVault } = require('../server/crypto');
+ const { createStore } = require('../server/store');
+ const { createApp } = require('../server/app');
+ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
+ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
+ 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, site = 'same-origin') => fetch(base + p, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': site, 'x-test-user': ADA, '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() }));
+ try {
+ const savings = await store.addAccount(ADA, { name: 'Rainy day', kind: 'savings', opening_cents: 120000 });
+ const visa = await store.addAccount(ADA, { name: 'Visa', kind: 'credit', opening_cents: -500000 });
+ const checking = await store.addAccount(ADA, { name: 'Checking', kind: 'checking' });
+
+ let r = await post('/goals', { name: 'Emergency fund', target: '6,000', target_on: '2027-11-01', account: savings.id });
+ assert.strictEqual(r.status, 303, r.text);
+ r = await post('/goals', { name: 'Trip to Lisbon', target: '1500', account: '' });
+ let goals = await store.goals(ADA);
+ assert.deepStrictEqual(goals.map((g) => [g.name, g.target_cents, g.have_cents]), [['Emergency fund', 600000, 120000], ['Trip to Lisbon', 150000, 0]]);
+ r = await post(`/goals/${goals[1].id}/saved`, { saved: '400' });
+ assert.strictEqual((await store.goals(ADA))[1].have_cents, 40000, 'a hand-kept amount');
+
+ r = await post(`/accounts/${visa.id}/debt`, { apr: '24.99', payment: '150' });
+ assert.strictEqual(r.status, 303, r.text);
+ const acc = (await store.accounts(ADA)).find((a) => a.id === visa.id);
+ assert.deepStrictEqual([acc.apr_bps, acc.payment_cents], [2499, 15000]);
+ r = await post(`/accounts/${checking.id}/debt`, { apr: '5', payment: '10' });
+ assert.strictEqual(r.status, 422, 'a checking account has no rate');
+ assert.match(r.text, /Only a loan or a credit card/);
+ r = await post('/goals', { name: 'x', target: '5' }, 'cross-site');
+ assert.strictEqual(r.status, 403);
+
+ const html = await fetch(`${base}/goals`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());
+ assert.match(html, /\$1,200\.00 of \$6,000\.00/);
+ assert.match(html, /\$400\.00 a month reaches it by November 2027/, '$4,800 left over 12 months');
+ assert.match(html, /Tracks <a href="\/accounts\//);
+ assert.match(html, /\$5,000\.00 owed/);
+ assert.match(html, /Paid off in <b>\d+ (months|years?)/);
+ assert.match(html, /more a month: .* sooner and .* less interest/);
+ assert.match(html, /Change the rate or payment/, 'set terms fold away');
+
+ const ex = await store.exportAll(ADA);
+ assert.strictEqual(ex.goals.length, 2);
+ assert.strictEqual(ex.accounts.find((a) => a.id === visa.id).apr_bps, 2499);
+ await post(`/goals/${goals[1].id}/delete`, {});
+ assert.strictEqual((await store.goals(ADA)).length, 1);
+ await store.removeAll(ADA);
+ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_goals WHERE owner = $1', [ADA])), 0);
+ } finally {
+ server.close();
+ await close();
+ }
+ console.log('goals and debt: payoff and interest, never, paying more, a month to reach a goal, the page, export and delete');
+})().catch((err) => { console.error(err); process.exit(1); });
@@ -40,6 +40,10 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
@@ -40,6 +40,10 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
await store.setBudget(ADA, 'Eating out', 4000);
await store.setBudget(ADA, 'Eating out', 4000);
await store.setBudget(ADA, 'Groceries', 40000);
await store.setBudget(ADA, 'Groceries', 40000);
await store.setBudget(ADA, 'Health', 5000);
await store.setBudget(ADA, 'Health', 5000);
+ const rainy = (await store.accounts(ADA)).find((x) => x.name === 'Rainy day');
+ await store.addGoal(ADA, { name: 'Emergency fund', target_cents: 1000000, target_on: '2027-11-01', account_id: rainy.id });
+ await store.addGoal(ADA, { name: 'Trip to Lisbon', target_cents: 150000, saved_cents: 40000 });
+ await store.setDebt(ADA, card.id, { apr_bps: 2499, payment_cents: 15000 });
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}`));