openvibers/openvibe.finance testgoals.test.js

goals.test.js

main 6.2 KB · 85 lines · javascript

1'use strict';
2/**
3 * Goals and debt (migrations/0004, server/plan.js): payoff months and interest, a payment that never covers the
4 * interest, paying more; a goal's amount a month to reach it by its date; goals tracking an account or a hand-kept
5 * amount; a card's rate and payment from the page; only loans and cards take them; export and delete carry them.
6 */
7const assert = require('assert');
8const path = require('node:path');
9const crypto = require('node:crypto');
10const { payoff, faster, perMonth } = require('../server/plan');
11
12assert.deepStrictEqual(payoff({ owed_cents: 500000, apr_bps: 0, payment_cents: 15000 }), { months: 34, interest_cents: 0, never: false }, '$5,000 at 0%, $150 a month');
13const card = payoff({ owed_cents: 500000, apr_bps: 2499, payment_cents: 15000 });
14// The standard amortisation: n = -ln(1 - rP/A) / ln(1 + r) = 57.5 months, about $3,622 of interest.
15assert.deepStrictEqual(card, { months: 58, interest_cents: 362226, never: false }, '$5,000 at 24.99%, $150 a month');
16assert.strictEqual(payoff({ owed_cents: 500000, apr_bps: 2499, payment_cents: 10000 }).never, true, '$100 a month never covers $104 of interest');
17assert.deepStrictEqual(payoff({ owed_cents: 0, apr_bps: 2499, payment_cents: 15000 }), { months: 0, interest_cents: 0, never: false });
18const more = faster({ owed_cents: 500000, apr_bps: 2499, payment_cents: 15000 }, 5000);
19assert.ok(more.months_sooner > 0 && more.interest_saved_cents > 0, 'paying more is sooner and cheaper');
20assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: '2027-11-01', today: '2026-11-18' }), 50000, '$6,000 in 12 months');
21assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 600000, target_on: '2027-11-01', today: '2026-11-18' }), 0, 'reached');
22assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: null, today: '2026-11-18' }), null, 'no date');
23assert.strictEqual(perMonth({ target_cents: 600000, have_cents: 0, target_on: '2026-10-01', today: '2026-11-18' }), null, 'past');
24
25(async () => {
26 const { createTestDb } = require('openvibe-sdk/testing');
27 const { createVault } = require('../server/crypto');
28 const { createStore } = require('../server/store');
29 const { createApp } = require('../server/app');
30 const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
31 const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
32 const vault = createVault(crypto.randomBytes(32).toString('base64'));
33 const store = createStore({ db, vault });
34 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(); } };
35 const server = createApp({ db, vault, auth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
36 await new Promise((r) => server.once('listening', r));
37 const base = `http://127.0.0.1:${server.address().port}`;
38 const post = (p, form, site = 'same-origin') => fetch(base + p, { method: 'POST', redirect: 'manual', headers: { 'sec-fetch-site': site, 'x-test-user': ADA, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString() })
39 .then(async (r) => ({ status: r.status, location: r.headers.get('location'), text: await r.text() }));
40 try {
41 const savings = await store.addAccount(ADA, { name: 'Rainy day', kind: 'savings', opening_cents: 120000 });
42 const visa = await store.addAccount(ADA, { name: 'Visa', kind: 'credit', opening_cents: -500000 });
43 const checking = await store.addAccount(ADA, { name: 'Checking', kind: 'checking' });
44
45 let r = await post('/goals', { name: 'Emergency fund', target: '6,000', target_on: '2027-11-01', account: savings.id });
46 assert.strictEqual(r.status, 303, r.text);
47 r = await post('/goals', { name: 'Trip to Lisbon', target: '1500', account: '' });
48 let goals = await store.goals(ADA);
49 assert.deepStrictEqual(goals.map((g) => [g.name, g.target_cents, g.have_cents]), [['Emergency fund', 600000, 120000], ['Trip to Lisbon', 150000, 0]]);
50 r = await post(`/goals/${goals[1].id}/saved`, { saved: '400' });
51 assert.strictEqual((await store.goals(ADA))[1].have_cents, 40000, 'a hand-kept amount');
52
53 r = await post(`/accounts/${visa.id}/debt`, { apr: '24.99', payment: '150' });
54 assert.strictEqual(r.status, 303, r.text);
55 const acc = (await store.accounts(ADA)).find((a) => a.id === visa.id);
56 assert.deepStrictEqual([acc.apr_bps, acc.payment_cents], [2499, 15000]);
57 r = await post(`/accounts/${checking.id}/debt`, { apr: '5', payment: '10' });
58 assert.strictEqual(r.status, 422, 'a checking account has no rate');
59 assert.match(r.text, /Only a loan or a credit card/);
60 r = await post('/goals', { name: 'x', target: '5' }, 'cross-site');
61 assert.strictEqual(r.status, 403);
62
63 const html = await fetch(`${base}/goals`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());
64 assert.match(html, /\$1,200\.00 of \$6,000\.00/);
65 assert.match(html, /\$400\.00 a month reaches it by November 2027/, '$4,800 left over 12 months');
66 assert.match(html, /Tracks <a href="\/accounts\//);
67 assert.match(html, /\$5,000\.00 owed/);
68 assert.match(html, /Paid off in <b>\d+ (months|years?)/);
69 assert.match(html, /more a month: .* sooner and .* less interest/);
70 assert.match(html, /Change the rate or payment/, 'set terms fold away');
71
72 const ex = await store.exportAll(ADA);
73 assert.strictEqual(ex.goals.length, 2);
74 assert.strictEqual(ex.accounts.find((a) => a.id === visa.id).apr_bps, 2499);
75 await post(`/goals/${goals[1].id}/delete`, {});
76 assert.strictEqual((await store.goals(ADA)).length, 1);
77 await store.removeAll(ADA);
78 assert.strictEqual(Number(await db.value('SELECT count(*) FROM finance_goals WHERE owner = $1', [ADA])), 0);
79 } finally {
80 server.close();
81 await close();
82 }
83 console.log('goals and debt: payoff and interest, never, paying more, a month to reach a goal, the page, export and delete');
84})().catch((err) => { console.error(err); process.exit(1); });
85