openvibers/openvibe.finance Commits

Receipt photos, read here and checked before adding (v0.12) (#13)

OP OpenVibers committed 13 days ago · b45ed5d724 · 10 files, +265 −6

Plan §L.2 (getting data in: receipt photos, always free). "From a receipt photo" on the account page: the
photo is redrawn at most 2000 px in the browser (its camera data not carried over) and read on this server
by Tesseract (the local reader Vision uses first), from memory to memory: never written, sent or kept
(Tesseract 5.5 with English is on the host). The total (never a subtotal, tax or change), the day and the
store fill the usual add form; what was not clear is said. Nothing is added before "Add it".
test/receipt.test.js (a rendered receipt read for real where Tesseract is installed; the page flow with an
injected reader).

Changes

ddiff --git a/README.md b/README.md
iindex f7a11df..f8c731c 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.11)
++## What it does today (v0.12)
- 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:
@@@ -21,6 +21,8 @@ to connect.
- 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.
++- A receipt photo: read on openvibe.finance by Tesseract, from memory (never written, sent or kept); the store, the
++ day and the total fill the add form, and what was not clear is said, for the person to check before adding it.
- 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.
ddiff --git a/package-lock.json b/package-lock.json
iindex 8668bec..23e05de 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-finance",
-- "version": "0.11.0",
++ "version": "0.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-finance",
-- "version": "0.11.0",
++ "version": "0.12.0",
"license": "AGPL-3.0-only",
"dependencies": {
"@electric-sql/pglite": "^0.5.8",
ddiff --git a/package.json b/package.json
iindex 8411617..448d91c 100644
---- a/package.json
++++ b/package.json
@@@ -1,6 +1,6 @@
{
"name": "openvibe-finance",
-- "version": "0.11.0",
++ "version": "0.12.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 6bb3ec5..c54e2b0 100644
---- a/public/finance.css
++++ b/public/finance.css
@@@ -193,3 +193,12 @@ html[data-ov-motion="off"] .fin-pick input, html[data-ov-motion="off"] .fin-pick
.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; } }
++/* A receipt photo (v0.12). */
++.fin-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
++.fin-receipt { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: 10px 0 4px; }
++.fin-receipt-btn { position: relative; }
++.fin-receipt-said { color: var(--text-secondary, #9aa4b2); font-size: 14px; }
++.fin-receipt.is-busy .fin-receipt-btn { opacity: .6; pointer-events: none; }
++.fin-receipt.is-busy .fin-receipt-said { color: var(--text, #e8ecf3); animation: fin-pulse 1.2s ease-in-out infinite; }
++html[data-ov-motion="off"] .fin-receipt.is-busy .fin-receipt-said { animation: none; }
++@keyframes fin-pulse { 50% { opacity: .55; } }
ddiff --git a/public/finance.js b/public/finance.js
iindex bedd2b2..9e7859e 100644
---- a/public/finance.js
++++ b/public/finance.js
@@@ -32,3 +32,33 @@
reader.readAsText(file);
});
})();
++
++// A receipt photo (v0.12): redrawn at most 2000 px (enough to read, and the camera's own data is not carried over), then
++// sent once for this server to read; nothing is added before the person checks it.
++(function () {
++ document.addEventListener('change', function (e) {
++ var input = e.target;
++ if (!input || !input.matches || !input.matches('input[data-fin-receipt]') || !input.files || !input.files[0]) return;
++ var form = input.closest('form');
++ var out = form && form.querySelector('[data-fin-image]');
++ var said = form && form.querySelector('[data-fin-receipt-said]');
++ var file = input.files[0];
++ if (!out || !/^image\//.test(file.type)) { if (said) said.textContent = 'That is not a photo.'; return; }
++ if (said) said.textContent = 'Reading the receipt…';
++ form.classList.add('is-busy');
++ var url = URL.createObjectURL(file);
++ var img = new Image();
++ img.onload = function () {
++ var scale = Math.min(1, 2000 / Math.max(img.naturalWidth, img.naturalHeight));
++ var c = document.createElement('canvas');
++ c.width = Math.max(1, Math.round(img.naturalWidth * scale));
++ c.height = Math.max(1, Math.round(img.naturalHeight * scale));
++ c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
++ URL.revokeObjectURL(url);
++ out.value = c.toDataURL('image/jpeg', 0.92);
++ form.submit();
++ };
++ img.onerror = function () { URL.revokeObjectURL(url); form.classList.remove('is-busy'); if (said) said.textContent = 'That photo could not be opened.'; };
++ img.src = url;
++ });
++})();
ddiff --git a/server/app.js b/server/app.js
iindex c6a9358..35dbc96 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -24,9 +24,10 @@ const readExport = (text) => (isOfx(text) ? readOfx(text) : readCsv(text));
const { findRecurring } = require('./recurring');
const { pdfText } = require('./pdf');
const { readStatement } = require('./statement');
++const receipts = require('./receipt');
const v = require('./views');
--function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvibe.finance', now = () => new Date() }) {
++function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvibe.finance', now = () => new Date(), readImage = receipts.ocr }) {
const store = createStore({ db, vault });
const app = express();
app.disable('x-powered-by');
@@@ -147,6 +148,26 @@ function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvib
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) }));
}));
++ // A receipt photo (v0.12): read on this server by Tesseract from memory, never written, sent or kept; the add form,
++ // filled in, for the person to check.
++ app.post('/accounts/:id/receipt', 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 m = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=]+)$/.exec(String(req.body.image || ''));
++ if (!m) throw new FinanceError(422, 'finance.receipt.image', 'Choose a photo of the receipt (JPEG, PNG or WebP).');
++ const bytes = Buffer.from(m[2], 'base64');
++ if (bytes.length > 6 * 1024 * 1024) throw new FinanceError(413, 'finance.receipt.too_large', 'That photo is over 6 MB.');
++ let text;
++ try { text = await readImage(bytes); } catch (err) {
++ if (err instanceof receipts.ReceiptError) throw new FinanceError(422, 'finance.receipt.unreadable', err.message);
++ throw err;
++ }
++ const today = now().toISOString().slice(0, 10);
++ res.send(v.receiptPreview({ account, r: receipts.readReceipt(text, { today }), today }));
++ }));
app.post('/accounts/:id/statement/import', pdfForm, handle(async (req, res) => {
const me = who(req);
if (!me) return signIn(req, res);
ddiff --git a/server/receipt.js b/server/receipt.js
nnew file mode 100644
iindex 0000000..37e04d2
---- /dev/null
++++ b/server/receipt.js
@@@ -0,0 +1,89 @@
++'use strict';
++/**
++ * A receipt photo → a transaction to check (plan §L.2: "receipt photos … always free"). The picture is read on this
++ * server by Tesseract (the same local reader OpenVibe Vision uses first), from memory to memory: it is never written to
++ * disk, sent anywhere, or kept. The person checks the store, the day and the total before anything is added.
++ *
++ * ocr(buffer, { timeoutMs }) → text (tesseract stdin stdout; throws ReceiptError when it cannot read)
++ * readReceipt(text, { today }) → { payee, posted_on, amount_cents, found: { payee, date, total } }
++ * amount_cents is money out (negative); null when no total was found. found says which parts were read, so the page
++ * can say what to check.
++ */
++const { spawn } = require('node:child_process');
++
++class ReceiptError extends Error {}
++
++function ocr(buffer, { timeoutMs = 20000, bin = '/usr/bin/tesseract' } = {}) {
++ return new Promise((resolve, reject) => {
++ let child;
++ try {
++ child = spawn(bin, ['stdin', 'stdout', '-l', 'eng', '--psm', '6'], { stdio: ['pipe', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin', OMP_THREAD_LIMIT: '1' } });
++ } catch { return reject(new ReceiptError('The receipt reader is not available on this server.')); }
++ const out = [];
++ let size = 0;
++ const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new ReceiptError('Reading the receipt took too long. Try a closer, sharper photo.')); }, timeoutMs);
++ child.stdout.on('data', (d) => { size += d.length; if (size < 512 * 1024) out.push(d); });
++ child.stderr.on('data', () => {});
++ child.on('error', () => { clearTimeout(timer); reject(new ReceiptError('The receipt reader is not available on this server.')); });
++ child.on('close', (code) => {
++ clearTimeout(timer);
++ if (code !== 0) return reject(new ReceiptError('That photo could not be read. A JPEG or PNG of the whole receipt works best.'));
++ resolve(Buffer.concat(out).toString('utf8'));
++ });
++ child.stdin.on('error', () => {});
++ child.stdin.end(buffer);
++ });
++}
++
++const MONTHS = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
++const MONEY = /(-)?[$£€]?\s?(\d{1,3}(?:[,\s]\d{3})*|\d+)[.,](\d{2})(?!\d)/g;
++const TOTAL = /\b(grand\s+total|total\s+due|amount\s+due|balance\s+due|total)\b/i;
++const NOT_TOTAL = /\b(sub\s*-?\s*total|tax|savings|discount|you\s+saved|items?\s+sold|tip|change)\b/i;
++const NOT_PAYEE = /\b(receipt|welcome|thank|store\s*#|tel|phone|www\.|http|cashier|register|order|invoice|date|time)\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 dateOf(text, today) {
++ const s = String(text || '');
++ const tries = [
++ [/\b(20\d{2})-(\d{1,2})-(\d{1,2})\b/, (m) => [+m[1], +m[2], +m[3]]],
++ [/\b(\d{1,2})[/.-](\d{1,2})[/.-](20\d{2}|\d{2})\b/, (m) => { const y = m[3].length === 2 ? 2000 + +m[3] : +m[3]; return +m[1] > 12 ? [y, +m[2], +m[1]] : [y, +m[1], +m[2]]; }],
++ [/\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?\s+(\d{1,2}),?\s+(20\d{2})\b/i, (m) => [+m[3], MONTHS[m[1].toLowerCase().slice(0, 3)], +m[2]]],
++ [/\b(\d{1,2})\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?,?\s+(20\d{2})\b/i, (m) => [+m[3], MONTHS[m[2].toLowerCase().slice(0, 3)], +m[1]]],
++ ];
++ for (const [re, pick] of tries) {
++ const m = re.exec(s);
++ if (!m) continue;
++ const [y, mo, d] = pick(m);
++ if (realDay(y, mo, d) && `${y}-${pad(mo)}-${pad(d)}` <= today) return `${y}-${pad(mo)}-${pad(d)}`;
++ }
++ return null;
++}
++
++const amountsOf = (line) => [...String(line).matchAll(MONEY)].map((m) => Number(m[2].replace(/[,\s]/g, '')) * 100 + Number(m[3]));
++
++function readReceipt(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 total: the first line that says total (never a subtotal, tax or change) with an amount; else the largest
++ // amount on the receipt.
++ let total = null;
++ for (const l of lines) {
++ if (!TOTAL.test(l) || NOT_TOTAL.test(l)) continue;
++ const a = amountsOf(l);
++ if (a.length) { total = a[a.length - 1]; break; }
++ }
++ let foundTotal = total != null;
++ if (total == null) {
++ const all = lines.flatMap(amountsOf).filter((c) => c > 0 && c < 1e8);
++ if (all.length) total = Math.max(...all);
++ }
++ // The store: the first of the top lines that reads as a name (letters, not an address or a greeting).
++ const payee = lines.slice(0, 6).find((l) => /[A-Za-z]{3,}/.test(l) && !NOT_PAYEE.test(l) && !/^\d/.test(l) && (l.match(/\d/g) || []).length < l.length / 3) || '';
++ const date = dateOf(lines.join('\n'), today);
++ return {
++ payee: payee.slice(0, 60), posted_on: date || today, amount_cents: total == null ? null : -total,
++ found: { payee: Boolean(payee), date: Boolean(date), total: foundTotal },
++ };
++}
++
++module.exports = { ocr, readReceipt, ReceiptError };
ddiff --git a/server/views.js b/server/views.js
iindex f6dedb9..52250b4 100644
---- a/server/views.js
++++ b/server/views.js
@@@ -261,6 +261,25 @@ ${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 receipt photo, read: the add form filled in, with what to check (v0.12). Nothing is saved until Add it. */
++function receiptPreview({ account, r, today }) {
++ const check = [!r.found.payee && 'the store', !r.found.date && 'the day', !r.found.total && 'the amount'].filter(Boolean);
++ const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;
++ return page({
++ title: 'Check the receipt', 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 receipt</h1>
++<p class="fin-sub">${check.length ? `Read from your photo. Check ${check.join(' and ')}: ${check.length === 1 ? 'it was' : 'they were'} not clear.` : 'Read from your photo. Check it, then add it.'}</p></header>${cats}
++<form class="fin-form" method="post" action="/accounts/${esc(account.id)}/transactions">
++<div class="fin-row"><label class="fin-field"><span>Date</span><input type="date" name="posted_on" value="${esc(r.posted_on)}" max="${esc(today)}" required></label>
++<label class="fin-field"><span>Amount</span><input name="amount" inputmode="decimal" required value="${r.amount_cents == null ? '' : (Math.abs(r.amount_cents) / 100).toFixed(2)}" placeholder="12.34" autocomplete="off"${r.found.total ? '' : ' autofocus'}></label></div>
++<input type="hidden" name="direction" value="out">
++<label class="fin-field"><span>Payee</span><input name="payee" maxlength="300" value="${esc(r.payee)}" autocomplete="off"></label>
++<label class="fin-field"><span>Category</span><input name="category" list="fin-cats" maxlength="60" autocomplete="off" placeholder="Groceries"></label>
++<p class="fin-actions"><button class="fin-btn fin-btn--primary" type="submit">Add it</button><a class="fin-btn" href="/accounts/${esc(account.id)}">Cancel</a></p>
++<p class="fin-note">Read on openvibe.finance; the photo was not kept.</p>
++</form>` });
++}
++
/** 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;
@@@ -313,6 +332,10 @@ function accountPage({ account, balance, txns, month, o = {} }) {
${notice(o)}${cats}
<div class="fin-tools">
<details class="fin-fold"><summary>Add a transaction</summary>
++<form class="fin-receipt" method="post" action="/accounts/${esc(account.id)}/receipt">
++<input type="hidden" name="image" value="" data-fin-image>
++<label class="fin-btn fin-receipt-btn"><input type="file" accept="image/*" capture="environment" data-fin-receipt class="fin-sr"><span>From a receipt photo</span></label>
++<span class="fin-receipt-said" role="status" data-fin-receipt-said>Read here; the photo is not kept.</span></form>
<form class="fin-form" method="post" action="/accounts/${esc(account.id)}/transactions">
<div class="fin-row"><label class="fin-field"><span>Date</span><input type="date" name="posted_on" value="${today}" required></label>
<label class="fin-field"><span>Amount</span><input name="amount" inputmode="decimal" required placeholder="12.34" autocomplete="off"></label></div>
@@@ -391,4 +414,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, statementPreview, lineChart, money, esc, monthName };
++module.exports = { page, welcome, home, accountPage, monthPage, dataPage, rulesPage, billsPage, goalsPage, aheadPage, statementPreview, receiptPreview, lineChart, money, esc, monthName };
ddiff --git a/test/fixtures/receipt.png b/test/fixtures/receipt.png
nnew file mode 100644
iindex 0000000..75ecbf3
BBinary files /dev/null and b/test/fixtures/receipt.png differ
ddiff --git a/test/receipt.test.js b/test/receipt.test.js
nnew file mode 100644
iindex 0000000..f2593fc
---- /dev/null
++++ b/test/receipt.test.js
@@@ -0,0 +1,85 @@
++'use strict';
++/**
++ * Receipt photos (v0.12; server/receipt.js): the total (never a subtotal, tax or change), the day, the store; what was
++ * not clear is said; a real picture read by Tesseract (where it is installed); the page: a photo in, the add form
++ * filled in, nothing saved until Add it; refusals (not a photo, unreadable, another person's account, cross-site).
++ */
++const assert = require('assert');
++const fs = require('node:fs');
++const path = require('node:path');
++const crypto = require('node:crypto');
++const { readReceipt, ocr, ReceiptError } = require('../server/receipt');
++
++const TODAY = '2026-11-18';
++let r = readReceipt('CORNER GROCER\n123 Main St, Springfield\nTel 555-0100\n11/14/2026 18:42\nBananas 1.29\nMilk 2% 3.49\nSUBTOTAL 7.77\nTAX 0.62\nTOTAL 8.39\nVISA 8.39\nCHANGE 0.00\nThank you!', { today: TODAY });
++assert.deepStrictEqual(r, { payee: 'CORNER GROCER', posted_on: '2026-11-14', amount_cents: -839, found: { payee: true, date: true, total: true } });
++r = readReceipt('Welcome to\nBean There Coffee\nLatte 4.75\nMuffin 3.25\nNov 17, 2026', { today: TODAY });
++assert.deepStrictEqual([r.payee, r.posted_on, r.found.total], ['Bean There Coffee', '2026-11-17', false], 'no total line: the largest amount, said to check');
++r = readReceipt('THE HARDWARE PLACE\n18/11/2026\nGRAND TOTAL £ 1,204.50', { today: TODAY });
++assert.deepStrictEqual([r.posted_on, r.amount_cents], ['2026-11-18', -120450], 'day first when the day is over 12');
++r = readReceipt('Shop\n12/31/2027\nTOTAL 3.00', { today: TODAY });
++assert.deepStrictEqual([r.posted_on, r.found.date], [TODAY, false], 'a day in the future is not the receipt\'s');
++assert.deepStrictEqual(readReceipt('', { today: TODAY }), { payee: '', posted_on: TODAY, amount_cents: null, found: { payee: false, date: false, total: false } });
++
++(async () => {
++ if (fs.existsSync('/usr/bin/tesseract')) {
++ const text = await ocr(fs.readFileSync(path.join(__dirname, 'fixtures', 'receipt.png')));
++ assert.deepStrictEqual(readReceipt(text, { today: TODAY }), { payee: 'CORNER GROCER', posted_on: '2026-11-14', amount_cents: -839, found: { payee: true, date: true, total: true } }, 'a real picture, read');
++ await assert.rejects(ocr(Buffer.from('not an image')), ReceiptError);
++ } else {
++ console.log('receipt: tesseract is not installed here, the real picture is skipped');
++ }
++
++ 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(); } };
++ let seen = null;
++ const readImage = async (bytes) => {
++ seen = bytes;
++ if (bytes.toString() === 'blurry') throw new ReceiptError('That photo could not be read. A JPEG or PNG of the whole receipt works best.');
++ return 'CORNER GROCER\n11/14/2026\nTOTAL 8.39';
++ };
++ const server = createApp({ db, vault, auth, readImage, 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() }));
++ const photo = (s) => `data:image/jpeg;base64,${Buffer.from(s).toString('base64')}`;
++ try {
++ const acc = await store.addAccount(ADA, { name: 'Checking' });
++ const page = await fetch(`${base}/accounts/${acc.id}`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());
++ assert.match(page, /From a receipt photo/);
++ assert.match(page, /action="\/accounts\/[^"]+\/receipt"/);
++
++ let res = await post(`/accounts/${acc.id}/receipt`, { image: photo('jpeg bytes') });
++ assert.strictEqual(res.status, 200, res.text.slice(0, 200));
++ assert.strictEqual(seen.toString(), 'jpeg bytes', 'the photo reached the reader as bytes');
++ assert.match(res.text, /Check the receipt/);
++ assert.match(res.text, /name="posted_on" value="2026-11-14"/);
++ assert.match(res.text, /name="amount"[^>]*value="8\.39"/);
++ assert.match(res.text, /name="payee"[^>]*value="CORNER GROCER"/);
++ assert.match(res.text, /action="\/accounts\/[^"]+\/transactions"/, 'the usual add form');
++ assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_transactions')), 0, 'nothing is saved before Add it');
++
++ res = await post(`/accounts/${acc.id}/receipt`, { image: photo('blurry') });
++ assert.strictEqual(res.status, 422);
++ assert.match(res.text, /could not be read/);
++ res = await post(`/accounts/${acc.id}/receipt`, { image: 'data:text/html;base64,PGI+' });
++ assert.match(res.text, /Choose a photo of the receipt/);
++ res = await post(`/accounts/${acc.id}/receipt`, { image: photo('x') }, { as: BO });
++ assert.strictEqual(res.status, 404, 'never another person\'s account');
++ res = await post(`/accounts/${acc.id}/receipt`, { image: photo('x') }, { site: 'cross-site' });
++ assert.strictEqual(res.status, 403);
++ } finally {
++ server.close();
++ await close();
++ }
++ console.log('receipt: the total, the day and the store read; a real picture through Tesseract; checked before it is added');
++})().catch((err) => { console.error(err); process.exit(1); });