openvibers/openvibe.finance teststatement.test.js
statement.test.js
| 1 | ; |
| 2 | /** |
| 3 | * Statement PDFs (v0.11; server/pdf.js, server/statement.js): a text PDF read here, plain or Flate-compressed; lines with |
| 4 | * a date and an amount (a running balance at the end skipped; minus, brackets, DR and CR; dates with and without a year, |
| 5 | * day first with £ or a day over 12); balances and totals skipped; amounts that are all positive guessed by their words |
| 6 | * and checked by the person; the preview, the ticked rows imported, the same statement twice adding nothing, and the |
| 7 | * refusals (not a PDF, no lines, another person's account, a cross-site post). |
| 8 | */ |
| 9 | const assert = require('assert'); |
| 10 | const path = require('node:path'); |
| 11 | const zlib = require('node:zlib'); |
| 12 | const crypto = require('node:crypto'); |
| 13 | const { pdfText } = require('../server/pdf'); |
| 14 | const { readStatement } = require('../server/statement'); |
| 15 | |
| 16 | const esc = (s) => s.replace(/[()\\]/g, (m) => `\\${m}`); |
| 17 | function pdf(lines, { deflate = false } = {}) { |
| 18 | const content = `BT /F1 10 Tf 40 760 Td ${lines.map((l) => `(${esc(l)}) Tj T*`).join(' ')} ET`; |
| 19 | const data = deflate ? zlib.deflateSync(Buffer.from(content, 'latin1')) : Buffer.from(content, 'latin1'); |
| 20 | 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')]); |
| 21 | } |
| 22 | |
| 23 | 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', |
| 24 | '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', |
| 25 | 'Closing balance 4,060.08', 'Total fees 0.00']; |
| 26 | |
| 27 | // ── The PDF's text ── |
| 28 | for (const deflate of [false, true]) { |
| 29 | const t = pdfText(pdf(CARD, { deflate })); |
| 30 | assert.strictEqual(t.pages.length, 1, `deflate ${deflate}`); |
| 31 | assert.match(t.pages[0], /11\/05 STREAMFLIX \(15\.99\) 4,080\.83/); |
| 32 | } |
| 33 | assert.match(pdfText(Buffer.from('Date,Amount\n')).reason, /not a PDF/); |
| 34 | assert.match(pdfText(Buffer.from('%PDF-1.4\n/Encrypt 5 0 R\n')).reason, /encrypted/); |
| 35 | assert.match(pdfText(Buffer.from('%PDF-1.4\n1 0 obj << /Filter /DCTDecode >>\nstream\nxx\nendstream\n')).reason, /no readable text/); |
| 36 | |
| 37 | // ── The lines ── |
| 38 | let r = readStatement(CARD.join('\n'), { today: '2026-11-18' }); |
| 39 | assert.strictEqual(r.signs, 'explicit'); |
| 40 | assert.deepStrictEqual(r.rows.map((x) => [x.posted_on, x.amount_cents, x.payee]), [ |
| 41 | ['2026-11-02', -2318, 'CORNER GROCER #44'], ['2026-11-03', 312000, 'PAYROLL ACME CORP'], ['2026-11-05', -1599, 'STREAMFLIX'], |
| 42 | ['2026-11-07', -475, 'COFFEE SHOP'], ['2026-11-12', 2000, 'REFUND SHOES'], |
| 43 | ], 'the balance at the end is not the amount; balances and totals are skipped'); |
| 44 | 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' }); |
| 45 | assert.strictEqual(r.signs, 'guessed'); |
| 46 | 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'); |
| 47 | r = readStatement('2026-11-02 Gym 29.00\nNov 30 2026 Interest paid 1.12', { today: '2026-11-18' }); |
| 48 | assert.deepStrictEqual(r.rows.map((x) => x.amount_cents), [-2900, 112]); |
| 49 | assert.match(readStatement('Nothing here\nat all', {}).problem, /No lines with a date and an amount/); |
| 50 | |
| 51 | (async () => { |
| 52 | const { createTestDb } = require('openvibe-sdk/testing'); |
| 53 | const { createVault } = require('../server/crypto'); |
| 54 | const { createStore } = require('../server/store'); |
| 55 | const { createApp } = require('../server/app'); |
| 56 | const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' }); |
| 57 | const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW'; |
| 58 | const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX'; |
| 59 | const vault = createVault(crypto.randomBytes(32).toString('base64')); |
| 60 | const store = createStore({ db, vault }); |
| 61 | 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(); } }; |
| 62 | const server = createApp({ db, vault, auth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1'); |
| 63 | await new Promise((x) => server.once('listening', x)); |
| 64 | const base = `http://127.0.0.1:${server.address().port}`; |
| 65 | 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() }) |
| 66 | .then(async (x) => ({ status: x.status, location: x.headers.get('location'), text: await x.text() })); |
| 67 | try { |
| 68 | const card = await store.addAccount(ADA, { name: 'Card', kind: 'credit' }); |
| 69 | const b64 = `data:application/pdf;base64,${pdf(CARD, { deflate: true }).toString('base64')}`; |
| 70 | let res = await post(`/accounts/${card.id}/statement`, { pdf: b64, name: 'nov.pdf' }); |
| 71 | assert.strictEqual(res.status, 200, res.text.slice(0, 300)); |
| 72 | assert.match(res.text, /Check the statement/); |
| 73 | assert.match(res.text, /nov\.pdf: 5 transactions found, \$3,140\.00 in and \$43\.92 out/); |
| 74 | assert.strictEqual((res.text.match(/name="take" value="\d+" checked/g) || []).length, 5); |
| 75 | assert.doesNotMatch(res.text, /name="signs" value="out"/, 'marked signs need no choice'); |
| 76 | assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_transactions WHERE owner = $1', [ADA])), 0, 'nothing is saved before Import'); |
| 77 | const rows = /name="rows" value="([^"]*)"/.exec(res.text)[1].replace(/"/g, '"').replace(/&/g, '&').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>'); |
| 78 | |
| 79 | const form = new URLSearchParams({ rows, signs: 'asread' }); |
| 80 | for (const i of [0, 2, 3]) form.append('take', String(i)); |
| 81 | 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() }) |
| 82 | .then(async (x) => ({ status: x.status, location: x.headers.get('location') })); |
| 83 | assert.strictEqual(res.status, 303); |
| 84 | assert.match(res.location, /\?m=2026-11&imported=3,0$/, 'only the ticked ones'); |
| 85 | const saved = await store.transactions(ADA, card.id); |
| 86 | assert.deepStrictEqual(saved.map((t) => t.payee).sort(), ['COFFEE SHOP', 'CORNER GROCER #44', 'STREAMFLIX']); |
| 87 | 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() }) |
| 88 | .then(async (x) => ({ location: x.headers.get('location') })); |
| 89 | assert.match(res.location, /imported=0,3$/, 'the same statement twice adds nothing'); |
| 90 | |
| 91 | // All positive: the person chooses how to read them. |
| 92 | const plain = `data:application/pdf;base64,${pdf(['11/04/2026 Gym 29.00', '11/06/2026 Books 18.99']).toString('base64')}`; |
| 93 | res = await post(`/accounts/${card.id}/statement`, { pdf: plain }); |
| 94 | assert.match(res.text, /does not mark money in and out/); |
| 95 | const plainRows = /name="rows" value="([^"]*)"/.exec(res.text)[1].replace(/"/g, '"'); |
| 96 | const f2 = new URLSearchParams({ rows: plainRows, signs: 'in' }); f2.append('take', '0'); f2.append('take', '1'); |
| 97 | 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() }); |
| 98 | 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'); |
| 99 | |
| 100 | res = await post(`/accounts/${card.id}/statement`, { pdf: Buffer.from('Date,Amount').toString('base64') }); |
| 101 | assert.strictEqual(res.status, 422); |
| 102 | assert.match(res.text, /could not be read: this is not a PDF/); |
| 103 | res = await post(`/accounts/${card.id}/statement`, { pdf: pdf(['Hello there']).toString('base64') }); |
| 104 | assert.match(res.text, /No lines with a date and an amount/); |
| 105 | res = await post(`/accounts/${card.id}/statement`, { pdf: b64 }, { as: BO }); |
| 106 | assert.strictEqual(res.status, 404, 'never another person\'s account'); |
| 107 | res = await post(`/accounts/${card.id}/statement`, { pdf: b64 }, { site: 'cross-site' }); |
| 108 | assert.strictEqual(res.status, 403); |
| 109 | const page = await fetch(`${base}/accounts/${card.id}`, { headers: { 'x-test-user': ADA } }).then((x) => x.text()); |
| 110 | assert.match(page, /accept="\.csv,\.ofx,\.qfx,\.pdf/); |
| 111 | assert.match(page, /data-fin-statement="\/accounts\//); |
| 112 | } finally { |
| 113 | server.close(); |
| 114 | await close(); |
| 115 | } |
| 116 | console.log('statement: text PDFs read here, lines with a date and an amount, signs marked or chosen, checked before import, never twice'); |
| 117 | })().catch((err) => { console.error(err); process.exit(1); }); |
| 118 |