'use strict'; /** * Finance's pages, server-rendered in the network's shell (openvibe-shared/shell, kit.css) with this site's own * finance.css. Every value that reaches markup goes through esc(). Forms post to the same origin and work without * script; public/finance.js only reads a chosen CSV file into the paste box. */ const shell = require('openvibe-shared/shell'); const serve = require('openvibe-shared/serve'); const { CATEGORIES, KINDS } = require('./store'); const { payoff, faster, perMonth } = require('./plan'); // Our own files by their content (a release's change is a new address, so neither a browser nor Cloudflare keeps an old // one for the hour they may cache it): /x.css?v=, read once at boot. const asset = (() => { const fs = require('node:fs'); const crypto = require('node:crypto'); const kept = new Map(); return (name) => { if (!kept.has(name)) { let v = 'dev'; 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 */ } kept.set(name, `/${name}?v=${v}`); } return kept.get(name); }; })(); const SITE = 'https://openvibe.finance'; const esc = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const money = (cents, currency = 'USD') => { try { return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100); } catch { return `${(cents / 100).toFixed(2)} ${currency}`; } }; const monthName = (m) => new Date(`${m}-01T00:00:00Z`).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' }); const shiftMonth = (m, by) => { const d = new Date(`${m}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() + by); return d.toISOString().slice(0, 7); }; const KIND_WORDS = { checking: 'Checking', savings: 'Savings', credit: 'Credit card', cash: 'Cash', loan: 'Loan', investment: 'Investments', other: 'Other' }; 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({ 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' }, { label: 'What if', href: '/ahead' }] }, footer: { service: 'finance', variant: 'full', mount: '#ov-footer' }, head: ``, body: `
${body}
`, }); } const notice = (o) => (o.error ? `` : '') + (o.said ? `

${esc(o.said)}

` : ''); function welcome() { return page({ title: 'Your money, your rules, your data', robots: 'index, follow', body: `

Your money, your rules, your data

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.

Sign in to start

` }); } // OpenVibe's money Experts on Actor (Actor #623): they read your numbers here through /mcp, as you, once you allow // Actor in OpenVibe Finance on your Apps page; none moves money. const EXPERTS = [ { id: 'bp_budget_coach', name: 'Budget coach', what: 'A budget you can live with, from your real month.' }, { 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.' }, { id: 'bp_debt_planner', name: 'Debt planner', what: 'The fastest and the cheapest way out of your loans and cards.' }, { id: 'bp_subscription_auditor', name: 'Subscription auditor', what: 'Every recurring charge, and what dropping each saves.' }, ]; const expertsSection = () => `

Ask an Expert

They read your numbers here as you once you allow Actor in OpenVibe Finance on your Apps page, 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.

`; function home({ accounts, month, o = {} }) { const total = {}; for (const a of accounts) total[a.currency] = (total[a.currency] || 0) + a.balance_cents; const totals = Object.entries(total).map(([c, v]) => money(v, c)).join(' · '); const kindChips = KINDS.map((k, i) => ``).join(''); return page({ title: 'Your money', body: `

Your money

${accounts.length ? `

${esc(totals)}

` : ''}
${notice(o)} ${accounts.length ? `
${esc(monthName(month.month))} In ${esc(money(month.income_cents))}Out ${esc(money(month.spent_cents))}
` : `

Start with an account: name it, then type in transactions or import your bank's download (CSV, OFX or QFX).

`}
Add an account
Kind${kindChips}

${accounts.length ? expertsSection() : ''}

Net worth and what if · Goals and debt · Recurring bills · Your category rules · Your data: download or delete everything

` }); } const CADENCE_WORDS = { weekly: 'Every week', 'every two weeks': 'Every two weeks', monthly: 'Every month', quarterly: 'Every three months', yearly: 'Every year' }; const dayName = (iso) => new Date(`${iso}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); function billsPage({ found, today, o = {} }) { const out = found.filter((r) => r.direction === 'out'); const income = found.filter((r) => r.direction === 'in'); const monthly = out.reduce((n, r) => n + r.monthly_cents, 0); const soon = out.filter((r) => !r.overdue && r.next_on >= today && Date.parse(r.next_on) - Date.parse(today) <= 31 * 86400000); const row = (r) => `
  • ${esc(r.payee)} ${esc(CADENCE_WORDS[r.cadence] || r.cadence)} · seen ${r.count} times · last ${esc(dayName(r.last_on))} ${r.overdue ? `Expected ${esc(dayName(r.next_on))}: not seen` : `Next ${esc(dayName(r.next_on))}`}${esc(money(r.typical_cents))}
  • `; return page({ title: 'Recurring', path: '/bills', body: `

    Your money

    Recurring

    ${out.length ? `

    About ${esc(money(monthly))} a month

    ` : ''}
    ${notice(o)}

    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.

    ${soon.length ? `

    The next 31 days

    ` : ''}

    Bills and subscriptions

    ${out.length ? `` : '

    None found yet. A few months of transactions show them.

    '}
    ${income.length ? `

    Money that comes in regularly

    ` : ''}` }); } const monthsWords = (n) => (n < 12 ? `${n} month${n === 1 ? '' : 's'}` : `${Math.floor(n / 12)} year${n >= 24 ? 's' : ''}${n % 12 ? ` ${n % 12} month${n % 12 === 1 ? '' : 's'}` : ''}`); const pct = (bps) => `${(bps / 100).toFixed(2).replace(/\.?0+$/, '')}%`; function goalsPage({ goals, accounts, today, o = {} }) { const debts = accounts.filter((a) => (a.kind === 'loan' || a.kind === 'credit')); const savings = accounts.filter((a) => a.kind !== 'loan' && a.kind !== 'credit'); const goalRow = (g) => { const have = Math.max(0, g.have_cents); const done = have >= g.target_cents; const need = perMonth({ target_cents: g.target_cents, have_cents: have, target_on: g.target_on, today }); const tracked = g.account_id ? accounts.find((a) => a.id === g.account_id) : null; return `
  • ${esc(g.name)}${esc(money(have))} of ${esc(money(g.target_cents))}

    ${done ? 'Reached.' : need ? `${esc(money(need))} a month reaches it by ${esc(monthName(g.target_on.slice(0, 7)))}.` : g.target_on ? `The date (${esc(monthName(g.target_on.slice(0, 7)))}) has passed.` : 'No date: it is there when it is there.'} ${tracked ? ` Tracks ${esc(tracked.name)}.` : ''}

    ${tracked ? '' : `
    `}
  • `; }; const debtRow = (a) => { const owed = Math.max(0, -a.balance_cents); const terms = a.apr_bps != null && a.payment_cents; let said = 'Add its yearly rate and your monthly payment to see when it is paid off.'; let tip = ''; if (!owed) said = 'Nothing owed.'; else if (terms) { const p = payoff({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents }); if (p.never) said = `At ${esc(money(a.payment_cents))} a month it never gets paid off: that does not cover the ${esc(pct(a.apr_bps))} interest.`; else { const extra = Math.max(2500, Math.round(a.payment_cents * 0.25 / 500) * 500); const f = faster({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents }, extra); said = `Paid off in ${esc(monthsWords(p.months))} at ${esc(money(a.payment_cents))} a month, ${esc(money(p.interest_cents))} of it interest (${esc(pct(a.apr_bps))} a year).`; if (f && f.months_sooner) tip = `${esc(money(extra))} more a month: ${esc(monthsWords(f.months_sooner))} sooner and ${esc(money(f.interest_saved_cents))} less interest.`; } } return `
  • ${esc(a.name)}${esc(money(owed, a.currency))} owed

    ${said}

    ${tip ? `

    ${tip}

    ` : ''} ${terms ? '
    Change the rate or payment' : ''}

    ${terms ? '
    ' : ''}
  • `; }; const accountChips = savings.map((a) => ``).join(''); return page({ title: 'Goals and debt', path: '/goals', body: `

    Your money

    Goals and debt

    ${notice(o)}

    Goals

    ${goals.length ? `` : '

    No goals yet: an emergency fund, a trip, a deposit.

    '}
    Add a goal
    ${savings.length ? `
    Its progress is (optional)${accountChips}
    ` : ''}

    Debt

    ${debts.length ? `` : '

    No loans or credit cards. Add one as an account (its kind: Loan or Credit card) to plan paying it off.

    '}
    ` }); } 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 ? `` : ''; const fill = area ? `` : ''; return `${fill}${zero}${lines.map((l) => ``).join('')}`; } 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 ? '

    Add an account on Your money to see your net worth.

    ' : `

    ${esc(money(last.net_cents))}

    ${esc(money(last.assets_cents))} in your accounts · ${esc(money(last.owed_cents))} owed${first.month !== last.month ? ` · ${change < 0 ? '−' : '+'}${esc(money(Math.abs(change)))} since ${esc(monthName(first.month))}` : ''}

    ${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 })}
    ${esc(shortMonth(net_worth[0].month))}Now
    ` : ''}`; 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) => `
    ${legend}
    ${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 ``; }).join('')}
    `; const dirIn = q.dir === 'in'; const form = `
    Can I afford it? A one-off cost ${whenChips('cost_on', 'Paid in')}
    What if something changes every month
    ${whenChips('from', 'From')}

    ${asked ? 'Start over' : ''}

    `; let result = ''; if (plan) { const end = plan.with[plan.with.length - 1]; let verdict; if (plan.now_below_zero_on) verdict = `

    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))}.

    `; else if (!asked) verdict = `

    At your average month you have about ${esc(money(end.cents))} to spend in ${esc(monthName(end.month))}.

    `; else if (plan.below_zero_on) verdict = `

    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 ${esc(monthName(plan.afford_by))} and stay above zero.` : ''}

    `; else verdict = `

    Yes. The lowest it gets is ${esc(money(plan.lowest.cents))}, in ${esc(monthName(plan.lowest.month))}; about ${esc(money(end.cents))} in ${esc(monthName(end.month))}.

    `; const changeLine = asked && ask.change_cents ? `

    Left over each month: ${esc(money(plan.left_now_cents))} now, ${esc(money(plan.left_with_cents))} with the change.

    ` : ''; const goalsLine = goals_need_cents ? `

    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 (Goals).` : '.'}

    ` : ''; 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 = `
    ${verdict}${changeLine}${goalsLine} ${lineChart(lines, { label: `Money to spend at the end of each month, now to ${monthName(end.month)}` })}
    Now${esc(shortMonth(end.month))}
    ${asked ? '

    As things areWith the change

    ' : ''}
    Month by month
    ${asked ? '' : ''} ${plan.now.map((p, i) => `${asked ? `` : ''}`).join('')}
    End of${asked ? 'As things are' : 'To spend'}With the change
    ${esc(shortMonth(p.month))}${esc(money(p.cents))}${esc(money(plan.with[i].cents))}
    `; } const base = average.months.length ? `

    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, ${esc(money(average.income_cents - average.spending_cents))} left over. ${esc(money(spendable_cents))} to spend now.

    ` : '

    A month or two of transactions (the months before this one) shows what is ahead.

    '; return page({ title: 'Net worth and what if', path: '/ahead', body: `

    Your money

    Net worth and what if

    Net worth

    ${worth}

    What if

    ${base} ${error ? `` : ''}${result}${average.months.length ? form : ''}

    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.

    ` }); } /** A receipt photo, read: the add form filled in, with what to check (v0.12). Nothing is saved until Add it. */ function receiptPreview({ account, r, today }) { const check = [!r.found.payee && 'the store', !r.found.date && 'the day', !r.found.total && 'the amount'].filter(Boolean); const cats = `${CATEGORIES.map((c) => ``; return page({ title: 'Check the receipt', path: `/accounts/${account.id}`, body: `

    ${esc(account.name)}

    Check the receipt

    ${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.'}

    ${cats}

    Cancel

    Read on openvibe.finance; the photo was not kept.

    ` }); } /** A statement PDF's rows to check before importing (v0.11). Nothing is saved until Import. */ function statementPreview({ account, read, name = '' }) { const rows = read.rows; const guessed = read.signs !== 'explicit'; const total = (list) => list.reduce((n, r) => n + r.amount_cents, 0); const list = rows.map((r, i) => `
  • `).join(''); const ins = rows.filter((r) => r.amount_cents > 0), outs = rows.filter((r) => r.amount_cents < 0); return page({ title: 'Check the statement', path: `/accounts/${account.id}`, body: `

    ${esc(account.name)}

    Check the statement

    ${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.

    ${guessed ? `
    The PDF does not mark money in and out. Read the amounts as
    ` : ''}
      ${list}

    Cancel

    It was read on openvibe.finance and the PDF was not kept. Importing the same statement twice adds nothing twice.

    ` }); } function rulesPage({ rules, o = {} }) { return page({ title: 'Your category rules', path: '/rules', body: `

    Your money

    Your category rules

    ${notice(o)}

    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 Always when you change a transaction's category.

    ${rules.length ? `
      ${rules.map((r) => `
    • ${esc(r.match)}→ ${esc(r.category)}
    • `).join('')}
    ` : '

    No rules yet.

    '}` }); } function accountPage({ account, balance, txns, month, o = {} }) { const groups = new Map(); 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); } const cats = `${CATEGORIES.map((c) => ``; const row = (t) => `
  • ${esc(t.posted_on.slice(5))} ${esc(t.payee || 'No payee')}${t.memo ? `${esc(t.memo)}` : ''}
    ${t.category_from === 'ai' ? 'agent' : ''}${t.payee ? `` : ''}
    ${t.category_from === 'rule' ? 'by a rule' : ''}
    ${esc(money(t.amount_cents, account.currency))}
  • `; const today = new Date().toISOString().slice(0, 10); return page({ title: account.name, path: `/accounts/${account.id}`, body: `

    Your money

    ${esc(account.name)}

    ${esc(money(balance, account.currency))}

    ${notice(o)}${cats}
    Add a transaction
    Read here; the photo is not kept.
    Money

    Import a bank's export (CSV, OFX, QFX or a PDF statement)

    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.

    ${txns.length ? [...groups.values()].map((list) => `
      ${list.map(row).join('')}
    `).join('') : `

    Nothing in ${esc(monthName(month))}. Add a transaction, or import your bank's export.

    `}` }); } function monthPage({ m, budgets = [], o = {} }) { const limit = new Map(budgets.map((b) => [b.category, b.monthly_cents])); const spentBy = new Map(m.by_category.filter((c) => c.out_cents > 0).map((c) => [c.category, c])); // Budgeted categories with nothing spent yet still show: what is left is the whole budget. for (const b of budgets) if (!spentBy.has(b.category)) spentBy.set(b.category, { category: b.category, out_cents: 0, count: 0 }); const spent = [...spentBy.values()].sort((a, b) => b.out_cents - a.out_cents); // Budgets read against their own limit (a full bar is the budget, red once over); the rest against the largest. const withBudget = spent.filter((c) => limit.has(c.category)); const without = spent.filter((c) => !limit.has(c.category)); const most = Math.max(1, ...without.map((c) => c.out_cents)); const budgeted = budgets.reduce((n, b) => n + b.monthly_cents, 0); // What the budgeted categories really spent (an overspend is counted, not capped at its budget). const usedOfBudgets = withBudget.reduce((n, c) => n + c.out_cents, 0); const cats = `${CATEGORIES.filter((c) => !['Income', 'Transfers', 'Uncategorized'].includes(c)).map((c) => ``; const budgetBar = (c) => { const cap = limit.get(c.category); const over = c.out_cents > cap; const left = cap - c.out_cents; return `
  • ${esc(c.category)}${c.count} ${esc(money(c.out_cents))}of ${esc(money(cap))} · ${over ? `${esc(money(-left))} over` : `${esc(money(left))} left`}
  • `; }; const bar = (c) => `
  • ${esc(c.category)}${c.count} ${esc(money(c.out_cents))}
  • `; return page({ title: `${monthName(m.month)}`, path: '/month', body: `

    Your money

    ${esc(monthName(m.month))}

    ${notice(o)}

    In${esc(money(m.income_cents))}

    Out${esc(money(m.spent_cents))}

    Left${esc(money(m.income_cents - m.spent_cents))}

    ${withBudget.length ? `

    Budgets

    ${esc(money(usedOfBudgets))} of ${esc(money(budgeted))} spent

      ${withBudget.map(budgetBar).join('')}
    ` : ''} ${without.length ? `
    ${withBudget.length ? '

    Everything else

    ' : ''}
      ${without.map(bar).join('')}
    ` : (withBudget.length ? '' : '

    No spending this month.

    ')}
    ${budgets.length ? 'Change a budget' : 'Set a monthly budget for a category'}
    ${cats}

    Transfers between your own accounts are left out. Amounts in other currencies are added as they are.

    ` }); } function dataPage({ o = {} }) { return page({ title: 'Your data', path: '/data', body: `

    Your money

    Your data

    ${notice(o)}

    Download everything

    Every account and transaction, as one JSON file, readable anywhere.

    Download

    Delete everything

    Every account, transaction and import of yours, for good. There is no undo.

    ` }); } module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, aheadPage, statementPreview, receiptPreview, lineChart, money, esc, monthName };