openvibers/openvibe.finance Commits

Recurring: bills, subscriptions and regular income (v0.3) (#3)

OP OpenVibers committed 13 days ago · 45e90b9907 · 9 files, +210 −9

Plan §L.2's next step (recurring detection and the bill calendar). /bills: about how much a month goes to
recurring payments, the next 31 days, every bill and subscription with its cadence, usual amount and next date,
the ones that stopped (overdue), and the money that comes in regularly. A series is one payee (reference
numbers dropped) going one way, three times or more, amounts within 20% of the median, steady gaps around a
week, two weeks, a month, a quarter or a year. Worked out in memory from the person's own rows each time;
nothing stored. /api/v1/recurring. test/recurring.test.js.

Changes

ddiff --git a/README.md b/README.md
iindex 8613934..adfa837 100644
---- a/README.md
++++ b/README.md
@@@ -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.2)
++## What it does today (v0.3)
- Accounts (checking, savings, credit card, cash, loan, investments) with an opening balance and a running balance.
- Transactions typed in, or imported from a bank's CSV export: the columns are read from the header (date; amount, or
@@@ -20,9 +20,11 @@ to connect.
- 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.
- The month: money in, money out, and spending by category (transfers between your accounts left out).
++- Recurring: bills, subscriptions and regular income found in your own transactions (the same payee and a similar
++ amount at a steady rhythm, three times or more): what each costs a month, when the next is due, and which stopped.
- A JSON API for all of it (`/api/v1/…`), for the person signed in.
--Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: recurring bills, budgets, goals, OFX/QFX, the Link plugin
++Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: budgets, goals, OFX/QFX, the Link plugin
for local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.
## Running
ddiff --git a/package-lock.json b/package-lock.json
iindex 16cfa59..a93db9e 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-finance",
-- "version": "0.2.0",
++ "version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-finance",
-- "version": "0.2.0",
++ "version": "0.3.0",
"license": "AGPL-3.0-only",
"dependencies": {
"@electric-sql/pglite": "^0.5.8",
ddiff --git a/package.json b/package.json
iindex b665525..24fbf01 100644
---- a/package.json
++++ b/package.json
@@@ -1,6 +1,6 @@
{
"name": "openvibe-finance",
-- "version": "0.2.0",
++ "version": "0.3.0",
"private": true,
"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you",
"main": "server/index.js",
ddiff --git a/public/finance.css b/public/finance.css
iindex 41fd00f..bf94ee9 100644
---- a/public/finance.css
++++ b/public/finance.css
@@@ -95,3 +95,13 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
.fin-rule-what { display: grid; gap: 2px; min-width: 0; }
.fin-rule-what b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fin-rule-what span { color: var(--text-secondary, #9aa4b2); font-size: 14px; }
++/* Recurring (v0.3). */
++.fin-bills { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; }
++.fin-bill { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 14px; border-radius: 12px; border: 1px solid var(--border, #1f2937); }
++.fin-bill.is-late { border-style: dashed; }
++.fin-bill-what { display: grid; gap: 2px; min-width: 0; }
++.fin-bill-what b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
++.fin-bill-what span { color: var(--text-secondary, #9aa4b2); font-size: 13px; }
++.fin-bill-when { display: grid; justify-items: end; gap: 2px; white-space: nowrap; font-variant-numeric: tabular-nums; }
++.fin-bill-when small { color: var(--text-secondary, #9aa4b2); font-size: 12px; }
++.fin-bill.is-late .fin-bill-when small { color: var(--warning, #f59e0b); }
ddiff --git a/server/app.js b/server/app.js
iindex 25332f9..f96e04f 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -14,6 +14,7 @@ const express = require('express');
const path = require('node:path');
const { createStore, FinanceError } = require('./store');
const { readCsv, readAmount } = require('./csv');
++const { findRecurring } = require('./recurring');
const v = require('./views');
function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now = () => new Date() }) {
@@@ -128,6 +129,12 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
if (!me) return signIn(req, res);
res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)) }));
}));
++ app.get('/bills', handle(async (req, res) => {
++ const me = who(req);
++ if (!me) return signIn(req, res);
++ const today = now().toISOString().slice(0, 10);
++ res.send(v.billsPage({ found: findRecurring(await store.recent(me), { today }), today }));
++ }));
app.get('/rules', handle(async (req, res) => {
const me = who(req);
if (!me) return signIn(req, res);
@@@ -176,6 +183,7 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
}));
api.get('/months/:m', handle(async (req, res) => res.json(await store.month(who(req), req.params.m))));
api.get('/rules', handle(async (req, res) => res.json({ rules: await store.rules(who(req)) })));
++ api.get('/recurring', handle(async (req, res) => res.json({ recurring: findRecurring(await store.recent(who(req)), { today: now().toISOString().slice(0, 10) }).map(({ key, ...r }) => r) })));
api.post('/rules', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addRule(who(req), req.body || {}))));
api.delete('/rules/:id', handle(async (req, res) => { await store.removeRule(who(req), req.params.id); res.status(204).end(); }));
api.get('/export', handle(async (req, res) => res.json(await store.exportAll(who(req)))));
ddiff --git a/server/recurring.js b/server/recurring.js
nnew file mode 100644
iindex 0000000..d2e8998
---- /dev/null
++++ b/server/recurring.js
@@@ -0,0 +1,70 @@
++'use strict';
++/**
++ * Recurring payments and income, found in a person's own transactions (plan §L.2: "recurring detection and the bill
++ * calendar"). Nothing is stored: it is worked out from the rows each time, in memory, for their owner.
++ *
++ * findRecurring(transactions, { today }) → [{ key, payee, direction, cadence, every_days, typical_cents, count,
++ * last_on, next_on, monthly_cents, overdue }]
++ *
++ * A series is one payee (its words, with reference numbers dropped: store.matchable) going the same way (in or out),
++ * seen at least three times, its amounts within 20% of their median and its gaps steady around a week, two weeks,
++ * a month, a quarter or a year. The next date is the last one plus the usual gap; a series whose next date is more than
++ * half a gap behind is "overdue" (maybe cancelled, maybe late).
++ */
++const { matchable } = require('./store');
++
++const CADENCES = [
++ { name: 'weekly', days: 7, tolerance: 2 },
++ { name: 'every two weeks', days: 14, tolerance: 3 },
++ { name: 'monthly', days: 30.4, tolerance: 5 },
++ { name: 'quarterly', days: 91, tolerance: 12 },
++ { name: 'yearly', days: 365, tolerance: 20 },
++];
++const DAY_MS = 86400000;
++const dayNum = (iso) => Math.round(Date.parse(`${iso}T00:00:00Z`) / DAY_MS);
++const isoOf = (n) => new Date(n * DAY_MS).toISOString().slice(0, 10);
++const median = (xs) => { const s = [...xs].sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
++
++function findRecurring(transactions, { today = new Date().toISOString().slice(0, 10) } = {}) {
++ const groups = new Map();
++ for (const t of transactions) {
++ const words = matchable(t.payee);
++ if (!words || !t.amount_cents) continue;
++ const key = `${t.amount_cents < 0 ? 'out' : 'in'}|${words}`;
++ if (!groups.has(key)) groups.set(key, []);
++ groups.get(key).push(t);
++ }
++ const now = dayNum(today);
++ const out = [];
++ for (const [key, list] of groups) {
++ if (list.length < 3) continue;
++ const rows = [...list].sort((a, b) => a.posted_on.localeCompare(b.posted_on));
++ const amounts = rows.map((r) => Math.abs(r.amount_cents));
++ const typical = median(amounts);
++ // Amounts that wander more than 20% from the usual one are not a bill (a grocery store is not a subscription).
++ const steady = rows.filter((r) => Math.abs(Math.abs(r.amount_cents) - typical) <= typical * 0.2);
++ if (steady.length < 3) continue;
++ const days = [...new Set(steady.map((r) => dayNum(r.posted_on)))];
++ if (days.length < 3) continue;
++ const gaps = days.slice(1).map((d, i) => d - days[i]);
++ const gap = median(gaps);
++ const cadence = CADENCES.find((c) => Math.abs(gap - c.days) <= c.tolerance);
++ if (!cadence) continue;
++ // Most gaps must fit the cadence: a payee seen three times in a month and then twice a year later is not monthly.
++ const fit = gaps.filter((g) => Math.abs(g - cadence.days) <= cadence.tolerance * 1.5).length;
++ if (fit < Math.ceil(gaps.length * 0.6)) continue;
++ const last = days[days.length - 1];
++ const every = Math.round(cadence.days);
++ const next = last + every;
++ const latest = steady[steady.length - 1];
++ out.push({
++ key, payee: latest.payee, direction: key.startsWith('out') ? 'out' : 'in', cadence: cadence.name, every_days: every,
++ typical_cents: Math.round(typical), count: steady.length, last_on: isoOf(last), next_on: isoOf(next),
++ monthly_cents: Math.round(typical * (30.4 / cadence.days)), overdue: now - next > every / 2,
++ category: latest.category,
++ });
++ }
++ return out.sort((a, b) => a.next_on.localeCompare(b.next_on) || b.typical_cents - a.typical_cents);
++}
++
++module.exports = { findRecurring, CADENCES };
ddiff --git a/server/store.js b/server/store.js
iindex 18a6576..42f8180 100644
---- a/server/store.js
++++ b/server/store.js
@@@ -59,6 +59,14 @@ function createStore({ db, vault }) {
return rows.map((r) => ({ id: r.id, name: r.name, kind: r.kind, currency: r.currency, balance_cents: Number(r.opening_cents) + Number(r.moved), count: r.count, last_on: r.last_on || null }));
}
++ /** Every transaction of the person from the last `days` days, across their accounts, opened (recurring, scenarios). */
++ async function recent(owner, { days = 400, limit = 20000 } = {}) {
++ own(owner);
++ const rows = await db.many(`SELECT t.* FROM finance_transactions t JOIN finance_accounts a ON a.id = t.account_id AND a.archived_at IS NULL
++ WHERE t.owner = $1 AND t.posted_on >= (CURRENT_DATE - $2::int) ORDER BY t.posted_on, t.id LIMIT ${Math.max(1, Math.min(50000, Number(limit) || 20000))}`, [owner, Math.max(1, Math.min(2000, Number(days) || 400))]);
++ return rows.map((r) => open(owner, r));
++ }
++
async function account(owner, id) {
own(owner);
const r = await db.maybe('SELECT id, name, kind, currency, opening_cents FROM finance_accounts WHERE id = $1 AND owner = $2 AND archived_at IS NULL', [String(id || ''), owner]);
@@@ -247,7 +255,7 @@ function createStore({ db, vault }) {
});
}
-- return { accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, exportAll, removeAll };
++ return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, exportAll, removeAll };
}
module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
ddiff --git a/server/views.js b/server/views.js
iindex 4e77952..517be02 100644
---- a/server/views.js
++++ b/server/views.js
@@@ -21,7 +21,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' }) {
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' }] },
++ navbar: { service: 'finance', apiBase: 'https://openvibe.network', links: [{ label: 'Money', href: '/' }, { label: 'This month', href: '/month' }, { label: 'Recurring', href: '/bills' }] },
footer: { service: 'finance', variant: 'full', mount: '#ov-footer' },
head: `<link rel="stylesheet" href="${serve.url('kit.css')}"><link rel="stylesheet" href="/finance.css"><script src="/finance.js" defer></script>`,
body: `<div id="navbar-mount"></div><main id="main" class="ovk-page fin">${body}</main>`,
@@@ -69,7 +69,29 @@ ${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="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });
++<p class="fin-foot"><a href="/bills">Recurring bills</a> · <a href="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });
++}
++
++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) => `<li class="fin-bill${r.overdue ? ' is-late' : ''}"><span class="fin-bill-what"><b>${esc(r.payee)}</b>
++<span>${esc(CADENCE_WORDS[r.cadence] || r.cadence)} · seen ${r.count} times · last ${esc(dayName(r.last_on))}</span></span>
++<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>`;
++ return page({
++ title: 'Recurring', path: '/bills', body: `
++<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Recurring</h1>
++${out.length ? `<p class="fin-total">About ${esc(money(monthly))} a month</p>` : ''}</header>
++${notice(o)}
++<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>
++${soon.length ? `<section class="fin-sec"><h2>The next 31 days</h2><ul class="fin-bills">${soon.map(row).join('')}</ul></section>` : ''}
++<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>
++${income.length ? `<section class="fin-sec"><h2>Money that comes in regularly</h2><ul class="fin-bills">${income.map(row).join('')}</ul></section>` : ''}` });
}
function rulesPage({ rules, o = {} }) {
@@@ -148,4 +170,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, money, esc, monthName };
++module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, money, esc, monthName };
ddiff --git a/test/recurring.test.js b/test/recurring.test.js
nnew file mode 100644
iindex 0000000..3150291
---- /dev/null
++++ b/test/recurring.test.js
@@@ -0,0 +1,81 @@
++'use strict';
++/**
++ * Recurring payments (server/recurring.js): a subscription whose reference number changes each month, rent, a paycheck
++ * every two weeks and a yearly fee are found with their cadence, usual amount and next date; groceries (amounts all
++ * over the place), one-offs and two sightings are not; a subscription that stopped is overdue. Then /bills and the API
++ * over a person's own data.
++ */
++const assert = require('assert');
++const path = require('node:path');
++const crypto = require('node:crypto');
++const { findRecurring } = require('../server/recurring');
++
++const tx = (posted_on, amount_cents, payee, category = 'Uncategorized') => ({ posted_on, amount_cents, payee, category });
++const monthly = (payee, cents, day, months) => months.map((m) => tx(`2026-${String(m).padStart(2, '0')}-${String(day).padStart(2, '0')}`, cents, payee));
++const days = (start, every, n) => Array.from({ length: n }, (_, i) => new Date(Date.parse(`${start}T00:00:00Z`) + i * every * 86400000).toISOString().slice(0, 10));
++
++const rows = [
++ ...[6, 7, 8, 9, 10, 11].map((m, i) => tx(`2026-${String(m).padStart(2, '0')}-05`, -1599, `STREAMFLIX ${881234 + i * 1111} CA`)),
++ ...monthly('Lakeview Apartments', -145000, 1, [6, 7, 8, 9, 10, 11]),
++ ...days('2026-08-07', 14, 8).map((d) => tx(d, 312000, 'Paycheck ACME Corp')),
++ tx('2024-03-15', -9900, 'Warehouse Club Membership'), tx('2025-03-14', -9900, 'Warehouse Club Membership'), tx('2026-03-16', -10500, 'Warehouse Club Membership'),
++ ...[-8642, -1210, -15433, -2299, -6400, -910].map((c, i) => tx(`2026-11-${String(i * 3 + 1).padStart(2, '0')}`, c, 'Corner Grocer')),
++ tx('2026-10-12', -41220, 'Airline Tickets'),
++ tx('2026-09-01', -999, 'Puzzle App'), tx('2026-10-01', -999, 'Puzzle App'),
++ ...monthly('Old Gym Co', -2900, 20, [4, 5, 6, 7]),
++];
++const found = findRecurring(rows, { today: '2026-11-18' });
++const by = (p) => found.find((r) => r.payee.toLowerCase().startsWith(p.toLowerCase()));
++
++const sub = by('STREAMFLIX');
++assert.ok(sub, 'a subscription whose reference number changes is one series');
++assert.deepStrictEqual([sub.cadence, sub.typical_cents, sub.count, sub.next_on, sub.overdue], ['monthly', 1599, 6, '2026-12-05', false]);
++const rent = by('Lakeview');
++assert.deepStrictEqual([rent.cadence, rent.typical_cents, rent.monthly_cents], ['monthly', 145000, 145000]);
++const pay = by('Paycheck');
++assert.deepStrictEqual([pay.direction, pay.cadence, pay.typical_cents], ['in', 'every two weeks', 312000]);
++assert.strictEqual(pay.monthly_cents, Math.round(312000 * 30.4 / 14));
++const club = by('Warehouse');
++assert.deepStrictEqual([club.cadence, club.typical_cents], ['yearly', 9900]);
++assert.ok(!by('Corner Grocer'), 'groceries are not a bill');
++assert.ok(!by('Airline'), 'a one-off is not');
++assert.ok(!by('Puzzle'), 'two sightings are not enough');
++const gym = by('Old Gym');
++assert.ok(gym && gym.overdue, 'a subscription that stopped is overdue');
++assert.ok(found.indexOf(sub) < found.indexOf(rent) === (sub.next_on < rent.next_on), 'soonest first');
++
++(async () => {
++ const { createTestDb } = require('openvibe-sdk/testing');
++ const { createVault } = require('../server/crypto');
++ const { createStore } = require('../server/store');
++ const { createApp } = require('../server/app');
++ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
++ const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
++ const vault = createVault(crypto.randomBytes(32).toString('base64'));
++ const store = createStore({ db, vault });
++ const acc = await store.addAccount(ADA, { name: 'Checking' });
++ // Recent rows only (store.recent reads the last 400 days from the database's today).
++ const today = new Date().toISOString().slice(0, 10);
++ const back = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);
++ await store.importRows(ADA, acc.id, [tx(back(95), -1599, 'STREAMFLIX 881001'), tx(back(64), -1599, 'STREAMFLIX 881002'), tx(back(34), -1599, 'STREAMFLIX 881003'), tx(back(3), -1599, 'STREAMFLIX 881004')]);
++ 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 }).listen(0, '127.0.0.1');
++ await new Promise((r) => server.once('listening', r));
++ const base = `http://127.0.0.1:${server.address().port}`;
++ try {
++ const page = await fetch(`${base}/bills`, { headers: { 'x-test-user': ADA } }).then((r) => r.text());
++ assert.match(page, /About \$15\.99 a month/);
++ assert.match(page, /STREAMFLIX 881004/);
++ assert.match(page, /Every month/);
++ const api = await fetch(`${base}/api/v1/recurring`, { headers: { 'x-test-user': ADA } }).then((r) => r.json());
++ assert.strictEqual(api.recurring.length, 1);
++ assert.strictEqual(api.recurring[0].key, undefined, 'the internal key stays inside');
++ const other = await fetch(`${base}/api/v1/recurring`, { headers: { 'x-test-user': 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX' } }).then((r) => r.json());
++ assert.deepStrictEqual(other.recurring, [], 'nobody sees another person\'s');
++ assert.ok(today, 'today');
++ } finally {
++ server.close();
++ await close();
++ }
++ console.log('recurring: subscriptions, rent, paychecks and yearly fees found; groceries and one-offs not; a stopped one overdue');
++})().catch((err) => { console.error(err); process.exit(1); });