openvibers/openvibe.finance Commits

OFX and QFX imports (v0.5) (#5)

OP OpenVibers committed 13 days ago · 6afa04af26 · 8 files, +190 −18

Plan §L.2 (getting data in: CSV, OFX, QFX, always free). The import takes a bank's OFX or QFX download as it
takes a CSV (detected by its header): OFX 1.x (SGML, open leaf tags) and 2.x (XML), bank and credit-card
statements, dates with times and zones, escaped names. Each transaction's FITID is its dedupe key, so the same
download twice, or two that overlap, add each transaction once, and two equal charges with their own ids are
two. The API takes application/x-ofx. test/ofx.test.js.

Changes

ddiff --git a/README.md b/README.md
iindex c04b023..629e3e8 100644
---- a/README.md
++++ b/README.md
@@@ -10,12 +10,15 @@ 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.4)
++## What it does today (v0.5)
- 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
-- debit and credit; payee or description; memo; category), with the date and amount shapes banks send. Importing the
-- same file twice adds nothing twice.
++- Transactions typed in, or imported from a bank's download:
++ - CSV: 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;
++ - OFX and QFX (Quicken), 1.x and 2.x, bank and credit-card statements: the bank's own transaction id (FITID) makes
++ repeated and overlapping downloads add each transaction once.
++ Importing the same 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.
@@@ -26,7 +29,7 @@ to connect.
amount at a steady rhythm, three times or more): what each costs a month, when the next is due, and which stopped.
- A JSON API for all of it (`/api/v1/…`), for the person signed in.
--Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: goals, OFX/QFX, the Link plugin
++Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: goals and debt, scenarios, 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 800dcdb..2ace100 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-finance",
-- "version": "0.4.0",
++ "version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-finance",
-- "version": "0.4.0",
++ "version": "0.5.0",
"license": "AGPL-3.0-only",
"dependencies": {
"@electric-sql/pglite": "^0.5.8",
ddiff --git a/package.json b/package.json
iindex a90c700..6536922 100644
---- a/package.json
++++ b/package.json
@@@ -1,6 +1,6 @@
{
"name": "openvibe-finance",
-- "version": "0.4.0",
++ "version": "0.5.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/server/app.js b/server/app.js
iindex ce50769..90ffa27 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -14,6 +14,9 @@ const express = require('express');
const path = require('node:path');
const { createStore, FinanceError } = require('./store');
const { readCsv, readAmount } = require('./csv');
++const { isOfx, readOfx } = require('./ofx');
++/** A bank's export, whichever it is: OFX or QFX by its header, else CSV. */
++const readExport = (text) => (isOfx(text) ? readOfx(text) : readCsv(text));
const { findRecurring } = require('./recurring');
const v = require('./views');
@@@ -111,7 +114,7 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
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.');
-- const read = readCsv(req.body.csv);
++ const read = readExport(req.body.csv);
if (read.problem) throw new FinanceError(422, 'finance.import.unreadable', read.problem);
const out = await store.importRows(me, req.params.id, read.rows);
const latest = read.rows.map((r) => r.posted_on).sort().pop();
@@@ -189,8 +192,8 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
res.json({ transactions: await store.transactions(who(req), req.params.id, { month: req.query.m ? String(req.query.m) : null }) });
}));
api.post('/accounts/:id/transactions', express.json({ limit: '16kb' }), handle(async (req, res) => res.status(201).json(await store.addTransaction(who(req), req.params.id, req.body || {}))));
-- api.post('/accounts/:id/import', express.text({ type: ['text/csv', 'text/plain'], limit: '4mb' }), handle(async (req, res) => {
-- const read = readCsv(typeof req.body === 'string' ? req.body : '');
++ api.post('/accounts/:id/import', express.text({ type: ['text/csv', 'text/plain', 'application/x-ofx', 'application/vnd.intu.qfx', 'application/ofx'], limit: '4mb' }), handle(async (req, res) => {
++ const read = readExport(typeof req.body === 'string' ? req.body : '');
if (read.problem) throw new FinanceError(422, 'finance.import.unreadable', read.problem);
res.status(201).json({ ...(await store.importRows(who(req), req.params.id, read.rows)), unreadable: read.skipped.slice(0, 50) });
}));
ddiff --git a/server/ofx.js b/server/ofx.js
nnew file mode 100644
iindex 0000000..983a7f1
---- /dev/null
++++ b/server/ofx.js
@@@ -0,0 +1,51 @@
++'use strict';
++/**
++ * A bank's OFX or QFX download → transactions (plan §L.2: "manual entry, CSV, OFX, QFX … always free").
++ *
++ * isOfx(text) → true for an OFX 1.x (SGML, "OFXHEADER:100") or 2.x (XML, "<?OFX") file, Quicken's QFX included
++ * readOfx(text) → { rows: [{ posted_on, amount_cents, payee, memo, category: '', fitid }], currency, skipped, problem }
++ *
++ * Both versions are read the same way: each <STMTTRN> … </STMTTRN> block (bank and credit-card statements), its
++ * fields as <TAG>value, closed or not (OFX 1.x leaves leaf tags open). FITID is the bank's own id for a transaction:
++ * the import keeps it, so the same download twice, or two overlapping ones, add each transaction once.
++ */
++const { readAmount } = require('./csv');
++
++const isOfx = (text) => /^\s*(?:)?(?:OFXHEADER\s*:|<\?xml[^>]*>\s*<\?OFX|<\?OFX|<OFX>)/i.test(String(text || '')) || /<OFX>[\s\S]*<STMTTRN>/i.test(String(text || '').slice(0, 200000));
++
++const decode = (v) => String(v || '').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;|&#39;/g, "'").replace(/\s+/g, ' ').trim();
++
++/** One leaf field of a block: <TAG>value, ended by its closing tag, the next tag, or the line. */
++function field(block, tag) {
++ const m = new RegExp(`<${tag}>([^<\\r\\n]*)`, 'i').exec(block);
++ return m ? decode(m[1]) : '';
++}
++
++/** An OFX date (20261118, 20261118120000, 20261118120000.000[-5:EST]) → 'YYYY-MM-DD' or null. */
++function ofxDate(v) {
++ const m = /^(\d{4})(\d{2})(\d{2})/.exec(String(v || '').trim());
++ if (!m) return null;
++ const [y, mo, d] = [+m[1], +m[2], +m[3]];
++ const t = new Date(Date.UTC(y, mo - 1, d));
++ return t.getUTCFullYear() === y && t.getUTCMonth() === mo - 1 && t.getUTCDate() === d ? `${m[1]}-${m[2]}-${m[3]}` : null;
++}
++
++function readOfx(text) {
++ const src = String(text || '');
++ const currency = field(src, 'CURDEF') || null;
++ const blocks = src.split(/<STMTTRN>/i).slice(1).map((b) => b.split(/<\/STMTTRN>/i)[0]);
++ if (!blocks.length) return { rows: [], currency, skipped: [], problem: 'No transactions in this file (no <STMTTRN> blocks).' };
++ const rows = [], skipped = [];
++ blocks.slice(0, 20000).forEach((b, i) => {
++ const posted_on = ofxDate(field(b, 'DTPOSTED')) || ofxDate(field(b, 'DTUSER'));
++ const amount_cents = readAmount(field(b, 'TRNAMT'));
++ if (!posted_on) { skipped.push({ line: i + 1, why: 'no posted date' }); return; }
++ if (amount_cents == null) { skipped.push({ line: i + 1, why: 'no amount' }); return; }
++ const name = field(b, 'NAME') || field(b, 'PAYEE');
++ const memo = field(b, 'MEMO');
++ rows.push({ posted_on, amount_cents, payee: (name || memo).slice(0, 300), memo: name ? memo.slice(0, 500) : '', category: '', fitid: field(b, 'FITID').slice(0, 255) || null });
++ });
++ return { rows, currency, skipped, problem: rows.length ? null : 'No transaction in this file could be read.' };
++}
++
++module.exports = { isOfx, readOfx, ofxDate };
ddiff --git a/server/store.js b/server/store.js
iindex 58cb364..2825f96 100644
---- a/server/store.js
++++ b/server/store.js
@@@ -159,10 +159,13 @@ function createStore({ db, vault }) {
const key = `${acc.id}|${r.posted_on}|${r.amount_cents}|${r.payee.toLowerCase()}`;
const nth = (seen.get(key) || 0) + 1;
seen.set(key, nth);
++ // The bank's own transaction id (an OFX/QFX FITID) is exact: the same download twice, or two that
++ // overlap, add each transaction once.
++ const fitid = typeof input.fitid === 'string' && input.fitid.trim() ? input.fitid.trim().slice(0, 255) : null;
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,
-- from, importId, vault.mark(owner, `${key}|${nth}`)]);
++ from, importId, vault.mark(owner, fitid ? `fitid|${acc.id}|${fitid}` : `${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]);
ddiff --git a/server/views.js b/server/views.js
iindex 7b2dd97..c5a6216 100644
---- a/server/views.js
++++ b/server/views.js
@@@ -35,7 +35,7 @@ function welcome() {
title: 'Your money, your rules, your data', robots: 'index, follow', body: `
<section class="fin-hero">
<h1>Your money, your rules, your data</h1>
--<p class="fin-lede">Your accounts in one place, from a bank's CSV export or typed in, and a clear picture of each month. Free, with nothing to connect.</p>
++<p class="fin-lede">Your accounts in one place, from your bank's download (CSV, OFX or QFX) or typed in, and a clear picture of each month. Free, with nothing to connect.</p>
<p><a class="fin-btn fin-btn--primary" href="/auth/login?next=%2F">Sign in to start</a></p>
</section>
<ul class="fin-promises">
@@@ -60,7 +60,7 @@ ${accounts.length ? `<section class="fin-month-card" aria-label="${esc(monthName
<ul class="fin-accounts">${accounts.map((a) => `<li><a class="fin-account" href="/accounts/${esc(a.id)}">
<span class="fin-account-name">${esc(a.name)}<small>${esc(KIND_WORDS[a.kind] || a.kind)} · ${a.count} transaction${a.count === 1 ? '' : 's'}</small></span>
<span class="fin-account-balance${a.balance_cents < 0 ? ' is-neg' : ''}">${esc(money(a.balance_cents, a.currency))}</span></a></li>`).join('')}</ul>`
-- : `<p class="fin-empty">Start with an account: name it, then type in transactions or import your bank's CSV export.</p>`}
++ : `<p class="fin-empty">Start with an account: name it, then type in transactions or import your bank's download (CSV, OFX or QFX).</p>`}
<details class="fin-fold"${accounts.length ? '' : ' open'}><summary>Add an account</summary>
<form class="fin-form" method="post" action="/accounts">
<label class="fin-field"><span>Name</span><input name="name" maxlength="80" required placeholder="Everyday checking" autocomplete="off"></label>
@@@ -129,17 +129,17 @@ ${notice(o)}${cats}
<label class="fin-field"><span>Category</span><input name="category" list="fin-cats" maxlength="60" autocomplete="off" placeholder="Groceries"></label>
<p><button class="fin-btn fin-btn--primary" type="submit">Add it</button></p>
</form></details>
--<details class="fin-fold"><summary>Import a bank's CSV export</summary>
++<details class="fin-fold"><summary>Import a bank's export (CSV, OFX or QFX)</summary>
<form class="fin-form" method="post" action="/accounts/${esc(account.id)}/import">
--<p class="fin-note">Most banks export a CSV with a date, an amount (or debit and credit) and a description. Importing the same file twice adds nothing twice.</p>
--<label class="fin-file"><input type="file" accept=".csv,text/csv,text/plain" data-fin-file="csv"><span class="fin-btn">Choose a CSV file</span><span class="fin-file-name" data-fin-file-name>No file chosen yet</span></label>
++<p class="fin-note">Banks offer a download as CSV, OFX or QFX (Quicken). Any of them works; importing the same file twice adds nothing twice.</p>
++<label class="fin-file"><input type="file" accept=".csv,.ofx,.qfx,text/csv,text/plain,application/x-ofx" data-fin-file="csv"><span class="fin-btn">Choose a file</span><span class="fin-file-name" data-fin-file-name>No file chosen yet</span></label>
<label class="fin-field"><span>Or paste it</span><textarea name="csv" rows="6" required data-fin-csv placeholder="Date,Description,Amount&#10;2026-11-02,Corner Grocer,-23.18"></textarea></label>
<p><button class="fin-btn fin-btn--primary" type="submit">Import</button></p>
</form></details>
</div>
<nav class="fin-monthnav" aria-label="Month"><a href="/accounts/${esc(account.id)}?m=${shiftMonth(month, -1)}">${esc(monthName(shiftMonth(month, -1)))}</a>
<b>${esc(monthName(month))}</b><a href="/accounts/${esc(account.id)}?m=${shiftMonth(month, 1)}">${esc(monthName(shiftMonth(month, 1)))}</a></nav>
--${txns.length ? [...groups.values()].map((list) => `<ul class="fin-txns">${list.map(row).join('')}</ul>`).join('') : `<p class="fin-empty">Nothing in ${esc(monthName(month))}. Add a transaction, or import a CSV.</p>`}` });
++${txns.length ? [...groups.values()].map((list) => `<ul class="fin-txns">${list.map(row).join('')}</ul>`).join('') : `<p class="fin-empty">Nothing in ${esc(monthName(month))}. Add a transaction, or import your bank's export.</p>`}` });
}
function monthPage({ m, budgets = [], o = {} }) {
ddiff --git a/test/ofx.test.js b/test/ofx.test.js
nnew file mode 100644
iindex 0000000..ebb42b5
---- /dev/null
++++ b/test/ofx.test.js
@@@ -0,0 +1,112 @@
++'use strict';
++/**
++ * OFX and QFX downloads (server/ofx.js): OFX 1.x (SGML, open leaf tags) and 2.x (XML), bank and credit-card statements,
++ * dates with times and zones, escaped names; FITIDs make the same download twice, and two downloads that overlap, add
++ * each transaction once; the page's import takes OFX as it takes CSV.
++ */
++const assert = require('assert');
++const path = require('node:path');
++const crypto = require('node:crypto');
++const { isOfx, readOfx, ofxDate } = require('../server/ofx');
++
++const OFX1 = `OFXHEADER:100
++DATA:OFXSGML
++VERSION:102
++SECURITY:NONE
++ENCODING:USASCII
++
++<OFX>
++<SIGNONMSGSRSV1><SONRS><STATUS><CODE>0<SEVERITY>INFO</STATUS><DTSERVER>20261118120000</SONRS></SIGNONMSGSRSV1>
++<BANKMSGSRSV1><STMTTRNRS><STMTRS><CURDEF>USD
++<BANKTRANLIST>
++<STMTTRN>
++<TRNTYPE>DEBIT
++<DTPOSTED>20261102120000.000[-5:EST]
++<TRNAMT>-23.18
++<FITID>2026110200001
++<NAME>CORNER GROCER &amp; DELI
++<MEMO>POS PURCHASE
++</STMTTRN>
++<STMTTRN>
++<TRNTYPE>CREDIT
++<DTPOSTED>20261101
++<TRNAMT>3120.00
++<FITID>2026110100007
++<NAME>ACME CORP PAYROLL
++</STMTTRN>
++<STMTTRN>
++<TRNTYPE>DEBIT
++<DTPOSTED>20261302
++<TRNAMT>-1.00
++<FITID>bad-date
++<NAME>NOWHERE
++</STMTTRN>
++</BANKTRANLIST>
++</STMTRS></STMTTRNRS></BANKMSGSRSV1>
++</OFX>`;
++
++const OFX2 = `<?xml version="1.0" encoding="UTF-8"?>
++<?OFX OFXHEADER="200" VERSION="211" SECURITY="NONE"?>
++<OFX><CREDITCARDMSGSRSV1><CCSTMTTRNRS><CCSTMTRS><CURDEF>USD</CURDEF><BANKTRANLIST>
++<STMTTRN><TRNTYPE>DEBIT</TRNTYPE><DTPOSTED>20261107</DTPOSTED><TRNAMT>-412.20</TRNAMT><FITID>CC-77</FITID><NAME>AIRLINE TICKETS</NAME></STMTTRN>
++<STMTTRN><TRNTYPE>DEBIT</TRNTYPE><DTPOSTED>20261107</DTPOSTED><TRNAMT>-412.20</TRNAMT><FITID>CC-78</FITID><NAME>AIRLINE TICKETS</NAME></STMTTRN>
++</BANKTRANLIST></CCSTMTRS></CCSTMTTRNRS></CREDITCARDMSGSRSV1></OFX>`;
++
++assert.ok(isOfx(OFX1) && isOfx(OFX2), 'both versions are OFX');
++assert.ok(!isOfx('Date,Description,Amount\n2026-11-01,x,1\n'), 'a CSV is not');
++assert.strictEqual(ofxDate('20261118120000.000[-5:EST]'), '2026-11-18');
++assert.strictEqual(ofxDate('20261302'), null);
++
++const one = readOfx(OFX1);
++assert.strictEqual(one.currency, 'USD');
++assert.deepStrictEqual(one.rows, [
++ { posted_on: '2026-11-02', amount_cents: -2318, payee: 'CORNER GROCER & DELI', memo: 'POS PURCHASE', category: '', fitid: '2026110200001' },
++ { posted_on: '2026-11-01', amount_cents: 312000, payee: 'ACME CORP PAYROLL', memo: '', category: '', fitid: '2026110100007' },
++]);
++assert.deepStrictEqual(one.skipped, [{ line: 3, why: 'no posted date' }]);
++const two = readOfx(OFX2);
++assert.deepStrictEqual(two.rows.map((r) => [r.posted_on, r.amount_cents, r.fitid]), [['2026-11-07', -41220, 'CC-77'], ['2026-11-07', -41220, 'CC-78']]);
++assert.match(readOfx('<OFX></OFX>').problem, /No transactions/);
++
++(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 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}`;
++ const importForm = (accId, text) => fetch(`${base}/accounts/${accId}/import`, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ csv: text }).toString() })
++ .then(async (r) => ({ status: r.status, location: r.headers.get('location'), text: await r.text() }));
++ try {
++ const checking = await store.addAccount(ADA, { name: 'Checking' });
++ let r = await importForm(checking.id, OFX1);
++ assert.strictEqual(r.status, 303, r.text);
++ assert.match(r.location, /imported=2,0$/);
++ r = await importForm(checking.id, OFX1);
++ assert.match(r.location, /imported=0,2$/, 'the same download twice adds nothing');
++ // A later download that overlaps: one transaction already here, one new.
++ const later = OFX1.replace(/<STMTTRN>\s*<TRNTYPE>CREDIT[\s\S]*?<\/STMTTRN>/, '<STMTTRN>\n<TRNTYPE>DEBIT\n<DTPOSTED>20261105\n<TRNAMT>-9.99\n<FITID>2026110500002\n<NAME>STREAMFLIX\n</STMTTRN>');
++ r = await importForm(checking.id, later);
++ assert.match(r.location, /imported=1,1$/);
++ const card = await store.addAccount(ADA, { name: 'Card', kind: 'credit' });
++ r = await importForm(card.id, OFX2);
++ assert.match(r.location, /imported=2,0$/, 'two equal charges with their own FITIDs are two');
++ const all = await store.transactions(ADA, checking.id);
++ assert.deepStrictEqual(all.map((t) => t.payee).sort(), ['ACME CORP PAYROLL', 'CORNER GROCER & DELI', 'STREAMFLIX']);
++ const api = await fetch(`${base}/api/v1/accounts/${card.id}/import`, { method: 'POST', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': ADA, 'content-type': 'application/x-ofx' }, body: OFX2 }).then((x) => x.json());
++ assert.deepStrictEqual([api.added, api.skipped], [0, 2], 'the API takes OFX too');
++ const page = await fetch(`${base}/accounts/${checking.id}?m=2026-11`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());
++ assert.match(page, /CSV, OFX or QFX/);
++ assert.match(page, /accept="\.csv,\.ofx,\.qfx/);
++ } finally {
++ server.close();
++ await close();
++ }
++ console.log('ofx: 1.x and 2.x, bank and card, FITIDs exact across downloads, the page and the API');
++})().catch((err) => { console.error(err); process.exit(1); });