openvibers/openvibe.finance Commits
Net worth and what if (v0.7) (#7)
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.6)++## What it does today (v0.7)- 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,6 +23,9 @@ 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).++- Net worth and what if: net worth at each month's end since the data starts; the average month of the last three++ repeated a year ahead, with a one-off cost ("can I afford it?": yes, or not yet and the month it would fit) or a++ monthly change ("what if rent rises?"), against the goals' monthly need.- Goals: an amount to reach, by a date or not, tracking a savings account or an amount kept by hand; the page sayswhat 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@@@ -33,7 +36,7 @@ to connect.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.--Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: scenarios, the Link plugin++Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: the Link pluginfor local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.## Running@@@ -1,12 +1,12 @@{"name": "openvibe-finance",-- "version": "0.6.0",++ "version": "0.7.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openvibe-finance",-- "version": "0.6.0",++ "version": "0.7.0","license": "AGPL-3.0-only","dependencies": {"@electric-sql/pglite": "^0.5.8",@@@ -1,6 +1,6 @@{"name": "openvibe-finance",-- "version": "0.6.0",++ "version": "0.7.0","private": true,"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you","main": "server/index.js",@@@ -130,3 +130,42 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco.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; }++/* Net worth and what if (v0.7): the big number, the charts (drawn in from the left, per the motion setting). */++.fin-big { margin: 0; font-size: clamp(1.8rem, 1.4rem + 1.6vw, 2.4rem); font-weight: 750; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }++.fin-sub { margin: 4px 0 10px; color: var(--text-secondary, #9aa4b2); line-height: 1.5; }++.fin-sub b { color: var(--text, #e8ecf3); }++.fin-chart { display: block; width: 100%; height: 150px; margin: 12px 0 4px; overflow: visible; animation: fin-reveal .8s cubic-bezier(.2, .7, .2, 1) both; }++html[data-ov-motion="calm"] .fin-chart { animation-duration: .35s; }++html[data-ov-motion="off"] .fin-chart { animation: none; }++@keyframes fin-reveal { from { clip-path: inset(0 100% 0 0); } to { clip-path: inset(0 0 0 0); } }++.fin-chart path { fill: none; stroke: var(--accent, #5b8cff); stroke-width: 2.5; vector-effect: non-scaling-stroke; stroke-linejoin: round; stroke-linecap: round; }++.fin-chart .fin-area { stroke: none; fill: color-mix(in srgb, var(--accent, #5b8cff) 14%, transparent); }++.fin-chart .fin-line--now { stroke: var(--text-secondary, #9aa4b2); opacity: .7; }++.fin-zero { stroke: var(--danger, #f87171); stroke-width: 1; vector-effect: non-scaling-stroke; opacity: .55; }++.fin-axis { display: flex; justify-content: space-between; color: var(--text-secondary, #9aa4b2); font-size: 12px; margin: 0 0 8px; }++.fin-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 0 0 6px; color: var(--text-secondary, #9aa4b2); font-size: 13px; }++.fin-key { display: inline-flex; align-items: center; gap: 6px; }++.fin-key::before { content: ''; width: 16px; height: 3px; border-radius: 2px; background: var(--accent, #5b8cff); }++.fin-key--now::before { background: var(--text-secondary, #9aa4b2); }++.fin-result { margin: 4px 0 16px; padding: 14px; border-radius: 14px; border: 1px solid var(--border, #1f2937); animation: fin-rise .35s ease both; }++html[data-ov-motion="off"] .fin-result { animation: none; }++@keyframes fin-rise { from { opacity: 0; transform: translateY(calc(8px * var(--ov-move, 1))); } to { opacity: 1; transform: none; } }++.fin-verdict { margin: 0 0 6px; font-size: 1.05rem; line-height: 1.5; }++.fin-verdict.is-yes b { color: var(--success, #22c55e); }++.fin-verdict.is-no { color: var(--text, #e8ecf3); }++.fin-verdict.is-no::before { content: ''; display: inline-block; width: 8px; height: 8px; margin-right: 8px; border-radius: 50%; background: var(--danger, #f87171); vertical-align: middle; }++.fin-ask { display: grid; gap: 12px; }++.fin-askset { margin: 0; padding: 12px 14px; border-radius: 14px; border: 1px solid var(--border, #1f2937); display: grid; gap: 10px; min-width: 0; }++.fin-askset legend { padding: 0 6px; font-weight: 600; }++.fin-ask-go { display: flex; flex-wrap: wrap; gap: 8px; margin: 0; }++.fin-table-wrap { overflow-x: auto; }++.fin-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; font-size: 14px; }++.fin-table th, .fin-table td { padding: 8px 6px; text-align: right; border-bottom: 1px solid var(--border, #1f2937); }++.fin-table th:first-child, .fin-table td:first-child { text-align: left; }++.fin-table th { font-weight: 600; color: var(--text-secondary, #9aa4b2); }++.fin-chips--scroll { position: relative; min-width: 0; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; margin: 0 -14px; padding: 2px 14px; scroll-padding-inline: 14px; }++.fin-chips--scroll::-webkit-scrollbar { display: none; }++.fin-when { display: grid; gap: 6px; min-width: 0; }++.fin-when-label { font-weight: 600; }++.fin-chips--scroll .fin-chip { flex: 0 0 auto; }++.fin-chips--scroll .fin-chip span { padding: 0 14px; white-space: nowrap; }nnew file mode 100644@@@ -0,0 +1,68 @@++'use strict';++/**++ * Net worth over time and what lies ahead (plan §L.2: "net worth … scenarios ('can I afford this?', 'what if rent++ * rises?')"). Pure arithmetic on whole cents: the store gathers the numbers, the page and the API show them.++ *++ * history({ accounts: [{ id, opening_cents }], moves: [{ account_id, month, cents }], months })++ * → [{ month, assets_cents, owed_cents, net_cents }] at each month's end (a negative balance is owed)++ * averageMonth(monthResults) → { income_cents, spending_cents, months } over the months that had any transactions++ * whatIf({ start_cents, income_cents, spending_cents, months, cost_cents, cost_on, change_cents, change_from })++ * → { now, with, lowest, below_zero_on, now_below_zero_on, left_now_cents, left_with_cents, afford_by }++ * The average month repeated from next month: `now` without the change, `with` it. A one-off cost lands in its++ * month; a monthly change (signed: more coming in is positive) applies from its month on. afford_by: for a cost++ * that would go below zero, the first month it could be paid without going below zero, at the average month.++ */++++function history({ accounts, moves, months }) {++ const bal = new Map(accounts.map((a) => [a.id, Number(a.opening_cents) || 0]));++ const sorted = moves.slice().sort((a, b) => (a.month < b.month ? -1 : a.month > b.month ? 1 : 0));++ const out = [];++ let i = 0;++ for (const m of months) {++ while (i < sorted.length && sorted[i].month <= m) {++ if (bal.has(sorted[i].account_id)) bal.set(sorted[i].account_id, bal.get(sorted[i].account_id) + Number(sorted[i].cents));++ i++;++ }++ let assets = 0, owed = 0;++ for (const b of bal.values()) { if (b >= 0) assets += b; else owed -= b; }++ out.push({ month: m, assets_cents: assets, owed_cents: owed, net_cents: assets - owed });++ }++ return out;++}++++function averageMonth(results) {++ const used = results.filter((r) => r.income_cents || r.spent_cents);++ if (!used.length) return { income_cents: 0, spending_cents: 0, months: [] };++ const sum = (k) => used.reduce((n, r) => n + r[k], 0);++ return { income_cents: Math.round(sum('income_cents') / used.length), spending_cents: Math.round(sum('spent_cents') / used.length), months: used.map((r) => r.month) };++}++++function whatIf({ start_cents, income_cents, spending_cents, months, cost_cents = 0, cost_on = null, change_cents = 0, change_from = null }) {++ const net = income_cents - spending_cents;++ const costAt = cost_cents ? Math.max(0, cost_on ? months.indexOf(cost_on) : 0) : -1;++ const fromAt = change_cents ? Math.max(0, change_from ? months.indexOf(change_from) : 0) : -1;++ let a = start_cents, b = start_cents;++ const now = [], withIt = [];++ months.forEach((m, i) => {++ a += net;++ b += net;++ if (i === costAt) b -= cost_cents;++ if (fromAt >= 0 && i >= fromAt) b += change_cents;++ now.push({ month: m, cents: a });++ withIt.push({ month: m, cents: b });++ });++ const lowest = withIt.reduce((lo, p) => (p.cents < lo.cents ? p : lo), withIt[0]);++ const firstBelow = (list) => (list.find((p) => p.cents < 0) || { month: null }).month;++ let affordBy = null;++ if (cost_cents && !change_cents && firstBelow(withIt) && !firstBelow(now) && net > 0) {++ // The first month k where paying it then leaves every month from k on at zero or more (net > 0: from k is enough).++ const k = months.findIndex((_m, i) => start_cents + (i + 1) * net - cost_cents >= 0);++ affordBy = k >= 0 ? months[k] : null;++ }++ return {++ now, with: withIt, lowest, below_zero_on: firstBelow(withIt), now_below_zero_on: firstBelow(now),++ left_now_cents: net, left_with_cents: net + (change_cents || 0), afford_by: affordBy,++ };++}++++module.exports = { history, averageMonth, whatIf };@@@ -15,6 +15,8 @@ const path = require('node:path');const { createStore, FinanceError } = require('./store');const { readCsv, readAmount } = require('./csv');const { isOfx, readOfx } = require('./ofx');++const ahead = require('./ahead');++const { perMonth } = require('./plan');/** A bank's export, whichever it is: OFX or QFX by its header, else CSV. */const readExport = (text) => (isOfx(text) ? readOfx(text) : readCsv(text));const { findRecurring } = require('./recurring');@@@ -57,7 +59,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowconst form = express.urlencoded({ extended: false, limit: '4mb' });const handle = (fn) => async (req, res, next) => {try { await fn(req, res); } catch (err) {-- if (err instanceof FinanceError) return req.path.startsWith('/api/') ? res.status(err.status).json({ error: err.message, code: err.code }) : res.status(err.status).send(v.page({ title: 'Something is wrong', body: `<p class="fin-error" role="alert">${v.esc(err.message)}</p><p><a href="/">Back</a></p>` }));++ // Under the /api/v1 router req.path is relative to it: the mount (baseUrl) says it is the API.++ if (err instanceof FinanceError) return `${req.baseUrl}${req.path}`.startsWith('/api/') ? res.status(err.status).json({ error: err.message, code: err.code }) : res.status(err.status).send(v.page({ title: 'Something is wrong', body: `<p class="fin-error" role="alert">${v.esc(err.message)}</p><p><a href="/">Back</a></p>` }));next(err);}};@@@ -142,6 +145,59 @@ 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 }));}));++ const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;++ const addMonths = (m, by) => { const d = new Date(`${m}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() + by); return d.toISOString().slice(0, 7); };++ /** The question asked (all optional): a one-off cost in a month, a monthly change from a month. → the ask, or throws. */++ function readAsk(q, months) {++ const amount = (text, what) => {++ const t = String(text || '').trim();++ if (!t) return 0;++ const c = readAmount(t);++ if (c == null) throw new FinanceError(422, 'finance.ahead.amount', `${what} is not a number.`);++ return Math.abs(c);++ };++ const when = (text, what) => {++ const t = String(text || '').trim();++ if (!t) return null;++ if (!MONTH_RE.test(t)) throw new FinanceError(422, 'finance.ahead.month', `${what} is a month (YYYY-MM).`);++ if (t > months[months.length - 1]) throw new FinanceError(422, 'finance.ahead.month', `${what} is within the next twelve months.`);++ return t < months[0] ? months[0] : t;++ };++ const change = amount(q.change, 'The monthly change');++ return {++ cost_cents: amount(q.cost, 'The cost'), cost_on: when(q.cost_on, 'When it is paid'),++ change_cents: q.dir === 'in' ? change : -change, change_from: when(q.from, 'When the change starts'),++ };++ }++ /** Net worth over the last twelve months and the average month repeated over the next twelve, with the ask. */++ async function aheadFor(me, q = {}) {++ const today = now().toISOString().slice(0, 10), m = today.slice(0, 7);++ const next = Array.from({ length: 12 }, (_, i) => addMonths(m, i + 1));++ const data = await store.ahead(me);++ // The line starts where the data does (an opening balance is "before the first transaction", not a year ago).++ const firstMove = data.moves.reduce((lo, x) => (x.month < lo ? x.month : lo), m);++ const past = Array.from({ length: 12 }, (_, i) => addMonths(m, i - 11)).filter((pm) => pm >= firstMove);++ const recent = [];++ for (const pm of [addMonths(m, -3), addMonths(m, -2), addMonths(m, -1)]) recent.push(await store.month(me, pm));++ const avg = ahead.averageMonth(recent);++ // What can be spent: checking, savings and cash, less what the cards owe (they are paid from it).++ const spendable = data.accounts.reduce((n, a) => n + (['checking', 'savings', 'cash'].includes(a.kind) ? a.balance_cents : a.kind === 'credit' ? Math.min(0, a.balance_cents) : 0), 0);++ let ask = null, error = null;++ try { ask = readAsk(q, next); } catch (err) { if (!(err instanceof FinanceError)) throw err; error = err.message; }++ const asked = Boolean(ask && (ask.cost_cents || ask.change_cents));++ const goalsNeed = (await store.goals(me)).reduce((n, g) => n + (perMonth({ target_cents: g.target_cents, have_cents: g.have_cents, target_on: g.target_on, today }) || 0), 0);++ return {++ net_worth: ahead.history({ accounts: data.accounts, moves: data.moves, months: past }),++ average: avg, spendable_cents: spendable, goals_need_cents: goalsNeed, has_accounts: data.accounts.length > 0,++ asked, ask, error,++ plan: avg.months.length ? ahead.whatIf({ start_cents: spendable, income_cents: avg.income_cents, spending_cents: avg.spending_cents, months: next, ...(asked ? ask : {}) }) : null,++ };++ }++ app.get('/ahead', handle(async (req, res) => {++ const me = who(req);++ if (!me) return signIn(req, res);++ res.send(v.aheadPage({ ...(await aheadFor(me, req.query)), q: req.query }));++ }));app.get('/goals', handle(async (req, res) => {const me = who(req);if (!me) return signIn(req, res);@@@ -228,6 +284,12 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowapi.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.get('/net-worth', handle(async (req, res) => { const a = await aheadFor(who(req)); res.json({ net_worth: a.net_worth }); }));++ api.get('/what-if', handle(async (req, res) => {++ const a = await aheadFor(who(req), req.query);++ if (a.error) throw new FinanceError(422, 'finance.ahead.ask', a.error);++ res.json({ average: a.average, spendable_cents: a.spendable_cents, goals_need_cents: a.goals_need_cents, ask: a.asked ? a.ask : null, plan: a.plan });++ }));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;@@@ -22,6 +22,7 @@* 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++ * ahead(owner) → { accounts: [{ id, kind, opening_cents, balance_cents }], moves: [{ account_id, month, cents }] }* exportAll(owner) → everything, opened (the person's own copy)* removeAll(owner) → everything of theirs deleted*/@@@ -309,6 +310,21 @@ function createStore({ db, vault }) {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]);}++ /** What net worth over time and the what-if are worked out from (server/ahead.js): no payee is opened. */++ async function ahead(owner) {++ own(owner);++ const accs = await db.many('SELECT id, kind, opening_cents FROM finance_accounts WHERE owner = $1 AND archived_at IS NULL', [owner]);++ const moves = await db.many(`SELECT t.account_id, to_char(date_trunc('month', t.posted_on), 'YYYY-MM') AS month, SUM(t.amount_cents)::bigint AS cents++ FROM finance_transactions t JOIN finance_accounts a ON a.id = t.account_id AND a.archived_at IS NULL++ WHERE t.owner = $1 GROUP BY 1, 2`, [owner]);++ const moved = new Map();++ for (const m of moves) moved.set(m.account_id, (moved.get(m.account_id) || 0) + Number(m.cents));++ return {++ accounts: accs.map((a) => ({ id: a.id, kind: a.kind, opening_cents: Number(a.opening_cents), balance_cents: Number(a.opening_cents) + (moved.get(a.id) || 0) })),++ moves: moves.map((m) => ({ account_id: m.account_id, month: m.month, cents: Number(m.cents) })),++ };++ }++async function exportAll(owner) {own(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]);@@@ -335,7 +351,7 @@ function createStore({ db, vault }) {});}-- return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, goals, addGoal, setGoalSaved, removeGoal, setDebt, exportAll, removeAll };++ return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, goals, addGoal, setGoalSaved, removeGoal, setDebt, ahead, exportAll, removeAll };}module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };@@@ -22,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' }, { label: 'Goals', href: '/goals' }] },++ navbar: { service: 'finance', apiBase: 'https://openvibe.network', links: [{ label: 'Money', href: '/' }, { label: 'This month', href: '/month' }, { label: 'Recurring', href: '/bills' }, { label: 'Goals', href: '/goals' }, { label: 'What if', href: '/ahead' }] },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>`,@@@ -70,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="/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>` });++<p class="fin-foot"><a href="/ahead">Net worth and what if</a> · <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' };@@@ -153,6 +153,85 @@ ${savings.length ? `<fieldset class="fin-chips"><legend>Its progress is (optiona<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>` });}++const shortMonth = (m) => new Date(`${m}-01T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', year: 'numeric', timeZone: 'UTC' });++++/** A small line chart in the page's own colours: lines [{ cls, points: [cents] }], the zero line when it is crossed. */++function lineChart(lines, { label, area = false }) {++ const all = lines.flatMap((l) => l.points);++ let lo = Math.min(...all), hi = Math.max(...all);++ if (lo === hi) { lo -= 10000; hi += 10000; }++ const pad = (hi - lo) * 0.08;++ lo -= pad; hi += pad;++ const W = 600, H = 160, n = lines[0].points.length;++ const x = (i) => (n === 1 ? W / 2 : (i / (n - 1)) * W).toFixed(1);++ const y = (c) => (H - ((c - lo) / (hi - lo)) * H).toFixed(1);++ const d = (pts) => pts.map((c, i) => `${i ? 'L' : 'M'}${x(i)},${y(c)}`).join('');++ const zero = lo < 0 && hi > 0 ? `<line class="fin-zero" x1="0" x2="${W}" y1="${y(0)}" y2="${y(0)}"/>` : '';++ const fill = area ? `<path class="fin-area" d="${d(lines[0].points)}L${W},${H}L0,${H}Z"/>` : '';++ return `<svg class="fin-chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(label)}">${fill}${zero}${lines.map((l) => `<path class="${l.cls}" d="${d(l.points)}"/>`).join('')}</svg>`;++}++++function aheadPage({ net_worth, average, spendable_cents, goals_need_cents, has_accounts, asked, ask, error, plan, q = {} }) {++ const last = net_worth[net_worth.length - 1];++ const first = net_worth.find((p) => p.assets_cents || p.owed_cents) || net_worth[0];++ const change = last.net_cents - first.net_cents;++ const worth = !has_accounts ? '<p class="fin-empty">Add an account on <a href="/">Your money</a> to see your net worth.</p>' : `++<p class="fin-big${last.net_cents < 0 ? ' is-neg' : ''}">${esc(money(last.net_cents))}</p>++<p class="fin-sub">${esc(money(last.assets_cents))} in your accounts · ${esc(money(last.owed_cents))} owed${first.month !== last.month ? ` · <span class="${change < 0 ? 'is-neg' : 'fin-in'}">${change < 0 ? '−' : '+'}${esc(money(Math.abs(change)))}</span> since ${esc(monthName(first.month))}` : ''}</p>++${net_worth.length > 1 ? `${lineChart([{ cls: 'fin-line', points: net_worth.map((p) => p.net_cents) }], { label: `Net worth at the end of each month, ${monthName(net_worth[0].month)} to ${monthName(last.month)}`, area: true })}++<div class="fin-axis"><span>${esc(shortMonth(net_worth[0].month))}</span><span>Now</span></div>` : ''}`;++++ const val = (k) => esc(q[k] || '');++ const months = plan ? plan.now.map((p) => p.month) : [];++ // When: a row of month chips (the first, "next month", by default), never the browser's month box.++ const whenChips = (name, legend) => `<div class="fin-when"><span class="fin-when-label" id="fin-when-${name}">${legend}</span><div class="fin-chips fin-chips--scroll" role="radiogroup" aria-labelledby="fin-when-${name}">${months.map((mm, i) => {++ const on = (q[name] || months[0]) === mm;++ const label = i === 0 ? 'Next month' : mm.endsWith('-01') || i === 1 ? shortMonth(mm) : new Date(`${mm}-01T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', timeZone: 'UTC' });++ return `<label class="fin-chip"><input type="radio" name="${name}" value="${i === 0 ? '' : mm}"${on ? ' checked' : ''}><span>${esc(label)}</span></label>`;++ }).join('')}</div></div>`;++ const dirIn = q.dir === 'in';++ const form = `<form class="fin-form fin-ask" method="get" action="/ahead">++<fieldset class="fin-askset"><legend>Can I afford it? A one-off cost</legend>++<label class="fin-field"><span>Amount</span><input name="cost" inputmode="decimal" placeholder="1,200.00" value="${val('cost')}" autocomplete="off"></label>++${whenChips('cost_on', 'Paid in')}</fieldset>++<fieldset class="fin-askset"><legend>What if something changes every month</legend>++<div class="fin-chips"><label class="fin-chip"><input type="radio" name="dir" value="out"${dirIn ? '' : ' checked'}><span>More going out</span></label><label class="fin-chip"><input type="radio" name="dir" value="in"${dirIn ? ' checked' : ''}><span>More coming in</span></label></div>++<label class="fin-field"><span>Amount a month</span><input name="change" inputmode="decimal" placeholder="200.00" value="${val('change')}" autocomplete="off"></label>++${whenChips('from', 'From')}</fieldset>++<p class="fin-ask-go"><button class="fin-btn fin-btn--primary" type="submit">See what happens</button>${asked ? '<a class="fin-btn" href="/ahead">Start over</a>' : ''}</p>++</form>`;++++ let result = '';++ if (plan) {++ const end = plan.with[plan.with.length - 1];++ let verdict;++ if (plan.now_below_zero_on) verdict = `<p class="fin-verdict is-no">Your average month spends more than comes in: at this rate the money to spend runs out in ${esc(monthName(plan.now_below_zero_on))}.</p>`;++ else if (!asked) verdict = `<p class="fin-verdict">At your average month you have about <b>${esc(money(end.cents))}</b> to spend in ${esc(monthName(end.month))}.</p>`;++ else if (plan.below_zero_on) verdict = `<p class="fin-verdict is-no">Not yet: it takes you below zero in ${esc(monthName(plan.below_zero_on))} (lowest ${esc(money(plan.lowest.cents))}).${plan.afford_by ? ` At your average month you could pay it in <b>${esc(monthName(plan.afford_by))}</b> and stay above zero.` : ''}</p>`;++ else verdict = `<p class="fin-verdict is-yes">Yes. The lowest it gets is <b>${esc(money(plan.lowest.cents))}</b>, in ${esc(monthName(plan.lowest.month))}; about ${esc(money(end.cents))} in ${esc(monthName(end.month))}.</p>`;++ const changeLine = asked && ask.change_cents ? `<p class="fin-sub">Left over each month: ${esc(money(plan.left_now_cents))} now, <b>${esc(money(plan.left_with_cents))}</b> with the change.</p>` : '';++ const goalsLine = goals_need_cents ? `<p class="fin-sub">Your goals with dates need ${esc(money(goals_need_cents))} a month${plan.left_with_cents < goals_need_cents ? `: ${asked ? 'this leaves' : 'your average month leaves'} less than that (<a href="/goals">Goals</a>).` : '.'}</p>` : '';++ const lines = asked ? [{ cls: 'fin-line fin-line--now', points: [spendable_cents, ...plan.now.map((p) => p.cents)] }, { cls: 'fin-line', points: [spendable_cents, ...plan.with.map((p) => p.cents)] }]++ : [{ cls: 'fin-line', points: [spendable_cents, ...plan.now.map((p) => p.cents)] }];++ result = `<div class="fin-result" aria-live="polite">${verdict}${changeLine}${goalsLine}++${lineChart(lines, { label: `Money to spend at the end of each month, now to ${monthName(end.month)}` })}++<div class="fin-axis"><span>Now</span><span>${esc(shortMonth(end.month))}</span></div>++${asked ? '<p class="fin-legend"><span class="fin-key fin-key--now">As things are</span><span class="fin-key">With the change</span></p>' : ''}++<details class="fin-fold fin-fold--quiet"><summary>Month by month</summary><div class="fin-table-wrap"><table class="fin-table"><thead><tr><th>End of</th><th>${asked ? 'As things are' : 'To spend'}</th>${asked ? '<th>With the change</th>' : ''}</tr></thead><tbody>++${plan.now.map((p, i) => `<tr><td>${esc(shortMonth(p.month))}</td><td class="${p.cents < 0 ? 'is-neg' : ''}">${esc(money(p.cents))}</td>${asked ? `<td class="${plan.with[i].cents < 0 ? 'is-neg' : ''}">${esc(money(plan.with[i].cents))}</td>` : ''}</tr>`).join('')}++</tbody></table></div></details></div>`;++ }++ const base = average.months.length ? `<p class="fin-sub">Your average month (${esc(average.months.length === 1 ? monthName(average.months[0]) : `${shortMonth(average.months[0])} to ${shortMonth(average.months[average.months.length - 1])}`)}): ${esc(money(average.income_cents))} in, ${esc(money(average.spending_cents))} out, <b>${esc(money(average.income_cents - average.spending_cents))}</b> left over. ${esc(money(spendable_cents))} to spend now.</p>`++ : '<p class="fin-empty">A month or two of transactions (the months before this one) shows what is ahead.</p>';++ return page({++ title: 'Net worth and what if', path: '/ahead', body: `++<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Net worth and what if</h1></header>++<section class="fin-sec"><h2>Net worth</h2>${worth}</section>++<section class="fin-sec"><h2>What if</h2>${base}++${error ? `<p class="fin-error" role="alert">${esc(error)}</p>` : ''}${result}${average.months.length ? form : ''}</section>++<p class="fin-note">Roughly: your average month of the last three, repeated from next month. Money to spend is checking, savings and cash, less what cards owe; investments and loans are left out, as are transfers between your accounts. Nothing here moves money.</p>` });++}++function rulesPage({ rules, o = {} }) {return page({title: 'Your category rules', path: '/rules', body: `@@@ -257,4 +336,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, goalsPage, money, esc, monthName };++module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, aheadPage, lineChart, money, esc, monthName };nnew file mode 100644@@@ -0,0 +1,122 @@++'use strict';++/**++ * Net worth and what if (server/ahead.js, /ahead, /api/v1/net-worth, /api/v1/what-if): net worth at each month's end++ * (moves before the window counted, a negative balance owed); the average month over the months that had any; a++ * one-off cost that fits, one that does not yet (and the month it would), a monthly change from a month, a baseline++ * that runs out on its own; the page's verdicts, the goals line, bad input shown on the page, the API, another person.++ */++const assert = require('assert');++const path = require('node:path');++const crypto = require('node:crypto');++const { history, averageMonth, whatIf } = require('../server/ahead');++++const months12 = ['2026-12', '2027-01', '2027-02', '2027-03', '2027-04', '2027-05', '2027-06', '2027-07', '2027-08', '2027-09', '2027-10', '2027-11'];++++assert.deepStrictEqual(history({++ accounts: [{ id: 'a', opening_cents: 100000 }, { id: 'b', opening_cents: 0 }],++ moves: [{ account_id: 'a', month: '2026-01', cents: 7 }, { account_id: 'a', month: '2026-09', cents: 50000 }, { account_id: 'b', month: '2026-10', cents: -30000 }, { account_id: 'a', month: '2026-11', cents: -20000 }],++ months: ['2026-09', '2026-10', '2026-11'],++}), [++ { month: '2026-09', assets_cents: 150007, owed_cents: 0, net_cents: 150007 },++ { month: '2026-10', assets_cents: 150007, owed_cents: 30000, net_cents: 120007 },++ { month: '2026-11', assets_cents: 130007, owed_cents: 30000, net_cents: 100007 },++]);++assert.deepStrictEqual(averageMonth([++ { month: '2026-08', income_cents: 0, spent_cents: 0 }, { month: '2026-09', income_cents: 300000, spent_cents: 200000 }, { month: '2026-10', income_cents: 310000, spent_cents: 220000 },++]), { income_cents: 305000, spending_cents: 210000, months: ['2026-09', '2026-10'] }, 'an empty month is not an average month');++++const base = { start_cents: 100000, income_cents: 300000, spending_cents: 250000, months: months12 };++let p = whatIf(base);++assert.strictEqual(p.now[11].cents, 700000);++assert.strictEqual(p.below_zero_on, null);++p = whatIf({ ...base, cost_cents: 200000 });++assert.strictEqual(p.with[0].cents, -50000);++assert.strictEqual(p.below_zero_on, '2026-12');++assert.strictEqual(p.afford_by, '2027-01', 'two months of $500 left over pay a $2,000 cost from $1,000');++p = whatIf({ ...base, cost_cents: 100000, cost_on: '2027-03' });++assert.deepStrictEqual([p.with[2].cents, p.with[3].cents, p.below_zero_on], [250000, 200000, null]);++p = whatIf({ ...base, change_cents: -60000, change_from: '2027-02' });++assert.deepStrictEqual([p.with[1].cents, p.with[2].cents, p.with[11].cents, p.left_with_cents], [200000, 190000, 100000, -10000], 'rent up $600 from February');++p = whatIf({ start_cents: 120000, income_cents: 100000, spending_cents: 150000, months: months12 });++assert.strictEqual(p.now_below_zero_on, '2027-02', 'more going out than coming in runs out on its own');++++(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 BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';++ 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 page = (q = '', as = ADA) => fetch(`${base}/ahead${q}`, { redirect: 'manual', headers: as ? { 'x-test-user': as } : {} }).then(async (r) => ({ status: r.status, text: await r.text() }));++ const api = (p, as = ADA) => fetch(`${base}/api/v1${p}`, { headers: { 'x-test-user': as } }).then(async (r) => ({ status: r.status, body: await r.json() }));++ try {++ const checking = await store.addAccount(ADA, { name: 'Checking', kind: 'checking', opening_cents: 100000 });++ const savings = await store.addAccount(ADA, { name: 'Savings', kind: 'savings', opening_cents: 500000 });++ const card = await store.addAccount(ADA, { name: 'Card', kind: 'credit' });++ const rows = [];++ for (const m of ['2026-08', '2026-09', '2026-10']) {++ rows.push({ posted_on: `${m}-01`, amount_cents: 300000, payee: 'Paycheck', category: 'Income' });++ rows.push({ posted_on: `${m}-03`, amount_cents: -150000, payee: 'Rent', category: 'Housing' });++ rows.push({ posted_on: `${m}-10`, amount_cents: -50000, payee: 'Grocer', category: 'Groceries' });++ }++ rows.push({ posted_on: '2026-10-20', amount_cents: -50000, payee: 'To savings', category: 'Transfers' });++ await store.importRows(ADA, checking.id, rows);++ await store.importRows(ADA, savings.id, [{ posted_on: '2026-10-20', amount_cents: 50000, payee: 'From checking', category: 'Transfers' }]);++ await store.importRows(ADA, card.id, [{ posted_on: '2026-10-12', amount_cents: -30000, payee: 'Shoes', category: 'Shopping' }]);++++ let r = await page();++ assert.strictEqual(r.status, 200, r.text.slice(0, 300));++ assert.match(r.text, /<p class="fin-big">\$8,700\.00<\/p>/, '$3,500 checking + $5,500 savings − $300 owed');++ assert.match(r.text, /\+\$1,700\.00<\/span> since August 2026/, 'from the first month with data, not a year of openings');++ assert.match(r.text, /\$3,000\.00 in, \$2,100\.00 out, <b>\$900\.00<\/b> left over\. \$8,700\.00 to spend now/, 'transfers left out of the average');++ assert.match(r.text, /about <b>\$19,500\.00<\/b> to spend in November 2027/);++ assert.match(r.text, /<svg class="fin-chart"/);++++ r = await page('?cost=12%2C000&cost_on=2026-12');++ assert.match(r.text, /Not yet: it takes you below zero in December 2026/);++ assert.match(r.text, /could pay it in <b>March 2027<\/b>/);++ r = await page('?cost=5000');++ assert.match(r.text, /Yes\. The lowest it gets is <b>\$4,600\.00<\/b>, in December 2026/);++ assert.match(r.text, /As things are/);++++ await store.addGoal(ADA, { name: 'House', target_cents: 1000000, target_on: '2027-11-01' });++ r = await page('?change=1000&dir=out&from=2027-02');++ assert.match(r.text, /Left over each month: \$900\.00 now, <b>-\$100\.00<\/b> with the change/);++ assert.match(r.text, /Your goals with dates need \$833\.34 a month: this leaves less than that/);++ assert.match(r.text, /name="change"[^>]*value="1000"/, 'the question stays in the form');++ assert.match(r.text, /name="from" value="2027-02" checked/, 'and its month chip');++ assert.doesNotMatch(r.text, /type="month"/, 'no browser month box');++++ r = await page('?cost=lots');++ assert.strictEqual(r.status, 200);++ assert.match(r.text, /role="alert">The cost is not a number\./);++ r = await page('?cost=10&cost_on=2030-01');++ assert.match(r.text, /within the next twelve months/);++++ let a = await api('/what-if?cost=5000');++ assert.strictEqual(a.status, 200);++ assert.deepStrictEqual([a.body.plan.lowest.cents, a.body.spendable_cents, a.body.average.income_cents], [460000, 870000, 300000]);++ a = await api('/what-if?cost=abc');++ assert.strictEqual(a.status, 422);++ assert.deepStrictEqual(a.body, { error: 'The cost is not a number.', code: 'finance.ahead.ask' }, 'an API error is JSON, not a page');++ a = await api('/net-worth');++ assert.deepStrictEqual(a.body.net_worth.map((x) => [x.month, x.net_cents]), [['2026-08', 700000], ['2026-09', 800000], ['2026-10', 870000], ['2026-11', 870000]]);++++ r = await page('', BO);++ assert.match(r.text, /Add an account on <a href="\/">Your money<\/a>/, 'another person sees none of it');++ assert.doesNotMatch(r.text, /8,700/);++ r = await page('', null);++ assert.ok([302, 303].includes(r.status), `signed out goes to sign in: ${r.status}`);++ } finally {++ server.close();++ await close();++ }++ console.log('ahead: net worth over time, the average month, yes, not yet and when, a monthly change, goals, bad input, the API, another person');++})().catch((err) => { console.error(err); process.exit(1); });@@@ -36,6 +36,16 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';2026-11-16,Gym Monthly,-29.00,Subscriptions`;await store.importRows(ADA, checking.id, readCsv(csv).rows);++ // Three earlier months, so the average month (Net worth and what if) has something to stand on.++ for (const [m, extra] of [['2026-08', 0], ['2026-09', 12000], ['2026-10', -8000]]) {++ await store.importRows(ADA, checking.id, [++ { posted_on: `${m}-01`, amount_cents: 312000, payee: 'Paycheck ACME Corp', category: 'Income' },++ { posted_on: `${m}-01`, amount_cents: -145000, payee: 'Lakeview Apartments', category: 'Housing' },++ { posted_on: `${m}-04`, amount_cents: -42000 - extra, payee: 'Corner Grocer', category: 'Groceries' },++ { posted_on: `${m}-09`, amount_cents: -7130, payee: 'City Power & Light', category: 'Utilities' },++ { posted_on: `${m}-15`, amount_cents: -38500, payee: 'Eating out, various', category: 'Eating out' },++ ]);++ }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);
@@ -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.6)
+## What it does today (v0.7)
- 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,6 +23,9 @@ to connect.
@@ -23,6 +23,9 @@ 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).
+- Net worth and what if: net worth at each month's end since the data starts; the average month of the last three
+ repeated a year ahead, with a one-off cost ("can I afford it?": yes, or not yet and the month it would fit) or a
+ monthly change ("what if rent rises?"), against the goals' monthly need.
- Goals: an amount to reach, by a date or not, tracking a savings account or an amount kept by hand; the page says
- 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.
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
- Debt: a loan's or card's yearly rate and monthly payment give when it is paid off, the interest it costs, and what
@@ -33,7 +36,7 @@ to connect.
@@ -33,7 +36,7 @@ to connect.
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: scenarios, the Link plugin
+Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: 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
@@ -1,12 +1,12 @@
@@ -1,12 +1,12 @@
{
{
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.6.0",
+ "version": "0.7.0",
"lockfileVersion": 3,
"lockfileVersion": 3,
"requires": true,
"requires": true,
"packages": {
"packages": {
"": {
"": {
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.6.0",
+ "version": "0.7.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.6.0",
+ "version": "0.7.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",
@@ -130,3 +130,42 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
@@ -130,3 +130,42 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
.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-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 { align-items: end; }
.fin-debt p { margin: 0; }
.fin-debt p { margin: 0; }
+/* Net worth and what if (v0.7): the big number, the charts (drawn in from the left, per the motion setting). */
+.fin-big { margin: 0; font-size: clamp(1.8rem, 1.4rem + 1.6vw, 2.4rem); font-weight: 750; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
+.fin-sub { margin: 4px 0 10px; color: var(--text-secondary, #9aa4b2); line-height: 1.5; }
+.fin-sub b { color: var(--text, #e8ecf3); }
+.fin-chart { display: block; width: 100%; height: 150px; margin: 12px 0 4px; overflow: visible; animation: fin-reveal .8s cubic-bezier(.2, .7, .2, 1) both; }
+html[data-ov-motion="calm"] .fin-chart { animation-duration: .35s; }
+html[data-ov-motion="off"] .fin-chart { animation: none; }
+@keyframes fin-reveal { from { clip-path: inset(0 100% 0 0); } to { clip-path: inset(0 0 0 0); } }
+.fin-chart path { fill: none; stroke: var(--accent, #5b8cff); stroke-width: 2.5; vector-effect: non-scaling-stroke; stroke-linejoin: round; stroke-linecap: round; }
+.fin-chart .fin-area { stroke: none; fill: color-mix(in srgb, var(--accent, #5b8cff) 14%, transparent); }
+.fin-chart .fin-line--now { stroke: var(--text-secondary, #9aa4b2); opacity: .7; }
+.fin-zero { stroke: var(--danger, #f87171); stroke-width: 1; vector-effect: non-scaling-stroke; opacity: .55; }
+.fin-axis { display: flex; justify-content: space-between; color: var(--text-secondary, #9aa4b2); font-size: 12px; margin: 0 0 8px; }
+.fin-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 0 0 6px; color: var(--text-secondary, #9aa4b2); font-size: 13px; }
+.fin-key { display: inline-flex; align-items: center; gap: 6px; }
+.fin-key::before { content: ''; width: 16px; height: 3px; border-radius: 2px; background: var(--accent, #5b8cff); }
+.fin-key--now::before { background: var(--text-secondary, #9aa4b2); }
+.fin-result { margin: 4px 0 16px; padding: 14px; border-radius: 14px; border: 1px solid var(--border, #1f2937); animation: fin-rise .35s ease both; }
+html[data-ov-motion="off"] .fin-result { animation: none; }
+@keyframes fin-rise { from { opacity: 0; transform: translateY(calc(8px * var(--ov-move, 1))); } to { opacity: 1; transform: none; } }
+.fin-verdict { margin: 0 0 6px; font-size: 1.05rem; line-height: 1.5; }
+.fin-verdict.is-yes b { color: var(--success, #22c55e); }
+.fin-verdict.is-no { color: var(--text, #e8ecf3); }
+.fin-verdict.is-no::before { content: ''; display: inline-block; width: 8px; height: 8px; margin-right: 8px; border-radius: 50%; background: var(--danger, #f87171); vertical-align: middle; }
+.fin-ask { display: grid; gap: 12px; }
+.fin-askset { margin: 0; padding: 12px 14px; border-radius: 14px; border: 1px solid var(--border, #1f2937); display: grid; gap: 10px; min-width: 0; }
+.fin-askset legend { padding: 0 6px; font-weight: 600; }
+.fin-ask-go { display: flex; flex-wrap: wrap; gap: 8px; margin: 0; }
+.fin-table-wrap { overflow-x: auto; }
+.fin-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; font-size: 14px; }
+.fin-table th, .fin-table td { padding: 8px 6px; text-align: right; border-bottom: 1px solid var(--border, #1f2937); }
+.fin-table th:first-child, .fin-table td:first-child { text-align: left; }
+.fin-table th { font-weight: 600; color: var(--text-secondary, #9aa4b2); }
+.fin-chips--scroll { position: relative; min-width: 0; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; margin: 0 -14px; padding: 2px 14px; scroll-padding-inline: 14px; }
+.fin-chips--scroll::-webkit-scrollbar { display: none; }
+.fin-when { display: grid; gap: 6px; min-width: 0; }
+.fin-when-label { font-weight: 600; }
+.fin-chips--scroll .fin-chip { flex: 0 0 auto; }
+.fin-chips--scroll .fin-chip span { padding: 0 14px; white-space: nowrap; }
new file mode 100644
new file mode 100644
@@ -0,0 +1,68 @@
@@ -0,0 +1,68 @@
+'use strict';
+/**
+ * Net worth over time and what lies ahead (plan §L.2: "net worth … scenarios ('can I afford this?', 'what if rent
+ * rises?')"). Pure arithmetic on whole cents: the store gathers the numbers, the page and the API show them.
+ *
+ * history({ accounts: [{ id, opening_cents }], moves: [{ account_id, month, cents }], months })
+ * → [{ month, assets_cents, owed_cents, net_cents }] at each month's end (a negative balance is owed)
+ * averageMonth(monthResults) → { income_cents, spending_cents, months } over the months that had any transactions
+ * whatIf({ start_cents, income_cents, spending_cents, months, cost_cents, cost_on, change_cents, change_from })
+ * → { now, with, lowest, below_zero_on, now_below_zero_on, left_now_cents, left_with_cents, afford_by }
+ * The average month repeated from next month: `now` without the change, `with` it. A one-off cost lands in its
+ * month; a monthly change (signed: more coming in is positive) applies from its month on. afford_by: for a cost
+ * that would go below zero, the first month it could be paid without going below zero, at the average month.
+ */
+
+function history({ accounts, moves, months }) {
+ const bal = new Map(accounts.map((a) => [a.id, Number(a.opening_cents) || 0]));
+ const sorted = moves.slice().sort((a, b) => (a.month < b.month ? -1 : a.month > b.month ? 1 : 0));
+ const out = [];
+ let i = 0;
+ for (const m of months) {
+ while (i < sorted.length && sorted[i].month <= m) {
+ if (bal.has(sorted[i].account_id)) bal.set(sorted[i].account_id, bal.get(sorted[i].account_id) + Number(sorted[i].cents));
+ i++;
+ }
+ let assets = 0, owed = 0;
+ for (const b of bal.values()) { if (b >= 0) assets += b; else owed -= b; }
+ out.push({ month: m, assets_cents: assets, owed_cents: owed, net_cents: assets - owed });
+ }
+ return out;
+}
+
+function averageMonth(results) {
+ const used = results.filter((r) => r.income_cents || r.spent_cents);
+ if (!used.length) return { income_cents: 0, spending_cents: 0, months: [] };
+ const sum = (k) => used.reduce((n, r) => n + r[k], 0);
+ return { income_cents: Math.round(sum('income_cents') / used.length), spending_cents: Math.round(sum('spent_cents') / used.length), months: used.map((r) => r.month) };
+}
+
+function whatIf({ start_cents, income_cents, spending_cents, months, cost_cents = 0, cost_on = null, change_cents = 0, change_from = null }) {
+ const net = income_cents - spending_cents;
+ const costAt = cost_cents ? Math.max(0, cost_on ? months.indexOf(cost_on) : 0) : -1;
+ const fromAt = change_cents ? Math.max(0, change_from ? months.indexOf(change_from) : 0) : -1;
+ let a = start_cents, b = start_cents;
+ const now = [], withIt = [];
+ months.forEach((m, i) => {
+ a += net;
+ b += net;
+ if (i === costAt) b -= cost_cents;
+ if (fromAt >= 0 && i >= fromAt) b += change_cents;
+ now.push({ month: m, cents: a });
+ withIt.push({ month: m, cents: b });
+ });
+ const lowest = withIt.reduce((lo, p) => (p.cents < lo.cents ? p : lo), withIt[0]);
+ const firstBelow = (list) => (list.find((p) => p.cents < 0) || { month: null }).month;
+ let affordBy = null;
+ if (cost_cents && !change_cents && firstBelow(withIt) && !firstBelow(now) && net > 0) {
+ // The first month k where paying it then leaves every month from k on at zero or more (net > 0: from k is enough).
+ const k = months.findIndex((_m, i) => start_cents + (i + 1) * net - cost_cents >= 0);
+ affordBy = k >= 0 ? months[k] : null;
+ }
+ return {
+ now, with: withIt, lowest, below_zero_on: firstBelow(withIt), now_below_zero_on: firstBelow(now),
+ left_now_cents: net, left_with_cents: net + (change_cents || 0), afford_by: affordBy,
+ };
+}
+
+module.exports = { history, averageMonth, whatIf };
@@ -15,6 +15,8 @@ const path = require('node:path');
@@ -15,6 +15,8 @@ const path = require('node:path');
const { createStore, FinanceError } = require('./store');
const { createStore, FinanceError } = require('./store');
const { readCsv, readAmount } = require('./csv');
const { readCsv, readAmount } = require('./csv');
const { isOfx, readOfx } = require('./ofx');
const { isOfx, readOfx } = require('./ofx');
+const ahead = require('./ahead');
+const { perMonth } = require('./plan');
/** A bank's export, whichever it is: OFX or QFX by its header, else CSV. */
/** A bank's export, whichever it is: OFX or QFX by its header, else CSV. */
const readExport = (text) => (isOfx(text) ? readOfx(text) : readCsv(text));
const readExport = (text) => (isOfx(text) ? readOfx(text) : readCsv(text));
const { findRecurring } = require('./recurring');
const { findRecurring } = require('./recurring');
@@ -57,7 +59,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -57,7 +59,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
const form = express.urlencoded({ extended: false, limit: '4mb' });
const form = express.urlencoded({ extended: false, limit: '4mb' });
const handle = (fn) => async (req, res, next) => {
const handle = (fn) => async (req, res, next) => {
try { await fn(req, res); } catch (err) {
try { await fn(req, res); } catch (err) {
- if (err instanceof FinanceError) return req.path.startsWith('/api/') ? res.status(err.status).json({ error: err.message, code: err.code }) : res.status(err.status).send(v.page({ title: 'Something is wrong', body: `<p class="fin-error" role="alert">${v.esc(err.message)}</p><p><a href="/">Back</a></p>` }));
+ // Under the /api/v1 router req.path is relative to it: the mount (baseUrl) says it is the API.
+ if (err instanceof FinanceError) return `${req.baseUrl}${req.path}`.startsWith('/api/') ? res.status(err.status).json({ error: err.message, code: err.code }) : res.status(err.status).send(v.page({ title: 'Something is wrong', body: `<p class="fin-error" role="alert">${v.esc(err.message)}</p><p><a href="/">Back</a></p>` }));
next(err);
next(err);
}
}
};
};
@@ -142,6 +145,59 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -142,6 +145,59 @@ 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 }));
}));
}));
+ const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
+ const addMonths = (m, by) => { const d = new Date(`${m}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() + by); return d.toISOString().slice(0, 7); };
+ /** The question asked (all optional): a one-off cost in a month, a monthly change from a month. → the ask, or throws. */
+ function readAsk(q, months) {
+ const amount = (text, what) => {
+ const t = String(text || '').trim();
+ if (!t) return 0;
+ const c = readAmount(t);
+ if (c == null) throw new FinanceError(422, 'finance.ahead.amount', `${what} is not a number.`);
+ return Math.abs(c);
+ };
+ const when = (text, what) => {
+ const t = String(text || '').trim();
+ if (!t) return null;
+ if (!MONTH_RE.test(t)) throw new FinanceError(422, 'finance.ahead.month', `${what} is a month (YYYY-MM).`);
+ if (t > months[months.length - 1]) throw new FinanceError(422, 'finance.ahead.month', `${what} is within the next twelve months.`);
+ return t < months[0] ? months[0] : t;
+ };
+ const change = amount(q.change, 'The monthly change');
+ return {
+ cost_cents: amount(q.cost, 'The cost'), cost_on: when(q.cost_on, 'When it is paid'),
+ change_cents: q.dir === 'in' ? change : -change, change_from: when(q.from, 'When the change starts'),
+ };
+ }
+ /** Net worth over the last twelve months and the average month repeated over the next twelve, with the ask. */
+ async function aheadFor(me, q = {}) {
+ const today = now().toISOString().slice(0, 10), m = today.slice(0, 7);
+ const next = Array.from({ length: 12 }, (_, i) => addMonths(m, i + 1));
+ const data = await store.ahead(me);
+ // The line starts where the data does (an opening balance is "before the first transaction", not a year ago).
+ const firstMove = data.moves.reduce((lo, x) => (x.month < lo ? x.month : lo), m);
+ const past = Array.from({ length: 12 }, (_, i) => addMonths(m, i - 11)).filter((pm) => pm >= firstMove);
+ const recent = [];
+ for (const pm of [addMonths(m, -3), addMonths(m, -2), addMonths(m, -1)]) recent.push(await store.month(me, pm));
+ const avg = ahead.averageMonth(recent);
+ // What can be spent: checking, savings and cash, less what the cards owe (they are paid from it).
+ const spendable = data.accounts.reduce((n, a) => n + (['checking', 'savings', 'cash'].includes(a.kind) ? a.balance_cents : a.kind === 'credit' ? Math.min(0, a.balance_cents) : 0), 0);
+ let ask = null, error = null;
+ try { ask = readAsk(q, next); } catch (err) { if (!(err instanceof FinanceError)) throw err; error = err.message; }
+ const asked = Boolean(ask && (ask.cost_cents || ask.change_cents));
+ const goalsNeed = (await store.goals(me)).reduce((n, g) => n + (perMonth({ target_cents: g.target_cents, have_cents: g.have_cents, target_on: g.target_on, today }) || 0), 0);
+ return {
+ net_worth: ahead.history({ accounts: data.accounts, moves: data.moves, months: past }),
+ average: avg, spendable_cents: spendable, goals_need_cents: goalsNeed, has_accounts: data.accounts.length > 0,
+ asked, ask, error,
+ plan: avg.months.length ? ahead.whatIf({ start_cents: spendable, income_cents: avg.income_cents, spending_cents: avg.spending_cents, months: next, ...(asked ? ask : {}) }) : null,
+ };
+ }
+ app.get('/ahead', handle(async (req, res) => {
+ const me = who(req);
+ if (!me) return signIn(req, res);
+ res.send(v.aheadPage({ ...(await aheadFor(me, req.query)), q: req.query }));
+ }));
app.get('/goals', handle(async (req, res) => {
app.get('/goals', handle(async (req, res) => {
const me = who(req);
const me = who(req);
if (!me) return signIn(req, res);
if (!me) return signIn(req, res);
@@ -228,6 +284,12 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -228,6 +284,12 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
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.get('/goals', handle(async (req, res) => res.json({ goals: await store.goals(who(req)) })));
+ api.get('/net-worth', handle(async (req, res) => { const a = await aheadFor(who(req)); res.json({ net_worth: a.net_worth }); }));
+ api.get('/what-if', handle(async (req, res) => {
+ const a = await aheadFor(who(req), req.query);
+ if (a.error) throw new FinanceError(422, 'finance.ahead.ask', a.error);
+ res.json({ average: a.average, spendable_cents: a.spendable_cents, goals_need_cents: a.goals_need_cents, ask: a.asked ? a.ask : null, plan: a.plan });
+ }));
api.post('/goals', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addGoal(who(req), req.body || {}))));
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;
@@ -22,6 +22,7 @@
@@ -22,6 +22,7 @@
* goals(owner) → [{ id, name, target_cents, target_on, account_id, saved_cents, have_cents }]
* 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
* 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
* setDebt(owner, accountId, { apr_bps, payment_cents }) a loan's or card's rate and monthly payment
+ * ahead(owner) → { accounts: [{ id, kind, opening_cents, balance_cents }], moves: [{ account_id, month, cents }] }
* 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
*/
*/
@@ -309,6 +310,21 @@ function createStore({ db, vault }) {
@@ -309,6 +310,21 @@ function createStore({ db, vault }) {
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]);
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]);
}
}
+ /** What net worth over time and the what-if are worked out from (server/ahead.js): no payee is opened. */
+ async function ahead(owner) {
+ own(owner);
+ const accs = await db.many('SELECT id, kind, opening_cents FROM finance_accounts WHERE owner = $1 AND archived_at IS NULL', [owner]);
+ const moves = await db.many(`SELECT t.account_id, to_char(date_trunc('month', t.posted_on), 'YYYY-MM') AS month, SUM(t.amount_cents)::bigint AS cents
+ FROM finance_transactions t JOIN finance_accounts a ON a.id = t.account_id AND a.archived_at IS NULL
+ WHERE t.owner = $1 GROUP BY 1, 2`, [owner]);
+ const moved = new Map();
+ for (const m of moves) moved.set(m.account_id, (moved.get(m.account_id) || 0) + Number(m.cents));
+ return {
+ accounts: accs.map((a) => ({ id: a.id, kind: a.kind, opening_cents: Number(a.opening_cents), balance_cents: Number(a.opening_cents) + (moved.get(a.id) || 0) })),
+ moves: moves.map((m) => ({ account_id: m.account_id, month: m.month, cents: Number(m.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, apr_bps, payment_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]);
@@ -335,7 +351,7 @@ function createStore({ db, vault }) {
@@ -335,7 +351,7 @@ function createStore({ db, vault }) {
});
});
}
}
- return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, goals, addGoal, setGoalSaved, removeGoal, setDebt, exportAll, removeAll };
+ return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, goals, addGoal, setGoalSaved, removeGoal, setDebt, ahead, exportAll, removeAll };
}
}
module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
@@ -22,7 +22,7 @@ const KIND_WORDS = { checking: 'Checking', savings: 'Savings', credit: 'Credit c
@@ -22,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' }, { label: 'Goals', href: '/goals' }] },
+ navbar: { service: 'finance', apiBase: 'https://openvibe.network', links: [{ label: 'Money', href: '/' }, { label: 'This month', href: '/month' }, { label: 'Recurring', href: '/bills' }, { label: 'Goals', href: '/goals' }, { label: 'What if', href: '/ahead' }] },
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>`,
@@ -70,7 +70,7 @@ ${accounts.length ? `<section class="fin-month-card" aria-label="${esc(monthName
@@ -70,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="/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>` });
+<p class="fin-foot"><a href="/ahead">Net worth and what if</a> · <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' };
@@ -153,6 +153,85 @@ ${savings.length ? `<fieldset class="fin-chips"><legend>Its progress is (optiona
@@ -153,6 +153,85 @@ ${savings.length ? `<fieldset class="fin-chips"><legend>Its progress is (optiona
<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>` });
<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>` });
}
}
+const shortMonth = (m) => new Date(`${m}-01T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', year: 'numeric', timeZone: 'UTC' });
+
+/** A small line chart in the page's own colours: lines [{ cls, points: [cents] }], the zero line when it is crossed. */
+function lineChart(lines, { label, area = false }) {
+ const all = lines.flatMap((l) => l.points);
+ let lo = Math.min(...all), hi = Math.max(...all);
+ if (lo === hi) { lo -= 10000; hi += 10000; }
+ const pad = (hi - lo) * 0.08;
+ lo -= pad; hi += pad;
+ const W = 600, H = 160, n = lines[0].points.length;
+ const x = (i) => (n === 1 ? W / 2 : (i / (n - 1)) * W).toFixed(1);
+ const y = (c) => (H - ((c - lo) / (hi - lo)) * H).toFixed(1);
+ const d = (pts) => pts.map((c, i) => `${i ? 'L' : 'M'}${x(i)},${y(c)}`).join('');
+ const zero = lo < 0 && hi > 0 ? `<line class="fin-zero" x1="0" x2="${W}" y1="${y(0)}" y2="${y(0)}"/>` : '';
+ const fill = area ? `<path class="fin-area" d="${d(lines[0].points)}L${W},${H}L0,${H}Z"/>` : '';
+ return `<svg class="fin-chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(label)}">${fill}${zero}${lines.map((l) => `<path class="${l.cls}" d="${d(l.points)}"/>`).join('')}</svg>`;
+}
+
+function aheadPage({ net_worth, average, spendable_cents, goals_need_cents, has_accounts, asked, ask, error, plan, q = {} }) {
+ const last = net_worth[net_worth.length - 1];
+ const first = net_worth.find((p) => p.assets_cents || p.owed_cents) || net_worth[0];
+ const change = last.net_cents - first.net_cents;
+ const worth = !has_accounts ? '<p class="fin-empty">Add an account on <a href="/">Your money</a> to see your net worth.</p>' : `
+<p class="fin-big${last.net_cents < 0 ? ' is-neg' : ''}">${esc(money(last.net_cents))}</p>
+<p class="fin-sub">${esc(money(last.assets_cents))} in your accounts · ${esc(money(last.owed_cents))} owed${first.month !== last.month ? ` · <span class="${change < 0 ? 'is-neg' : 'fin-in'}">${change < 0 ? '−' : '+'}${esc(money(Math.abs(change)))}</span> since ${esc(monthName(first.month))}` : ''}</p>
+${net_worth.length > 1 ? `${lineChart([{ cls: 'fin-line', points: net_worth.map((p) => p.net_cents) }], { label: `Net worth at the end of each month, ${monthName(net_worth[0].month)} to ${monthName(last.month)}`, area: true })}
+<div class="fin-axis"><span>${esc(shortMonth(net_worth[0].month))}</span><span>Now</span></div>` : ''}`;
+
+ const val = (k) => esc(q[k] || '');
+ const months = plan ? plan.now.map((p) => p.month) : [];
+ // When: a row of month chips (the first, "next month", by default), never the browser's month box.
+ const whenChips = (name, legend) => `<div class="fin-when"><span class="fin-when-label" id="fin-when-${name}">${legend}</span><div class="fin-chips fin-chips--scroll" role="radiogroup" aria-labelledby="fin-when-${name}">${months.map((mm, i) => {
+ const on = (q[name] || months[0]) === mm;
+ const label = i === 0 ? 'Next month' : mm.endsWith('-01') || i === 1 ? shortMonth(mm) : new Date(`${mm}-01T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', timeZone: 'UTC' });
+ return `<label class="fin-chip"><input type="radio" name="${name}" value="${i === 0 ? '' : mm}"${on ? ' checked' : ''}><span>${esc(label)}</span></label>`;
+ }).join('')}</div></div>`;
+ const dirIn = q.dir === 'in';
+ const form = `<form class="fin-form fin-ask" method="get" action="/ahead">
+<fieldset class="fin-askset"><legend>Can I afford it? A one-off cost</legend>
+<label class="fin-field"><span>Amount</span><input name="cost" inputmode="decimal" placeholder="1,200.00" value="${val('cost')}" autocomplete="off"></label>
+${whenChips('cost_on', 'Paid in')}</fieldset>
+<fieldset class="fin-askset"><legend>What if something changes every month</legend>
+<div class="fin-chips"><label class="fin-chip"><input type="radio" name="dir" value="out"${dirIn ? '' : ' checked'}><span>More going out</span></label><label class="fin-chip"><input type="radio" name="dir" value="in"${dirIn ? ' checked' : ''}><span>More coming in</span></label></div>
+<label class="fin-field"><span>Amount a month</span><input name="change" inputmode="decimal" placeholder="200.00" value="${val('change')}" autocomplete="off"></label>
+${whenChips('from', 'From')}</fieldset>
+<p class="fin-ask-go"><button class="fin-btn fin-btn--primary" type="submit">See what happens</button>${asked ? '<a class="fin-btn" href="/ahead">Start over</a>' : ''}</p>
+</form>`;
+
+ let result = '';
+ if (plan) {
+ const end = plan.with[plan.with.length - 1];
+ let verdict;
+ if (plan.now_below_zero_on) verdict = `<p class="fin-verdict is-no">Your average month spends more than comes in: at this rate the money to spend runs out in ${esc(monthName(plan.now_below_zero_on))}.</p>`;
+ else if (!asked) verdict = `<p class="fin-verdict">At your average month you have about <b>${esc(money(end.cents))}</b> to spend in ${esc(monthName(end.month))}.</p>`;
+ else if (plan.below_zero_on) verdict = `<p class="fin-verdict is-no">Not yet: it takes you below zero in ${esc(monthName(plan.below_zero_on))} (lowest ${esc(money(plan.lowest.cents))}).${plan.afford_by ? ` At your average month you could pay it in <b>${esc(monthName(plan.afford_by))}</b> and stay above zero.` : ''}</p>`;
+ else verdict = `<p class="fin-verdict is-yes">Yes. The lowest it gets is <b>${esc(money(plan.lowest.cents))}</b>, in ${esc(monthName(plan.lowest.month))}; about ${esc(money(end.cents))} in ${esc(monthName(end.month))}.</p>`;
+ const changeLine = asked && ask.change_cents ? `<p class="fin-sub">Left over each month: ${esc(money(plan.left_now_cents))} now, <b>${esc(money(plan.left_with_cents))}</b> with the change.</p>` : '';
+ const goalsLine = goals_need_cents ? `<p class="fin-sub">Your goals with dates need ${esc(money(goals_need_cents))} a month${plan.left_with_cents < goals_need_cents ? `: ${asked ? 'this leaves' : 'your average month leaves'} less than that (<a href="/goals">Goals</a>).` : '.'}</p>` : '';
+ const lines = asked ? [{ cls: 'fin-line fin-line--now', points: [spendable_cents, ...plan.now.map((p) => p.cents)] }, { cls: 'fin-line', points: [spendable_cents, ...plan.with.map((p) => p.cents)] }]
+ : [{ cls: 'fin-line', points: [spendable_cents, ...plan.now.map((p) => p.cents)] }];
+ result = `<div class="fin-result" aria-live="polite">${verdict}${changeLine}${goalsLine}
+${lineChart(lines, { label: `Money to spend at the end of each month, now to ${monthName(end.month)}` })}
+<div class="fin-axis"><span>Now</span><span>${esc(shortMonth(end.month))}</span></div>
+${asked ? '<p class="fin-legend"><span class="fin-key fin-key--now">As things are</span><span class="fin-key">With the change</span></p>' : ''}
+<details class="fin-fold fin-fold--quiet"><summary>Month by month</summary><div class="fin-table-wrap"><table class="fin-table"><thead><tr><th>End of</th><th>${asked ? 'As things are' : 'To spend'}</th>${asked ? '<th>With the change</th>' : ''}</tr></thead><tbody>
+${plan.now.map((p, i) => `<tr><td>${esc(shortMonth(p.month))}</td><td class="${p.cents < 0 ? 'is-neg' : ''}">${esc(money(p.cents))}</td>${asked ? `<td class="${plan.with[i].cents < 0 ? 'is-neg' : ''}">${esc(money(plan.with[i].cents))}</td>` : ''}</tr>`).join('')}
+</tbody></table></div></details></div>`;
+ }
+ const base = average.months.length ? `<p class="fin-sub">Your average month (${esc(average.months.length === 1 ? monthName(average.months[0]) : `${shortMonth(average.months[0])} to ${shortMonth(average.months[average.months.length - 1])}`)}): ${esc(money(average.income_cents))} in, ${esc(money(average.spending_cents))} out, <b>${esc(money(average.income_cents - average.spending_cents))}</b> left over. ${esc(money(spendable_cents))} to spend now.</p>`
+ : '<p class="fin-empty">A month or two of transactions (the months before this one) shows what is ahead.</p>';
+ return page({
+ title: 'Net worth and what if', path: '/ahead', body: `
+<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Net worth and what if</h1></header>
+<section class="fin-sec"><h2>Net worth</h2>${worth}</section>
+<section class="fin-sec"><h2>What if</h2>${base}
+${error ? `<p class="fin-error" role="alert">${esc(error)}</p>` : ''}${result}${average.months.length ? form : ''}</section>
+<p class="fin-note">Roughly: your average month of the last three, repeated from next month. Money to spend is checking, savings and cash, less what cards owe; investments and loans are left out, as are transfers between your accounts. Nothing here moves money.</p>` });
+}
+
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: `
@@ -257,4 +336,4 @@ ${notice(o)}
@@ -257,4 +336,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, goalsPage, money, esc, monthName };
+module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, aheadPage, lineChart, money, esc, monthName };
new file mode 100644
new file mode 100644
@@ -0,0 +1,122 @@
@@ -0,0 +1,122 @@
+'use strict';
+/**
+ * Net worth and what if (server/ahead.js, /ahead, /api/v1/net-worth, /api/v1/what-if): net worth at each month's end
+ * (moves before the window counted, a negative balance owed); the average month over the months that had any; a
+ * one-off cost that fits, one that does not yet (and the month it would), a monthly change from a month, a baseline
+ * that runs out on its own; the page's verdicts, the goals line, bad input shown on the page, the API, another person.
+ */
+const assert = require('assert');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const { history, averageMonth, whatIf } = require('../server/ahead');
+
+const months12 = ['2026-12', '2027-01', '2027-02', '2027-03', '2027-04', '2027-05', '2027-06', '2027-07', '2027-08', '2027-09', '2027-10', '2027-11'];
+
+assert.deepStrictEqual(history({
+ accounts: [{ id: 'a', opening_cents: 100000 }, { id: 'b', opening_cents: 0 }],
+ moves: [{ account_id: 'a', month: '2026-01', cents: 7 }, { account_id: 'a', month: '2026-09', cents: 50000 }, { account_id: 'b', month: '2026-10', cents: -30000 }, { account_id: 'a', month: '2026-11', cents: -20000 }],
+ months: ['2026-09', '2026-10', '2026-11'],
+}), [
+ { month: '2026-09', assets_cents: 150007, owed_cents: 0, net_cents: 150007 },
+ { month: '2026-10', assets_cents: 150007, owed_cents: 30000, net_cents: 120007 },
+ { month: '2026-11', assets_cents: 130007, owed_cents: 30000, net_cents: 100007 },
+]);
+assert.deepStrictEqual(averageMonth([
+ { month: '2026-08', income_cents: 0, spent_cents: 0 }, { month: '2026-09', income_cents: 300000, spent_cents: 200000 }, { month: '2026-10', income_cents: 310000, spent_cents: 220000 },
+]), { income_cents: 305000, spending_cents: 210000, months: ['2026-09', '2026-10'] }, 'an empty month is not an average month');
+
+const base = { start_cents: 100000, income_cents: 300000, spending_cents: 250000, months: months12 };
+let p = whatIf(base);
+assert.strictEqual(p.now[11].cents, 700000);
+assert.strictEqual(p.below_zero_on, null);
+p = whatIf({ ...base, cost_cents: 200000 });
+assert.strictEqual(p.with[0].cents, -50000);
+assert.strictEqual(p.below_zero_on, '2026-12');
+assert.strictEqual(p.afford_by, '2027-01', 'two months of $500 left over pay a $2,000 cost from $1,000');
+p = whatIf({ ...base, cost_cents: 100000, cost_on: '2027-03' });
+assert.deepStrictEqual([p.with[2].cents, p.with[3].cents, p.below_zero_on], [250000, 200000, null]);
+p = whatIf({ ...base, change_cents: -60000, change_from: '2027-02' });
+assert.deepStrictEqual([p.with[1].cents, p.with[2].cents, p.with[11].cents, p.left_with_cents], [200000, 190000, 100000, -10000], 'rent up $600 from February');
+p = whatIf({ start_cents: 120000, income_cents: 100000, spending_cents: 150000, months: months12 });
+assert.strictEqual(p.now_below_zero_on, '2027-02', 'more going out than coming in runs out on its own');
+
+(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 BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
+ 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 page = (q = '', as = ADA) => fetch(`${base}/ahead${q}`, { redirect: 'manual', headers: as ? { 'x-test-user': as } : {} }).then(async (r) => ({ status: r.status, text: await r.text() }));
+ const api = (p, as = ADA) => fetch(`${base}/api/v1${p}`, { headers: { 'x-test-user': as } }).then(async (r) => ({ status: r.status, body: await r.json() }));
+ try {
+ const checking = await store.addAccount(ADA, { name: 'Checking', kind: 'checking', opening_cents: 100000 });
+ const savings = await store.addAccount(ADA, { name: 'Savings', kind: 'savings', opening_cents: 500000 });
+ const card = await store.addAccount(ADA, { name: 'Card', kind: 'credit' });
+ const rows = [];
+ for (const m of ['2026-08', '2026-09', '2026-10']) {
+ rows.push({ posted_on: `${m}-01`, amount_cents: 300000, payee: 'Paycheck', category: 'Income' });
+ rows.push({ posted_on: `${m}-03`, amount_cents: -150000, payee: 'Rent', category: 'Housing' });
+ rows.push({ posted_on: `${m}-10`, amount_cents: -50000, payee: 'Grocer', category: 'Groceries' });
+ }
+ rows.push({ posted_on: '2026-10-20', amount_cents: -50000, payee: 'To savings', category: 'Transfers' });
+ await store.importRows(ADA, checking.id, rows);
+ await store.importRows(ADA, savings.id, [{ posted_on: '2026-10-20', amount_cents: 50000, payee: 'From checking', category: 'Transfers' }]);
+ await store.importRows(ADA, card.id, [{ posted_on: '2026-10-12', amount_cents: -30000, payee: 'Shoes', category: 'Shopping' }]);
+
+ let r = await page();
+ assert.strictEqual(r.status, 200, r.text.slice(0, 300));
+ assert.match(r.text, /<p class="fin-big">\$8,700\.00<\/p>/, '$3,500 checking + $5,500 savings − $300 owed');
+ assert.match(r.text, /\+\$1,700\.00<\/span> since August 2026/, 'from the first month with data, not a year of openings');
+ assert.match(r.text, /\$3,000\.00 in, \$2,100\.00 out, <b>\$900\.00<\/b> left over\. \$8,700\.00 to spend now/, 'transfers left out of the average');
+ assert.match(r.text, /about <b>\$19,500\.00<\/b> to spend in November 2027/);
+ assert.match(r.text, /<svg class="fin-chart"/);
+
+ r = await page('?cost=12%2C000&cost_on=2026-12');
+ assert.match(r.text, /Not yet: it takes you below zero in December 2026/);
+ assert.match(r.text, /could pay it in <b>March 2027<\/b>/);
+ r = await page('?cost=5000');
+ assert.match(r.text, /Yes\. The lowest it gets is <b>\$4,600\.00<\/b>, in December 2026/);
+ assert.match(r.text, /As things are/);
+
+ await store.addGoal(ADA, { name: 'House', target_cents: 1000000, target_on: '2027-11-01' });
+ r = await page('?change=1000&dir=out&from=2027-02');
+ assert.match(r.text, /Left over each month: \$900\.00 now, <b>-\$100\.00<\/b> with the change/);
+ assert.match(r.text, /Your goals with dates need \$833\.34 a month: this leaves less than that/);
+ assert.match(r.text, /name="change"[^>]*value="1000"/, 'the question stays in the form');
+ assert.match(r.text, /name="from" value="2027-02" checked/, 'and its month chip');
+ assert.doesNotMatch(r.text, /type="month"/, 'no browser month box');
+
+ r = await page('?cost=lots');
+ assert.strictEqual(r.status, 200);
+ assert.match(r.text, /role="alert">The cost is not a number\./);
+ r = await page('?cost=10&cost_on=2030-01');
+ assert.match(r.text, /within the next twelve months/);
+
+ let a = await api('/what-if?cost=5000');
+ assert.strictEqual(a.status, 200);
+ assert.deepStrictEqual([a.body.plan.lowest.cents, a.body.spendable_cents, a.body.average.income_cents], [460000, 870000, 300000]);
+ a = await api('/what-if?cost=abc');
+ assert.strictEqual(a.status, 422);
+ assert.deepStrictEqual(a.body, { error: 'The cost is not a number.', code: 'finance.ahead.ask' }, 'an API error is JSON, not a page');
+ a = await api('/net-worth');
+ assert.deepStrictEqual(a.body.net_worth.map((x) => [x.month, x.net_cents]), [['2026-08', 700000], ['2026-09', 800000], ['2026-10', 870000], ['2026-11', 870000]]);
+
+ r = await page('', BO);
+ assert.match(r.text, /Add an account on <a href="\/">Your money<\/a>/, 'another person sees none of it');
+ assert.doesNotMatch(r.text, /8,700/);
+ r = await page('', null);
+ assert.ok([302, 303].includes(r.status), `signed out goes to sign in: ${r.status}`);
+ } finally {
+ server.close();
+ await close();
+ }
+ console.log('ahead: net worth over time, the average month, yes, not yet and when, a monthly change, goals, bad input, the API, another person');
+})().catch((err) => { console.error(err); process.exit(1); });
@@ -36,6 +36,16 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
@@ -36,6 +36,16 @@ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
2026-11-16,Gym Monthly,-29.00,Subscriptions
2026-11-16,Gym Monthly,-29.00,Subscriptions
`;
`;
await store.importRows(ADA, checking.id, readCsv(csv).rows);
await store.importRows(ADA, checking.id, readCsv(csv).rows);
+ // Three earlier months, so the average month (Net worth and what if) has something to stand on.
+ for (const [m, extra] of [['2026-08', 0], ['2026-09', 12000], ['2026-10', -8000]]) {
+ await store.importRows(ADA, checking.id, [
+ { posted_on: `${m}-01`, amount_cents: 312000, payee: 'Paycheck ACME Corp', category: 'Income' },
+ { posted_on: `${m}-01`, amount_cents: -145000, payee: 'Lakeview Apartments', category: 'Housing' },
+ { posted_on: `${m}-04`, amount_cents: -42000 - extra, payee: 'Corner Grocer', category: 'Groceries' },
+ { posted_on: `${m}-09`, amount_cents: -7130, payee: 'City Power & Light', category: 'Utilities' },
+ { posted_on: `${m}-15`, amount_cents: -38500, payee: 'Eating out, various', category: 'Eating out' },
+ ]);
+ }
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, 'Eating out', 4000);
await store.setBudget(ADA, 'Groceries', 40000);
await store.setBudget(ADA, 'Groceries', 40000);