openvibers/openvibe.finance testrecurring.test.js

recurring.test.js

main 5.5 KB · 82 lines · javascript

1'use strict';
2/**
3 * Recurring payments (server/recurring.js): a subscription whose reference number changes each month, rent, a paycheck
4 * every two weeks and a yearly fee are found with their cadence, usual amount and next date; groceries (amounts all
5 * over the place), one-offs and two sightings are not; a subscription that stopped is overdue. Then /bills and the API
6 * over a person's own data.
7 */
8const assert = require('assert');
9const path = require('node:path');
10const crypto = require('node:crypto');
11const { findRecurring } = require('../server/recurring');
12
13const tx = (posted_on, amount_cents, payee, category = 'Uncategorized') => ({ posted_on, amount_cents, payee, category });
14const monthly = (payee, cents, day, months) => months.map((m) => tx(`2026-${String(m).padStart(2, '0')}-${String(day).padStart(2, '0')}`, cents, payee));
15const days = (start, every, n) => Array.from({ length: n }, (_, i) => new Date(Date.parse(`${start}T00:00:00Z`) + i * every * 86400000).toISOString().slice(0, 10));
16
17const rows = [
18 ...[6, 7, 8, 9, 10, 11].map((m, i) => tx(`2026-${String(m).padStart(2, '0')}-05`, -1599, `STREAMFLIX ${881234 + i * 1111} CA`)),
19 ...monthly('Lakeview Apartments', -145000, 1, [6, 7, 8, 9, 10, 11]),
20 ...days('2026-08-07', 14, 8).map((d) => tx(d, 312000, 'Paycheck ACME Corp')),
21 tx('2024-03-15', -9900, 'Warehouse Club Membership'), tx('2025-03-14', -9900, 'Warehouse Club Membership'), tx('2026-03-16', -10500, 'Warehouse Club Membership'),
22 ...[-8642, -1210, -15433, -2299, -6400, -910].map((c, i) => tx(`2026-11-${String(i * 3 + 1).padStart(2, '0')}`, c, 'Corner Grocer')),
23 tx('2026-10-12', -41220, 'Airline Tickets'),
24 tx('2026-09-01', -999, 'Puzzle App'), tx('2026-10-01', -999, 'Puzzle App'),
25 ...monthly('Old Gym Co', -2900, 20, [4, 5, 6, 7]),
26];
27const found = findRecurring(rows, { today: '2026-11-18' });
28const by = (p) => found.find((r) => r.payee.toLowerCase().startsWith(p.toLowerCase()));
29
30const sub = by('STREAMFLIX');
31assert.ok(sub, 'a subscription whose reference number changes is one series');
32assert.deepStrictEqual([sub.cadence, sub.typical_cents, sub.count, sub.next_on, sub.overdue], ['monthly', 1599, 6, '2026-12-05', false]);
33const rent = by('Lakeview');
34assert.deepStrictEqual([rent.cadence, rent.typical_cents, rent.monthly_cents], ['monthly', 145000, 145000]);
35const pay = by('Paycheck');
36assert.deepStrictEqual([pay.direction, pay.cadence, pay.typical_cents], ['in', 'every two weeks', 312000]);
37assert.strictEqual(pay.monthly_cents, Math.round(312000 * 30.4 / 14));
38const club = by('Warehouse');
39assert.deepStrictEqual([club.cadence, club.typical_cents], ['yearly', 9900]);
40assert.ok(!by('Corner Grocer'), 'groceries are not a bill');
41assert.ok(!by('Airline'), 'a one-off is not');
42assert.ok(!by('Puzzle'), 'two sightings are not enough');
43const gym = by('Old Gym');
44assert.ok(gym && gym.overdue, 'a subscription that stopped is overdue');
45assert.ok(found.indexOf(sub) < found.indexOf(rent) === (sub.next_on < rent.next_on), 'soonest first');
46
47(async () => {
48 const { createTestDb } = require('openvibe-sdk/testing');
49 const { createVault } = require('../server/crypto');
50 const { createStore } = require('../server/store');
51 const { createApp } = require('../server/app');
52 const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
53 const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
54 const vault = createVault(crypto.randomBytes(32).toString('base64'));
55 const store = createStore({ db, vault });
56 const acc = await store.addAccount(ADA, { name: 'Checking' });
57 // Recent rows only (store.recent reads the last 400 days from the database's today).
58 const today = new Date().toISOString().slice(0, 10);
59 const back = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);
60 await store.importRows(ADA, acc.id, [tx(back(95), -1599, 'STREAMFLIX 881001'), tx(back(64), -1599, 'STREAMFLIX 881002'), tx(back(34), -1599, 'STREAMFLIX 881003'), tx(back(3), -1599, 'STREAMFLIX 881004')]);
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 }).listen(0, '127.0.0.1');
63 await new Promise((r) => server.once('listening', r));
64 const base = `http://127.0.0.1:${server.address().port}`;
65 try {
66 const page = await fetch(`${base}/bills`, { headers: { 'x-test-user': ADA } }).then((r) => r.text());
67 assert.match(page, /About \$15\.99 a month/);
68 assert.match(page, /STREAMFLIX 881004/);
69 assert.match(page, /Every month/);
70 const api = await fetch(`${base}/api/v1/recurring`, { headers: { 'x-test-user': ADA } }).then((r) => r.json());
71 assert.strictEqual(api.recurring.length, 1);
72 assert.strictEqual(api.recurring[0].key, undefined, 'the internal key stays inside');
73 const other = await fetch(`${base}/api/v1/recurring`, { headers: { 'x-test-user': 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX' } }).then((r) => r.json());
74 assert.deepStrictEqual(other.recurring, [], 'nobody sees another person\'s');
75 assert.ok(today, 'today');
76 } finally {
77 server.close();
78 await close();
79 }
80 console.log('recurring: subscriptions, rent, paychecks and yearly fees found; groceries and one-offs not; a stopped one overdue');
81})().catch((err) => { console.error(err); process.exit(1); });
82