openvibers/openvibe.finance serverapp.js

app.js

main 30.1 KB · 415 lines · javascript

1'use strict';
2/**
3 * OpenVibe.Finance (plan §L.2): the pages and the JSON API over one person's accounts and transactions.
4 *
5 * createApp({ db, vault, auth, mcpAuth, baseUrl }) → an Express app
6 * auth: openvibe-sdk/sso's client (router, optionalAuth); tests pass a stand-in that sets req.user.
7 * mcpAuth: a second client that also takes a delegated person token naming finance, used on POST /mcp only
8 * (server/mcp.js); without it /mcp reads the person from a Bearer token of the ordinary client.
9 *
10 * Pages: / (signed out: what it is; signed in: your accounts and this month), /accounts/:id (?m=YYYY-MM), /month,
11 * /data (download or delete everything). API (JSON, the same person, same rules): /api/v1/accounts,
12 * /api/v1/accounts/:id/transactions, /api/v1/accounts/:id/import (text/csv), /api/v1/months/:m, /api/v1/export.
13 * Every write is same-origin (a page form) or a Bearer call; nothing is cached; every answer says noindex.
14 */
15const express = require('express');
16const path = require('node:path');
17const { createStore, FinanceError } = require('./store');
18const { readCsv, readAmount } = require('./csv');
19const { isOfx, readOfx } = require('./ofx');
20const ahead = require('./ahead');
21const { perMonth } = require('./plan');
22/** A bank's export, whichever it is: OFX or QFX by its header, else CSV. */
23const readExport = (text) => (isOfx(text) ? readOfx(text) : readCsv(text));
24const { findRecurring } = require('./recurring');
25const { pdfText } = require('./pdf');
26const { readStatement } = require('./statement');
27const receipts = require('./receipt');
28const v = require('./views');
29
30function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvibe.finance', now = () => new Date(), readImage = receipts.ocr }) {
31 const store = createStore({ db, vault });
32 const app = express();
33 app.disable('x-powered-by');
34 app.set('trust proxy', 'loopback');
35 try {
36 const release = require('openvibe-shared/release').createRelease({ service: 'finance', root: path.join(__dirname, '..') });
37 require('openvibe-shared/metrics').instrument(app, { service: 'finance', release: release.release });
38 app.get('/release.json', release.handler);
39 } catch { /* metrics are optional in tests */ }
40 // Out of the index: everything but the public welcome (GET /) and the crawl files. This header used to go on every
41 // response, the welcome too, and it outweighs the page's own "index, follow": the 11-23 crawl found the home
42 // noindex while its sitemap listed it. A signed-in person's pages (their money) get it again below.
43 const INDEXABLE = new Set(['/', '/robots.txt', '/sitemap.xml', '/llms.txt', '/llms-full.txt']);
44 app.use((req, res, next) => {
45 res.set({ 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin', 'X-Frame-Options': 'DENY' });
46 if (!((req.method === 'GET' || req.method === 'HEAD') && INDEXABLE.has(req.path))) res.set('X-Robots-Tag', 'noindex, nofollow');
47 next();
48 });
49 app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'finance' }));
50 app.get('/api/ready', async (_req, res) => {
51 try { await db.value('SELECT 1'); res.json({ status: 'ok', service: 'finance' }); } catch { res.status(503).json({ status: 'unavailable' }); }
52 });
53 // Every page crawlable, by every bot, AI included (the owner, 11-21: "Everything should be just crawlable"); only the
54 // sign-in plumbing stays out. A signed-out visitor (a crawler) sees the welcome, never anyone's money.
55 const seo = require('openvibe-shared/seo');
56 app.get('/robots.txt', (_req, res) => res.type('text').set('Cache-Control', 'public, max-age=3600').send(seo.robotsTxt({ disallow: ['/auth/'], sitemaps: ['https://openvibe.finance/sitemap.xml'] })));
57 app.get('/sitemap.xml', (_req, res) => res.type('application/xml').set('Cache-Control', 'public, max-age=3600').send(seo.sitemapXml([{ loc: 'https://openvibe.finance/', changefreq: 'weekly', priority: 1.0 }])));
58 app.get('/llms.txt', (_req, res) => res.type('text').set('Cache-Control', 'public, max-age=3600').send([
59 '# OpenVibe.Finance', '',
60 '> Your money, your rules, your data: accounts, imports and a monthly picture, private to you.', '',
61 'A personal finance desk on your OpenVibe account: accounts and balances, CSV imports, the month at a glance, bills, what is ahead, goals and rules. Your data is private to you and exports in full.', '',
62 '## Pages', '',
63 '- [OpenVibe.Finance](https://openvibe.finance/): what it does, and the way in with your OpenVibe account', '',
64 '## Optional', '',
65 '- [Full text (llms-full.txt)](https://openvibe.finance/llms-full.txt): the page above as words', '',
66 ].join('\n')));
67 // The full text for language models (SEO-33): the welcome page llms.txt lists, as Markdown from its own render
68 // (11-28: /llms-full.txt was a 404, tools/llms-check.js). Signed out, as a crawler sees it: never anyone's money.
69 app.get('/llms-full.txt', (_req, res) => {
70 const words = require('openvibe-shared/agent-layer').markdownTwin({ html: v.welcome(), canonical: 'https://openvibe.finance/' }).replace(/^---[\s\S]*?\n---\n/, '').trim();
71 res.type('text').set('Cache-Control', 'public, max-age=3600').send(seo.llmsFull({
72 site: { name: 'OpenVibe.Finance', url: 'https://openvibe.finance' },
73 summary: 'Your money, your rules, your data: accounts, imports and a monthly picture, private to you.',
74 sections: [{ title: 'OpenVibe.Finance', url: '/', body: words }],
75 }));
76 });
77 app.use(express.static(path.join(__dirname, '..', 'public'), { maxAge: '1h' }));
78 app.use('/shared', require('openvibe-shared/serve').handler());
79 if (auth) app.use('/auth', auth.router(express));
80 // POST /mcp (server/mcp.js), before the pages' sign-in: a Bearer token only (never a cookie), which may be a
81 // delegated person token for this service (mcpAuth); the pages and the API below never take one.
82 const finMcp = require('./mcp').createMcp({ store, aheadFor: (me, q) => aheadFor(me, q), now });
83 const bearerOnly = (req, _res, next) => { if (!/^Bearer\s+\S/i.test(String(req.get('authorization') || ''))) { delete req.headers.cookie; req.user = undefined; } next(); };
84 const mcpWho = mcpAuth || auth;
85 app.post('/mcp', express.json({ limit: '5mb' }), bearerOnly, (req, res, next) => (mcpWho && /^Bearer\s/i.test(String(req.get('authorization') || '')) ? mcpWho.optionalAuth()(req, res, next) : next()),
86 (req, res, next) => { res.set('Cache-Control', 'private, no-store'); Promise.resolve(finMcp.handler(req, res)).catch(next); });
87 app.all('/mcp', (_req, res) => res.status(405).set('Allow', 'POST').json({ error: 'POST a JSON-RPC request.' }));
88 app.use(auth ? auth.optionalAuth() : (_req, _res, next) => next());
89 app.use((req, res, next) => {
90 res.set('Cache-Control', 'private, no-store');
91 if (req.user) res.set('X-Robots-Tag', 'noindex, nofollow'); // a signed-in page shows someone's money
92 next();
93 });
94
95 // The pages and the API: the person's own sign-in only. A delegated token (something acting for them) is for /mcp.
96 const { isDelegated } = require('openvibe-sdk/auth/delegated');
97 const who = (req) => (req.user && !isDelegated(req.user) && /^usr_/.test(String(req.user.subject_id || '')) ? String(req.user.subject_id) : null);
98 const own = new URL(baseUrl).origin;
99 const sameOrigin = (req) => {
100 if (/^Bearer\s/i.test(String(req.get('authorization') || ''))) return true;
101 const site = req.get('sec-fetch-site');
102 if (site) return site === 'same-origin';
103 const origin = req.get('origin');
104 return !origin || origin === own;
105 };
106 const form = express.urlencoded({ extended: false, limit: '4mb' });
107 const handle = (fn) => async (req, res, next) => {
108 try { await fn(req, res); } catch (err) {
109 // Under the /api/v1 router req.path is relative to it: the mount (baseUrl) says it is the API.
110 if (err instanceof FinanceError) return `${req.baseUrl}${req.path}`.startsWith('/api/') ? res.status(err.status).json({ error: err.message, code: err.code }) : res.status(err.status).send(v.page({ title: 'Something is wrong', body: `<p class="fin-error" role="alert">${v.esc(err.message)}</p><p><a href="/">Back</a></p>` }));
111 next(err);
112 }
113 };
114 const signIn = (req, res) => res.redirect(303, `/auth/login?next=${encodeURIComponent(req.originalUrl)}`);
115 const thisMonth = () => now().toISOString().slice(0, 7);
116 const monthOf = (q) => (/^\d{4}-(0[1-9]|1[0-2])$/.test(String(q || '')) ? String(q) : thisMonth());
117 const said = (q) => {
118 if (q.imported) { const [a, s] = String(q.imported).split(','); return `Imported ${Number(a) || 0} new transaction${Number(a) === 1 ? '' : 's'}${Number(s) ? `; ${Number(s)} already here` : ''}.`; }
119 if (q.ruled != null) return `Rule made. It also put ${Number(q.ruled) || 0} earlier transaction${Number(q.ruled) === 1 ? '' : 's'} in that category.`;
120 if (q.goal) return 'Goal added.';
121 if (q.debt) return 'Saved.';
122 if (q.budgeted) return 'Budget saved.';
123 if (q.unbudgeted) return 'Budget removed.';
124 if (q.added) return 'Added.';
125 if (q.removed) return 'Rule removed. What it categorised stays as it is.';
126 if (q.deleted) return 'Everything is deleted.';
127 return '';
128 };
129 /** A typed amount and its direction → signed cents, or null. */
130 const amountOf = (text, direction) => { const c = readAmount(text); return c == null ? null : (direction === 'in' ? Math.abs(c) : -Math.abs(c)); };
131
132 // ── Pages ──
133 app.get('/', handle(async (req, res) => {
134 const me = who(req);
135 if (!me) return res.send(v.welcome());
136 res.send(v.home({ accounts: await store.accounts(me), month: await store.month(me, thisMonth()), o: { said: said(req.query) } }));
137 }));
138 app.post('/accounts', form, handle(async (req, res) => {
139 const me = who(req);
140 if (!me) return signIn(req, res);
141 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
142 const opening = String(req.body.opening || '').trim() ? readAmount(req.body.opening) : 0;
143 if (opening == null) return res.status(422).send(v.home({ accounts: await store.accounts(me), month: await store.month(me, thisMonth()), o: { error: 'The opening balance is not a number.' } }));
144 const acc = await store.addAccount(me, { name: req.body.name, kind: req.body.kind, currency: req.body.currency, opening_cents: opening });
145 res.redirect(303, `/accounts/${acc.id}?added=1`);
146 }));
147 app.get('/accounts/:id', handle(async (req, res) => {
148 const me = who(req);
149 if (!me) return signIn(req, res);
150 const account = await store.account(me, req.params.id);
151 if (!account) return res.status(404).send(v.page({ title: 'No such account', body: '<h1>No such account of yours</h1><p><a href="/">Your money</a></p>' }));
152 const month = monthOf(req.query.m);
153 const all = (await store.accounts(me)).find((a) => a.id === account.id);
154 res.send(v.accountPage({ account, balance: all ? all.balance_cents : account.opening_cents, txns: await store.transactions(me, account.id, { month }), month, o: { said: said(req.query) } }));
155 }));
156 app.post('/accounts/:id/transactions', form, handle(async (req, res) => {
157 const me = who(req);
158 if (!me) return signIn(req, res);
159 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
160 const cents = amountOf(req.body.amount, req.body.direction);
161 if (cents == null) throw new FinanceError(422, 'finance.transaction.amount', 'The amount is not a number.');
162 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 });
163 res.redirect(303, `/accounts/${encodeURIComponent(req.params.id)}?m=${t.posted_on.slice(0, 7)}&added=1`);
164 }));
165 // A statement PDF (v0.11): read here, never sent anywhere; the person checks the rows before anything is imported.
166 const pdfForm = express.urlencoded({ extended: false, limit: '9mb' });
167 app.post('/accounts/:id/statement', pdfForm, handle(async (req, res) => {
168 const me = who(req);
169 if (!me) return signIn(req, res);
170 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
171 const account = await store.account(me, req.params.id);
172 if (!account) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
173 const b64 = String(req.body.pdf || '').replace(/^data:[^,]*,/, '');
174 const bytes = Buffer.from(b64, 'base64');
175 if (!bytes.length) throw new FinanceError(422, 'finance.statement.empty', 'Choose a statement PDF first.');
176 if (bytes.length > 6 * 1024 * 1024) throw new FinanceError(413, 'finance.statement.too_large', 'That PDF is over 6 MB.');
177 const text = pdfText(bytes);
178 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.`);
179 const read = readStatement(text.pages.join('\n'), { today: now().toISOString().slice(0, 10) });
180 if (read.problem) throw new FinanceError(422, 'finance.statement.no_rows', `${read.problem} Your bank's CSV, OFX or QFX download works too.`);
181 res.send(v.statementPreview({ account, read, name: String(req.body.name || '').slice(0, 120) }));
182 }));
183 // A receipt photo (v0.12): read on this server by Tesseract from memory, never written, sent or kept; the add form,
184 // filled in, for the person to check.
185 app.post('/accounts/:id/receipt', pdfForm, handle(async (req, res) => {
186 const me = who(req);
187 if (!me) return signIn(req, res);
188 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
189 const account = await store.account(me, req.params.id);
190 if (!account) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
191 const m = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=]+)$/.exec(String(req.body.image || ''));
192 if (!m) throw new FinanceError(422, 'finance.receipt.image', 'Choose a photo of the receipt (JPEG, PNG or WebP).');
193 const bytes = Buffer.from(m[2], 'base64');
194 if (bytes.length > 6 * 1024 * 1024) throw new FinanceError(413, 'finance.receipt.too_large', 'That photo is over 6 MB.');
195 let text;
196 try { text = await readImage(bytes); } catch (err) {
197 if (err instanceof receipts.ReceiptError) throw new FinanceError(422, 'finance.receipt.unreadable', err.message);
198 throw err;
199 }
200 const today = now().toISOString().slice(0, 10);
201 res.send(v.receiptPreview({ account, r: receipts.readReceipt(text, { today }), today }));
202 }));
203 app.post('/accounts/:id/statement/import', pdfForm, handle(async (req, res) => {
204 const me = who(req);
205 if (!me) return signIn(req, res);
206 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
207 let rows;
208 try { rows = JSON.parse(String(req.body.rows || '[]')); } catch { rows = null; }
209 if (!Array.isArray(rows) || !rows.length || rows.length > 2000) throw new FinanceError(422, 'finance.statement.rows', 'Read the PDF again.');
210 const take = new Set([].concat(req.body.take || []).map((x) => Number(x)));
211 const turn = String(req.body.signs || 'asread');
212 const chosen = rows.map((r, i) => ({ r, i })).filter(({ i }) => take.has(i)).map(({ r }) => {
213 const cents = Number(r && r.amount_cents);
214 if (!Number.isSafeInteger(cents)) throw new FinanceError(422, 'finance.statement.rows', 'Read the PDF again.');
215 return { posted_on: String(r.posted_on || ''), payee: String(r.payee || ''), memo: '', category: '',
216 amount_cents: turn === 'out' ? -Math.abs(cents) : turn === 'in' ? Math.abs(cents) : cents };
217 });
218 if (!chosen.length) throw new FinanceError(422, 'finance.statement.none', 'Tick at least one transaction to import.');
219 const out = await store.importRows(me, req.params.id, chosen);
220 const latest = chosen.map((r) => r.posted_on).sort().pop();
221 res.redirect(303, `/accounts/${encodeURIComponent(req.params.id)}?m=${latest.slice(0, 7)}&imported=${out.added},${out.skipped}`);
222 }));
223 app.post('/accounts/:id/import', form, handle(async (req, res) => {
224 const me = who(req);
225 if (!me) return signIn(req, res);
226 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
227 const read = readExport(req.body.csv);
228 if (read.problem) throw new FinanceError(422, 'finance.import.unreadable', read.problem);
229 const out = await store.importRows(me, req.params.id, read.rows);
230 const latest = read.rows.map((r) => r.posted_on).sort().pop();
231 res.redirect(303, `/accounts/${encodeURIComponent(req.params.id)}?m=${latest.slice(0, 7)}&imported=${out.added},${out.skipped}`);
232 }));
233 app.post('/transactions/:id/category', form, handle(async (req, res) => {
234 const me = who(req);
235 if (!me) return signIn(req, res);
236 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
237 const t = await store.setCategory(me, req.params.id, req.body.category);
238 let ruled = '';
239 if (req.body.always === 'yes' && t.payee && t.category !== 'Uncategorized') ruled = `&ruled=${(await store.addRule(me, { match: t.payee, category: t.category })).applied}`;
240 res.redirect(303, `/accounts/${encodeURIComponent(t.account_id)}?m=${t.posted_on.slice(0, 7)}${ruled}`);
241 }));
242 app.get('/month', handle(async (req, res) => {
243 const me = who(req);
244 if (!me) return signIn(req, res);
245 res.send(v.monthPage({ m: await store.month(me, monthOf(req.query.m)), budgets: await store.budgets(me), o: { said: said(req.query) } }));
246 }));
247 app.get('/bills', handle(async (req, res) => {
248 const me = who(req);
249 if (!me) return signIn(req, res);
250 const today = now().toISOString().slice(0, 10);
251 res.send(v.billsPage({ found: findRecurring(await store.recent(me), { today }), today }));
252 }));
253 const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
254 const addMonths = (m, by) => { const d = new Date(`${m}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() + by); return d.toISOString().slice(0, 7); };
255 /** The question asked (all optional): a one-off cost in a month, a monthly change from a month. → the ask, or throws. */
256 function readAsk(q, months) {
257 const amount = (text, what) => {
258 const t = String(text || '').trim();
259 if (!t) return 0;
260 const c = readAmount(t);
261 if (c == null) throw new FinanceError(422, 'finance.ahead.amount', `${what} is not a number.`);
262 return Math.abs(c);
263 };
264 const when = (text, what) => {
265 const t = String(text || '').trim();
266 if (!t) return null;
267 if (!MONTH_RE.test(t)) throw new FinanceError(422, 'finance.ahead.month', `${what} is a month (YYYY-MM).`);
268 if (t > months[months.length - 1]) throw new FinanceError(422, 'finance.ahead.month', `${what} is within the next twelve months.`);
269 return t < months[0] ? months[0] : t;
270 };
271 const change = amount(q.change, 'The monthly change');
272 return {
273 cost_cents: amount(q.cost, 'The cost'), cost_on: when(q.cost_on, 'When it is paid'),
274 change_cents: q.dir === 'in' ? change : -change, change_from: when(q.from, 'When the change starts'),
275 };
276 }
277 /** Net worth over the last twelve months and the average month repeated over the next twelve, with the ask. */
278 async function aheadFor(me, q = {}) {
279 const today = now().toISOString().slice(0, 10), m = today.slice(0, 7);
280 const next = Array.from({ length: 12 }, (_, i) => addMonths(m, i + 1));
281 const data = await store.ahead(me);
282 // The line starts where the data does (an opening balance is "before the first transaction", not a year ago).
283 const firstMove = data.moves.reduce((lo, x) => (x.month < lo ? x.month : lo), m);
284 const past = Array.from({ length: 12 }, (_, i) => addMonths(m, i - 11)).filter((pm) => pm >= firstMove);
285 const recent = [];
286 for (const pm of [addMonths(m, -3), addMonths(m, -2), addMonths(m, -1)]) recent.push(await store.month(me, pm));
287 const avg = ahead.averageMonth(recent);
288 // What can be spent: checking, savings and cash, less what the cards owe (they are paid from it).
289 const spendable = data.accounts.reduce((n, a) => n + (['checking', 'savings', 'cash'].includes(a.kind) ? a.balance_cents : a.kind === 'credit' ? Math.min(0, a.balance_cents) : 0), 0);
290 let ask = null, error = null;
291 try { ask = readAsk(q, next); } catch (err) { if (!(err instanceof FinanceError)) throw err; error = err.message; }
292 const asked = Boolean(ask && (ask.cost_cents || ask.change_cents));
293 const goalsNeed = (await store.goals(me)).reduce((n, g) => n + (perMonth({ target_cents: g.target_cents, have_cents: g.have_cents, target_on: g.target_on, today }) || 0), 0);
294 return {
295 net_worth: ahead.history({ accounts: data.accounts, moves: data.moves, months: past }),
296 average: avg, spendable_cents: spendable, goals_need_cents: goalsNeed, has_accounts: data.accounts.length > 0,
297 asked, ask, error,
298 plan: avg.months.length ? ahead.whatIf({ start_cents: spendable, income_cents: avg.income_cents, spending_cents: avg.spending_cents, months: next, ...(asked ? ask : {}) }) : null,
299 };
300 }
301 app.get('/ahead', handle(async (req, res) => {
302 const me = who(req);
303 if (!me) return signIn(req, res);
304 res.send(v.aheadPage({ ...(await aheadFor(me, req.query)), q: req.query }));
305 }));
306 app.get('/goals', handle(async (req, res) => {
307 const me = who(req);
308 if (!me) return signIn(req, res);
309 res.send(v.goalsPage({ goals: await store.goals(me), accounts: await store.accounts(me), today: now().toISOString().slice(0, 10), o: { said: said(req.query) } }));
310 }));
311 const writer = (fn) => [form, handle(async (req, res) => {
312 const me = who(req);
313 if (!me) return signIn(req, res);
314 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
315 await fn(me, req, res);
316 })];
317 const cents = (text, what) => { const c = readAmount(text); if (c == null) throw new FinanceError(422, 'finance.amount', `${what} is not a number.`); return Math.abs(c); };
318 app.post('/goals', ...writer(async (me, req, res) => {
319 await store.addGoal(me, { name: req.body.name, target_cents: cents(req.body.target, 'The amount'), target_on: req.body.target_on || null, account_id: req.body.account || null });
320 res.redirect(303, '/goals?goal=1');
321 }));
322 app.post('/goals/:id/saved', ...writer(async (me, req, res) => { await store.setGoalSaved(me, req.params.id, cents(req.body.saved, 'Saved so far')); res.redirect(303, '/goals'); }));
323 app.post('/goals/:id/delete', ...writer(async (me, req, res) => { await store.removeGoal(me, req.params.id); res.redirect(303, '/goals'); }));
324 app.post('/accounts/:id/debt', ...writer(async (me, req, res) => {
325 const aprText = String(req.body.apr || '').trim(), payText = String(req.body.payment || '').trim();
326 const apr = aprText ? Math.round(Number(aprText.replace('%', '')) * 100) : null;
327 if (aprText && !Number.isFinite(apr)) throw new FinanceError(422, 'finance.debt.rate', 'The rate is not a number.');
328 await store.setDebt(me, req.params.id, { apr_bps: apr, payment_cents: payText ? cents(payText, 'The payment') : null });
329 res.redirect(303, '/goals?debt=1');
330 }));
331 app.get('/rules', handle(async (req, res) => {
332 const me = who(req);
333 if (!me) return signIn(req, res);
334 res.send(v.rulesPage({ rules: await store.rules(me), o: { said: said(req.query) } }));
335 }));
336 app.post('/rules/:id/delete', form, handle(async (req, res) => {
337 const me = who(req);
338 if (!me) return signIn(req, res);
339 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
340 await store.removeRule(me, req.params.id);
341 res.redirect(303, '/rules?removed=1');
342 }));
343 app.post('/budgets', form, handle(async (req, res) => {
344 const me = who(req);
345 if (!me) return signIn(req, res);
346 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
347 const text = String(req.body.amount || '').trim();
348 const cents = text ? readAmount(text) : null;
349 if (text && cents == null) throw new FinanceError(422, 'finance.budget.amount', 'The budget is not a number.');
350 await store.setBudget(me, req.body.category, cents == null ? null : Math.abs(cents));
351 const back = /^\d{4}-(0[1-9]|1[0-2])$/.test(String(req.body.back || '')) ? String(req.body.back) : thisMonth();
352 res.redirect(303, `/month?m=${back}&${cents ? 'budgeted' : 'unbudgeted'}=1`);
353 }));
354 app.get('/data', handle(async (req, res) => {
355 if (!who(req)) return signIn(req, res);
356 res.send(v.dataPage({ o: { said: said(req.query) } }));
357 }));
358 app.get('/data/export', handle(async (req, res) => {
359 const me = who(req);
360 if (!me) return signIn(req, res);
361 res.set('Content-Disposition', `attachment; filename="openvibe-finance-${thisMonth()}.json"`);
362 res.json(await store.exportAll(me));
363 }));
364 app.post('/data/delete', form, handle(async (req, res) => {
365 const me = who(req);
366 if (!me) return signIn(req, res);
367 if (!sameOrigin(req)) return res.status(403).send('A change must come from openvibe.finance itself.');
368 if (req.body.sure !== 'yes') return res.status(422).send(v.dataPage({ o: { error: 'Tick the box to say you are sure.' } }));
369 await store.removeAll(me);
370 res.redirect(303, '/data?deleted=1');
371 }));
372
373 // ── API (JSON) ──
374 const api = express.Router();
375 api.use((req, res, next) => { if (!who(req)) return res.status(401).json({ error: 'Sign in first.', code: 'finance.person' }); if (req.method !== 'GET' && !sameOrigin(req)) return res.status(403).json({ error: 'Cross-site writes are refused.', code: 'finance.cross_site' }); next(); });
376 api.get('/accounts', handle(async (req, res) => res.json({ accounts: await store.accounts(who(req)) })));
377 api.post('/accounts', express.json({ limit: '16kb' }), handle(async (req, res) => res.status(201).json(await store.addAccount(who(req), req.body || {}))));
378 api.get('/accounts/:id/transactions', handle(async (req, res) => {
379 if (!(await store.account(who(req), req.params.id))) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
380 res.json({ transactions: await store.transactions(who(req), req.params.id, { month: req.query.m ? String(req.query.m) : null }) });
381 }));
382 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 || {}))));
383 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) => {
384 const read = readExport(typeof req.body === 'string' ? req.body : '');
385 if (read.problem) throw new FinanceError(422, 'finance.import.unreadable', read.problem);
386 res.status(201).json({ ...(await store.importRows(who(req), req.params.id, read.rows)), unreadable: read.skipped.slice(0, 50) });
387 }));
388 api.get('/months/:m', handle(async (req, res) => res.json(await store.month(who(req), req.params.m))));
389 api.get('/rules', handle(async (req, res) => res.json({ rules: await store.rules(who(req)) })));
390 api.get('/budgets', handle(async (req, res) => res.json({ budgets: await store.budgets(who(req)) })));
391 api.get('/goals', handle(async (req, res) => res.json({ goals: await store.goals(who(req)) })));
392 api.get('/net-worth', handle(async (req, res) => { const a = await aheadFor(who(req)); res.json({ net_worth: a.net_worth }); }));
393 api.get('/what-if', handle(async (req, res) => {
394 const a = await aheadFor(who(req), req.query);
395 if (a.error) throw new FinanceError(422, 'finance.ahead.ask', a.error);
396 res.json({ average: a.average, spendable_cents: a.spendable_cents, goals_need_cents: a.goals_need_cents, ask: a.asked ? a.ask : null, plan: a.plan });
397 }));
398 api.post('/goals', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addGoal(who(req), req.body || {}))));
399 api.put('/budgets/:category', express.json({ limit: '2kb' }), handle(async (req, res) => {
400 const cents = req.body && req.body.monthly_cents;
401 res.json({ budget: await store.setBudget(who(req), decodeURIComponent(req.params.category), cents == null ? null : Number(cents)) });
402 }));
403 api.get('/recurring', handle(async (req, res) => res.json({ recurring: findRecurring(await store.recent(who(req)), { today: now().toISOString().slice(0, 10) }).map(({ key, ...r }) => r) })));
404 api.post('/rules', express.json({ limit: '4kb' }), handle(async (req, res) => res.status(201).json(await store.addRule(who(req), req.body || {}))));
405 api.delete('/rules/:id', handle(async (req, res) => { await store.removeRule(who(req), req.params.id); res.status(204).end(); }));
406 api.get('/export', handle(async (req, res) => res.json(await store.exportAll(who(req)))));
407 app.use('/api/v1', api);
408
409 app.use((_req, res) => res.status(404).send(v.page({ title: 'Not here', body: '<h1>Not here</h1><p><a href="/">Your money</a></p>' })));
410 app.use((err, _req, res, _next) => { console.error('[finance]', err && err.message); res.status(500).send('Something went wrong on our side.'); });
411 return app;
412}
413
414module.exports = { createApp };
415