openvibers/openvibe.finance serverrecurring.js

recurring.js

main 3.8 KB · 71 lines · javascript

1'use strict';
2/**
3 * Recurring payments and income, found in a person's own transactions (plan §L.2: "recurring detection and the bill
4 * calendar"). Nothing is stored: it is worked out from the rows each time, in memory, for their owner.
5 *
6 * findRecurring(transactions, { today }) → [{ key, payee, direction, cadence, every_days, typical_cents, count,
7 * last_on, next_on, monthly_cents, overdue }]
8 *
9 * A series is one payee (its words, with reference numbers dropped: store.matchable) going the same way (in or out),
10 * seen at least three times, its amounts within 20% of their median and its gaps steady around a week, two weeks,
11 * a month, a quarter or a year. The next date is the last one plus the usual gap; a series whose next date is more than
12 * half a gap behind is "overdue" (maybe cancelled, maybe late).
13 */
14const { matchable } = require('./store');
15
16const CADENCES = [
17 { name: 'weekly', days: 7, tolerance: 2 },
18 { name: 'every two weeks', days: 14, tolerance: 3 },
19 { name: 'monthly', days: 30.4, tolerance: 5 },
20 { name: 'quarterly', days: 91, tolerance: 12 },
21 { name: 'yearly', days: 365, tolerance: 20 },
22];
23const DAY_MS = 86400000;
24const dayNum = (iso) => Math.round(Date.parse(`${iso}T00:00:00Z`) / DAY_MS);
25const isoOf = (n) => new Date(n * DAY_MS).toISOString().slice(0, 10);
26const median = (xs) => { const s = [...xs].sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
27
28function findRecurring(transactions, { today = new Date().toISOString().slice(0, 10) } = {}) {
29 const groups = new Map();
30 for (const t of transactions) {
31 const words = matchable(t.payee);
32 if (!words || !t.amount_cents) continue;
33 const key = `${t.amount_cents < 0 ? 'out' : 'in'}|${words}`;
34 if (!groups.has(key)) groups.set(key, []);
35 groups.get(key).push(t);
36 }
37 const now = dayNum(today);
38 const out = [];
39 for (const [key, list] of groups) {
40 if (list.length < 3) continue;
41 const rows = [...list].sort((a, b) => a.posted_on.localeCompare(b.posted_on));
42 const amounts = rows.map((r) => Math.abs(r.amount_cents));
43 const typical = median(amounts);
44 // Amounts that wander more than 20% from the usual one are not a bill (a grocery store is not a subscription).
45 const steady = rows.filter((r) => Math.abs(Math.abs(r.amount_cents) - typical) <= typical * 0.2);
46 if (steady.length < 3) continue;
47 const days = [...new Set(steady.map((r) => dayNum(r.posted_on)))];
48 if (days.length < 3) continue;
49 const gaps = days.slice(1).map((d, i) => d - days[i]);
50 const gap = median(gaps);
51 const cadence = CADENCES.find((c) => Math.abs(gap - c.days) <= c.tolerance);
52 if (!cadence) continue;
53 // Most gaps must fit the cadence: a payee seen three times in a month and then twice a year later is not monthly.
54 const fit = gaps.filter((g) => Math.abs(g - cadence.days) <= cadence.tolerance * 1.5).length;
55 if (fit < Math.ceil(gaps.length * 0.6)) continue;
56 const last = days[days.length - 1];
57 const every = Math.round(cadence.days);
58 const next = last + every;
59 const latest = steady[steady.length - 1];
60 out.push({
61 key, payee: latest.payee, direction: key.startsWith('out') ? 'out' : 'in', cadence: cadence.name, every_days: every,
62 typical_cents: Math.round(typical), count: steady.length, last_on: isoOf(last), next_on: isoOf(next),
63 monthly_cents: Math.round(typical * (30.4 / cadence.days)), overdue: now - next > every / 2,
64 category: latest.category,
65 });
66 }
67 return out.sort((a, b) => a.next_on.localeCompare(b.next_on) || b.typical_cents - a.typical_cents);
68}
69
70module.exports = { findRecurring, CADENCES };
71