openvibers/openvibe.finance serverviews.js
views.js
| 1 | ; |
| 2 | /** |
| 3 | * Finance's pages, server-rendered in the network's shell (openvibe-shared/shell, kit.css) with this site's own |
| 4 | * finance.css. Every value that reaches markup goes through esc(). Forms post to the same origin and work without |
| 5 | * script; public/finance.js only reads a chosen CSV file into the paste box. |
| 6 | */ |
| 7 | const shell = require('openvibe-shared/shell'); |
| 8 | const serve = require('openvibe-shared/serve'); |
| 9 | const { CATEGORIES, KINDS } = require('./store'); |
| 10 | const { payoff, faster, perMonth } = require('./plan'); |
| 11 | |
| 12 | // Our own files by their content (a release's change is a new address, so neither a browser nor Cloudflare keeps an old |
| 13 | // one for the hour they may cache it): /x.css?v=<first 10 hex of its sha256>, read once at boot. |
| 14 | const asset = (() => { |
| 15 | const fs = require('node:fs'); |
| 16 | const crypto = require('node:crypto'); |
| 17 | const kept = new Map(); |
| 18 | return (name) => { |
| 19 | if (!kept.has(name)) { |
| 20 | let v = 'dev'; |
| 21 | try { v = crypto.createHash('sha256').update(fs.readFileSync(require('node:path').join(__dirname, '..', 'public', name))).digest('hex').slice(0, 10); } catch { /* missing in a test: unversioned */ } |
| 22 | kept.set(name, `/${name}?v=${v}`); |
| 23 | } |
| 24 | return kept.get(name); |
| 25 | }; |
| 26 | })(); |
| 27 | |
| 28 | const SITE = 'https://openvibe.finance'; |
| 29 | const esc = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); |
| 30 | const money = (cents, currency = 'USD') => { |
| 31 | try { return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100); } |
| 32 | catch { return `${(cents / 100).toFixed(2)} ${currency}`; } |
| 33 | }; |
| 34 | const monthName = (m) => new Date(`${m}-01T00:00:00Z`).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' }); |
| 35 | const shiftMonth = (m, by) => { const d = new Date(`${m}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() + by); return d.toISOString().slice(0, 7); }; |
| 36 | const KIND_WORDS = { checking: 'Checking', savings: 'Savings', credit: 'Credit card', cash: 'Cash', loan: 'Loan', investment: 'Investments', other: 'Other' }; |
| 37 | |
| 38 | function page({ title, body, path = '/', description = 'Your money, your rules, your data: accounts, imports and a monthly picture, private to you.', robots = 'noindex, nofollow' }) { |
| 39 | return shell.page({ |
| 40 | name: 'OpenVibe.Finance', siteName: 'OpenVibe.Finance', title, description, canonical: `${SITE}${path}`, robots, |
| 41 | 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' }] }, |
| 42 | footer: { service: 'finance', variant: 'full', mount: '#ov-footer' }, |
| 43 | head: `<link rel="stylesheet" href="${serve.url('kit.css')}"><link rel="stylesheet" href="${asset('finance.css')}"><script src="${asset('finance.js')}" defer></script>`, |
| 44 | body: `<div id="navbar-mount"></div><main id="main" class="ovk-page fin">${body}</main>`, |
| 45 | }); |
| 46 | } |
| 47 | |
| 48 | const notice = (o) => (o.error ? `<p class="fin-error" role="alert">${esc(o.error)}</p>` : '') + (o.said ? `<p class="fin-said" role="status">${esc(o.said)}</p>` : ''); |
| 49 | |
| 50 | function welcome() { |
| 51 | return page({ |
| 52 | title: 'Your money, your rules, your data', robots: 'index, follow', body: ` |
| 53 | <section class="fin-hero"> |
| 54 | <h1>Your money, your rules, your data</h1> |
| 55 | <p class="fin-lede">Your accounts in one place, from your bank's download (CSV, OFX or QFX) or typed in, and a clear picture of each month. Free, with nothing to connect.</p> |
| 56 | <p><a class="fin-btn fin-btn--primary" href="/auth/login?next=%2F">Sign in to start</a></p> |
| 57 | </section> |
| 58 | <ul class="fin-promises"> |
| 59 | <li><b>Private to you.</b> Payees and notes are stored encrypted under a key for your account alone. Nothing here enters search, analytics or AI training.</li> |
| 60 | <li><b>No money moves.</b> It reads and plans. It never pays, transfers or cancels anything.</li> |
| 61 | <li><b>Yours to take.</b> Download everything as one file, or delete everything, any time.</li> |
| 62 | </ul>` }); |
| 63 | } |
| 64 | |
| 65 | // OpenVibe's money Experts on Actor (Actor #623): they read your numbers here through /mcp, as you, once you allow |
| 66 | // Actor in OpenVibe Finance on your Apps page; none moves money. |
| 67 | const EXPERTS = [ |
| 68 | { id: 'bp_budget_coach', name: 'Budget coach', what: 'A budget you can live with, from your real month.' }, |
| 69 | { id: 'bp_can_i_afford_it', name: 'Can I afford it?', what: 'Yes, not yet or no, for a purchase or a new monthly cost.' }, |
| 70 | { id: 'bp_debt_planner', name: 'Debt planner', what: 'The fastest and the cheapest way out of your loans and cards.' }, |
| 71 | { id: 'bp_subscription_auditor', name: 'Subscription auditor', what: 'Every recurring charge, and what dropping each saves.' }, |
| 72 | ]; |
| 73 | const expertsSection = () => `<section class="fin-sec fin-experts" aria-labelledby="fin-experts-h"><h2 id="fin-experts-h">Ask an Expert</h2> |
| 74 | <ul class="fin-expert-list">${EXPERTS.map((e) => `<li><a class="fin-expert" href="https://openvibe.actor/experts/${e.id}"><b>${esc(e.name)}</b><span>${esc(e.what)}</span></a></li>`).join('')}</ul> |
| 75 | <p class="fin-note">They read your numbers here as you once you allow Actor in OpenVibe Finance on your <a href="https://openvibe.network/apps">Apps page</a>, and only to read: nothing here moves money. To answer, the model you chose in Actor reads the numbers the Expert fetched; take back the permission there at any time.</p></section>`; |
| 76 | |
| 77 | function home({ accounts, month, o = {} }) { |
| 78 | const total = {}; |
| 79 | for (const a of accounts) total[a.currency] = (total[a.currency] || 0) + a.balance_cents; |
| 80 | const totals = Object.entries(total).map(([c, v]) => money(v, c)).join(' · '); |
| 81 | const kindChips = KINDS.map((k, i) => `<label class="fin-chip"><input type="radio" name="kind" value="${k}"${i === 0 ? ' checked' : ''}><span>${esc(KIND_WORDS[k])}</span></label>`).join(''); |
| 82 | return page({ |
| 83 | title: 'Your money', body: ` |
| 84 | <header class="fin-head"><h1>Your money</h1>${accounts.length ? `<p class="fin-total">${esc(totals)}</p>` : ''}</header> |
| 85 | ${notice(o)} |
| 86 | ${accounts.length ? `<section class="fin-month-card" aria-label="${esc(monthName(month.month))}"> |
| 87 | <a class="fin-month-link" href="/month?m=${month.month}"><span>${esc(monthName(month.month))}</span> |
| 88 | <span class="fin-in">In ${esc(money(month.income_cents))}</span><span class="fin-out">Out ${esc(money(month.spent_cents))}</span></a></section> |
| 89 | <ul class="fin-accounts">${accounts.map((a) => `<li><a class="fin-account" href="/accounts/${esc(a.id)}"> |
| 90 | <span class="fin-account-name">${esc(a.name)}<small>${esc(KIND_WORDS[a.kind] || a.kind)} · ${a.count} transaction${a.count === 1 ? '' : 's'}</small></span> |
| 91 | <span class="fin-account-balance${a.balance_cents < 0 ? ' is-neg' : ''}">${esc(money(a.balance_cents, a.currency))}</span></a></li>`).join('')}</ul>` |
| 92 | : `<p class="fin-empty">Start with an account: name it, then type in transactions or import your bank's download (CSV, OFX or QFX).</p>`} |
| 93 | <details class="fin-fold"${accounts.length ? '' : ' open'}><summary>Add an account</summary> |
| 94 | <form class="fin-form" method="post" action="/accounts"> |
| 95 | <label class="fin-field"><span>Name</span><input name="name" maxlength="80" required placeholder="Everyday checking" autocomplete="off"></label> |
| 96 | <fieldset class="fin-chips"><legend>Kind</legend>${kindChips}</fieldset> |
| 97 | <div class="fin-row"><label class="fin-field"><span>Currency</span><input name="currency" value="USD" maxlength="3" pattern="[A-Za-z]{3}" autocomplete="off"></label> |
| 98 | <label class="fin-field"><span>Balance before the first transaction</span><input name="opening" inputmode="decimal" placeholder="0.00" autocomplete="off"></label></div> |
| 99 | <p><button class="fin-btn fin-btn--primary" type="submit">Add the account</button></p> |
| 100 | </form></details> |
| 101 | ${accounts.length ? expertsSection() : ''} |
| 102 | <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>` }); |
| 103 | } |
| 104 | |
| 105 | const CADENCE_WORDS = { weekly: 'Every week', 'every two weeks': 'Every two weeks', monthly: 'Every month', quarterly: 'Every three months', yearly: 'Every year' }; |
| 106 | const dayName = (iso) => new Date(`${iso}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); |
| 107 | |
| 108 | function billsPage({ found, today, o = {} }) { |
| 109 | const out = found.filter((r) => r.direction === 'out'); |
| 110 | const income = found.filter((r) => r.direction === 'in'); |
| 111 | const monthly = out.reduce((n, r) => n + r.monthly_cents, 0); |
| 112 | const soon = out.filter((r) => !r.overdue && r.next_on >= today && Date.parse(r.next_on) - Date.parse(today) <= 31 * 86400000); |
| 113 | const row = (r) => `<li class="fin-bill${r.overdue ? ' is-late' : ''}"><span class="fin-bill-what"><b>${esc(r.payee)}</b> |
| 114 | <span>${esc(CADENCE_WORDS[r.cadence] || r.cadence)} · seen ${r.count} times · last ${esc(dayName(r.last_on))}</span></span> |
| 115 | <span class="fin-bill-when">${r.overdue ? `<small>Expected ${esc(dayName(r.next_on))}: not seen</small>` : `<small>Next ${esc(dayName(r.next_on))}</small>`}<b>${esc(money(r.typical_cents))}</b></span></li>`; |
| 116 | return page({ |
| 117 | title: 'Recurring', path: '/bills', body: ` |
| 118 | <header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Recurring</h1> |
| 119 | ${out.length ? `<p class="fin-total">About ${esc(money(monthly))} a month</p>` : ''}</header> |
| 120 | ${notice(o)} |
| 121 | <p class="fin-note">Found in your own transactions: the same payee and a similar amount, at a steady rhythm, at least three times. Nothing here is stored or sent anywhere.</p> |
| 122 | ${soon.length ? `<section class="fin-sec"><h2>The next 31 days</h2><ul class="fin-bills">${soon.map(row).join('')}</ul></section>` : ''} |
| 123 | <section class="fin-sec"><h2>Bills and subscriptions</h2>${out.length ? `<ul class="fin-bills">${out.map(row).join('')}</ul>` : '<p class="fin-empty">None found yet. A few months of transactions show them.</p>'}</section> |
| 124 | ${income.length ? `<section class="fin-sec"><h2>Money that comes in regularly</h2><ul class="fin-bills">${income.map(row).join('')}</ul></section>` : ''}` }); |
| 125 | } |
| 126 | |
| 127 | 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'}` : ''}`); |
| 128 | const pct = (bps) => `${(bps / 100).toFixed(2).replace(/\.?0+$/, '')}%`; |
| 129 | |
| 130 | function goalsPage({ goals, accounts, today, o = {} }) { |
| 131 | const debts = accounts.filter((a) => (a.kind === 'loan' || a.kind === 'credit')); |
| 132 | const savings = accounts.filter((a) => a.kind !== 'loan' && a.kind !== 'credit'); |
| 133 | const goalRow = (g) => { |
| 134 | const have = Math.max(0, g.have_cents); |
| 135 | const done = have >= g.target_cents; |
| 136 | const need = perMonth({ target_cents: g.target_cents, have_cents: have, target_on: g.target_on, today }); |
| 137 | const tracked = g.account_id ? accounts.find((a) => a.id === g.account_id) : null; |
| 138 | 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> |
| 139 | <span class="fin-bar fin-bar--budget"><span style="--w:${Math.min(100, Math.round((have / g.target_cents) * 100))}%"></span></span> |
| 140 | <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.'} |
| 141 | ${tracked ? ` Tracks <a href="/accounts/${esc(tracked.id)}">${esc(tracked.name)}</a>.` : ''}</p> |
| 142 | <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>`} |
| 143 | <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>`; |
| 144 | }; |
| 145 | const debtRow = (a) => { |
| 146 | const owed = Math.max(0, -a.balance_cents); |
| 147 | const terms = a.apr_bps != null && a.payment_cents; |
| 148 | let said = 'Add its yearly rate and your monthly payment to see when it is paid off.'; |
| 149 | let tip = ''; |
| 150 | if (!owed) said = 'Nothing owed.'; |
| 151 | else if (terms) { |
| 152 | const p = payoff({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents }); |
| 153 | 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.`; |
| 154 | else { |
| 155 | const extra = Math.max(2500, Math.round(a.payment_cents * 0.25 / 500) * 500); |
| 156 | const f = faster({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents }, extra); |
| 157 | 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).`; |
| 158 | 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.`; |
| 159 | } |
| 160 | } |
| 161 | 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> |
| 162 | <p class="fin-goal-note">${said}</p>${tip ? `<p class="fin-goal-tip">${tip}</p>` : ''} |
| 163 | ${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"> |
| 164 | <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> |
| 165 | <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> |
| 166 | <p><button class="fin-btn" type="submit">Save</button></p></form>${terms ? '</details>' : ''}</li>`; |
| 167 | }; |
| 168 | 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(''); |
| 169 | return page({ |
| 170 | title: 'Goals and debt', path: '/goals', body: ` |
| 171 | <header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Goals and debt</h1></header> |
| 172 | ${notice(o)} |
| 173 | <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>'} |
| 174 | <details class="fin-fold"><summary>Add a goal</summary> |
| 175 | <form class="fin-form" method="post" action="/goals"> |
| 176 | <label class="fin-field"><span>Name</span><input name="name" maxlength="80" required placeholder="Emergency fund" autocomplete="off"></label> |
| 177 | <div class="fin-row"><label class="fin-field"><span>Amount</span><input name="target" inputmode="decimal" required placeholder="5000" autocomplete="off"></label> |
| 178 | <label class="fin-field"><span>By (optional)</span><input type="date" name="target_on"></label></div> |
| 179 | ${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>` : ''} |
| 180 | <p><button class="fin-btn fin-btn--primary" type="submit">Add the goal</button></p> |
| 181 | </form></details></section> |
| 182 | <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>` }); |
| 183 | } |
| 184 | |
| 185 | const shortMonth = (m) => new Date(`${m}-01T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', year: 'numeric', timeZone: 'UTC' }); |
| 186 | |
| 187 | /** A small line chart in the page's own colours: lines [{ cls, points: [cents] }], the zero line when it is crossed. */ |
| 188 | function lineChart(lines, { label, area = false }) { |
| 189 | const all = lines.flatMap((l) => l.points); |
| 190 | let lo = Math.min(...all), hi = Math.max(...all); |
| 191 | if (lo === hi) { lo -= 10000; hi += 10000; } |
| 192 | const pad = (hi - lo) * 0.08; |
| 193 | lo -= pad; hi += pad; |
| 194 | const W = 600, H = 160, n = lines[0].points.length; |
| 195 | const x = (i) => (n === 1 ? W / 2 : (i / (n - 1)) * W).toFixed(1); |
| 196 | const y = (c) => (H - ((c - lo) / (hi - lo)) * H).toFixed(1); |
| 197 | const d = (pts) => pts.map((c, i) => `${i ? 'L' : 'M'}${x(i)},${y(c)}`).join(''); |
| 198 | const zero = lo < 0 && hi > 0 ? `<line class="fin-zero" x1="0" x2="${W}" y1="${y(0)}" y2="${y(0)}"/>` : ''; |
| 199 | const fill = area ? `<path class="fin-area" d="${d(lines[0].points)}L${W},${H}L0,${H}Z"/>` : ''; |
| 200 | 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>`; |
| 201 | } |
| 202 | |
| 203 | function aheadPage({ net_worth, average, spendable_cents, goals_need_cents, has_accounts, asked, ask, error, plan, q = {} }) { |
| 204 | const last = net_worth[net_worth.length - 1]; |
| 205 | const first = net_worth.find((p) => p.assets_cents || p.owed_cents) || net_worth[0]; |
| 206 | const change = last.net_cents - first.net_cents; |
| 207 | const worth = !has_accounts ? '<p class="fin-empty">Add an account on <a href="/">Your money</a> to see your net worth.</p>' : ` |
| 208 | <p class="fin-big${last.net_cents < 0 ? ' is-neg' : ''}">${esc(money(last.net_cents))}</p> |
| 209 | <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> |
| 210 | ${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 })} |
| 211 | <div class="fin-axis"><span>${esc(shortMonth(net_worth[0].month))}</span><span>Now</span></div>` : ''}`; |
| 212 | |
| 213 | const val = (k) => esc(q[k] || ''); |
| 214 | const months = plan ? plan.now.map((p) => p.month) : []; |
| 215 | // When: a row of month chips (the first, "next month", by default), never the browser's month box. |
| 216 | 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) => { |
| 217 | const on = (q[name] || months[0]) === mm; |
| 218 | 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' }); |
| 219 | return `<label class="fin-chip"><input type="radio" name="${name}" value="${i === 0 ? '' : mm}"${on ? ' checked' : ''}><span>${esc(label)}</span></label>`; |
| 220 | }).join('')}</div></div>`; |
| 221 | const dirIn = q.dir === 'in'; |
| 222 | const form = `<form class="fin-form fin-ask" method="get" action="/ahead"> |
| 223 | <fieldset class="fin-askset"><legend>Can I afford it? A one-off cost</legend> |
| 224 | <label class="fin-field"><span>Amount</span><input name="cost" inputmode="decimal" placeholder="1,200.00" value="${val('cost')}" autocomplete="off"></label> |
| 225 | ${whenChips('cost_on', 'Paid in')}</fieldset> |
| 226 | <fieldset class="fin-askset"><legend>What if something changes every month</legend> |
| 227 | <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> |
| 228 | <label class="fin-field"><span>Amount a month</span><input name="change" inputmode="decimal" placeholder="200.00" value="${val('change')}" autocomplete="off"></label> |
| 229 | ${whenChips('from', 'From')}</fieldset> |
| 230 | <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> |
| 231 | </form>`; |
| 232 | |
| 233 | let result = ''; |
| 234 | if (plan) { |
| 235 | const end = plan.with[plan.with.length - 1]; |
| 236 | let verdict; |
| 237 | 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>`; |
| 238 | 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>`; |
| 239 | 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>`; |
| 240 | 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>`; |
| 241 | 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>` : ''; |
| 242 | 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>` : ''; |
| 243 | 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)] }] |
| 244 | : [{ cls: 'fin-line', points: [spendable_cents, ...plan.now.map((p) => p.cents)] }]; |
| 245 | result = `<div class="fin-result" aria-live="polite">${verdict}${changeLine}${goalsLine} |
| 246 | ${lineChart(lines, { label: `Money to spend at the end of each month, now to ${monthName(end.month)}` })} |
| 247 | <div class="fin-axis"><span>Now</span><span>${esc(shortMonth(end.month))}</span></div> |
| 248 | ${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>' : ''} |
| 249 | <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> |
| 250 | ${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('')} |
| 251 | </tbody></table></div></details></div>`; |
| 252 | } |
| 253 | 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>` |
| 254 | : '<p class="fin-empty">A month or two of transactions (the months before this one) shows what is ahead.</p>'; |
| 255 | return page({ |
| 256 | title: 'Net worth and what if', path: '/ahead', body: ` |
| 257 | <header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Net worth and what if</h1></header> |
| 258 | <section class="fin-sec"><h2>Net worth</h2>${worth}</section> |
| 259 | <section class="fin-sec"><h2>What if</h2>${base} |
| 260 | ${error ? `<p class="fin-error" role="alert">${esc(error)}</p>` : ''}${result}${average.months.length ? form : ''}</section> |
| 261 | <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>` }); |
| 262 | } |
| 263 | |
| 264 | /** A receipt photo, read: the add form filled in, with what to check (v0.12). Nothing is saved until Add it. */ |
| 265 | function receiptPreview({ account, r, today }) { |
| 266 | const check = [!r.found.payee && 'the store', !r.found.date && 'the day', !r.found.total && 'the amount'].filter(Boolean); |
| 267 | const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`; |
| 268 | return page({ |
| 269 | title: 'Check the receipt', path: `/accounts/${account.id}`, body: ` |
| 270 | <header class="fin-head"><p class="fin-crumb"><a href="/accounts/${esc(account.id)}">${esc(account.name)}</a></p><h1>Check the receipt</h1> |
| 271 | <p class="fin-sub">${check.length ? `Read from your photo. Check ${check.join(' and ')}: ${check.length === 1 ? 'it was' : 'they were'} not clear.` : 'Read from your photo. Check it, then add it.'}</p></header>${cats} |
| 272 | <form class="fin-form" method="post" action="/accounts/${esc(account.id)}/transactions"> |
| 273 | <div class="fin-row"><label class="fin-field"><span>Date</span><input type="date" name="posted_on" value="${esc(r.posted_on)}" max="${esc(today)}" required></label> |
| 274 | <label class="fin-field"><span>Amount</span><input name="amount" inputmode="decimal" required value="${r.amount_cents == null ? '' : (Math.abs(r.amount_cents) / 100).toFixed(2)}" placeholder="12.34" autocomplete="off"${r.found.total ? '' : ' autofocus'}></label></div> |
| 275 | <input type="hidden" name="direction" value="out"> |
| 276 | <label class="fin-field"><span>Payee</span><input name="payee" maxlength="300" value="${esc(r.payee)}" autocomplete="off"></label> |
| 277 | <label class="fin-field"><span>Category</span><input name="category" list="fin-cats" maxlength="60" autocomplete="off" placeholder="Groceries"></label> |
| 278 | <p class="fin-actions"><button class="fin-btn fin-btn--primary" type="submit">Add it</button><a class="fin-btn" href="/accounts/${esc(account.id)}">Cancel</a></p> |
| 279 | <p class="fin-note">Read on openvibe.finance; the photo was not kept.</p> |
| 280 | </form>` }); |
| 281 | } |
| 282 | |
| 283 | /** A statement PDF's rows to check before importing (v0.11). Nothing is saved until Import. */ |
| 284 | function statementPreview({ account, read, name = '' }) { |
| 285 | const rows = read.rows; |
| 286 | const guessed = read.signs !== 'explicit'; |
| 287 | const total = (list) => list.reduce((n, r) => n + r.amount_cents, 0); |
| 288 | const list = rows.map((r, i) => `<li class="fin-pick"><label><input type="checkbox" name="take" value="${i}" checked> |
| 289 | <span class="fin-pick-date">${esc(r.posted_on)}</span><span class="fin-pick-payee">${esc(r.payee)}</span> |
| 290 | <span class="fin-pick-amount${r.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(r.amount_cents, account.currency))}</span></label></li>`).join(''); |
| 291 | const ins = rows.filter((r) => r.amount_cents > 0), outs = rows.filter((r) => r.amount_cents < 0); |
| 292 | return page({ |
| 293 | title: 'Check the statement', path: `/accounts/${account.id}`, body: ` |
| 294 | <header class="fin-head"><p class="fin-crumb"><a href="/accounts/${esc(account.id)}">${esc(account.name)}</a></p><h1>Check the statement</h1> |
| 295 | <p class="fin-sub">${esc(name || 'Your PDF')}: ${rows.length} transaction${rows.length === 1 ? '' : 's'} found, ${esc(money(total(ins), account.currency))} in and ${esc(money(-total(outs), account.currency))} out. Untick any that are not right.</p></header> |
| 296 | <form class="fin-form" method="post" action="/accounts/${esc(account.id)}/statement/import"> |
| 297 | <input type="hidden" name="rows" value="${esc(JSON.stringify(rows.map((r) => ({ posted_on: r.posted_on, amount_cents: r.amount_cents, payee: r.payee }))))}"> |
| 298 | ${guessed ? `<fieldset class="fin-chips"><legend>The PDF does not mark money in and out. Read the amounts as</legend> |
| 299 | <label class="fin-chip"><input type="radio" name="signs" value="asread" checked><span>As shown (deposits and refunds in)</span></label> |
| 300 | <label class="fin-chip"><input type="radio" name="signs" value="out"><span>All money out</span></label> |
| 301 | <label class="fin-chip"><input type="radio" name="signs" value="in"><span>All money in</span></label></fieldset>` : '<input type="hidden" name="signs" value="asread">'} |
| 302 | <ul class="fin-picks">${list}</ul> |
| 303 | <p class="fin-actions"><button class="fin-btn fin-btn--primary" type="submit">Import the ticked ones</button><a class="fin-btn" href="/accounts/${esc(account.id)}">Cancel</a></p> |
| 304 | <p class="fin-note">It was read on openvibe.finance and the PDF was not kept. Importing the same statement twice adds nothing twice.</p> |
| 305 | </form>` }); |
| 306 | } |
| 307 | |
| 308 | function rulesPage({ rules, o = {} }) { |
| 309 | return page({ |
| 310 | title: 'Your category rules', path: '/rules', body: ` |
| 311 | <header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Your category rules</h1></header> |
| 312 | ${notice(o)} |
| 313 | <p class="fin-note">A rule puts every transaction whose payee contains its words in its category: the ones nobody has categorised yet, and every import from now on. A category you set yourself stays yours. Make one by ticking <b>Always</b> when you change a transaction's category.</p> |
| 314 | ${rules.length ? `<ul class="fin-rules">${rules.map((r) => `<li><span class="fin-rule-what"><b>${esc(r.match)}</b><span>→ ${esc(r.category)}</span></span> |
| 315 | <form method="post" action="/rules/${esc(r.id)}/delete"><button type="submit" class="fin-mini">Remove</button></form></li>`).join('')}</ul>` |
| 316 | : '<p class="fin-empty">No rules yet.</p>'}` }); |
| 317 | } |
| 318 | |
| 319 | function accountPage({ account, balance, txns, month, o = {} }) { |
| 320 | const groups = new Map(); |
| 321 | for (const t of txns) { const m = t.posted_on.slice(0, 7); if (!groups.has(m)) groups.set(m, []); groups.get(m).push(t); } |
| 322 | const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`; |
| 323 | const row = (t) => `<li class="fin-txn"><span class="fin-txn-date">${esc(t.posted_on.slice(5))}</span> |
| 324 | <span class="fin-txn-what"><b>${esc(t.payee || 'No payee')}</b>${t.memo ? `<small>${esc(t.memo)}</small>` : ''} |
| 325 | <form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category">${t.category_from === 'ai' ? '<span class="fin-by-agent" title="An agent you allowed set this category. Change it and it is yours.">agent</span>' : ''}<input name="category" list="fin-cats" value="${esc(t.category)}" aria-label="Category" maxlength="60">${t.payee ? `<label class="fin-always" title="Every transaction from ${esc(t.payee)} goes here, now and in future imports"><input type="checkbox" name="always" value="yes"><span>Always</span></label>` : ''}<button type="submit" class="fin-mini">Save</button></form>${t.category_from === 'rule' ? '<small class="fin-by-rule">by a rule</small>' : ''}</span> |
| 326 | <span class="fin-txn-amount${t.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(t.amount_cents, account.currency))}</span></li>`; |
| 327 | const today = new Date().toISOString().slice(0, 10); |
| 328 | return page({ |
| 329 | title: account.name, path: `/accounts/${account.id}`, body: ` |
| 330 | <header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>${esc(account.name)}</h1> |
| 331 | <p class="fin-total${balance < 0 ? ' is-neg' : ''}">${esc(money(balance, account.currency))}</p></header> |
| 332 | ${notice(o)}${cats} |
| 333 | <div class="fin-tools"> |
| 334 | <details class="fin-fold"><summary>Add a transaction</summary> |
| 335 | <form class="fin-receipt" method="post" action="/accounts/${esc(account.id)}/receipt"> |
| 336 | <input type="hidden" name="image" value="" data-fin-image> |
| 337 | <label class="fin-btn fin-receipt-btn"><input type="file" accept="image/*" capture="environment" data-fin-receipt class="fin-sr"><span>From a receipt photo</span></label> |
| 338 | <span class="fin-receipt-said" role="status" data-fin-receipt-said>Read here; the photo is not kept.</span></form> |
| 339 | <form class="fin-form" method="post" action="/accounts/${esc(account.id)}/transactions"> |
| 340 | <div class="fin-row"><label class="fin-field"><span>Date</span><input type="date" name="posted_on" value="${today}" required></label> |
| 341 | <label class="fin-field"><span>Amount</span><input name="amount" inputmode="decimal" required placeholder="12.34" autocomplete="off"></label></div> |
| 342 | <fieldset class="fin-chips"><legend>Money</legend><label class="fin-chip"><input type="radio" name="direction" value="out" checked><span>Out</span></label><label class="fin-chip"><input type="radio" name="direction" value="in"><span>In</span></label></fieldset> |
| 343 | <label class="fin-field"><span>Payee</span><input name="payee" maxlength="300" autocomplete="off"></label> |
| 344 | <label class="fin-field"><span>Category</span><input name="category" list="fin-cats" maxlength="60" autocomplete="off" placeholder="Groceries"></label> |
| 345 | <p><button class="fin-btn fin-btn--primary" type="submit">Add it</button></p> |
| 346 | </form></details> |
| 347 | <details class="fin-fold"><summary>Import a bank's export (CSV, OFX, QFX or a PDF statement)</summary> |
| 348 | <form class="fin-form" method="post" action="/accounts/${esc(account.id)}/import" data-fin-statement="/accounts/${esc(account.id)}/statement"> |
| 349 | <p class="fin-note">Banks offer a download as CSV, OFX or QFX (Quicken). Any of them works; importing the same file twice adds nothing twice. A PDF statement is read here, on openvibe.finance, and you check what it found before anything is imported.</p> |
| 350 | <input type="hidden" name="pdf" value="" data-fin-pdf><input type="hidden" name="name" value="" data-fin-pdf-name> |
| 351 | <label class="fin-file"><input type="file" accept=".csv,.ofx,.qfx,.pdf,text/csv,text/plain,application/x-ofx,application/pdf" data-fin-file="csv"><span class="fin-btn">Choose a file</span><span class="fin-file-name" data-fin-file-name>No file chosen yet</span></label> |
| 352 | <label class="fin-field"><span>Or paste it</span><textarea name="csv" rows="6" required data-fin-csv placeholder="Date,Description,Amount 2026-11-02,Corner Grocer,-23.18"></textarea></label> |
| 353 | <p><button class="fin-btn fin-btn--primary" type="submit">Import</button></p> |
| 354 | </form></details> |
| 355 | </div> |
| 356 | <nav class="fin-monthnav" aria-label="Month"><a href="/accounts/${esc(account.id)}?m=${shiftMonth(month, -1)}">${esc(monthName(shiftMonth(month, -1)))}</a> |
| 357 | <b>${esc(monthName(month))}</b><a href="/accounts/${esc(account.id)}?m=${shiftMonth(month, 1)}">${esc(monthName(shiftMonth(month, 1)))}</a></nav> |
| 358 | ${txns.length ? [...groups.values()].map((list) => `<ul class="fin-txns">${list.map(row).join('')}</ul>`).join('') : `<p class="fin-empty">Nothing in ${esc(monthName(month))}. Add a transaction, or import your bank's export.</p>`}` }); |
| 359 | } |
| 360 | |
| 361 | function monthPage({ m, budgets = [], o = {} }) { |
| 362 | const limit = new Map(budgets.map((b) => [b.category, b.monthly_cents])); |
| 363 | const spentBy = new Map(m.by_category.filter((c) => c.out_cents > 0).map((c) => [c.category, c])); |
| 364 | // Budgeted categories with nothing spent yet still show: what is left is the whole budget. |
| 365 | for (const b of budgets) if (!spentBy.has(b.category)) spentBy.set(b.category, { category: b.category, out_cents: 0, count: 0 }); |
| 366 | const spent = [...spentBy.values()].sort((a, b) => b.out_cents - a.out_cents); |
| 367 | // Budgets read against their own limit (a full bar is the budget, red once over); the rest against the largest. |
| 368 | const withBudget = spent.filter((c) => limit.has(c.category)); |
| 369 | const without = spent.filter((c) => !limit.has(c.category)); |
| 370 | const most = Math.max(1, ...without.map((c) => c.out_cents)); |
| 371 | const budgeted = budgets.reduce((n, b) => n + b.monthly_cents, 0); |
| 372 | // What the budgeted categories really spent (an overspend is counted, not capped at its budget). |
| 373 | const usedOfBudgets = withBudget.reduce((n, c) => n + c.out_cents, 0); |
| 374 | const cats = `<datalist id="fin-cats">${CATEGORIES.filter((c) => !['Income', 'Transfers', 'Uncategorized'].includes(c)).map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`; |
| 375 | const budgetBar = (c) => { |
| 376 | const cap = limit.get(c.category); |
| 377 | const over = c.out_cents > cap; |
| 378 | const left = cap - c.out_cents; |
| 379 | return `<li class="${over ? 'is-over' : ''}"><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span> |
| 380 | <span class="fin-bar fin-bar--budget"><span style="--w:${Math.min(100, Math.round((c.out_cents / cap) * 100))}%"></span></span> |
| 381 | <span class="fin-bar-sum">${esc(money(c.out_cents))}<small class="${over ? 'is-neg' : ''}">of ${esc(money(cap))} · ${over ? `${esc(money(-left))} over` : `${esc(money(left))} left`}</small></span></li>`; |
| 382 | }; |
| 383 | const bar = (c) => `<li><span class="fin-bar-name">${esc(c.category)}<small>${c.count}</small></span> |
| 384 | <span class="fin-bar"><span style="--w:${Math.max(2, Math.round((c.out_cents / most) * 100))}%"></span></span><span class="fin-bar-sum">${esc(money(c.out_cents))}</span></li>`; |
| 385 | return page({ |
| 386 | title: `${monthName(m.month)}`, path: '/month', body: ` |
| 387 | <header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>${esc(monthName(m.month))}</h1></header> |
| 388 | ${notice(o)} |
| 389 | <nav class="fin-monthnav" aria-label="Month"><a href="/month?m=${shiftMonth(m.month, -1)}">${esc(monthName(shiftMonth(m.month, -1)))}</a><b>${esc(monthName(m.month))}</b><a href="/month?m=${shiftMonth(m.month, 1)}">${esc(monthName(shiftMonth(m.month, 1)))}</a></nav> |
| 390 | <div class="fin-sums"><p><span>In</span><b class="fin-in">${esc(money(m.income_cents))}</b></p><p><span>Out</span><b class="fin-out">${esc(money(m.spent_cents))}</b></p> |
| 391 | <p><span>Left</span><b class="${m.income_cents - m.spent_cents < 0 ? 'is-neg' : ''}">${esc(money(m.income_cents - m.spent_cents))}</b></p></div> |
| 392 | ${withBudget.length ? `<section class="fin-sec"><h2>Budgets</h2><p class="fin-budget-sum">${esc(money(usedOfBudgets))} of ${esc(money(budgeted))} spent</p> |
| 393 | <ul class="fin-bars">${withBudget.map(budgetBar).join('')}</ul></section>` : ''} |
| 394 | ${without.length ? `<section class="fin-sec">${withBudget.length ? '<h2>Everything else</h2>' : ''}<ul class="fin-bars">${without.map(bar).join('')}</ul></section>` : (withBudget.length ? '' : '<p class="fin-empty">No spending this month.</p>')} |
| 395 | <details class="fin-fold"><summary>${budgets.length ? 'Change a budget' : 'Set a monthly budget for a category'}</summary> |
| 396 | <form class="fin-form" method="post" action="/budgets">${cats} |
| 397 | <div class="fin-row"><label class="fin-field"><span>Category</span><input name="category" list="fin-cats" required maxlength="60" placeholder="Eating out" autocomplete="off"></label> |
| 398 | <label class="fin-field"><span>A month</span><input name="amount" inputmode="decimal" placeholder="300.00 (empty removes it)" autocomplete="off"></label></div> |
| 399 | <input type="hidden" name="back" value="${esc(m.month)}"> |
| 400 | <p><button class="fin-btn fin-btn--primary" type="submit">Save the budget</button></p> |
| 401 | </form></details> |
| 402 | <p class="fin-note">Transfers between your own accounts are left out. Amounts in other currencies are added as they are.</p>` }); |
| 403 | } |
| 404 | |
| 405 | function dataPage({ o = {} }) { |
| 406 | return page({ |
| 407 | title: 'Your data', path: '/data', body: ` |
| 408 | <header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Your data</h1></header> |
| 409 | ${notice(o)} |
| 410 | <section class="fin-sec"><h2>Download everything</h2><p>Every account and transaction, as one JSON file, readable anywhere.</p> |
| 411 | <p><a class="fin-btn" href="/data/export" download>Download</a></p></section> |
| 412 | <section class="fin-sec"><h2>Delete everything</h2><p>Every account, transaction and import of yours, for good. There is no undo.</p> |
| 413 | <form method="post" action="/data/delete" class="fin-form"><label class="fin-check"><input type="checkbox" name="sure" value="yes" required><span>Yes, delete all my finance data</span></label> |
| 414 | <p><button class="fin-btn fin-btn--danger" type="submit">Delete everything</button></p></form></section>` }); |
| 415 | } |
| 416 | |
| 417 | module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, aheadPage, statementPreview, receiptPreview, lineChart, money, esc, monthName }; |
| 418 |