openvibers/openvibe.finance Commits
Category rules: Always for this payee, past and future imports (v0.2) (#2)
Changes
@@@ -10,17 +10,19 @@ 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.1)++## What it does today (v0.2)- 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, ordebit and credit; payee or description; memo; category), with the date and amount shapes banks send. Importing thesame file twice adds nothing twice.- Categories, corrected per transaction (each correction is a new revision; the category says where it came from).++- 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).- A JSON API for all of it (`/api/v1/…`), for the person signed in.--Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: rules and recurring bills, budgets, goals, OFX/QFX, the Link plugin++Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: recurring bills, budgets, goals, OFX/QFX, the Link pluginfor local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.## Runningnnew file mode 100644@@@ -0,0 +1,14 @@++-- phase: expand++-- Category rules (plan §L.2: "normalising, categories, rules"): "a payee containing these words is this category",++-- applied to transactions nobody has categorised (on import, and to the past when the rule is made); a category the++-- person set stays theirs. The words are sealed with the person's key like a payee (they are one); match_mark is the++-- person's HMAC of the normalised words, so the same rule is one row.++CREATE TABLE finance_rules (++ id text COLLATE "C" PRIMARY KEY,++ owner text COLLATE "C" NOT NULL,++ match_enc text NOT NULL,++ match_mark text COLLATE "C" NOT NULL,++ category text NOT NULL,++ created_at timestamptz NOT NULL DEFAULT now()++);++CREATE UNIQUE INDEX finance_rules_one ON finance_rules (owner, match_mark);@@@ -1,12 +1,12 @@{"name": "openvibe-finance",-- "version": "0.1.0",++ "version": "0.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openvibe-finance",-- "version": "0.1.0",++ "version": "0.2.0","license": "AGPL-3.0-only","dependencies": {"@electric-sql/pglite": "^0.5.8",@@@ -1,6 +1,6 @@{"name": "openvibe-finance",-- "version": "0.1.0",++ "version": "0.2.0","private": true,"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you","main": "server/index.js",@@@ -86,3 +86,12 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco.fin-file input { position: absolute; width: 1px; height: 1px; opacity: 0; overflow: hidden; }.fin-file input:focus-visible + .fin-btn { outline: 2px solid var(--accent, #5b8cff); outline-offset: 2px; }.fin-file-name { color: var(--text-secondary, #9aa4b2); font-size: 14px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++/* Category rules (v0.2). */++.fin-always { display: inline-flex; align-items: center; gap: 4px; min-height: 36px; font-size: 13px; color: var(--text-secondary, #9aa4b2); cursor: pointer; }++.fin-always input { width: 16px; height: 16px; accent-color: var(--accent, #5b8cff); }++.fin-by-rule { color: var(--text-secondary, #9aa4b2); font-size: 12px; }++.fin-rules { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; }++.fin-rules li { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px 14px; border-radius: 12px; border: 1px solid var(--border, #1f2937); }++.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; }@@@ -62,7 +62,9 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowconst monthOf = (q) => (/^\d{4}-(0[1-9]|1[0-2])$/.test(String(q || '')) ? String(q) : thisMonth());const said = (q) => {if (q.imported) { const [a, s] = String(q.imported).split(','); return `Imported ${Number(a) || 0} new transaction${Number(a) === 1 ? '' : 's'}${Number(s) ? `; ${Number(s)} already here` : ''}.`; }++ if (q.ruled != null) return `Rule made. It also put ${Number(q.ruled) || 0} earlier transaction${Number(q.ruled) === 1 ? '' : 's'} in that category.`;if (q.added) return 'Added.';++ if (q.removed) return 'Rule removed. What it categorised stays as it is.';if (q.deleted) return 'Everything is deleted.';return '';};@@@ -117,13 +119,27 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowif (!me) return signIn(req, res);if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');const t = await store.setCategory(me, req.params.id, req.body.category);-- res.redirect(303, `/accounts/${encodeURIComponent(t.account_id)}?m=${t.posted_on.slice(0, 7)}`);++ let ruled = '';++ if (req.body.always === 'yes' && t.payee && t.category !== 'Uncategorized') ruled = `&ruled=${(await store.addRule(me, { match: t.payee, category: t.category })).applied}`;++ res.redirect(303, `/accounts/${encodeURIComponent(t.account_id)}?m=${t.posted_on.slice(0, 7)}${ruled}`);}));app.get('/month', handle(async (req, res) => {const me = who(req);if (!me) return signIn(req, res);res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)) }));}));++ app.get('/rules', handle(async (req, res) => {++ const me = who(req);++ if (!me) return signIn(req, res);++ res.send(v.rulesPage({ rules: await store.rules(me), o: { said: said(req.query) } }));++ }));++ app.post('/rules/:id/delete', form, handle(async (req, res) => {++ const me = who(req);++ if (!me) return signIn(req, res);++ if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');++ await store.removeRule(me, req.params.id);++ res.redirect(303, '/rules?removed=1');++ }));app.get('/data', handle(async (req, res) => {if (!who(req)) return signIn(req, res);res.send(v.dataPage({ o: { said: said(req.query) } }));@@@ -159,6 +175,9 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', nowres.status(201).json({ ...(await store.importRows(who(req), req.params.id, read.rows)), unreadable: read.skipped.slice(0, 50) });}));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.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)))));app.use('/api/v1', api);@@@ -14,6 +14,9 @@* removeTransaction(owner, id)* importRows(owner, accountId, rows) → { import_id, read, added, skipped } (the same row twice is one)* month(owner, 'YYYY-MM') → { month, income_cents, spent_cents, by_category: [{ category, cents, count }] }++ * rules(owner) → [{ id, match, category }] (longest words first)++ * addRule(owner, { match, category }) the same words again replace the category; applied to the past++ * removeRule(owner, id)* exportAll(owner) → everything, opened (the person's own copy)* removeAll(owner) → everything of theirs deleted*/@@@ -36,6 +39,9 @@ function cleanCategory(c) {return t || 'Uncategorized';}++/** Words for matching: lower case, one space, no digits-only runs (card and reference numbers change every time). */++const matchable = (t) => String(t || '').toLowerCase().replace(/\b\d{3,}\b/g, ' ').replace(/[^a-z0-9&'.\- ]+/g, ' ').replace(/\s+/g, ' ').trim();++function createStore({ db, vault }) {const own = (owner) => { if (!/^usr_[0-9A-Za-z]{10,40}$/.test(String(owner || ''))) fail(401, 'finance.person', 'Sign in first.'); return owner; };const open = (owner, row) => ({@@@ -130,6 +136,7 @@ function createStore({ db, vault }) {if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.');const list = Array.isArray(rows) ? rows.slice(0, 20000) : [];const importId = newId('imp');++ const known = await rules(owner);let added = 0;await db.tx(async (t) => {await t.exec('INSERT INTO finance_imports (id, owner, account_id, format, rows_read) VALUES ($1, $2, $3, $4, $5)', [importId, owner, acc.id, 'csv', list.length]);@@@ -137,13 +144,15 @@ function createStore({ db, vault }) {const seen = new Map();for (const input of list) {const r = checkRow(input);++ let from = r.category === 'Uncategorized' ? 'none' : 'file';++ if (from === 'none') { const hit = ruleFor(known, r.payee); if (hit) { r.category = hit.category; from = 'rule'; } }const key = `${acc.id}|${r.posted_on}|${r.amount_cents}|${r.payee.toLowerCase()}`;const nth = (seen.get(key) || 0) + 1;seen.set(key, nth);const out = await t.exec(`INSERT INTO finance_transactions (id, owner, account_id, posted_on, amount_cents, payee_enc, memo_enc, category, category_from, import_id, dedupe)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) ON CONFLICT (account_id, dedupe) WHERE dedupe IS NOT NULL DO NOTHING`,[newId('txn'), owner, acc.id, r.posted_on, r.amount_cents, vault.seal(owner, r.payee), vault.seal(owner, r.memo), r.category,-- r.category === 'Uncategorized' ? 'none' : 'file', importId, vault.mark(owner, `${key}|${nth}`)]);++ from, importId, vault.mark(owner, `${key}|${nth}`)]);if (out) added++;}await t.exec('UPDATE finance_imports SET rows_added = $2, rows_skipped = $3 WHERE id = $1', [importId, added, list.length - added]);@@@ -171,6 +180,51 @@ function createStore({ db, vault }) {return { month: m, income_cents: income, spent_cents: spent, by_category: by };}++ async function rules(owner) {++ own(owner);++ const rows = await db.many('SELECT id, match_enc, category FROM finance_rules WHERE owner = $1', [owner]);++ return rows.map((r) => ({ id: r.id, match: vault.open(owner, r.match_enc), category: r.category })).sort((a, b) => b.match.length - a.match.length);++ }++ /** The rule a payee falls under: the longest words it contains. */++ const ruleFor = (list, payee) => { const p = matchable(payee); return p ? list.find((r) => p.includes(r.match)) || null : null; };++++ /** Put every uncategorised transaction of the person (or of one account) under the rules. → how many changed. */++ async function applyRules(owner, list = null) {++ const all = list || await rules(owner);++ if (!all.length) return 0;++ const rows = await db.many("SELECT id, payee_enc FROM finance_transactions WHERE owner = $1 AND category_from = 'none' LIMIT 20000", [owner]);++ let changed = 0;++ for (const r of rows) {++ const hit = ruleFor(all, vault.open(owner, r.payee_enc));++ if (!hit) continue;++ changed += await db.exec(`UPDATE finance_transactions SET category = $3, category_from = 'rule', revision = revision + 1, updated_at = now()++ WHERE id = $1 AND owner = $2 AND category_from = 'none'`, [r.id, owner, hit.category]);++ }++ return changed;++ }++++ async function addRule(owner, input = {}) {++ own(owner);++ const match = matchable(input.match).slice(0, 120);++ if (match.length < 2) fail(422, 'finance.rule.match', 'A rule needs a few words of the payee.');++ const category = cleanCategory(input.category);++ if (category === 'Uncategorized') fail(422, 'finance.rule.category', 'Say which category it is.');++ const count = Number(await db.value('SELECT count(*) FROM finance_rules WHERE owner = $1', [owner]));++ const mark = vault.mark(owner, `rule|${match}`);++ const known = await db.maybe('SELECT id FROM finance_rules WHERE owner = $1 AND match_mark = $2', [owner, mark]);++ if (!known && count >= 500) fail(422, 'finance.rule.limit', 'Five hundred rules is the most for now.');++ const id = known ? known.id : newId('rul');++ await db.exec(`INSERT INTO finance_rules (id, owner, match_enc, match_mark, category) VALUES ($1, $2, $3, $4, $5)++ ON CONFLICT (owner, match_mark) DO UPDATE SET category = EXCLUDED.category`, [id, owner, vault.seal(owner, match), mark, category]);++ const applied = await applyRules(owner);++ return { id, match, category, applied };++ }++++ async function removeRule(owner, id) {++ own(owner);++ await db.exec('DELETE FROM finance_rules WHERE id = $1 AND owner = $2', [String(id || ''), owner]);++ }++async function exportAll(owner) {own(owner);const accs = await db.many('SELECT id, name, kind, currency, opening_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);@@@ -179,6 +233,7 @@ function createStore({ db, vault }) {exported_at: new Date().toISOString(), format: 'openvibe.finance.export@1',accounts: accs.map((a) => ({ ...a, opening_cents: Number(a.opening_cents) })),transactions: txns.map((r) => open(owner, r)),++ rules: (await rules(owner)).map((r) => ({ match: r.match, category: r.category })),};}@@@ -187,11 +242,12 @@ function createStore({ db, vault }) {await db.tx(async (t) => {await t.exec('DELETE FROM finance_transactions WHERE owner = $1', [owner]);await t.exec('DELETE FROM finance_imports WHERE owner = $1', [owner]);++ await t.exec('DELETE FROM finance_rules WHERE owner = $1', [owner]);await t.exec('DELETE FROM finance_accounts WHERE owner = $1', [owner]);});}-- return { accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, exportAll, removeAll };++ return { accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, exportAll, removeAll };}--module.exports = { createStore, FinanceError, KINDS, CATEGORIES };++module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };@@@ -69,7 +69,18 @@ ${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="/data">Your data: download or delete everything</a></p>` });++<p class="fin-foot"><a href="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });++}++++function rulesPage({ rules, o = {} }) {++ return page({++ title: 'Your category rules', path: '/rules', body: `++<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Your category rules</h1></header>++${notice(o)}++<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>++${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>++<form method="post" action="/rules/${esc(r.id)}/delete"><button type="submit" class="fin-mini">Remove</button></form></li>`).join('')}</ul>`++ : '<p class="fin-empty">No rules yet.</p>'}` });}function accountPage({ account, balance, txns, month, o = {} }) {@@@ -78,7 +89,7 @@ function accountPage({ account, balance, txns, month, o = {} }) {const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;const row = (t) => `<li class="fin-txn"><span class="fin-txn-date">${esc(t.posted_on.slice(5))}</span><span class="fin-txn-what"><b>${esc(t.payee || 'No payee')}</b>${t.memo ? `<small>${esc(t.memo)}</small>` : ''}--<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category"><input name="category" list="fin-cats" value="${esc(t.category)}" aria-label="Category" maxlength="60"><button type="submit" class="fin-mini">Save</button></form></span>++<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category"><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><span class="fin-txn-amount${t.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(t.amount_cents, account.currency))}</span></li>`;const today = new Date().toISOString().slice(0, 10);return page({@@@ -137,4 +148,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, money, esc, monthName };++module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, money, esc, monthName };nnew file mode 100644@@@ -0,0 +1,101 @@++'use strict';++/**++ * Category rules (migrations/0002_rules.sql): "Always" on a transaction's category makes a rule for its payee's words;++ * the rule categorises the past transactions nobody categorised and every later import, never one the person set;++ * reference numbers do not matter; the words are sealed; the same words again replace the category; removing a rule++ * leaves what it did; export carries the rules and delete removes them.++ */++const assert = require('assert');++const path = require('node:path');++const crypto = require('node:crypto');++const { createTestDb } = require('openvibe-sdk/testing');++const { createVault } = require('../server/crypto');++const { createApp } = require('../server/app');++const { createStore, matchable } = require('../server/store');++++const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';++const SAME = { 'sec-fetch-site': 'same-origin' };++++(async () => {++ assert.strictEqual(matchable('AMAZON MKTPLACE PMTS 1234567 WA'), 'amazon mktplace pmts wa');++ assert.strictEqual(matchable(' Corner Grocer #22 '), 'corner grocer 22');++++ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });++ const vault = createVault(crypto.randomBytes(32).toString('base64'));++ const store = createStore({ db, vault });++ const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => { const u = req.get('x-test-user'); if (u) req.user = { subject_id: u }; next(); } };++ const server = createApp({ db, vault, auth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');++ await new Promise((r) => server.once('listening', r));++ const base = `http://127.0.0.1:${server.address().port}`;++ const post = async (p, form) => {++ const r = await fetch(base + p, { method: 'POST', redirect: 'manual', headers: { ...SAME, 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString() });++ return { status: r.status, location: r.headers.get('location'), text: await r.text() };++ };++ let failed = 0;++ const check = async (name, fn) => { try { await fn(); console.log(` ✓ ${name}`); } catch (e) { failed++; console.log(` ✗ ${name}\n ${e.stack}`); } };++++ try {++ const acc = await store.addAccount(ADA, { name: 'Checking' });++ await store.importRows(ADA, acc.id, [++ { posted_on: '2026-11-01', amount_cents: -1299, payee: 'STREAMCO 88812345 CA' },++ { posted_on: '2026-10-01', amount_cents: -1299, payee: 'STREAMCO 77712345 CA' },++ { posted_on: '2026-11-02', amount_cents: -5000, payee: 'Corner Grocer' },++ ]);++ const list = await store.transactions(ADA, acc.id);++ const nov = list.find((t) => t.payee.startsWith('STREAMCO 888'));++++ await check('Always on a category makes a rule; it categorises the past, whatever the reference number', async () => {++ const r = await post(`/transactions/${nov.id}/category`, { category: 'Subscriptions', always: 'yes' });++ assert.strictEqual(r.status, 303, r.text);++ assert.match(r.location, /ruled=1$/, 'one earlier transaction (October\'s) besides this one');++ const after = await store.transactions(ADA, acc.id);++ assert.deepStrictEqual(after.filter((t) => t.payee.startsWith('STREAMCO')).map((t) => [t.category, t.category_from]).sort(), [['Subscriptions', 'rule'], ['Subscriptions', 'you']]);++ assert.strictEqual(after.find((t) => t.payee === 'Corner Grocer').category, 'Uncategorized', 'another payee is left alone');++ const rules = await store.rules(ADA);++ assert.deepStrictEqual(rules.map((r) => [r.match, r.category]), [['streamco ca', 'Subscriptions']]);++ const row = await db.maybe('SELECT match_enc FROM finance_rules WHERE owner = $1', [ADA]);++ assert.ok(row.match_enc.startsWith('v1.') && !row.match_enc.includes('streamco'), 'the words are sealed');++ });++++ await check('a later import falls under the rule; a category the file or the person gave stays', async () => {++ await store.importRows(ADA, acc.id, [++ { posted_on: '2026-12-01', amount_cents: -1299, payee: 'STREAMCO 99912345 CA' },++ { posted_on: '2026-12-02', amount_cents: -1299, payee: 'STREAMCO 99912345 CA', category: 'Entertainment' },++ ]);++ const dec = await store.transactions(ADA, acc.id, { month: '2026-12' });++ assert.deepStrictEqual(dec.map((t) => [t.category, t.category_from]).sort(), [['Entertainment', 'file'], ['Subscriptions', 'rule']]);++ const mine = await store.addTransaction(ADA, acc.id, { posted_on: '2026-12-03', amount_cents: -100, payee: 'STREAMCO gift', category: 'Gifts and giving' });++ await store.applyRules(ADA);++ assert.strictEqual((await store.transactions(ADA, acc.id, { month: '2026-12' })).find((t) => t.id === mine.id).category, 'Gifts and giving', 'yours stays yours');++ });++++ await check('the same words again replace the category; the rules page lists them; remove leaves what they did', async () => {++ const again = await store.addRule(ADA, { match: 'STREAMCO CA', category: 'Entertainment' });++ assert.strictEqual((await store.rules(ADA)).length, 1);++ assert.strictEqual((await store.rules(ADA))[0].category, 'Entertainment');++ assert.strictEqual(again.match, 'streamco ca');++ const page = await fetch(`${base}/rules`, { headers: { 'x-test-user': ADA } }).then((r) => r.text());++ assert.match(page, /streamco ca/);++ assert.match(page, /Entertainment/);++ const r = await post(`/rules/${again.id}/delete`, {});++ assert.strictEqual(r.status, 303);++ assert.deepStrictEqual(await store.rules(ADA), []);++ assert.strictEqual((await store.transactions(ADA, acc.id, { month: '2026-11' })).find((t) => t.id === nov.id).category, 'Subscriptions', 'what it did stays');++ await assert.rejects(store.addRule(ADA, { match: 'x', category: 'Fees' }), /few words/);++ await assert.rejects(store.addRule(ADA, { match: 'corner grocer', category: '' }), /which category/);++ });++++ await check('export carries the rules; delete everything removes them', async () => {++ await store.addRule(ADA, { match: 'Corner Grocer', category: 'Groceries' });++ const ex = await store.exportAll(ADA);++ assert.deepStrictEqual(ex.rules, [{ match: 'corner grocer', category: 'Groceries' }]);++ await store.removeAll(ADA);++ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_rules WHERE owner = $1', [ADA])), 0);++ });++ } finally {++ server.close();++ await close();++ }++ if (failed) { console.log(`${failed} failed`); process.exit(1); }++ console.log('rules: made from a category, the past and later imports, yours kept, sealed, exported and deleted');++})().catch((err) => { console.error(err); process.exit(1); });
@@ -10,17 +10,19 @@ to connect.
@@ -10,17 +10,19 @@ 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.1)
+## What it does today (v0.2)
- 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 CSV export: the columns are read from the header (date; amount, or
- Transactions typed in, or imported from a bank's CSV export: the columns are read from the header (date; amount, or
debit and credit; payee or description; memo; category), with the date and amount shapes banks send. Importing the
debit and credit; payee or description; memo; category), with the date and amount shapes banks send. Importing the
same file twice adds nothing twice.
same file twice adds nothing twice.
- Categories, corrected per transaction (each correction is a new revision; the category says where it came from).
- Categories, corrected per transaction (each correction is a new revision; the category says where it came from).
+- 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).
- The month: money in, money out, and spending by category (transfers between your accounts left out).
- 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: rules and recurring bills, budgets, goals, OFX/QFX, the Link plugin
+Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: recurring bills, budgets, goals, OFX/QFX, the Link plugin
for local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.
for local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.
## Running
## Running
new file mode 100644
new file mode 100644
@@ -0,0 +1,14 @@
@@ -0,0 +1,14 @@
+-- phase: expand
+-- Category rules (plan §L.2: "normalising, categories, rules"): "a payee containing these words is this category",
+-- applied to transactions nobody has categorised (on import, and to the past when the rule is made); a category the
+-- person set stays theirs. The words are sealed with the person's key like a payee (they are one); match_mark is the
+-- person's HMAC of the normalised words, so the same rule is one row.
+CREATE TABLE finance_rules (
+ id text COLLATE "C" PRIMARY KEY,
+ owner text COLLATE "C" NOT NULL,
+ match_enc text NOT NULL,
+ match_mark text COLLATE "C" NOT NULL,
+ category text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE UNIQUE INDEX finance_rules_one ON finance_rules (owner, match_mark);
@@ -1,12 +1,12 @@
@@ -1,12 +1,12 @@
{
{
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.1.0",
+ "version": "0.2.0",
"lockfileVersion": 3,
"lockfileVersion": 3,
"requires": true,
"requires": true,
"packages": {
"packages": {
"": {
"": {
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.1.0",
+ "version": "0.2.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.1.0",
+ "version": "0.2.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",
@@ -86,3 +86,12 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
@@ -86,3 +86,12 @@ html[data-ov-motion="off"] .fin-btn:active, html[data-ov-motion="off"] .fin-acco
.fin-file input { position: absolute; width: 1px; height: 1px; opacity: 0; overflow: hidden; }
.fin-file input { position: absolute; width: 1px; height: 1px; opacity: 0; overflow: hidden; }
.fin-file input:focus-visible + .fin-btn { outline: 2px solid var(--accent, #5b8cff); outline-offset: 2px; }
.fin-file input:focus-visible + .fin-btn { outline: 2px solid var(--accent, #5b8cff); outline-offset: 2px; }
.fin-file-name { color: var(--text-secondary, #9aa4b2); font-size: 14px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fin-file-name { color: var(--text-secondary, #9aa4b2); font-size: 14px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+/* Category rules (v0.2). */
+.fin-always { display: inline-flex; align-items: center; gap: 4px; min-height: 36px; font-size: 13px; color: var(--text-secondary, #9aa4b2); cursor: pointer; }
+.fin-always input { width: 16px; height: 16px; accent-color: var(--accent, #5b8cff); }
+.fin-by-rule { color: var(--text-secondary, #9aa4b2); font-size: 12px; }
+.fin-rules { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; }
+.fin-rules li { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px 14px; border-radius: 12px; border: 1px solid var(--border, #1f2937); }
+.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; }
@@ -62,7 +62,9 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -62,7 +62,9 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
const monthOf = (q) => (/^\d{4}-(0[1-9]|1[0-2])$/.test(String(q || '')) ? String(q) : thisMonth());
const monthOf = (q) => (/^\d{4}-(0[1-9]|1[0-2])$/.test(String(q || '')) ? String(q) : thisMonth());
const said = (q) => {
const said = (q) => {
if (q.imported) { const [a, s] = String(q.imported).split(','); return `Imported ${Number(a) || 0} new transaction${Number(a) === 1 ? '' : 's'}${Number(s) ? `; ${Number(s)} already here` : ''}.`; }
if (q.imported) { const [a, s] = String(q.imported).split(','); return `Imported ${Number(a) || 0} new transaction${Number(a) === 1 ? '' : 's'}${Number(s) ? `; ${Number(s)} already here` : ''}.`; }
+ if (q.ruled != null) return `Rule made. It also put ${Number(q.ruled) || 0} earlier transaction${Number(q.ruled) === 1 ? '' : 's'} in that category.`;
if (q.added) return 'Added.';
if (q.added) return 'Added.';
+ if (q.removed) return 'Rule removed. What it categorised stays as it is.';
if (q.deleted) return 'Everything is deleted.';
if (q.deleted) return 'Everything is deleted.';
return '';
return '';
};
};
@@ -117,13 +119,27 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -117,13 +119,27 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
if (!me) return signIn(req, res);
if (!me) return signIn(req, res);
if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
const t = await store.setCategory(me, req.params.id, req.body.category);
const t = await store.setCategory(me, req.params.id, req.body.category);
- res.redirect(303, `/accounts/${encodeURIComponent(t.account_id)}?m=${t.posted_on.slice(0, 7)}`);
+ let ruled = '';
+ if (req.body.always === 'yes' && t.payee && t.category !== 'Uncategorized') ruled = `&ruled=${(await store.addRule(me, { match: t.payee, category: t.category })).applied}`;
+ res.redirect(303, `/accounts/${encodeURIComponent(t.account_id)}?m=${t.posted_on.slice(0, 7)}${ruled}`);
}));
}));
app.get('/month', handle(async (req, res) => {
app.get('/month', handle(async (req, res) => {
const me = who(req);
const me = who(req);
if (!me) return signIn(req, res);
if (!me) return signIn(req, res);
res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)) }));
res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)) }));
}));
}));
+ app.get('/rules', handle(async (req, res) => {
+ const me = who(req);
+ if (!me) return signIn(req, res);
+ res.send(v.rulesPage({ rules: await store.rules(me), o: { said: said(req.query) } }));
+ }));
+ app.post('/rules/:id/delete', form, handle(async (req, res) => {
+ const me = who(req);
+ if (!me) return signIn(req, res);
+ if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
+ await store.removeRule(me, req.params.id);
+ res.redirect(303, '/rules?removed=1');
+ }));
app.get('/data', handle(async (req, res) => {
app.get('/data', handle(async (req, res) => {
if (!who(req)) return signIn(req, res);
if (!who(req)) return signIn(req, res);
res.send(v.dataPage({ o: { said: said(req.query) } }));
res.send(v.dataPage({ o: { said: said(req.query) } }));
@@ -159,6 +175,9 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
@@ -159,6 +175,9 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
res.status(201).json({ ...(await store.importRows(who(req), req.params.id, read.rows)), unreadable: read.skipped.slice(0, 50) });
res.status(201).json({ ...(await store.importRows(who(req), req.params.id, read.rows)), unreadable: read.skipped.slice(0, 50) });
}));
}));
api.get('/months/:m', handle(async (req, res) => res.json(await store.month(who(req), req.params.m))));
api.get('/months/:m', handle(async (req, res) => res.json(await store.month(who(req), req.params.m))));
+ api.get('/rules', handle(async (req, res) => res.json({ rules: await store.rules(who(req)) })));
+ api.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)))));
api.get('/export', handle(async (req, res) => res.json(await store.exportAll(who(req)))));
app.use('/api/v1', api);
app.use('/api/v1', api);
@@ -14,6 +14,9 @@
@@ -14,6 +14,9 @@
* removeTransaction(owner, id)
* removeTransaction(owner, id)
* importRows(owner, accountId, rows) → { import_id, read, added, skipped } (the same row twice is one)
* importRows(owner, accountId, rows) → { import_id, read, added, skipped } (the same row twice is one)
* month(owner, 'YYYY-MM') → { month, income_cents, spent_cents, by_category: [{ category, cents, count }] }
* month(owner, 'YYYY-MM') → { month, income_cents, spent_cents, by_category: [{ category, cents, count }] }
+ * rules(owner) → [{ id, match, category }] (longest words first)
+ * addRule(owner, { match, category }) the same words again replace the category; applied to the past
+ * removeRule(owner, id)
* 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
*/
*/
@@ -36,6 +39,9 @@ function cleanCategory(c) {
@@ -36,6 +39,9 @@ function cleanCategory(c) {
return t || 'Uncategorized';
return t || 'Uncategorized';
}
}
+/** Words for matching: lower case, one space, no digits-only runs (card and reference numbers change every time). */
+const matchable = (t) => String(t || '').toLowerCase().replace(/\b\d{3,}\b/g, ' ').replace(/[^a-z0-9&'.\- ]+/g, ' ').replace(/\s+/g, ' ').trim();
+
function createStore({ db, vault }) {
function createStore({ db, vault }) {
const own = (owner) => { if (!/^usr_[0-9A-Za-z]{10,40}$/.test(String(owner || ''))) fail(401, 'finance.person', 'Sign in first.'); return owner; };
const own = (owner) => { if (!/^usr_[0-9A-Za-z]{10,40}$/.test(String(owner || ''))) fail(401, 'finance.person', 'Sign in first.'); return owner; };
const open = (owner, row) => ({
const open = (owner, row) => ({
@@ -130,6 +136,7 @@ function createStore({ db, vault }) {
@@ -130,6 +136,7 @@ function createStore({ db, vault }) {
if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.');
if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.');
const list = Array.isArray(rows) ? rows.slice(0, 20000) : [];
const list = Array.isArray(rows) ? rows.slice(0, 20000) : [];
const importId = newId('imp');
const importId = newId('imp');
+ const known = await rules(owner);
let added = 0;
let added = 0;
await db.tx(async (t) => {
await db.tx(async (t) => {
await t.exec('INSERT INTO finance_imports (id, owner, account_id, format, rows_read) VALUES ($1, $2, $3, $4, $5)', [importId, owner, acc.id, 'csv', list.length]);
await t.exec('INSERT INTO finance_imports (id, owner, account_id, format, rows_read) VALUES ($1, $2, $3, $4, $5)', [importId, owner, acc.id, 'csv', list.length]);
@@ -137,13 +144,15 @@ function createStore({ db, vault }) {
@@ -137,13 +144,15 @@ function createStore({ db, vault }) {
const seen = new Map();
const seen = new Map();
for (const input of list) {
for (const input of list) {
const r = checkRow(input);
const r = checkRow(input);
+ let from = r.category === 'Uncategorized' ? 'none' : 'file';
+ if (from === 'none') { const hit = ruleFor(known, r.payee); if (hit) { r.category = hit.category; from = 'rule'; } }
const key = `${acc.id}|${r.posted_on}|${r.amount_cents}|${r.payee.toLowerCase()}`;
const key = `${acc.id}|${r.posted_on}|${r.amount_cents}|${r.payee.toLowerCase()}`;
const nth = (seen.get(key) || 0) + 1;
const nth = (seen.get(key) || 0) + 1;
seen.set(key, nth);
seen.set(key, nth);
const out = await t.exec(`INSERT INTO finance_transactions (id, owner, account_id, posted_on, amount_cents, payee_enc, memo_enc, category, category_from, import_id, dedupe)
const out = await t.exec(`INSERT INTO finance_transactions (id, owner, account_id, posted_on, amount_cents, payee_enc, memo_enc, category, category_from, import_id, dedupe)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) ON CONFLICT (account_id, dedupe) WHERE dedupe IS NOT NULL DO NOTHING`,
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) ON CONFLICT (account_id, dedupe) WHERE dedupe IS NOT NULL DO NOTHING`,
[newId('txn'), owner, acc.id, r.posted_on, r.amount_cents, vault.seal(owner, r.payee), vault.seal(owner, r.memo), r.category,
[newId('txn'), owner, acc.id, r.posted_on, r.amount_cents, vault.seal(owner, r.payee), vault.seal(owner, r.memo), r.category,
- r.category === 'Uncategorized' ? 'none' : 'file', importId, vault.mark(owner, `${key}|${nth}`)]);
+ from, importId, vault.mark(owner, `${key}|${nth}`)]);
if (out) added++;
if (out) added++;
}
}
await t.exec('UPDATE finance_imports SET rows_added = $2, rows_skipped = $3 WHERE id = $1', [importId, added, list.length - added]);
await t.exec('UPDATE finance_imports SET rows_added = $2, rows_skipped = $3 WHERE id = $1', [importId, added, list.length - added]);
@@ -171,6 +180,51 @@ function createStore({ db, vault }) {
@@ -171,6 +180,51 @@ function createStore({ db, vault }) {
return { month: m, income_cents: income, spent_cents: spent, by_category: by };
return { month: m, income_cents: income, spent_cents: spent, by_category: by };
}
}
+ async function rules(owner) {
+ own(owner);
+ const rows = await db.many('SELECT id, match_enc, category FROM finance_rules WHERE owner = $1', [owner]);
+ return rows.map((r) => ({ id: r.id, match: vault.open(owner, r.match_enc), category: r.category })).sort((a, b) => b.match.length - a.match.length);
+ }
+ /** The rule a payee falls under: the longest words it contains. */
+ const ruleFor = (list, payee) => { const p = matchable(payee); return p ? list.find((r) => p.includes(r.match)) || null : null; };
+
+ /** Put every uncategorised transaction of the person (or of one account) under the rules. → how many changed. */
+ async function applyRules(owner, list = null) {
+ const all = list || await rules(owner);
+ if (!all.length) return 0;
+ const rows = await db.many("SELECT id, payee_enc FROM finance_transactions WHERE owner = $1 AND category_from = 'none' LIMIT 20000", [owner]);
+ let changed = 0;
+ for (const r of rows) {
+ const hit = ruleFor(all, vault.open(owner, r.payee_enc));
+ if (!hit) continue;
+ changed += await db.exec(`UPDATE finance_transactions SET category = $3, category_from = 'rule', revision = revision + 1, updated_at = now()
+ WHERE id = $1 AND owner = $2 AND category_from = 'none'`, [r.id, owner, hit.category]);
+ }
+ return changed;
+ }
+
+ async function addRule(owner, input = {}) {
+ own(owner);
+ const match = matchable(input.match).slice(0, 120);
+ if (match.length < 2) fail(422, 'finance.rule.match', 'A rule needs a few words of the payee.');
+ const category = cleanCategory(input.category);
+ if (category === 'Uncategorized') fail(422, 'finance.rule.category', 'Say which category it is.');
+ const count = Number(await db.value('SELECT count(*) FROM finance_rules WHERE owner = $1', [owner]));
+ const mark = vault.mark(owner, `rule|${match}`);
+ const known = await db.maybe('SELECT id FROM finance_rules WHERE owner = $1 AND match_mark = $2', [owner, mark]);
+ if (!known && count >= 500) fail(422, 'finance.rule.limit', 'Five hundred rules is the most for now.');
+ const id = known ? known.id : newId('rul');
+ await db.exec(`INSERT INTO finance_rules (id, owner, match_enc, match_mark, category) VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (owner, match_mark) DO UPDATE SET category = EXCLUDED.category`, [id, owner, vault.seal(owner, match), mark, category]);
+ const applied = await applyRules(owner);
+ return { id, match, category, applied };
+ }
+
+ async function removeRule(owner, id) {
+ own(owner);
+ await db.exec('DELETE FROM finance_rules WHERE id = $1 AND owner = $2', [String(id || ''), owner]);
+ }
+
async function exportAll(owner) {
async function exportAll(owner) {
own(owner);
own(owner);
const accs = await db.many('SELECT id, name, kind, currency, opening_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);
const accs = await db.many('SELECT id, name, kind, currency, opening_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]);
@@ -179,6 +233,7 @@ function createStore({ db, vault }) {
@@ -179,6 +233,7 @@ function createStore({ db, vault }) {
exported_at: new Date().toISOString(), format: 'openvibe.finance.export@1',
exported_at: new Date().toISOString(), format: 'openvibe.finance.export@1',
accounts: accs.map((a) => ({ ...a, opening_cents: Number(a.opening_cents) })),
accounts: accs.map((a) => ({ ...a, opening_cents: Number(a.opening_cents) })),
transactions: txns.map((r) => open(owner, r)),
transactions: txns.map((r) => open(owner, r)),
+ rules: (await rules(owner)).map((r) => ({ match: r.match, category: r.category })),
};
};
}
}
@@ -187,11 +242,12 @@ function createStore({ db, vault }) {
@@ -187,11 +242,12 @@ function createStore({ db, vault }) {
await db.tx(async (t) => {
await db.tx(async (t) => {
await t.exec('DELETE FROM finance_transactions WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_transactions WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_imports WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_imports WHERE owner = $1', [owner]);
+ await t.exec('DELETE FROM finance_rules WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_accounts WHERE owner = $1', [owner]);
await t.exec('DELETE FROM finance_accounts WHERE owner = $1', [owner]);
});
});
}
}
- return { accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, exportAll, removeAll };
+ return { accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, exportAll, removeAll };
}
}
-module.exports = { createStore, FinanceError, KINDS, CATEGORIES };
+module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable };
@@ -69,7 +69,18 @@ ${accounts.length ? `<section class="fin-month-card" aria-label="${esc(monthName
@@ -69,7 +69,18 @@ ${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="/data">Your data: download or delete everything</a></p>` });
+<p class="fin-foot"><a href="/rules">Your category rules</a> · <a href="/data">Your data: download or delete everything</a></p>` });
+}
+
+function rulesPage({ rules, o = {} }) {
+ return page({
+ title: 'Your category rules', path: '/rules', body: `
+<header class="fin-head"><p class="fin-crumb"><a href="/">Your money</a></p><h1>Your category rules</h1></header>
+${notice(o)}
+<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>
+${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>
+<form method="post" action="/rules/${esc(r.id)}/delete"><button type="submit" class="fin-mini">Remove</button></form></li>`).join('')}</ul>`
+ : '<p class="fin-empty">No rules yet.</p>'}` });
}
}
function accountPage({ account, balance, txns, month, o = {} }) {
function accountPage({ account, balance, txns, month, o = {} }) {
@@ -78,7 +89,7 @@ function accountPage({ account, balance, txns, month, o = {} }) {
@@ -78,7 +89,7 @@ function accountPage({ account, balance, txns, month, o = {} }) {
const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;
const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;
const row = (t) => `<li class="fin-txn"><span class="fin-txn-date">${esc(t.posted_on.slice(5))}</span>
const row = (t) => `<li class="fin-txn"><span class="fin-txn-date">${esc(t.posted_on.slice(5))}</span>
<span class="fin-txn-what"><b>${esc(t.payee || 'No payee')}</b>${t.memo ? `<small>${esc(t.memo)}</small>` : ''}
<span class="fin-txn-what"><b>${esc(t.payee || 'No payee')}</b>${t.memo ? `<small>${esc(t.memo)}</small>` : ''}
-<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category"><input name="category" list="fin-cats" value="${esc(t.category)}" aria-label="Category" maxlength="60"><button type="submit" class="fin-mini">Save</button></form></span>
+<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category"><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>
<span class="fin-txn-amount${t.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(t.amount_cents, account.currency))}</span></li>`;
<span class="fin-txn-amount${t.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(t.amount_cents, account.currency))}</span></li>`;
const today = new Date().toISOString().slice(0, 10);
const today = new Date().toISOString().slice(0, 10);
return page({
return page({
@@ -137,4 +148,4 @@ ${notice(o)}
@@ -137,4 +148,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, money, esc, monthName };
+module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, money, esc, monthName };
new file mode 100644
new file mode 100644
@@ -0,0 +1,101 @@
@@ -0,0 +1,101 @@
+'use strict';
+/**
+ * Category rules (migrations/0002_rules.sql): "Always" on a transaction's category makes a rule for its payee's words;
+ * the rule categorises the past transactions nobody categorised and every later import, never one the person set;
+ * reference numbers do not matter; the words are sealed; the same words again replace the category; removing a rule
+ * leaves what it did; export carries the rules and delete removes them.
+ */
+const assert = require('assert');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const { createTestDb } = require('openvibe-sdk/testing');
+const { createVault } = require('../server/crypto');
+const { createApp } = require('../server/app');
+const { createStore, matchable } = require('../server/store');
+
+const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
+const SAME = { 'sec-fetch-site': 'same-origin' };
+
+(async () => {
+ assert.strictEqual(matchable('AMAZON MKTPLACE PMTS 1234567 WA'), 'amazon mktplace pmts wa');
+ assert.strictEqual(matchable(' Corner Grocer #22 '), 'corner grocer 22');
+
+ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
+ const vault = createVault(crypto.randomBytes(32).toString('base64'));
+ const store = createStore({ db, vault });
+ const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => { const u = req.get('x-test-user'); if (u) req.user = { subject_id: u }; next(); } };
+ const server = createApp({ db, vault, auth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
+ await new Promise((r) => server.once('listening', r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ const post = async (p, form) => {
+ const r = await fetch(base + p, { method: 'POST', redirect: 'manual', headers: { ...SAME, 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString() });
+ return { status: r.status, location: r.headers.get('location'), text: await r.text() };
+ };
+ let failed = 0;
+ const check = async (name, fn) => { try { await fn(); console.log(` ✓ ${name}`); } catch (e) { failed++; console.log(` ✗ ${name}\n ${e.stack}`); } };
+
+ try {
+ const acc = await store.addAccount(ADA, { name: 'Checking' });
+ await store.importRows(ADA, acc.id, [
+ { posted_on: '2026-11-01', amount_cents: -1299, payee: 'STREAMCO 88812345 CA' },
+ { posted_on: '2026-10-01', amount_cents: -1299, payee: 'STREAMCO 77712345 CA' },
+ { posted_on: '2026-11-02', amount_cents: -5000, payee: 'Corner Grocer' },
+ ]);
+ const list = await store.transactions(ADA, acc.id);
+ const nov = list.find((t) => t.payee.startsWith('STREAMCO 888'));
+
+ await check('Always on a category makes a rule; it categorises the past, whatever the reference number', async () => {
+ const r = await post(`/transactions/${nov.id}/category`, { category: 'Subscriptions', always: 'yes' });
+ assert.strictEqual(r.status, 303, r.text);
+ assert.match(r.location, /ruled=1$/, 'one earlier transaction (October\'s) besides this one');
+ const after = await store.transactions(ADA, acc.id);
+ assert.deepStrictEqual(after.filter((t) => t.payee.startsWith('STREAMCO')).map((t) => [t.category, t.category_from]).sort(), [['Subscriptions', 'rule'], ['Subscriptions', 'you']]);
+ assert.strictEqual(after.find((t) => t.payee === 'Corner Grocer').category, 'Uncategorized', 'another payee is left alone');
+ const rules = await store.rules(ADA);
+ assert.deepStrictEqual(rules.map((r) => [r.match, r.category]), [['streamco ca', 'Subscriptions']]);
+ const row = await db.maybe('SELECT match_enc FROM finance_rules WHERE owner = $1', [ADA]);
+ assert.ok(row.match_enc.startsWith('v1.') && !row.match_enc.includes('streamco'), 'the words are sealed');
+ });
+
+ await check('a later import falls under the rule; a category the file or the person gave stays', async () => {
+ await store.importRows(ADA, acc.id, [
+ { posted_on: '2026-12-01', amount_cents: -1299, payee: 'STREAMCO 99912345 CA' },
+ { posted_on: '2026-12-02', amount_cents: -1299, payee: 'STREAMCO 99912345 CA', category: 'Entertainment' },
+ ]);
+ const dec = await store.transactions(ADA, acc.id, { month: '2026-12' });
+ assert.deepStrictEqual(dec.map((t) => [t.category, t.category_from]).sort(), [['Entertainment', 'file'], ['Subscriptions', 'rule']]);
+ const mine = await store.addTransaction(ADA, acc.id, { posted_on: '2026-12-03', amount_cents: -100, payee: 'STREAMCO gift', category: 'Gifts and giving' });
+ await store.applyRules(ADA);
+ assert.strictEqual((await store.transactions(ADA, acc.id, { month: '2026-12' })).find((t) => t.id === mine.id).category, 'Gifts and giving', 'yours stays yours');
+ });
+
+ await check('the same words again replace the category; the rules page lists them; remove leaves what they did', async () => {
+ const again = await store.addRule(ADA, { match: 'STREAMCO CA', category: 'Entertainment' });
+ assert.strictEqual((await store.rules(ADA)).length, 1);
+ assert.strictEqual((await store.rules(ADA))[0].category, 'Entertainment');
+ assert.strictEqual(again.match, 'streamco ca');
+ const page = await fetch(`${base}/rules`, { headers: { 'x-test-user': ADA } }).then((r) => r.text());
+ assert.match(page, /streamco ca/);
+ assert.match(page, /Entertainment/);
+ const r = await post(`/rules/${again.id}/delete`, {});
+ assert.strictEqual(r.status, 303);
+ assert.deepStrictEqual(await store.rules(ADA), []);
+ assert.strictEqual((await store.transactions(ADA, acc.id, { month: '2026-11' })).find((t) => t.id === nov.id).category, 'Subscriptions', 'what it did stays');
+ await assert.rejects(store.addRule(ADA, { match: 'x', category: 'Fees' }), /few words/);
+ await assert.rejects(store.addRule(ADA, { match: 'corner grocer', category: '' }), /which category/);
+ });
+
+ await check('export carries the rules; delete everything removes them', async () => {
+ await store.addRule(ADA, { match: 'Corner Grocer', category: 'Groceries' });
+ const ex = await store.exportAll(ADA);
+ assert.deepStrictEqual(ex.rules, [{ match: 'corner grocer', category: 'Groceries' }]);
+ await store.removeAll(ADA);
+ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_rules WHERE owner = $1', [ADA])), 0);
+ });
+ } finally {
+ server.close();
+ await close();
+ }
+ if (failed) { console.log(`${failed} failed`); process.exit(1); }
+ console.log('rules: made from a category, the past and later imports, yours kept, sealed, exported and deleted');
+})().catch((err) => { console.error(err); process.exit(1); });