openvibers/openvibe.finance serverplan.js

plan.js

main 2.4 KB · 48 lines · javascript

1'use strict';
2/**
3 * The arithmetic of goals and debt (plan §L.2), on whole cents, with no rounding drift that matters to a person.
4 *
5 * payoff({ owed_cents, apr_bps, payment_cents }) → { months, interest_cents, never } (never: the payment does not
6 * cover the interest, so the balance never falls)
7 * faster({ owed_cents, apr_bps, payment_cents }, extra_cents) → { months_sooner, interest_saved_cents }
8 * perMonth({ target_cents, have_cents, target_on, today }) → cents a month to reach it by then (0 when reached,
9 * null without a date or when the date has passed)
10 */
11
12function payoff({ owed_cents, apr_bps = 0, payment_cents }) {
13 let owed = Math.max(0, Math.round(owed_cents));
14 if (!owed) return { months: 0, interest_cents: 0, never: false };
15 if (!payment_cents || payment_cents <= 0) return { months: null, interest_cents: null, never: true };
16 const rate = Math.max(0, apr_bps) / 10000 / 12;
17 let months = 0, interest = 0;
18 while (owed > 0 && months < 1200) {
19 const charge = Math.round(owed * rate);
20 if (payment_cents <= charge) return { months: null, interest_cents: null, never: true };
21 interest += charge;
22 owed = owed + charge - payment_cents;
23 months++;
24 }
25 return months >= 1200 ? { months: null, interest_cents: null, never: true } : { months, interest_cents: interest, never: false };
26}
27
28function faster(debt, extra_cents) {
29 const now = payoff(debt);
30 const more = payoff({ ...debt, payment_cents: (debt.payment_cents || 0) + extra_cents });
31 if (more.never) return null;
32 if (now.never) return { months_sooner: null, interest_saved_cents: null, months: more.months };
33 return { months_sooner: now.months - more.months, interest_saved_cents: now.interest_cents - more.interest_cents, months: more.months };
34}
35
36function perMonth({ target_cents, have_cents, target_on, today = new Date().toISOString().slice(0, 10) }) {
37 const left = target_cents - Math.max(0, have_cents);
38 if (left <= 0) return 0;
39 if (!target_on) return null;
40 const [ty, tm] = target_on.split('-').map(Number);
41 const [ny, nm] = today.split('-').map(Number);
42 const months = (ty - ny) * 12 + (tm - nm);
43 if (months <= 0) return null;
44 return Math.ceil(left / months);
45}
46
47module.exports = { payoff, faster, perMonth };
48