openvibers/openvibe.finance Commits

Statement PDFs, read here and checked before importing (v0.11) (#11)

OP OpenVibers committed 13 days ago · 6600494de6 · 10 files, +416 −14

Plan §L.2 (getting data in: statement PDFs, always free). The account page's import takes a PDF statement:
- its text is read on openvibe.finance (server/pdf.js, OpenVibe.AI's small dependency-free extractor:
  plain and Flate streams, Tj/TJ/'/"), never sent anywhere and not kept;
- server/statement.js reads the lines with a date and an amount: the running balance at a line's end
  skipped; minus, brackets, DR and CR; dates with or without a year (the statement's), day first with £/€
  or a day over 12; balances and totals skipped. When nothing marks money in and out, words like deposit,
  payroll or refund read as in, and the person chooses as shown, all out or all in;
- a preview lists every row ticked, with the totals in and out; Import takes the ticked ones, with the
  usual dedupe (the same statement twice adds nothing). Encrypted, scanned or unreadable PDFs say so and
  point to the CSV/OFX/QFX download.
test/statement.test.js (real PDF bytes, plain and compressed, through the page flow).

Changes

ddiff --git a/README.md b/README.md
iindex 1167cc6..f7a11df 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.10)
++## What it does today (v0.11)
- 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 download:
@@@ -18,6 +18,8 @@ to connect.
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.
++ - a PDF statement (text PDFs): read on openvibe.finance and never sent anywhere; the lines with a date and an
++ amount, money in and out as marked (or as the person chooses when nothing marks them), checked before importing.
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
ddiff --git a/package-lock.json b/package-lock.json
iindex 51850f8..8668bec 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-finance",
-- "version": "0.10.0",
++ "version": "0.11.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-finance",
-- "version": "0.10.0",
++ "version": "0.11.0",
"license": "AGPL-3.0-only",
"dependencies": {
"@electric-sql/pglite": "^0.5.8",
ddiff --git a/package.json b/package.json
iindex c693cac..8411617 100644
---- a/package.json
++++ b/package.json
@@@ -1,6 +1,6 @@
{
"name": "openvibe-finance",
-- "version": "0.10.0",
++ "version": "0.11.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 ba7c5e6..6bb3ec5 100644
---- a/public/finance.css
++++ b/public/finance.css
@@@ -178,3 +178,18 @@ html[data-ov-motion="off"] .fin-result { animation: none; }
html[data-ov-motion="off"] .fin-expert { transition: none; }
/* A category an agent set (v0.10): marked, so it is easy to check and change. */
.fin-by-agent { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 12px; color: var(--accent, #5b8cff); border: 1px solid color-mix(in srgb, var(--accent, #5b8cff) 45%, transparent); }
++/* A statement PDF's rows to check (v0.11). */
++.fin-picks { list-style: none; padding: 0; margin: 4px 0 12px; display: grid; gap: 6px; }
++.fin-pick label { display: grid; grid-template-columns: auto auto minmax(0, 1fr) auto; gap: 10px; align-items: center; min-height: 48px; padding: 8px 12px; border-radius: 12px; border: 1px solid var(--border, #1f2937); cursor: pointer; }
++.fin-pick input { appearance: none; -webkit-appearance: none; width: 22px; height: 22px; margin: 0; border-radius: 7px; border: 2px solid var(--border-strong, #334155); display: grid; place-content: center; transition: background .12s ease, border-color .12s ease; }
++.fin-pick input::before { content: ''; width: 11px; height: 11px; clip-path: polygon(14% 52%, 0 66%, 38% 100%, 100% 22%, 86% 8%, 38% 72%); background: var(--accent-contrast, #fff); transform: scale(0); transition: transform .12s ease; }
++.fin-pick input:checked { background: var(--accent, #5b8cff); border-color: var(--accent, #5b8cff); }
++.fin-pick input:checked::before { transform: scale(1); }
++.fin-pick input:focus-visible { outline: 2px solid var(--accent, #5b8cff); outline-offset: 2px; }
++html[data-ov-motion="off"] .fin-pick input, html[data-ov-motion="off"] .fin-pick input::before { transition: none; }
++.fin-pick-date { color: var(--text-secondary, #9aa4b2); font-size: 13px; font-variant-numeric: tabular-nums; }
++.fin-pick-payee { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
++.fin-pick-amount { font-variant-numeric: tabular-nums; }
++.fin-pick input:not(:checked) ~ span { opacity: .45; text-decoration: line-through; }
++.fin-actions { display: flex; flex-wrap: wrap; gap: 8px; }
++@media (max-width: 480px) { .fin-pick label { grid-template-columns: auto minmax(0, 1fr) auto; } .fin-pick-date { grid-column: 2; grid-row: 2; } .fin-pick-payee { grid-column: 2; grid-row: 1; } .fin-pick-amount { grid-column: 3; grid-row: 1 / span 2; } }
ddiff --git a/public/finance.js b/public/finance.js
iindex 5d67833..bedd2b2 100644
---- a/public/finance.js
++++ b/public/finance.js
@@@ -1,16 +1,33 @@
--// OpenVibe.Finance: a chosen CSV file goes into the paste box (the form posts the text; nothing leaves before Import).
++// OpenVibe.Finance: a chosen CSV, OFX or QFX file goes into the paste box; a PDF statement is read as data for the server
++// to read (the form posts it to /accounts/:id/statement, which shows what it found before anything is imported).
(function () {
document.addEventListener('change', function (e) {
var input = e.target;
if (!input || !input.matches || !input.matches('input[data-fin-file="csv"]') || !input.files || !input.files[0]) return;
var file = input.files[0];
++ var form = input.closest('form');
input.setCustomValidity('');
-- if (file.size > 4 * 1024 * 1024) { input.setCustomValidity('That file is over 4 MB. Export fewer months at a time.'); input.reportValidity(); input.value = ''; return; }
-- var box = input.closest('form') && input.closest('form').querySelector('textarea[data-fin-csv]');
-- if (!box) return;
-- var reader = new FileReader();
++ var isPdf = /\.pdf$/i.test(file.name) || file.type === 'application/pdf';
++ var limit = isPdf ? 6 : 4;
++ if (file.size > limit * 1024 * 1024) { input.setCustomValidity('That file is over ' + limit + ' MB. Export fewer months at a time.'); input.reportValidity(); input.value = ''; return; }
++ var box = form && form.querySelector('textarea[data-fin-csv]');
++ var pdf = form && form.querySelector('[data-fin-pdf]');
var named = input.closest('label') && input.closest('label').querySelector('[data-fin-file-name]');
if (named) named.textContent = file.name;
++ var reader = new FileReader();
++ if (isPdf && pdf && form.getAttribute('data-fin-statement')) {
++ if (!form.getAttribute('data-fin-import')) form.setAttribute('data-fin-import', form.getAttribute('action'));
++ form.setAttribute('action', form.getAttribute('data-fin-statement'));
++ if (box) { box.required = false; box.value = ''; }
++ var nm = form.querySelector('[data-fin-pdf-name]'); if (nm) nm.value = file.name;
++ reader.onload = function () { pdf.value = String(reader.result || ''); };
++ reader.readAsDataURL(file);
++ return;
++ }
++ if (form && form.getAttribute('data-fin-import')) form.setAttribute('action', form.getAttribute('data-fin-import'));
++ if (pdf) pdf.value = '';
++ if (box) box.required = true;
++ if (!box) return;
reader.onload = function () { box.value = String(reader.result || ''); };
reader.readAsText(file);
});
ddiff --git a/server/app.js b/server/app.js
iindex 4e3e58e..c6a9358 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -22,6 +22,8 @@ const { perMonth } = require('./plan');
/** 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 { pdfText } = require('./pdf');
++const { readStatement } = require('./statement');
const v = require('./views');
function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvibe.finance', now = () => new Date() }) {
@@@ -127,6 +129,44 @@ function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvib
const t = await store.addTransaction(me, req.params.id, { posted_on: req.body.posted_on, amount_cents: cents, payee: req.body.payee, category: req.body.category });
res.redirect(303, `/accounts/${encodeURIComponent(req.params.id)}?m=${t.posted_on.slice(0, 7)}&added=1`);
}));
++ // A statement PDF (v0.11): read here, never sent anywhere; the person checks the rows before anything is imported.
++ const pdfForm = express.urlencoded({ extended: false, limit: '9mb' });
++ app.post('/accounts/:id/statement', pdfForm, 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.');
++ const account = await store.account(me, req.params.id);
++ if (!account) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
++ const b64 = String(req.body.pdf || '').replace(/^data:[^,]*,/, '');
++ const bytes = Buffer.from(b64, 'base64');
++ if (!bytes.length) throw new FinanceError(422, 'finance.statement.empty', 'Choose a statement PDF first.');
++ if (bytes.length > 6 * 1024 * 1024) throw new FinanceError(413, 'finance.statement.too_large', 'That PDF is over 6 MB.');
++ const text = pdfText(bytes);
++ if (!text.pages.length) throw new FinanceError(422, 'finance.statement.unreadable', `This PDF could not be read: ${text.reason}. Your bank's CSV, OFX or QFX download works too.`);
++ const read = readStatement(text.pages.join('\n'), { today: now().toISOString().slice(0, 10) });
++ if (read.problem) throw new FinanceError(422, 'finance.statement.no_rows', `${read.problem} Your bank's CSV, OFX or QFX download works too.`);
++ res.send(v.statementPreview({ account, read, name: String(req.body.name || '').slice(0, 120) }));
++ }));
++ app.post('/accounts/:id/statement/import', pdfForm, 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.');
++ let rows;
++ try { rows = JSON.parse(String(req.body.rows || '[]')); } catch { rows = null; }
++ if (!Array.isArray(rows) || !rows.length || rows.length > 2000) throw new FinanceError(422, 'finance.statement.rows', 'Read the PDF again.');
++ const take = new Set([].concat(req.body.take || []).map((x) => Number(x)));
++ const turn = String(req.body.signs || 'asread');
++ const chosen = rows.map((r, i) => ({ r, i })).filter(({ i }) => take.has(i)).map(({ r }) => {
++ const cents = Number(r && r.amount_cents);
++ if (!Number.isSafeInteger(cents)) throw new FinanceError(422, 'finance.statement.rows', 'Read the PDF again.');
++ return { posted_on: String(r.posted_on || ''), payee: String(r.payee || ''), memo: '', category: '',
++ amount_cents: turn === 'out' ? -Math.abs(cents) : turn === 'in' ? Math.abs(cents) : cents };
++ });
++ if (!chosen.length) throw new FinanceError(422, 'finance.statement.none', 'Tick at least one transaction to import.');
++ const out = await store.importRows(me, req.params.id, chosen);
++ const latest = chosen.map((r) => r.posted_on).sort().pop();
++ res.redirect(303, `/accounts/${encodeURIComponent(req.params.id)}?m=${latest.slice(0, 7)}&imported=${out.added},${out.skipped}`);
++ }));
app.post('/accounts/:id/import', form, handle(async (req, res) => {
const me = who(req);
if (!me) return signIn(req, res);
ddiff --git a/server/pdf.js b/server/pdf.js
nnew file mode 100644
iindex 0000000..7b6fef9
---- /dev/null
++++ b/server/pdf.js
@@@ -0,0 +1,103 @@
++'use strict';
++/**
++ * A PDF's text, page by page, with no dependency: the small extractor OpenVibe.AI uses for files on a turn
++ * (OpenVibe.AI server/file-inputs.js pdfText/contentText, MIT, the same organisation), so a statement is read here and
++ * never leaves Finance.
++ *
++ * pdfText(buffer) → { pages: [text] } | { pages: [], reason }
++ *
++ * It reads uncompressed and FlateDecode content streams and the text the Tj, TJ, ' and " operators show; a new line at
++ * T*, Td, TD and ET. An encrypted PDF, a scanned one (images only) or one with a custom font encoding has no readable
++ * text, and says so.
++ */
++const zlib = require('node:zlib');
++
++const MAX_STREAMS = 500;
++const MAX_TEXT_CHARS = 400000;
++
++function pdfText(buffer) {
++ const raw = Buffer.isBuffer(buffer) ? buffer.toString('latin1') : String(buffer || '');
++ if (!raw.startsWith('%PDF')) return { pages: [], reason: 'this is not a PDF' };
++ if (/\/Encrypt\s/.test(raw)) return { pages: [], reason: 'the PDF is encrypted (password protected)' };
++ const pages = [];
++ let total = 0;
++ let seen = 0;
++ const re = /stream\r?\n?([\s\S]*?)\r?\n?endstream/g;
++ let m;
++ while ((m = re.exec(raw)) && seen < MAX_STREAMS) {
++ seen++;
++ const before = raw.slice(Math.max(0, m.index - 400), m.index);
++ let data = Buffer.from(m[1], 'latin1');
++ if (/\/FlateDecode\b/.test(before)) {
++ try { data = zlib.inflateSync(data, { maxOutputLength: 8 * 1024 * 1024 }); } catch { continue; }
++ } else if (/\/Filter\b/.test(before)) {
++ continue; // an image (DCT) or another filter, not text
++ }
++ const text = contentText(data.toString('latin1'));
++ if (text) { pages.push(text); total += text.length; }
++ if (total >= MAX_TEXT_CHARS) break;
++ }
++ if (!pages.length) return { pages: [], reason: 'the PDF has no readable text (it may be scanned pages, or use a custom font encoding)' };
++ return { pages };
++}
++
++/** The text the Tj/TJ/'/" operators show in one content stream. */
++function contentText(stream) {
++ const parts = [];
++ let i = 0;
++ const n = stream.length;
++ const readString = () => {
++ let out = '';
++ let depth = 1;
++ i++;
++ while (i < n && depth > 0) {
++ const c = stream[i++];
++ if (c === '\\') {
++ const d = stream[i++];
++ if (d === 'n') out += '\n';
++ else if (d === 'r') out += '\r';
++ else if (d === 't') out += '\t';
++ else if (d === 'b' || d === 'f') out += ' ';
++ else if (d === '\n' || d === '\r') { if (d === '\r' && stream[i] === '\n') i++; }
++ else if (/[0-7]/.test(d)) {
++ let oct = d;
++ while (oct.length < 3 && /[0-7]/.test(stream[i])) oct += stream[i++];
++ out += String.fromCharCode(parseInt(oct, 8));
++ } else out += d;
++ } else if (c === '(') { depth++; out += c; }
++ else if (c === ')') { depth--; if (depth) out += c; }
++ else out += c;
++ }
++ return out;
++ };
++ while (i < n) {
++ const c = stream[i];
++ if (c === '(') {
++ const s = readString();
++ let j = i;
++ while (j < n && /\s/.test(stream[j])) j++;
++ if (stream.startsWith('Tj', j)) { parts.push(s); i = j + 2; continue; }
++ if (stream.startsWith("'", j) || stream.startsWith('"', j)) { parts.push(`\n${s}`); i = j + 1; continue; }
++ continue;
++ }
++ if (c === '[') {
++ i++;
++ const arr = [];
++ while (i < n && stream[i] !== ']') {
++ if (stream[i] === '(') arr.push(readString());
++ else i++;
++ }
++ i++;
++ const tm = /^\s*TJ/.exec(stream.slice(i, i + 8));
++ if (tm) { parts.push(arr.join('')); i += tm[0].length; }
++ continue;
++ }
++ if (stream.startsWith('T*', i) || stream.startsWith('Td', i) || stream.startsWith('TD', i) || stream.startsWith('ET', i)) {
++ parts.push('\n'); i += 2; continue;
++ }
++ i++;
++ }
++ return parts.join('').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
++}
++
++module.exports = { pdfText };
ddiff --git a/server/statement.js b/server/statement.js
nnew file mode 100644
iindex 0000000..2311f20
---- /dev/null
++++ b/server/statement.js
@@@ -0,0 +1,82 @@
++'use strict';
++/**
++ * A statement's lines → transactions (plan §L.2: "statement PDFs … always free"). A bank or card statement lists one
++ * transaction a line: a date first, then the description, then the amount (and often the running balance last).
++ *
++ * readStatement(text, { today }) → { rows: [{ posted_on, amount_cents, payee, memo: '', category: '', signed }],
++ * signs, year, problem }
++ * signs: 'explicit' when the statement marks money out (a minus, brackets, DR) and in (CR); else 'guessed' (every
++ * amount positive: a word such as deposit, payroll, refund or payment received reads as money in, the rest
++ * as money out). The person checks them in the preview before anything is imported.
++ *
++ * Dates: 2026-11-02, 11/02/2026, 02.11.26, 11/02 (the statement's year), 2 Nov 2026, Nov 2. Day first when any date's
++ * first part is over 12 (or the text uses £ or €), month first otherwise. Summary lines (balances, totals) are skipped.
++ */
++const MONTHS = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, sept: 9, oct: 10, nov: 11, dec: 12 };
++const MON = '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept?|Oct|Nov|Dec)[a-z]*\\.?';
++const DATES = [
++ { re: /^(\d{4})-(\d{1,2})-(\d{1,2})\b/, pick: (m) => ({ y: +m[1], a: +m[2], b: +m[3], iso: true }) },
++ { re: /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4}|\d{2})\b/, pick: (m) => ({ a: +m[1], b: +m[2], y: m[3].length === 2 ? 2000 + +m[3] : +m[3] }) },
++ { re: /^(\d{1,2})[/.-](\d{1,2})(?![/.\-\d])/, pick: (m) => ({ a: +m[1], b: +m[2], y: null }) },
++ { re: new RegExp(`^(\\d{1,2})\\s+${MON}(?:,?\\s+(\\d{4}))?\\b`, 'i'), pick: (m) => ({ d: +m[1], mo: MONTHS[m[2].toLowerCase().slice(0, 3)], y: m[3] ? +m[3] : null }) },
++ { re: new RegExp(`^${MON}\\s+(\\d{1,2})(?:,?\\s+(\\d{4}))?\\b`, 'i'), pick: (m) => ({ d: +m[2], mo: MONTHS[m[1].toLowerCase().slice(0, 3)], y: m[3] ? +m[3] : null }) },
++];
++const MONEY = /(?:^|\s)(-|\()?\s?[$£€]?\s?(\d{1,3}(?:[,\s]\d{3})*|\d+)[.,](\d{2})\)?(?:\s?(CR|DR|-))?(?=\s|$)/gi;
++const SUMMARY = /\b(opening|closing|previous|new|beginning|ending|available|statement)\s+balance\b|\bbalance\s+(forward|brought|carried)\b|^total\b|\bsubtotal\b|\bminimum payment\b|\bpayment due\b/i;
++const INWARD = /\b(deposit|payroll|salary|direct dep|refund|reversal|interest (paid|earned)|payment (received|thank you)|thank you payment|transfer from|credit)\b/i;
++
++const pad = (n) => String(n).padStart(2, '0');
++const realDay = (y, m, d) => { const t = new Date(Date.UTC(y, m - 1, d)); return t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d; };
++
++function readStatement(text, { today = new Date().toISOString().slice(0, 10) } = {}) {
++ const lines = String(text || '').split(/\r?\n/).map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean);
++ // The statement's year, for dates printed without one: the most common 20xx in the text, else this year.
++ const years = {};
++ for (const y of String(text || '').match(/\b20\d{2}\b/g) || []) years[y] = (years[y] || 0) + 1;
++ const year = Number(Object.entries(years).sort((x, y) => y[1] - x[1])[0]?.[0]) || Number(today.slice(0, 4));
++ const found = [];
++ for (const line of lines) {
++ let date = null;
++ let rest = null;
++ for (const f of DATES) {
++ const m = f.re.exec(line);
++ if (m) { date = f.pick(m); rest = line.slice(m[0].length).trim(); break; }
++ }
++ if (!date || !rest) continue;
++ // A second date (posting after transaction date) is not part of the payee.
++ for (const f of DATES) { const m = f.re.exec(rest); if (m) { rest = rest.slice(m[0].length).trim(); break; } }
++ const money = [...rest.matchAll(MONEY)];
++ if (!money.length) continue;
++ // The amount: the last money on the line, or the one before it when the line also ends with the balance.
++ const pick = money.length >= 2 ? money[money.length - 2] : money[money.length - 1];
++ const payee = rest.slice(0, pick.index).replace(/\s+/g, ' ').trim().replace(/[\s:–-]+$/, '');
++ if (!payee || SUMMARY.test(payee)) continue;
++ const cents = Number(pick[2].replace(/[,\s]/g, '')) * 100 + Number(pick[3]);
++ const mark = (pick[4] || '').toUpperCase();
++ const minus = pick[1] === '-' || pick[1] === '(' || mark === 'DR' || mark === '-';
++ const plus = mark === 'CR';
++ found.push({ date, payee: payee.slice(0, 300), cents, minus, plus });
++ }
++ if (!found.length) return { rows: [], signs: 'guessed', year, problem: 'No lines with a date and an amount were found in this statement.' };
++ const dayFirst = /[£€]/.test(String(text || '')) || found.some((f) => f.date.a > 12);
++ const rows = [];
++ for (const f of found) {
++ let y = f.date.y || year, mo, d;
++ if (f.date.iso) { mo = f.date.a; d = f.date.b; }
++ else if (f.date.mo) { mo = f.date.mo; d = f.date.d; }
++ else if (dayFirst) { d = f.date.a; mo = f.date.b; }
++ else { mo = f.date.a; d = f.date.b; }
++ if (!realDay(y, mo, d)) continue;
++ rows.push({ posted_on: `${y}-${pad(mo)}-${pad(d)}`, cents: f.cents, payee: f.payee, minus: f.minus, plus: f.plus });
++ }
++ const explicit = rows.some((r) => r.minus || r.plus);
++ return {
++ signs: explicit ? 'explicit' : 'guessed', year, problem: rows.length ? null : 'No line had a real date.',
++ rows: rows.slice(0, 2000).map((r) => {
++ const inward = explicit ? !r.minus : INWARD.test(r.payee);
++ return { posted_on: r.posted_on, amount_cents: inward ? r.cents : -r.cents, payee: r.payee, memo: '', category: '', signed: explicit };
++ }),
++ };
++}
++
++module.exports = { readStatement };
ddiff --git a/server/views.js b/server/views.js
iindex 08a665c..1867e1b 100644
---- a/server/views.js
++++ b/server/views.js
@@@ -245,6 +245,31 @@ ${error ? `<p class="fin-error" role="alert">${esc(error)}</p>` : ''}${result}${
<p class="fin-note">Roughly: your average month of the last three, repeated from next month. Money to spend is checking, savings and cash, less what cards owe; investments and loans are left out, as are transfers between your accounts. Nothing here moves money.</p>` });
}
++/** A statement PDF's rows to check before importing (v0.11). Nothing is saved until Import. */
++function statementPreview({ account, read, name = '' }) {
++ const rows = read.rows;
++ const guessed = read.signs !== 'explicit';
++ const total = (list) => list.reduce((n, r) => n + r.amount_cents, 0);
++ const list = rows.map((r, i) => `<li class="fin-pick"><label><input type="checkbox" name="take" value="${i}" checked>
++<span class="fin-pick-date">${esc(r.posted_on)}</span><span class="fin-pick-payee">${esc(r.payee)}</span>
++<span class="fin-pick-amount${r.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(r.amount_cents, account.currency))}</span></label></li>`).join('');
++ const ins = rows.filter((r) => r.amount_cents > 0), outs = rows.filter((r) => r.amount_cents < 0);
++ return page({
++ title: 'Check the statement', path: `/accounts/${account.id}`, body: `
++<header class="fin-head"><p class="fin-crumb"><a href="/accounts/${esc(account.id)}">${esc(account.name)}</a></p><h1>Check the statement</h1>
++<p class="fin-sub">${esc(name || 'Your PDF')}: ${rows.length} transaction${rows.length === 1 ? '' : 's'} found, ${esc(money(total(ins), account.currency))} in and ${esc(money(-total(outs), account.currency))} out. Untick any that are not right.</p></header>
++<form class="fin-form" method="post" action="/accounts/${esc(account.id)}/statement/import">
++<input type="hidden" name="rows" value="${esc(JSON.stringify(rows.map((r) => ({ posted_on: r.posted_on, amount_cents: r.amount_cents, payee: r.payee }))))}">
++${guessed ? `<fieldset class="fin-chips"><legend>The PDF does not mark money in and out. Read the amounts as</legend>
++<label class="fin-chip"><input type="radio" name="signs" value="asread" checked><span>As shown (deposits and refunds in)</span></label>
++<label class="fin-chip"><input type="radio" name="signs" value="out"><span>All money out</span></label>
++<label class="fin-chip"><input type="radio" name="signs" value="in"><span>All money in</span></label></fieldset>` : '<input type="hidden" name="signs" value="asread">'}
++<ul class="fin-picks">${list}</ul>
++<p class="fin-actions"><button class="fin-btn fin-btn--primary" type="submit">Import the ticked ones</button><a class="fin-btn" href="/accounts/${esc(account.id)}">Cancel</a></p>
++<p class="fin-note">It was read on openvibe.finance and the PDF was not kept. Importing the same statement twice adds nothing twice.</p>
++</form>` });
++}
++
function rulesPage({ rules, o = {} }) {
return page({
title: 'Your category rules', path: '/rules', body: `
@@@ -280,10 +305,11 @@ ${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 export (CSV, OFX or QFX)</summary>
--<form class="fin-form" method="post" action="/accounts/${esc(account.id)}/import">
--<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>
++<details class="fin-fold"><summary>Import a bank's export (CSV, OFX, QFX or a PDF statement)</summary>
++<form class="fin-form" method="post" action="/accounts/${esc(account.id)}/import" data-fin-statement="/accounts/${esc(account.id)}/statement">
++<p class="fin-note">Banks offer a download as CSV, OFX or QFX (Quicken). Any of them works; importing the same file twice adds nothing twice. A PDF statement is read here, on openvibe.finance, and you check what it found before anything is imported.</p>
++<input type="hidden" name="pdf" value="" data-fin-pdf><input type="hidden" name="name" value="" data-fin-pdf-name>
++<label class="fin-file"><input type="file" accept=".csv,.ofx,.qfx,.pdf,text/csv,text/plain,application/x-ofx,application/pdf" data-fin-file="csv"><span class="fin-btn">Choose a file</span><span class="fin-file-name" data-fin-file-name>No file chosen yet</span></label>
<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>
@@@ -349,4 +375,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, billsPage, goalsPage, aheadPage, lineChart, money, esc, monthName };
++module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, aheadPage, statementPreview, lineChart, money, esc, monthName };
ddiff --git a/test/statement.test.js b/test/statement.test.js
nnew file mode 100644
iindex 0000000..82fd017
---- /dev/null
++++ b/test/statement.test.js
@@@ -0,0 +1,117 @@
++'use strict';
++/**
++ * Statement PDFs (v0.11; server/pdf.js, server/statement.js): a text PDF read here, plain or Flate-compressed; lines with
++ * a date and an amount (a running balance at the end skipped; minus, brackets, DR and CR; dates with and without a year,
++ * day first with £ or a day over 12); balances and totals skipped; amounts that are all positive guessed by their words
++ * and checked by the person; the preview, the ticked rows imported, the same statement twice adding nothing, and the
++ * refusals (not a PDF, no lines, another person's account, a cross-site post).
++ */
++const assert = require('assert');
++const path = require('node:path');
++const zlib = require('node:zlib');
++const crypto = require('node:crypto');
++const { pdfText } = require('../server/pdf');
++const { readStatement } = require('../server/statement');
++
++const esc = (s) => s.replace(/[()\\]/g, (m) => `\\${m}`);
++function pdf(lines, { deflate = false } = {}) {
++ const content = `BT /F1 10 Tf 40 760 Td ${lines.map((l) => `(${esc(l)}) Tj T*`).join(' ')} ET`;
++ const data = deflate ? zlib.deflateSync(Buffer.from(content, 'latin1')) : Buffer.from(content, 'latin1');
++ return Buffer.concat([Buffer.from(`%PDF-1.4\n1 0 obj << /Length ${data.length}${deflate ? ' /Filter /FlateDecode' : ''} >>\nstream\n`, 'latin1'), data, Buffer.from('\nendstream\nendobj\n%%EOF\n', 'latin1')]);
++}
++
++const CARD = ['ACME BANK Statement period Nov 1 - Nov 30, 2026', 'Opening balance 1,000.00', '11/02 CORNER GROCER #44 -23.18 976.82',
++ '11/03 PAYROLL ACME CORP 3,120.00 4,096.82', '11/05 STREAMFLIX (15.99) 4,080.83', 'Nov 7 COFFEE SHOP 4.75 DR', '12 Nov 2026 REFUND SHOES 20.00 CR',
++ 'Closing balance 4,060.08', 'Total fees 0.00'];
++
++// ── The PDF's text ──
++for (const deflate of [false, true]) {
++ const t = pdfText(pdf(CARD, { deflate }));
++ assert.strictEqual(t.pages.length, 1, `deflate ${deflate}`);
++ assert.match(t.pages[0], /11\/05 STREAMFLIX \(15\.99\) 4,080\.83/);
++}
++assert.match(pdfText(Buffer.from('Date,Amount\n')).reason, /not a PDF/);
++assert.match(pdfText(Buffer.from('%PDF-1.4\n/Encrypt 5 0 R\n')).reason, /encrypted/);
++assert.match(pdfText(Buffer.from('%PDF-1.4\n1 0 obj << /Filter /DCTDecode >>\nstream\nxx\nendstream\n')).reason, /no readable text/);
++
++// ── The lines ──
++let r = readStatement(CARD.join('\n'), { today: '2026-11-18' });
++assert.strictEqual(r.signs, 'explicit');
++assert.deepStrictEqual(r.rows.map((x) => [x.posted_on, x.amount_cents, x.payee]), [
++ ['2026-11-02', -2318, 'CORNER GROCER #44'], ['2026-11-03', 312000, 'PAYROLL ACME CORP'], ['2026-11-05', -1599, 'STREAMFLIX'],
++ ['2026-11-07', -475, 'COFFEE SHOP'], ['2026-11-12', 2000, 'REFUND SHOES'],
++], 'the balance at the end is not the amount; balances and totals are skipped');
++r = readStatement('02/11/2026 Tesco £23.18\n15/11/2026 Salary £2,100.00\n20/11/2026 Rent £900.00', { today: '2026-11-18' });
++assert.strictEqual(r.signs, 'guessed');
++assert.deepStrictEqual(r.rows.map((x) => [x.posted_on, x.amount_cents]), [['2026-11-02', -2318], ['2026-11-15', 210000], ['2026-11-20', -90000]], 'day first; a salary reads as money in');
++r = readStatement('2026-11-02 Gym 29.00\nNov 30 2026 Interest paid 1.12', { today: '2026-11-18' });
++assert.deepStrictEqual(r.rows.map((x) => x.amount_cents), [-2900, 112]);
++assert.match(readStatement('Nothing here\nat all', {}).problem, /No lines with a date and an amount/);
++
++(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 BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
++ 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((x) => server.once('listening', x));
++ const base = `http://127.0.0.1:${server.address().port}`;
++ const post = (p, form, { as = ADA, site = 'same-origin' } = {}) => fetch(base + p, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': site, 'x-test-user': as, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString() })
++ .then(async (x) => ({ status: x.status, location: x.headers.get('location'), text: await x.text() }));
++ try {
++ const card = await store.addAccount(ADA, { name: 'Card', kind: 'credit' });
++ const b64 = `data:application/pdf;base64,${pdf(CARD, { deflate: true }).toString('base64')}`;
++ let res = await post(`/accounts/${card.id}/statement`, { pdf: b64, name: 'nov.pdf' });
++ assert.strictEqual(res.status, 200, res.text.slice(0, 300));
++ assert.match(res.text, /Check the statement/);
++ assert.match(res.text, /nov\.pdf: 5 transactions found, \$3,140\.00 in and \$43\.92 out/);
++ assert.strictEqual((res.text.match(/name="take" value="\d+" checked/g) || []).length, 5);
++ assert.doesNotMatch(res.text, /name="signs" value="out"/, 'marked signs need no choice');
++ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_transactions WHERE owner = $1', [ADA])), 0, 'nothing is saved before Import');
++ const rows = /name="rows" value="([^"]*)"/.exec(res.text)[1].replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>');
++
++ const form = new URLSearchParams({ rows, signs: 'asread' });
++ for (const i of [0, 2, 3]) form.append('take', String(i));
++ res = await fetch(`${base}/accounts/${card.id}/statement/import`, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: form.toString() })
++ .then(async (x) => ({ status: x.status, location: x.headers.get('location') }));
++ assert.strictEqual(res.status, 303);
++ assert.match(res.location, /\?m=2026-11&imported=3,0$/, 'only the ticked ones');
++ const saved = await store.transactions(ADA, card.id);
++ assert.deepStrictEqual(saved.map((t) => t.payee).sort(), ['COFFEE SHOP', 'CORNER GROCER #44', 'STREAMFLIX']);
++ res = await fetch(`${base}/accounts/${card.id}/statement/import`, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: form.toString() })
++ .then(async (x) => ({ location: x.headers.get('location') }));
++ assert.match(res.location, /imported=0,3$/, 'the same statement twice adds nothing');
++
++ // All positive: the person chooses how to read them.
++ const plain = `data:application/pdf;base64,${pdf(['11/04/2026 Gym 29.00', '11/06/2026 Books 18.99']).toString('base64')}`;
++ res = await post(`/accounts/${card.id}/statement`, { pdf: plain });
++ assert.match(res.text, /does not mark money in and out/);
++ const plainRows = /name="rows" value="([^"]*)"/.exec(res.text)[1].replace(/&quot;/g, '"');
++ const f2 = new URLSearchParams({ rows: plainRows, signs: 'in' }); f2.append('take', '0'); f2.append('take', '1');
++ await fetch(`${base}/accounts/${card.id}/statement/import`, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': 'same-origin', 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: f2.toString() });
++ assert.ok((await store.transactions(ADA, card.id)).filter((t) => ['Gym', 'Books'].includes(t.payee)).every((t) => t.amount_cents > 0), '"all money in" turns them');
++
++ res = await post(`/accounts/${card.id}/statement`, { pdf: Buffer.from('Date,Amount').toString('base64') });
++ assert.strictEqual(res.status, 422);
++ assert.match(res.text, /could not be read: this is not a PDF/);
++ res = await post(`/accounts/${card.id}/statement`, { pdf: pdf(['Hello there']).toString('base64') });
++ assert.match(res.text, /No lines with a date and an amount/);
++ res = await post(`/accounts/${card.id}/statement`, { pdf: b64 }, { as: BO });
++ assert.strictEqual(res.status, 404, 'never another person\'s account');
++ res = await post(`/accounts/${card.id}/statement`, { pdf: b64 }, { site: 'cross-site' });
++ assert.strictEqual(res.status, 403);
++ const page = await fetch(`${base}/accounts/${card.id}`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());
++ assert.match(page, /accept="\.csv,\.ofx,\.qfx,\.pdf/);
++ assert.match(page, /data-fin-statement="\/accounts\//);
++ } finally {
++ server.close();
++ await close();
++ }
++ console.log('statement: text PDFs read here, lines with a date and an amount, signs marked or chosen, checked before import, never twice');
++})().catch((err) => { console.error(err); process.exit(1); });