openvibers/openvibe.finance testrules.test.js

rules.test.js

main 7.0 KB · 102 lines · javascript

1'use strict';
2/**
3 * Category rules (migrations/0002_rules.sql): "Always" on a transaction's category makes a rule for its payee's words;
4 * the rule categorises the past transactions nobody categorised and every later import, never one the person set;
5 * reference numbers do not matter; the words are sealed; the same words again replace the category; removing a rule
6 * leaves what it did; export carries the rules and delete removes them.
7 */
8const assert = require('assert');
9const path = require('node:path');
10const crypto = require('node:crypto');
11const { createTestDb } = require('openvibe-sdk/testing');
12const { createVault } = require('../server/crypto');
13const { createApp } = require('../server/app');
14const { createStore, matchable } = require('../server/store');
15
16const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
17const SAME = { 'sec-fetch-site': 'same-origin' };
18
19(async () => {
20 assert.strictEqual(matchable('AMAZON MKTPLACE PMTS 1234567 WA'), 'amazon mktplace pmts wa');
21 assert.strictEqual(matchable(' Corner Grocer #22 '), 'corner grocer 22');
22
23 const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
24 const vault = createVault(crypto.randomBytes(32).toString('base64'));
25 const store = createStore({ db, vault });
26 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(); } };
27 const server = createApp({ db, vault, auth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
28 await new Promise((r) => server.once('listening', r));
29 const base = `http://127.0.0.1:${server.address().port}`;
30 const post = async (p, form) => {
31 const r = await fetch(base + p, { method: 'POST', redirect: 'manual', headers: { ...SAME, 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString() });
32 return { status: r.status, location: r.headers.get('location'), text: await r.text() };
33 };
34 let failed = 0;
35 const check = async (name, fn) => { try { await fn(); console.log(` ✓ ${name}`); } catch (e) { failed++; console.log(` ✗ ${name}\n ${e.stack}`); } };
36
37 try {
38 const acc = await store.addAccount(ADA, { name: 'Checking' });
39 await store.importRows(ADA, acc.id, [
40 { posted_on: '2026-11-01', amount_cents: -1299, payee: 'STREAMCO 88812345 CA' },
41 { posted_on: '2026-10-01', amount_cents: -1299, payee: 'STREAMCO 77712345 CA' },
42 { posted_on: '2026-11-02', amount_cents: -5000, payee: 'Corner Grocer' },
43 ]);
44 const list = await store.transactions(ADA, acc.id);
45 const nov = list.find((t) => t.payee.startsWith('STREAMCO 888'));
46
47 await check('Always on a category makes a rule; it categorises the past, whatever the reference number', async () => {
48 const r = await post(`/transactions/${nov.id}/category`, { category: 'Subscriptions', always: 'yes' });
49 assert.strictEqual(r.status, 303, r.text);
50 assert.match(r.location, /ruled=1$/, 'one earlier transaction (October\'s) besides this one');
51 const after = await store.transactions(ADA, acc.id);
52 assert.deepStrictEqual(after.filter((t) => t.payee.startsWith('STREAMCO')).map((t) => [t.category, t.category_from]).sort(), [['Subscriptions', 'rule'], ['Subscriptions', 'you']]);
53 assert.strictEqual(after.find((t) => t.payee === 'Corner Grocer').category, 'Uncategorized', 'another payee is left alone');
54 const rules = await store.rules(ADA);
55 assert.deepStrictEqual(rules.map((r) => [r.match, r.category]), [['streamco ca', 'Subscriptions']]);
56 const row = await db.maybe('SELECT match_enc FROM finance_rules WHERE owner = $1', [ADA]);
57 assert.ok(row.match_enc.startsWith('v1.') && !row.match_enc.includes('streamco'), 'the words are sealed');
58 });
59
60 await check('a later import falls under the rule; a category the file or the person gave stays', async () => {
61 await store.importRows(ADA, acc.id, [
62 { posted_on: '2026-12-01', amount_cents: -1299, payee: 'STREAMCO 99912345 CA' },
63 { posted_on: '2026-12-02', amount_cents: -1299, payee: 'STREAMCO 99912345 CA', category: 'Entertainment' },
64 ]);
65 const dec = await store.transactions(ADA, acc.id, { month: '2026-12' });
66 assert.deepStrictEqual(dec.map((t) => [t.category, t.category_from]).sort(), [['Entertainment', 'file'], ['Subscriptions', 'rule']]);
67 const mine = await store.addTransaction(ADA, acc.id, { posted_on: '2026-12-03', amount_cents: -100, payee: 'STREAMCO gift', category: 'Gifts and giving' });
68 await store.applyRules(ADA);
69 assert.strictEqual((await store.transactions(ADA, acc.id, { month: '2026-12' })).find((t) => t.id === mine.id).category, 'Gifts and giving', 'yours stays yours');
70 });
71
72 await check('the same words again replace the category; the rules page lists them; remove leaves what they did', async () => {
73 const again = await store.addRule(ADA, { match: 'STREAMCO CA', category: 'Entertainment' });
74 assert.strictEqual((await store.rules(ADA)).length, 1);
75 assert.strictEqual((await store.rules(ADA))[0].category, 'Entertainment');
76 assert.strictEqual(again.match, 'streamco ca');
77 const page = await fetch(`${base}/rules`, { headers: { 'x-test-user': ADA } }).then((r) => r.text());
78 assert.match(page, /streamco ca/);
79 assert.match(page, /Entertainment/);
80 const r = await post(`/rules/${again.id}/delete`, {});
81 assert.strictEqual(r.status, 303);
82 assert.deepStrictEqual(await store.rules(ADA), []);
83 assert.strictEqual((await store.transactions(ADA, acc.id, { month: '2026-11' })).find((t) => t.id === nov.id).category, 'Subscriptions', 'what it did stays');
84 await assert.rejects(store.addRule(ADA, { match: 'x', category: 'Fees' }), /few words/);
85 await assert.rejects(store.addRule(ADA, { match: 'corner grocer', category: '' }), /which category/);
86 });
87
88 await check('export carries the rules; delete everything removes them', async () => {
89 await store.addRule(ADA, { match: 'Corner Grocer', category: 'Groceries' });
90 const ex = await store.exportAll(ADA);
91 assert.deepStrictEqual(ex.rules, [{ match: 'corner grocer', category: 'Groceries' }]);
92 await store.removeAll(ADA);
93 assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_rules WHERE owner = $1', [ADA])), 0);
94 });
95 } finally {
96 server.close();
97 await close();
98 }
99 if (failed) { console.log(`${failed} failed`); process.exit(1); }
100 console.log('rules: made from a category, the past and later imports, yours kept, sealed, exported and deleted');
101})().catch((err) => { console.error(err); process.exit(1); });
102