zero-debt 0.0.0-stage → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +249 -3
- package/lib/claude.js +148 -0
- package/package.json +18 -6
- package/public/css/zero.css +341 -0
- package/public/fonts/OFL-hanken-grotesk.txt +93 -0
- package/public/fonts/OFL-jetbrains-mono.txt +93 -0
- package/public/fonts/hanken-grotesk.woff2 +0 -0
- package/public/fonts/jetbrains-mono.woff2 +0 -0
- package/public/index.html +245 -0
- package/public/js/analysis.js +62 -0
- package/public/js/api.js +88 -0
- package/public/js/categorize.js +69 -0
- package/public/js/charts.js +173 -0
- package/public/js/demo.js +84 -0
- package/public/js/format.js +38 -0
- package/public/js/importers.js +251 -0
- package/public/js/insights.js +137 -0
- package/public/js/keys.js +50 -0
- package/public/js/main.js +946 -0
- package/public/js/palette.js +67 -0
- package/public/js/payoff.js +143 -0
- package/public/js/progress.js +91 -0
- package/public/js/settings.js +112 -0
- package/public/js/state.js +130 -0
- package/public/og.png +0 -0
- package/server.js +314 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// palette.js — the command palette. Every action in the app is a command:
|
|
2
|
+
// { id, title, hint?, run() }
|
|
3
|
+
// Typing filters by fuzzy match (letters in order, closer together ranks higher).
|
|
4
|
+
|
|
5
|
+
import { esc } from './format.js';
|
|
6
|
+
|
|
7
|
+
export function score(query, text) {
|
|
8
|
+
const q = query.toLowerCase().replace(/\s+/g, ''), t = text.toLowerCase();
|
|
9
|
+
if (!q) return 1;
|
|
10
|
+
let ti = 0, s = 0, last = -1;
|
|
11
|
+
for (const ch of q) {
|
|
12
|
+
const i = t.indexOf(ch, ti);
|
|
13
|
+
if (i === -1) return 0;
|
|
14
|
+
s += i === last + 1 ? 3 : 1; // consecutive letters score higher
|
|
15
|
+
if (i === 0 || t[i - 1] === ' ' || t[i - 1] === ':') s += 2; // word starts too
|
|
16
|
+
last = i; ti = i + 1;
|
|
17
|
+
}
|
|
18
|
+
return s;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createPalette(dialog, getCommands) {
|
|
22
|
+
const input = dialog.querySelector('input');
|
|
23
|
+
const list = dialog.querySelector('ol');
|
|
24
|
+
let shown = [], active = 0;
|
|
25
|
+
|
|
26
|
+
function render() {
|
|
27
|
+
const q = input.value.trim();
|
|
28
|
+
shown = getCommands()
|
|
29
|
+
.map((c) => ({ c, s: score(q, `${c.title} ${c.hint || ''}`) }))
|
|
30
|
+
.filter((x) => x.s > 0)
|
|
31
|
+
.sort((a, b) => b.s - a.s)
|
|
32
|
+
.slice(0, 40)
|
|
33
|
+
.map((x) => x.c);
|
|
34
|
+
active = Math.min(active, Math.max(0, shown.length - 1));
|
|
35
|
+
list.innerHTML = shown.map((c, i) => `
|
|
36
|
+
<li id="cmd-${i}" role="option" aria-selected="${i === active}" data-i="${i}">
|
|
37
|
+
<span>${esc(c.title)}</span>${c.hint ? `<kbd>${esc(c.hint)}</kbd>` : ''}
|
|
38
|
+
</li>`).join('') || '<li class="none">no command matches</li>';
|
|
39
|
+
input.setAttribute('aria-activedescendant', shown.length ? `cmd-${active}` : '');
|
|
40
|
+
list.querySelector('[aria-selected=true]')?.scrollIntoView({ block: 'nearest' });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function run(i) {
|
|
44
|
+
const cmd = shown[i];
|
|
45
|
+
if (!cmd) return;
|
|
46
|
+
dialog.close();
|
|
47
|
+
cmd.run();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
input.addEventListener('input', () => { active = 0; render(); });
|
|
51
|
+
input.addEventListener('keydown', (e) => {
|
|
52
|
+
if (e.key === 'ArrowDown') { active = (active + 1) % Math.max(1, shown.length); render(); e.preventDefault(); }
|
|
53
|
+
else if (e.key === 'ArrowUp') { active = (active - 1 + shown.length) % Math.max(1, shown.length); render(); e.preventDefault(); }
|
|
54
|
+
else if (e.key === 'Enter') { run(active); e.preventDefault(); }
|
|
55
|
+
});
|
|
56
|
+
list.addEventListener('click', (e) => { const li = e.target.closest('[data-i]'); if (li) run(Number(li.dataset.i)); });
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
open(prefill = '') {
|
|
60
|
+
input.value = prefill;
|
|
61
|
+
active = 0;
|
|
62
|
+
render();
|
|
63
|
+
dialog.showModal();
|
|
64
|
+
input.focus();
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// payoff.js — month-by-month debt payoff simulation.
|
|
2
|
+
//
|
|
3
|
+
// Pure functions, no DOM. Every number the app shows about the future comes from here.
|
|
4
|
+
//
|
|
5
|
+
// A debt looks like:
|
|
6
|
+
// { id, name, balance, apr, promoApr, promoEnd, min }
|
|
7
|
+
// apr standard yearly rate, as a percent (26.74)
|
|
8
|
+
// promoApr optional promo rate, as a percent (0)
|
|
9
|
+
// promoEnd optional 'YYYY-MM-DD'; the promo rate applies to months before the month it ends in
|
|
10
|
+
// (conservative: a promo ending Apr 2 is treated as gone for all of April)
|
|
11
|
+
// min minimum monthly payment in dollars
|
|
12
|
+
// payInFull optional true for a card you clear every statement (no interest as long as
|
|
13
|
+
// you do). It always gets paid first, whatever the strategy.
|
|
14
|
+
//
|
|
15
|
+
// Each simulated month: interest is added, every minimum is paid, then whatever is
|
|
16
|
+
// left of the monthly budget goes to debts in strategy order. Money freed up by a
|
|
17
|
+
// paid-off debt rolls into the next one automatically, because the budget stays fixed.
|
|
18
|
+
|
|
19
|
+
export const STRATEGIES = {
|
|
20
|
+
avalanche: 'highest rate first',
|
|
21
|
+
snowball: 'smallest balance first',
|
|
22
|
+
custom: 'your order',
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const MAX_MONTHS = 360;
|
|
26
|
+
const round2 = (n) => Math.round(n * 100) / 100;
|
|
27
|
+
|
|
28
|
+
/** 'YYYY-MM' for the month after `date` (a Date). Simulations start next month. */
|
|
29
|
+
export function nextMonth(date = new Date()) {
|
|
30
|
+
const y = date.getFullYear();
|
|
31
|
+
const m = date.getMonth() + 2; // getMonth is 0-based, +1 for next month
|
|
32
|
+
return m > 12 ? `${y + 1}-01` : `${y}-${String(m).padStart(2, '0')}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function addMonths(ym, n) {
|
|
36
|
+
const [y, m] = ym.split('-').map(Number);
|
|
37
|
+
const t = y * 12 + (m - 1) + n;
|
|
38
|
+
return `${Math.floor(t / 12)}-${String((t % 12) + 1).padStart(2, '0')}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The yearly rate (percent) that applies to a debt during month `ym`. */
|
|
42
|
+
export function rateFor(debt, ym) {
|
|
43
|
+
if (debt.payInFull) return 0; // cleared every statement, so the rate never applies
|
|
44
|
+
const hasPromo = debt.promoEnd && debt.promoApr !== undefined && debt.promoApr !== null && debt.promoApr !== '';
|
|
45
|
+
if (hasPromo && ym < debt.promoEnd.slice(0, 7)) return Number(debt.promoApr);
|
|
46
|
+
return Number(debt.apr) || 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Debts with a balance, in the order extra money should go to them this month. */
|
|
50
|
+
function priority(debts, balances, strategy, order, ym) {
|
|
51
|
+
const open = debts.filter((d) => balances[d.id] > 0.005);
|
|
52
|
+
const first = open.filter((d) => d.payInFull);
|
|
53
|
+
const rest = open.filter((d) => !d.payInFull);
|
|
54
|
+
return [...first, ...sortByStrategy(rest, balances, strategy, order, ym)];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function sortByStrategy(open, balances, strategy, order, ym) {
|
|
58
|
+
if (strategy === 'snowball') {
|
|
59
|
+
return open.sort((a, b) => balances[a.id] - balances[b.id]);
|
|
60
|
+
}
|
|
61
|
+
if (strategy === 'custom' && order?.length) {
|
|
62
|
+
const pos = (d) => { const i = order.indexOf(d.id); return i === -1 ? 999 : i; };
|
|
63
|
+
return open.sort((a, b) => pos(a) - pos(b));
|
|
64
|
+
}
|
|
65
|
+
// avalanche: highest rate right now; ties go to the promo that ends sooner, then the smaller balance
|
|
66
|
+
return open.sort((a, b) =>
|
|
67
|
+
rateFor(b, ym) - rateFor(a, ym) ||
|
|
68
|
+
(a.promoEnd || '9999').localeCompare(b.promoEnd || '9999') ||
|
|
69
|
+
balances[a.id] - balances[b.id]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Run the plan.
|
|
74
|
+
* @param {Array} debts
|
|
75
|
+
* @param {Object} plan { budget, strategy, order, lump: { amount, month: 'YYYY-MM' }, start: 'YYYY-MM' }
|
|
76
|
+
* @returns {{ months, debtFree, totalInterest, totalPaid, paidOff, shortfall, stalled }}
|
|
77
|
+
*/
|
|
78
|
+
export function simulate(debts, plan) {
|
|
79
|
+
const start = plan.start || nextMonth();
|
|
80
|
+
const balances = Object.fromEntries(debts.map((d) => [d.id, Math.max(0, Number(d.balance) || 0)]));
|
|
81
|
+
const months = [];
|
|
82
|
+
const paidOff = {};
|
|
83
|
+
let totalInterest = 0;
|
|
84
|
+
let totalPaid = 0;
|
|
85
|
+
let shortfall = false;
|
|
86
|
+
|
|
87
|
+
for (let i = 0; i < MAX_MONTHS; i++) {
|
|
88
|
+
const ym = addMonths(start, i);
|
|
89
|
+
if (Object.values(balances).every((b) => b <= 0.005)) break;
|
|
90
|
+
|
|
91
|
+
let interest = 0;
|
|
92
|
+
for (const d of debts) {
|
|
93
|
+
const add = round2(balances[d.id] * rateFor(d, ym) / 100 / 12);
|
|
94
|
+
balances[d.id] = round2(balances[d.id] + add);
|
|
95
|
+
interest += add;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
let money = Number(plan.budget) || 0;
|
|
99
|
+
if (plan.lump?.amount && plan.lump.month === ym) money += Number(plan.lump.amount);
|
|
100
|
+
|
|
101
|
+
const order = priority(debts, balances, plan.strategy, plan.order, ym);
|
|
102
|
+
const minsDue = order.reduce((s, d) => s + Math.min(Number(d.min) || 0, balances[d.id]), 0);
|
|
103
|
+
if (money + 0.005 < minsDue) shortfall = true;
|
|
104
|
+
|
|
105
|
+
// 1) minimums, in priority order (if money runs short, the top priorities get paid)
|
|
106
|
+
for (const d of order) {
|
|
107
|
+
const pay = round2(Math.min(Number(d.min) || 0, balances[d.id], money));
|
|
108
|
+
balances[d.id] = round2(balances[d.id] - pay);
|
|
109
|
+
money = round2(money - pay);
|
|
110
|
+
}
|
|
111
|
+
// 2) everything left, in priority order
|
|
112
|
+
for (const d of order) {
|
|
113
|
+
const pay = round2(Math.min(balances[d.id], money));
|
|
114
|
+
balances[d.id] = round2(balances[d.id] - pay);
|
|
115
|
+
money = round2(money - pay);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const total = round2(Object.values(balances).reduce((s, b) => s + b, 0));
|
|
119
|
+
for (const d of debts) if (!paidOff[d.id] && balances[d.id] <= 0.005) paidOff[d.id] = ym;
|
|
120
|
+
totalInterest = round2(totalInterest + interest);
|
|
121
|
+
totalPaid = round2(totalPaid + (Number(plan.budget) || 0) + (plan.lump?.month === ym ? Number(plan.lump.amount) || 0 : 0) - money);
|
|
122
|
+
months.push({ ym, balances: { ...balances }, total, interest: round2(interest) });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const last = months[months.length - 1];
|
|
126
|
+
const done = !last || last.total <= 0.005;
|
|
127
|
+
// "stalled" = the plan never finishes because payments don't outrun interest
|
|
128
|
+
return {
|
|
129
|
+
months,
|
|
130
|
+
debtFree: done ? (last ? last.ym : start) : null,
|
|
131
|
+
totalInterest,
|
|
132
|
+
totalPaid,
|
|
133
|
+
paidOff,
|
|
134
|
+
shortfall,
|
|
135
|
+
stalled: !done,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Minimums-only baseline, for comparison. Minimums are held fixed at today's amounts. */
|
|
140
|
+
export function minimumsOnly(debts, start) {
|
|
141
|
+
const budget = debts.reduce((s, d) => s + (Number(d.balance) > 0 ? Number(d.min) || 0 : 0), 0);
|
|
142
|
+
return simulate(debts, { budget, strategy: 'avalanche', start });
|
|
143
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// progress.js — "am i on track?"
|
|
2
|
+
//
|
|
3
|
+
// You set a plan (a snapshot of the payoff forecast), then check in now and then with
|
|
4
|
+
// your real balances. Each check-in is compared with where the plan said you'd be on
|
|
5
|
+
// that day. Pure functions, no DOM.
|
|
6
|
+
//
|
|
7
|
+
// state.progress = {
|
|
8
|
+
// baseline: { setOn: 'YYYY-MM-DD', startTotal, debtFree: 'YYYY-MM' | null,
|
|
9
|
+
// months: [{ ym: 'YYYY-MM', total }] } | null,
|
|
10
|
+
// checkins: [{ date: 'YYYY-MM-DD', total, balances: { debtId: amount } }],
|
|
11
|
+
// }
|
|
12
|
+
//
|
|
13
|
+
// The plan's month totals are balances after that month's payment, so the plan is a
|
|
14
|
+
// line through (setOn, startTotal) and the end of each month. A check-in mid-month is
|
|
15
|
+
// compared against the point on that line for its exact day.
|
|
16
|
+
|
|
17
|
+
import { simulate, nextMonth } from './payoff.js';
|
|
18
|
+
|
|
19
|
+
export const empty = () => ({ baseline: null, checkins: [] });
|
|
20
|
+
|
|
21
|
+
const DAY = 86400000;
|
|
22
|
+
const toTime = (iso) => { const [y, m, d] = iso.split('-').map(Number); return Date.UTC(y, m - 1, d); };
|
|
23
|
+
const endOfMonth = (ym) => { const [y, m] = ym.split('-').map(Number); return Date.UTC(y, m, 0); };
|
|
24
|
+
const round2 = (n) => Math.round(n * 100) / 100;
|
|
25
|
+
|
|
26
|
+
/** 'YYYY-MM-DD' for a Date, in local time. */
|
|
27
|
+
export function isoDay(d = new Date()) {
|
|
28
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Snapshot of today's forecast: the plan future check-ins are measured against. */
|
|
32
|
+
export function makeBaseline(debts, plan, today = isoDay()) {
|
|
33
|
+
const open = debts.filter((d) => Number(d.balance) > 0);
|
|
34
|
+
const startTotal = round2(open.reduce((s, d) => s + Number(d.balance), 0));
|
|
35
|
+
const r = simulate(open, { ...plan, start: plan.start || nextMonth(new Date(`${today}T12:00:00`)) });
|
|
36
|
+
return { setOn: today, startTotal, debtFree: r.debtFree, months: r.months.map((m) => ({ ym: m.ym, total: m.total })) };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Where the plan said the total would be on a given day (linear between month ends). */
|
|
40
|
+
export function plannedAt(baseline, day) {
|
|
41
|
+
const pts = [[toTime(baseline.setOn), baseline.startTotal], ...baseline.months.map((m) => [endOfMonth(m.ym), m.total])];
|
|
42
|
+
const t = toTime(day);
|
|
43
|
+
if (t <= pts[0][0]) return baseline.startTotal;
|
|
44
|
+
for (let i = 1; i < pts.length; i++) {
|
|
45
|
+
const [t0, v0] = pts[i - 1], [t1, v1] = pts[i];
|
|
46
|
+
if (t <= t1) return round2(v0 + (v1 - v0) * ((t - t0) / Math.max(DAY, t1 - t0)));
|
|
47
|
+
}
|
|
48
|
+
return pts[pts.length - 1][1]; // past the end of the plan: it said $0 (or wherever it stalled)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Records a check-in and makes those balances the current ones. A second check-in on
|
|
53
|
+
* the same day replaces the first. Sets the plan first if there isn't one yet, so the
|
|
54
|
+
* very first check-in has something to be measured against.
|
|
55
|
+
*/
|
|
56
|
+
export function checkIn(state, { date, balances }, plan) {
|
|
57
|
+
state.progress ||= empty();
|
|
58
|
+
if (!state.progress.baseline) state.progress.baseline = makeBaseline(state.debts, plan, date);
|
|
59
|
+
const clean = {};
|
|
60
|
+
for (const d of state.debts) {
|
|
61
|
+
const v = Number(balances[d.id]);
|
|
62
|
+
if (Number.isFinite(v) && v >= 0) { clean[d.id] = round2(v); d.balance = round2(v); }
|
|
63
|
+
}
|
|
64
|
+
const total = round2(Object.values(clean).reduce((s, v) => s + v, 0));
|
|
65
|
+
state.progress.checkins = [...state.progress.checkins.filter((c) => c.date !== date), { date, total, balances: clean }]
|
|
66
|
+
.sort((a, b) => a.date.localeCompare(b.date));
|
|
67
|
+
return total;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* How you're doing. Returns null without a plan. Otherwise:
|
|
72
|
+
* { points: [{ date, actual, planned, diff }], latest, status, diff, due }
|
|
73
|
+
* diff > 0 means ahead of plan (you owe less than it expected).
|
|
74
|
+
* status: 'ahead' | 'behind' | 'on track' | 'no check-ins'
|
|
75
|
+
* due: true when there's no check-in yet this month
|
|
76
|
+
*/
|
|
77
|
+
export function progressOf(state, today = isoDay()) {
|
|
78
|
+
const p = state.progress;
|
|
79
|
+
if (!p?.baseline) return null;
|
|
80
|
+
// within $25 or 2% of the plan counts as on track: payments land a few days either side
|
|
81
|
+
const statusOf = (diff, planned) => (Math.abs(diff) <= Math.max(25, planned * 0.02) ? 'on track' : diff > 0 ? 'ahead' : 'behind');
|
|
82
|
+
const points = p.checkins.map((c) => {
|
|
83
|
+
const planned = plannedAt(p.baseline, c.date);
|
|
84
|
+
const diff = round2(planned - c.total);
|
|
85
|
+
return { date: c.date, actual: c.total, planned, diff, status: statusOf(diff, planned) };
|
|
86
|
+
});
|
|
87
|
+
const latest = points[points.length - 1] || null;
|
|
88
|
+
const due = !p.checkins.some((c) => c.date.slice(0, 7) === today.slice(0, 7)) && p.baseline.setOn.slice(0, 7) !== today.slice(0, 7);
|
|
89
|
+
if (!latest) return { points, latest, status: 'no check-ins', diff: 0, due };
|
|
90
|
+
return { points, latest, status: latest.status, diff: latest.diff, due };
|
|
91
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// settings.js — everything about how zero looks and behaves. Saved as data/settings.json
|
|
2
|
+
// (or in the browser in demo mode). Every key is optional: anything you leave out falls
|
|
3
|
+
// back to DEFAULTS, and anything invalid is ignored with a warning instead of breaking.
|
|
4
|
+
|
|
5
|
+
export const THEMES = {
|
|
6
|
+
graph: { label: 'graph paper', bg: '#eceee9', surface: '#e1e4de', fg: '#1c2433', muted: '#5f656e', rule: '#c9cdc6', accent: '#1c2433', danger: '#b8362a', good: '#2f6b4f', grid: true },
|
|
7
|
+
ink: { label: 'ink (dark)', bg: '#14161b', surface: '#1d2027', fg: '#e3e6eb', muted: '#959ba5', rule: '#2e333c', accent: '#e3e6eb', danger: '#ef6b5c', good: '#6fbf98', grid: true },
|
|
8
|
+
phosphor: { label: 'phosphor', bg: '#0f0f0e', surface: '#1a1916', fg: '#f0b35c', muted: '#a37a3f', rule: '#3a3022', accent: '#f0b35c', danger: '#ff6b4f', good: '#a6d470', grid: false },
|
|
9
|
+
plain: { label: 'plain', bg: '#f6f6f4', surface: '#ebebe8', fg: '#16171a', muted: '#62646a', rule: '#d4d5d1', accent: '#2251c4', danger: '#bf3326', good: '#23744c', grid: false },
|
|
10
|
+
};
|
|
11
|
+
export const COLOR_KEYS = ['bg', 'surface', 'fg', 'muted', 'rule', 'accent', 'danger', 'good'];
|
|
12
|
+
|
|
13
|
+
export const PANES = {
|
|
14
|
+
payoff: 'payoff',
|
|
15
|
+
progress: 'progress',
|
|
16
|
+
debts: 'debts',
|
|
17
|
+
plan: 'plan',
|
|
18
|
+
notes: 'notes',
|
|
19
|
+
flow: 'money in / out',
|
|
20
|
+
transactions: 'transactions',
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const FONTS = {
|
|
24
|
+
mono: "'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, Consolas, monospace",
|
|
25
|
+
sans: "'Hanken Grotesk', 'Helvetica Neue', Helvetica, Arial, sans-serif",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const DEFAULTS = {
|
|
29
|
+
theme: 'system', // 'system' (graph by day, ink by night) or a THEMES key
|
|
30
|
+
colors: {}, // overrides, e.g. { "accent": "#ff5500" }
|
|
31
|
+
font: 'mono', // 'mono', 'sans', or any font installed on your machine
|
|
32
|
+
fontSize: 14, // px, 11–20
|
|
33
|
+
density: 'comfortable', // 'comfortable' | 'compact'
|
|
34
|
+
columns: 2, // 1 or 2
|
|
35
|
+
panes: ['payoff', 'debts', 'plan', 'progress', 'notes', 'flow', 'transactions'], // order; leave one out to hide it
|
|
36
|
+
wide: ['payoff', 'debts', 'notes', 'flow', 'transactions'], // panes that span both columns
|
|
37
|
+
dates: 'iso', // 'iso' (2027-03) | 'words' (march 2027)
|
|
38
|
+
locale: 'en-US',
|
|
39
|
+
currency: 'USD',
|
|
40
|
+
chart: { animate: true, minimums: true, promos: true },
|
|
41
|
+
model: 'claude-sonnet-5-5',
|
|
42
|
+
keys: {
|
|
43
|
+
palette: 'mod+k', settings: ',', import: 'i', checkin: 'c', ask: 'a', student: 's', search: '/', help: '?',
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const HEX = /^#[0-9a-f]{6}$/i;
|
|
48
|
+
|
|
49
|
+
/** Merges saved settings over the defaults, keeping only valid values. Returns { settings, warnings }. */
|
|
50
|
+
export function resolve(saved = {}) {
|
|
51
|
+
const s = structuredClone(DEFAULTS);
|
|
52
|
+
const warnings = [];
|
|
53
|
+
const warn = (k) => warnings.push(`ignored “${k}”: not a valid value`);
|
|
54
|
+
if (!saved || typeof saved !== 'object') return { settings: s, warnings };
|
|
55
|
+
for (const k of Object.keys(saved)) if (!(k in DEFAULTS)) warnings.push(`ignored “${k}”: not a setting`);
|
|
56
|
+
|
|
57
|
+
if (saved.theme !== undefined) (saved.theme === 'system' || THEMES[saved.theme]) ? (s.theme = saved.theme) : warn('theme');
|
|
58
|
+
if (saved.colors && typeof saved.colors === 'object') {
|
|
59
|
+
for (const [k, v] of Object.entries(saved.colors)) (COLOR_KEYS.includes(k) && HEX.test(v)) ? (s.colors[k] = v) : warn(`colors.${k}`);
|
|
60
|
+
}
|
|
61
|
+
if (typeof saved.font === 'string' && saved.font.trim() && saved.font.length < 80 && !/[;{}<>'"\\]/.test(saved.font)) s.font = saved.font.trim();
|
|
62
|
+
else if (saved.font !== undefined) warn('font');
|
|
63
|
+
if (saved.fontSize !== undefined) (Number(saved.fontSize) >= 11 && Number(saved.fontSize) <= 20) ? (s.fontSize = Number(saved.fontSize)) : warn('fontSize');
|
|
64
|
+
if (saved.density !== undefined) ['comfortable', 'compact'].includes(saved.density) ? (s.density = saved.density) : warn('density');
|
|
65
|
+
if (saved.columns !== undefined) [1, 2].includes(Number(saved.columns)) ? (s.columns = Number(saved.columns)) : warn('columns');
|
|
66
|
+
if (Array.isArray(saved.panes)) {
|
|
67
|
+
const ok = saved.panes.filter((p) => PANES[p]);
|
|
68
|
+
if (ok.length !== saved.panes.length) warn('panes (unknown names)');
|
|
69
|
+
s.panes = [...new Set(ok)];
|
|
70
|
+
}
|
|
71
|
+
if (Array.isArray(saved.wide)) s.wide = saved.wide.filter((p) => PANES[p]);
|
|
72
|
+
if (saved.dates !== undefined) ['iso', 'words'].includes(saved.dates) ? (s.dates = saved.dates) : warn('dates');
|
|
73
|
+
if (typeof saved.locale === 'string') { try { new Intl.NumberFormat(saved.locale); s.locale = saved.locale; } catch { warn('locale'); } }
|
|
74
|
+
if (typeof saved.currency === 'string') { try { new Intl.NumberFormat('en-US', { style: 'currency', currency: saved.currency }); s.currency = saved.currency.toUpperCase(); } catch { warn('currency'); } }
|
|
75
|
+
if (saved.chart && typeof saved.chart === 'object') for (const k of Object.keys(s.chart)) if (typeof saved.chart[k] === 'boolean') s.chart[k] = saved.chart[k];
|
|
76
|
+
if (typeof saved.model === 'string' && /^[a-z0-9.\-]{3,64}$/.test(saved.model)) s.model = saved.model;
|
|
77
|
+
else if (saved.model !== undefined) warn('model');
|
|
78
|
+
if (saved.keys && typeof saved.keys === 'object') {
|
|
79
|
+
for (const [k, v] of Object.entries(saved.keys)) (k in s.keys && typeof v === 'string' && v.length <= 20) ? (s.keys[k] = v.toLowerCase()) : warn(`keys.${k}`);
|
|
80
|
+
}
|
|
81
|
+
return { settings: s, warnings };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Only the keys that differ from the defaults — what gets written to settings.json. */
|
|
85
|
+
export function diff(settings) {
|
|
86
|
+
const out = {};
|
|
87
|
+
for (const [k, v] of Object.entries(settings)) {
|
|
88
|
+
if (JSON.stringify(v) !== JSON.stringify(DEFAULTS[k])) out[k] = v;
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The theme in effect right now (resolving 'system' against the OS preference). */
|
|
94
|
+
export function activeTheme(settings) {
|
|
95
|
+
const name = settings.theme === 'system'
|
|
96
|
+
? (matchMedia('(prefers-color-scheme: dark)').matches ? 'ink' : 'graph')
|
|
97
|
+
: settings.theme;
|
|
98
|
+
return { name, ...THEMES[name], ...settings.colors };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Writes the settings onto the page as CSS custom properties and data attributes. */
|
|
102
|
+
export function apply(settings, root = document.documentElement) {
|
|
103
|
+
const t = activeTheme(settings);
|
|
104
|
+
for (const k of COLOR_KEYS) root.style.setProperty(`--${k}`, t[k]);
|
|
105
|
+
root.style.setProperty('--font', FONTS[settings.font] || `'${settings.font}', ${FONTS.mono}`);
|
|
106
|
+
root.style.setProperty('--size', `${settings.fontSize}px`);
|
|
107
|
+
root.style.setProperty('--cols', settings.columns);
|
|
108
|
+
root.dataset.density = settings.density;
|
|
109
|
+
root.dataset.grid = t.grid ? 'on' : 'off';
|
|
110
|
+
root.dataset.font = FONTS[settings.font] ? settings.font : 'custom';
|
|
111
|
+
document.querySelector('meta[name=theme-color]')?.setAttribute('content', t.bg);
|
|
112
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// state.js — the shape of your money data, and the pure functions that change it.
|
|
2
|
+
// Where it's stored is api.js's job: data/state.json with the local server, or this
|
|
3
|
+
// browser's localStorage in demo mode.
|
|
4
|
+
|
|
5
|
+
import { categorize, merchantKey } from './categorize.js';
|
|
6
|
+
import { txId, fitId } from './importers.js';
|
|
7
|
+
import { DEMO } from './demo.js';
|
|
8
|
+
import { empty as emptyProgress } from './progress.js';
|
|
9
|
+
|
|
10
|
+
export const VERSION = 1;
|
|
11
|
+
|
|
12
|
+
/*
|
|
13
|
+
{
|
|
14
|
+
version: 1,
|
|
15
|
+
sample: true, // true while the demo numbers are showing
|
|
16
|
+
settings: { // money settings (look-and-feel lives in settings.json)
|
|
17
|
+
takeHome: 1768, // monthly take-home pay
|
|
18
|
+
netHourly: 17.20, // take-home per hour, for the extra-shifts slider
|
|
19
|
+
fixed: 152, // bills that don't move: giving, loans, rent…
|
|
20
|
+
living: 880, // everyday spending, normal month
|
|
21
|
+
studentLiving: 555, // everyday spending, bare-bones month
|
|
22
|
+
studentMode: false,
|
|
23
|
+
extraHours: 0, // extra hours per week
|
|
24
|
+
extraMonthly: 0, // any other extra per month
|
|
25
|
+
strategy: 'avalanche',
|
|
26
|
+
order: [], // debt ids, for the custom strategy
|
|
27
|
+
lump: { amount: 0, month: '' },
|
|
28
|
+
},
|
|
29
|
+
debts: [ { id, name, balance, apr, promoApr, promoEnd, min, payInFull } ],
|
|
30
|
+
transactions: [ { id, date, account, description, amount, category } ],
|
|
31
|
+
learned: { merchantKey: category }, // your category corrections
|
|
32
|
+
progress: { baseline, checkins }, // your plan snapshot and check-ins (progress.js)
|
|
33
|
+
}
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const clone = (x) => JSON.parse(JSON.stringify(x));
|
|
37
|
+
|
|
38
|
+
/** Saved data → a complete state. Nothing saved yet → the sample. */
|
|
39
|
+
export function fromSaved(saved) {
|
|
40
|
+
return saved && typeof saved === 'object' ? migrate(saved) : clone(DEMO);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function sample() { return clone(DEMO); }
|
|
44
|
+
|
|
45
|
+
/** A blank slate for a new user: no debts, no transactions, no income filled in yet. */
|
|
46
|
+
export function empty() {
|
|
47
|
+
const s = clone(DEMO);
|
|
48
|
+
Object.assign(s.settings, { takeHome: 0, netHourly: 0, fixed: 0, living: 0, studentLiving: 0, studentMode: false });
|
|
49
|
+
return { ...s, sample: false, debts: [], transactions: [], learned: {}, progress: emptyProgress() };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Fills in anything an older or hand-edited backup is missing. */
|
|
53
|
+
export function migrate(s) {
|
|
54
|
+
const base = clone(DEMO);
|
|
55
|
+
return {
|
|
56
|
+
version: VERSION,
|
|
57
|
+
sample: Boolean(s.sample),
|
|
58
|
+
settings: { ...base.settings, ...(s.settings || {}), lump: { ...base.settings.lump, ...(s.settings?.lump || {}) } },
|
|
59
|
+
debts: Array.isArray(s.debts) ? s.debts : [],
|
|
60
|
+
transactions: Array.isArray(s.transactions) ? s.transactions : [],
|
|
61
|
+
learned: s.learned && typeof s.learned === 'object' ? s.learned : {},
|
|
62
|
+
progress: s.progress && typeof s.progress === 'object' && Array.isArray(s.progress.checkins)
|
|
63
|
+
? { baseline: s.progress.baseline || null, checkins: s.progress.checkins }
|
|
64
|
+
: emptyProgress(),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Validates a backup file before it replaces anything. Throws with a readable message. */
|
|
69
|
+
export function parseBackup(text) {
|
|
70
|
+
let data;
|
|
71
|
+
try { data = JSON.parse(text); } catch { throw new Error('that file isn’t valid JSON'); }
|
|
72
|
+
if (!data || typeof data !== 'object' || !Array.isArray(data.debts) || !Array.isArray(data.transactions)) {
|
|
73
|
+
throw new Error('that file doesn’t look like a zero backup');
|
|
74
|
+
}
|
|
75
|
+
return migrate({ ...data, sample: false });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Money per month that goes to debt under the current settings. */
|
|
79
|
+
export function monthlyBudget(settings) {
|
|
80
|
+
const living = settings.studentMode ? settings.studentLiving : settings.living;
|
|
81
|
+
const shifts = (Number(settings.extraHours) || 0) * (Number(settings.netHourly) || 0) * 52 / 12;
|
|
82
|
+
const b = (Number(settings.takeHome) || 0) - (Number(settings.fixed) || 0) - (Number(living) || 0)
|
|
83
|
+
+ shifts + (Number(settings.extraMonthly) || 0);
|
|
84
|
+
return Math.max(0, Math.round(b));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Adds imported rows, skipping ones already present. Identical rows inside one file
|
|
89
|
+
* (two $0.32 work meals on the same day) are kept apart by their position.
|
|
90
|
+
* @returns {{ added, skipped }}
|
|
91
|
+
*/
|
|
92
|
+
export function addTransactions(state, rows, account) {
|
|
93
|
+
const existing = new Set(state.transactions.map((t) => t.id));
|
|
94
|
+
const seen = {};
|
|
95
|
+
let added = 0, skipped = 0;
|
|
96
|
+
for (const r of rows) {
|
|
97
|
+
const base = r.fitid ? fitId(account, r.fitid) : txId({ ...r, account });
|
|
98
|
+
seen[base] = (seen[base] || 0) + 1;
|
|
99
|
+
const id = seen[base] > 1 ? `${base}-${seen[base]}` : base;
|
|
100
|
+
if (existing.has(id)) { skipped++; continue; }
|
|
101
|
+
state.transactions.push({
|
|
102
|
+
id, account, date: r.date, description: r.description, amount: Number(r.amount),
|
|
103
|
+
category: r.category || categorize(r.description, r.amount, state.learned),
|
|
104
|
+
});
|
|
105
|
+
existing.add(id);
|
|
106
|
+
added++;
|
|
107
|
+
}
|
|
108
|
+
state.transactions.sort((a, b) => b.date.localeCompare(a.date));
|
|
109
|
+
if (added) state.sample = false;
|
|
110
|
+
return { added, skipped };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Sets a category and remembers it for every transaction from the same merchant. */
|
|
114
|
+
export function recategorize(state, id, category) {
|
|
115
|
+
const t = state.transactions.find((x) => x.id === id);
|
|
116
|
+
if (!t) return 0;
|
|
117
|
+
const key = merchantKey(t.description);
|
|
118
|
+
state.learned[key] = category;
|
|
119
|
+
let changed = 0;
|
|
120
|
+
for (const x of state.transactions) {
|
|
121
|
+
if (merchantKey(x.description) === key && x.category !== category) { x.category = category; changed++; }
|
|
122
|
+
}
|
|
123
|
+
return changed;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function newDebtId(state) {
|
|
127
|
+
let i = state.debts.length + 1;
|
|
128
|
+
while (state.debts.some((d) => d.id === `d${i}`)) i++;
|
|
129
|
+
return `d${i}`;
|
|
130
|
+
}
|
package/public/og.png
ADDED
|
Binary file
|