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,946 @@
|
|
|
1
|
+
// main.js — wires the page together. Read top to bottom:
|
|
2
|
+
// 1. state 2. saving 3. look & layout 4. payoff 4b. progress
|
|
3
|
+
// 5. plan 6. debts 7. notes 8. money in/out
|
|
4
|
+
// 9. transactions 10. import 11. settings dialog
|
|
5
|
+
// 12. commands, keys, boot
|
|
6
|
+
|
|
7
|
+
import * as api from './api.js';
|
|
8
|
+
import { fromSaved, sample, empty, parseBackup, monthlyBudget, addTransactions, recategorize, newDebtId } from './state.js';
|
|
9
|
+
import { resolve, diff, apply, THEMES, PANES, FONTS, COLOR_KEYS, DEFAULTS, activeTheme } from './settings.js';
|
|
10
|
+
import { simulate, minimumsOnly, nextMonth } from './payoff.js';
|
|
11
|
+
import { importCSV, parseDate, fileToBase64, isOFX, parseOFX } from './importers.js';
|
|
12
|
+
import { CATEGORIES, categorize } from './categorize.js';
|
|
13
|
+
import { localInsights, summaryForClaude } from './insights.js';
|
|
14
|
+
import { monthlyFlow, byCategory, since } from './analysis.js';
|
|
15
|
+
import { payoffChart, flowChart, progressChart } from './charts.js';
|
|
16
|
+
import { makeBaseline, checkIn, progressOf, isoDay } from './progress.js';
|
|
17
|
+
import { money, monthName, plural, esc, configure } from './format.js';
|
|
18
|
+
import { createPalette } from './palette.js';
|
|
19
|
+
import { listen, label as keyLabel } from './keys.js';
|
|
20
|
+
|
|
21
|
+
/* ---------- 1. state ---------- */
|
|
22
|
+
|
|
23
|
+
let state; // your money data (state.json)
|
|
24
|
+
let prefs = structuredClone(DEFAULTS); // look & behavior (settings.json), always fully resolved
|
|
25
|
+
let prefWarnings = [];
|
|
26
|
+
let animateNext = true; // the payoff line inks itself in once per load
|
|
27
|
+
let txShown = 60;
|
|
28
|
+
let pending = null; // an import waiting for confirmation
|
|
29
|
+
let saveStatus = { text: 'not saved yet', bad: false };
|
|
30
|
+
// files zero must not write: broken on disk, or changed in another tab. name → message
|
|
31
|
+
const blocked = {};
|
|
32
|
+
|
|
33
|
+
const $ = (sel) => document.querySelector(sel);
|
|
34
|
+
const num = (v) => (v === '' || v === null || v === undefined ? '' : Number(v));
|
|
35
|
+
const thisMonth = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; };
|
|
36
|
+
const openDebts = () => state.debts.filter((d) => Number(d.balance) > 0);
|
|
37
|
+
const currentPlan = () => {
|
|
38
|
+
const s = state.settings;
|
|
39
|
+
return { budget: monthlyBudget(s), strategy: s.strategy, order: s.order, lump: s.lump, start: nextMonth() };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
let toastTimer;
|
|
43
|
+
function toast(text) {
|
|
44
|
+
const t = $('#toast');
|
|
45
|
+
t.textContent = text;
|
|
46
|
+
t.classList.add('show');
|
|
47
|
+
clearTimeout(toastTimer);
|
|
48
|
+
toastTimer = setTimeout(() => t.classList.remove('show'), 3000);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Two-tap confirm for destructive buttons: the first tap relabels it, a second within 4s acts. */
|
|
52
|
+
function armed(btn, text) {
|
|
53
|
+
if (!btn || btn.dataset.armed) return true;
|
|
54
|
+
const original = btn.innerHTML;
|
|
55
|
+
btn.dataset.armed = '1';
|
|
56
|
+
btn.textContent = text;
|
|
57
|
+
setTimeout(() => { delete btn.dataset.armed; btn.innerHTML = original; }, 4000);
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/* ---------- 2. saving (debounced; to data/*.json or browser storage in demo mode) ---------- */
|
|
62
|
+
|
|
63
|
+
const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };
|
|
64
|
+
|
|
65
|
+
/** A write was refused because the file changed elsewhere or is broken: stop saving it. */
|
|
66
|
+
function block(name, err) {
|
|
67
|
+
if (err.status === 409 || err.status === 422) { blocked[name] = err.message; renderBanner(); }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const writeState = debounce(async () => {
|
|
71
|
+
if (blocked.state) return;
|
|
72
|
+
try {
|
|
73
|
+
await api.writeFile('state', state);
|
|
74
|
+
saveStatus = { text: `saved ${new Date().toLocaleTimeString([], { hour12: false })}`, bad: false };
|
|
75
|
+
} catch (err) {
|
|
76
|
+
block('state', err);
|
|
77
|
+
saveStatus = { text: 'not saved', bad: true };
|
|
78
|
+
}
|
|
79
|
+
renderStatus();
|
|
80
|
+
}, 350);
|
|
81
|
+
|
|
82
|
+
function persist() {
|
|
83
|
+
if (blocked.state) { saveStatus = { text: 'not saving', bad: true }; renderStatus(); return; }
|
|
84
|
+
saveStatus = { text: 'saving…', bad: false };
|
|
85
|
+
renderStatus();
|
|
86
|
+
writeState();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const writePrefs = debounce(async () => {
|
|
90
|
+
if (blocked.settings) return;
|
|
91
|
+
try { await api.writeFile('settings', diff(prefs)); } catch (err) { block('settings', err); if (!blocked.settings) toast(`settings not saved: ${err.message}`); }
|
|
92
|
+
}, 350);
|
|
93
|
+
|
|
94
|
+
/** Changes one or more settings, re-applies them, re-renders, and saves settings.json. */
|
|
95
|
+
function setPrefs(patch, { save = true } = {}) {
|
|
96
|
+
const next = resolve({ ...diff(prefs), ...patch });
|
|
97
|
+
prefs = next.settings;
|
|
98
|
+
prefWarnings = next.warnings;
|
|
99
|
+
applyPrefs();
|
|
100
|
+
if (save) writePrefs();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/* ---------- 3. look & layout ---------- */
|
|
104
|
+
|
|
105
|
+
function applyPrefs() {
|
|
106
|
+
configure(prefs);
|
|
107
|
+
apply(prefs);
|
|
108
|
+
// pane order, visibility, width, and the number key that jumps to each
|
|
109
|
+
const main = $('#panes');
|
|
110
|
+
const visible = prefs.panes;
|
|
111
|
+
for (const id of Object.keys(PANES)) {
|
|
112
|
+
const pane = main.querySelector(`[data-pane="${id}"]`);
|
|
113
|
+
const i = visible.indexOf(id);
|
|
114
|
+
pane.hidden = i === -1;
|
|
115
|
+
pane.classList.toggle('wide', prefs.wide.includes(id));
|
|
116
|
+
pane.querySelector('.idx').textContent = i > -1 && i < 9 ? String(i + 1) : '';
|
|
117
|
+
}
|
|
118
|
+
visible.forEach((id) => main.appendChild(main.querySelector(`[data-pane="${id}"]`)));
|
|
119
|
+
document.querySelectorAll('kbd[data-key]').forEach((k) => { k.textContent = prefs.keys[k.dataset.key] ? keyLabel(prefs.keys[k.dataset.key]) : ''; });
|
|
120
|
+
$('#key-min').hidden = !prefs.chart.minimums;
|
|
121
|
+
renderAll();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/* ---------- 4. payoff ---------- */
|
|
125
|
+
|
|
126
|
+
function renderPayoff() {
|
|
127
|
+
const debts = openDebts();
|
|
128
|
+
const plan = currentPlan();
|
|
129
|
+
const lead = $('#hero-lead'), hero = $('#hero-date'), facts = $('#facts');
|
|
130
|
+
hero.classList.remove('is-bad');
|
|
131
|
+
|
|
132
|
+
if (!debts.length) {
|
|
133
|
+
lead.textContent = state.debts.length ? 'every balance is at $0' : 'nothing to pay off yet';
|
|
134
|
+
hero.textContent = state.debts.length ? 'debt-free' : 'add a debt';
|
|
135
|
+
facts.innerHTML = '';
|
|
136
|
+
$('#payoff-chart').replaceChildren();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const result = simulate(debts, plan);
|
|
141
|
+
const base = minimumsOnly(debts, plan.start);
|
|
142
|
+
const total = debts.reduce((s, d) => s + Number(d.balance), 0);
|
|
143
|
+
|
|
144
|
+
lead.textContent = result.stalled ? 'at this budget you’re' : 'debt-free by';
|
|
145
|
+
hero.textContent = result.stalled ? 'not getting there' : monthName(result.debtFree);
|
|
146
|
+
hero.classList.toggle('is-bad', result.stalled);
|
|
147
|
+
|
|
148
|
+
facts.innerHTML = `
|
|
149
|
+
<div><dt>left to pay</dt><dd>${money(total)}</dd></div>
|
|
150
|
+
<div><dt>months to go</dt><dd>${result.stalled ? '—' : result.months.length}</dd></div>
|
|
151
|
+
<div class="cost"><dt>interest on the way</dt><dd>${result.stalled ? '—' : money(result.totalInterest)}</dd></div>
|
|
152
|
+
<div><dt>to debt each month</dt><dd>${money(plan.budget)}</dd></div>`;
|
|
153
|
+
|
|
154
|
+
const promos = prefs.chart.promos ? debts.filter((d) => d.promoEnd).map((d) => ({ ym: d.promoEnd.slice(0, 7), name: d.name })) : [];
|
|
155
|
+
$('#key-promo').hidden = !promos.length;
|
|
156
|
+
|
|
157
|
+
payoffChart($('#payoff-chart'), {
|
|
158
|
+
start: thisMonth(), startTotal: total, plan: result, base, promos,
|
|
159
|
+
showMin: prefs.chart.minimums, animate: animateNext && prefs.chart.animate,
|
|
160
|
+
label: result.stalled ? 'payoff chart: the balance never reaches zero at this budget'
|
|
161
|
+
: `payoff chart: ${money(total)} falls to zero by ${monthName(result.debtFree)}`,
|
|
162
|
+
onHover: (p, b) => {
|
|
163
|
+
$('#readout').textContent = p ? `${p.ym} ${money(p.total)} left${b && prefs.chart.minimums ? ` minimums only: ${money(b.total)}` : ''}` : '';
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
animateNext = false;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/* ---------- 4b. progress: am i on track? ---------- */
|
|
170
|
+
|
|
171
|
+
function renderProgress() {
|
|
172
|
+
const body = $('#progress-body');
|
|
173
|
+
const p = progressOf(state);
|
|
174
|
+
if (!p) {
|
|
175
|
+
body.innerHTML = `<p>set your plan, then check in once a month with your real balances. zero shows whether you’re ahead of the plan or behind it.</p>
|
|
176
|
+
<div class="progress-actions"><button type="button" data-cmd="set-plan" ${openDebts().length ? '' : 'disabled'}>set my plan</button><button type="button" class="quiet" data-cmd="checkin">check in now</button></div>`;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const b = state.progress.baseline;
|
|
180
|
+
const forecast = openDebts().length ? simulate(openDebts(), currentPlan()).debtFree : thisMonth();
|
|
181
|
+
const headline = {
|
|
182
|
+
ahead: `${money(p.diff)} ahead of plan`,
|
|
183
|
+
behind: `${money(-p.diff)} behind plan`,
|
|
184
|
+
'on track': 'on track',
|
|
185
|
+
'no check-ins': 'plan set. check in once a month.',
|
|
186
|
+
}[p.status];
|
|
187
|
+
const rows = [...p.points].reverse().slice(0, 6).map((pt) => `<tr><td>${esc(pt.date)}</td><td class="num">${money(pt.actual)}</td><td class="num">${money(pt.planned)}</td>
|
|
188
|
+
<td class="num ${pt.status.replace(' ', '-')}">${pt.status === 'on track' ? 'on track' : `${money(Math.abs(pt.diff))} ${pt.diff > 0 ? 'under' : 'over'}`}</td></tr>`).join('');
|
|
189
|
+
body.innerHTML = `
|
|
190
|
+
<p class="progress-status ${p.status.replace(' ', '-')}">${esc(headline)}</p>
|
|
191
|
+
<p class="progress-sub">plan set <span class="nowrap">${esc(b.setOn)}</span> at ${money(b.startTotal)}, debt-free <span class="nowrap">${b.debtFree ? esc(monthName(b.debtFree)) : 'never'}</span>.<br>
|
|
192
|
+
today’s forecast: <span class="nowrap">${forecast ? esc(monthName(forecast)) : 'not in sight'}</span>.${p.due ? ' a check-in is due this month.' : ''}</p>
|
|
193
|
+
${p.points.length ? `<div class="progress-chart" id="progress-chart"></div>
|
|
194
|
+
<p class="legend"><span class="key key-baseline">plan</span><span class="key key-you">your check-ins</span></p>
|
|
195
|
+
<div class="table-wrap"><table class="checkins"><thead><tr><th>date</th><th class="num">owed</th><th class="num">plan</th><th class="num">vs plan</th></tr></thead><tbody>${rows}</tbody></table></div>` : ''}
|
|
196
|
+
<div class="progress-actions"><button type="button" class="quiet" data-cmd="set-plan">reset plan to today’s forecast</button></div>`;
|
|
197
|
+
if (p.points.length) {
|
|
198
|
+
progressChart($('#progress-chart'), {
|
|
199
|
+
baseline: b, points: p.points,
|
|
200
|
+
label: `progress chart: plan from ${money(b.startTotal)}; latest check-in ${money(p.latest.actual)} against ${money(p.latest.planned)} planned`,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function openCheckin() {
|
|
206
|
+
if (!state.debts.length) { toast('add your debts first'); return; }
|
|
207
|
+
$('#checkin-date').value = isoDay();
|
|
208
|
+
$('#checkin-date').max = isoDay();
|
|
209
|
+
$('#checkin-rows').innerHTML = state.debts.map((d) => `
|
|
210
|
+
<label>${esc(d.name)} <input type="number" min="0" step="0.01" inputmode="decimal" data-checkin="${esc(d.id)}" value="${esc(Number(d.balance).toFixed(2))}"></label>`).join('');
|
|
211
|
+
updateCheckinTotal();
|
|
212
|
+
$('#checkin-dialog').showModal();
|
|
213
|
+
$('#checkin-rows input')?.select();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function updateCheckinTotal() {
|
|
217
|
+
const total = [...document.querySelectorAll('[data-checkin]')].reduce((s, i) => s + (Number(i.value) || 0), 0);
|
|
218
|
+
$('#checkin-total').textContent = `total owed: ${money(total, true)}`;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function saveCheckin() {
|
|
222
|
+
const date = $('#checkin-date').value;
|
|
223
|
+
if (!date) { $('#checkin-date').reportValidity(); return; }
|
|
224
|
+
const balances = Object.fromEntries([...document.querySelectorAll('[data-checkin]')].map((i) => [i.dataset.checkin, i.value]));
|
|
225
|
+
checkIn(state, { date, balances }, currentPlan());
|
|
226
|
+
state.sample = false;
|
|
227
|
+
persist();
|
|
228
|
+
$('#checkin-dialog').close();
|
|
229
|
+
renderAll();
|
|
230
|
+
const p = progressOf(state);
|
|
231
|
+
toast(p?.status === 'ahead' ? `checked in: ${money(p.diff)} ahead of plan` : p?.status === 'behind' ? `checked in: ${money(-p.diff)} behind plan` : 'checked in: on track');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function setPlan(btn) {
|
|
235
|
+
if (state.progress?.baseline && !armed(btn, 'tap again to reset')) return;
|
|
236
|
+
state.progress = { baseline: makeBaseline(state.debts, currentPlan()), checkins: [] };
|
|
237
|
+
persist(); renderProgress(); renderNotes();
|
|
238
|
+
toast('plan set from today’s forecast');
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/* ---------- 5. plan ---------- */
|
|
242
|
+
|
|
243
|
+
const STRATEGY_HINTS = {
|
|
244
|
+
avalanche: 'costs the least interest. promo rates count as low until they end.',
|
|
245
|
+
snowball: 'quick wins: the smallest balances disappear first.',
|
|
246
|
+
custom: 'set the order with the arrows in the debts table.',
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
function renderPlan() {
|
|
250
|
+
const s = state.settings;
|
|
251
|
+
document.querySelectorAll('input[name=strategy]').forEach((r) => { r.checked = r.value === s.strategy; });
|
|
252
|
+
$('#strategy-hint').textContent = STRATEGY_HINTS[s.strategy] || '';
|
|
253
|
+
$('#student-mode').checked = s.studentMode;
|
|
254
|
+
$('#student-hint').textContent = `everyday spending ${money(s.living)} → ${money(s.studentLiving)} a month`;
|
|
255
|
+
$('#extra-hours').value = s.extraHours;
|
|
256
|
+
const shift = s.extraHours * s.netHourly * 52 / 12;
|
|
257
|
+
$('#extra-hours-out').textContent = s.extraHours ? `+${s.extraHours} h/wk +${money(shift)}/mo` : 'none';
|
|
258
|
+
$('#extra-monthly').value = s.extraMonthly;
|
|
259
|
+
$('#extra-monthly-out').textContent = s.extraMonthly ? `+${money(s.extraMonthly)}/mo` : 'none';
|
|
260
|
+
$('#lump-amount').value = s.lump.amount || '';
|
|
261
|
+
$('#lump-month').value = s.lump.month || '';
|
|
262
|
+
$('#lump-month').min = nextMonth();
|
|
263
|
+
document.querySelectorAll('[data-money]').forEach((i) => { if (document.activeElement !== i) i.value = s[i.dataset.money]; });
|
|
264
|
+
renderMath();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function renderMath() {
|
|
268
|
+
const s = state.settings;
|
|
269
|
+
const living = s.studentMode ? s.studentLiving : s.living;
|
|
270
|
+
const extra = s.extraHours * s.netHourly * 52 / 12 + Number(s.extraMonthly || 0);
|
|
271
|
+
$('#budget-math').innerHTML = `${money(s.takeHome)} − ${money(s.fixed)} bills − ${money(living)} everyday${extra ? ` + ${money(extra)} extra` : ''} = <strong>${money(monthlyBudget(s))}/mo to debt</strong>`;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/* ---------- 6. debts ---------- */
|
|
275
|
+
|
|
276
|
+
function orderedDebts() {
|
|
277
|
+
const s = state.settings;
|
|
278
|
+
s.order = [...s.order.filter((id) => state.debts.some((d) => d.id === id)), ...state.debts.map((d) => d.id).filter((id) => !s.order.includes(id))];
|
|
279
|
+
return s.strategy === 'custom' ? [...state.debts].sort((a, b) => s.order.indexOf(a.id) - s.order.indexOf(b.id)) : state.debts;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function renderDebts() {
|
|
283
|
+
const custom = state.settings.strategy === 'custom';
|
|
284
|
+
$('#debt-rows').innerHTML = orderedDebts().map((d, i, all) => `
|
|
285
|
+
<tr data-id="${esc(d.id)}">
|
|
286
|
+
<td data-label="name"><input type="text" id="n-${esc(d.id)}" aria-label="debt name" data-field="name" value="${esc(d.name)}"></td>
|
|
287
|
+
<td class="num" data-label="balance"><input type="number" aria-label="${esc(d.name)} balance" data-field="balance" value="${esc(Number(d.balance).toFixed(2))}" min="0" step="0.01" inputmode="decimal"></td>
|
|
288
|
+
<td class="num" data-label="rate %"><input type="number" class="rate" aria-label="${esc(d.name)} rate percent" data-field="apr" value="${esc(d.apr)}" min="0" step="0.01" inputmode="decimal"></td>
|
|
289
|
+
<td class="num" data-label="promo %"><input type="number" class="rate" aria-label="${esc(d.name)} promo rate percent" data-field="promoApr" value="${esc(d.promoApr ?? '')}" min="0" step="0.01" inputmode="decimal" placeholder="—"></td>
|
|
290
|
+
<td data-label="promo ends"><input type="date" aria-label="${esc(d.name)} promo end date" data-field="promoEnd" value="${esc(d.promoEnd || '')}"></td>
|
|
291
|
+
<td class="num" data-label="minimum"><input type="number" aria-label="${esc(d.name)} minimum payment" data-field="min" value="${esc(d.min)}" min="0" step="1" inputmode="decimal"></td>
|
|
292
|
+
<td class="center" data-label="paid in full monthly"><input type="checkbox" aria-label="${esc(d.name)} is paid in full every month" data-field="payInFull" ${d.payInFull ? 'checked' : ''}></td>
|
|
293
|
+
<td class="gone" data-label="gone by" data-gone="${esc(d.id)}"></td>
|
|
294
|
+
<td><span class="row-actions">
|
|
295
|
+
${custom ? `<button type="button" data-cmd="debt-up" aria-label="move ${esc(d.name)} up" ${i === 0 ? 'disabled' : ''}>↑</button>
|
|
296
|
+
<button type="button" data-cmd="debt-down" aria-label="move ${esc(d.name)} down" ${i === all.length - 1 ? 'disabled' : ''}>↓</button>` : ''}
|
|
297
|
+
<button type="button" data-cmd="remove-debt" aria-label="remove ${esc(d.name)}">remove</button>
|
|
298
|
+
</span></td>
|
|
299
|
+
</tr>`).join('') || '<tr><td colspan="9" class="empty">no debts yet. add the cards and loans you want gone.</td></tr>';
|
|
300
|
+
renderGoneBy();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function renderGoneBy() {
|
|
304
|
+
const debts = openDebts();
|
|
305
|
+
const paidOff = debts.length ? simulate(debts, currentPlan()).paidOff : {};
|
|
306
|
+
document.querySelectorAll('[data-gone]').forEach((cell) => {
|
|
307
|
+
const d = state.debts.find((x) => x.id === cell.dataset.gone);
|
|
308
|
+
const ym = paidOff[cell.dataset.gone];
|
|
309
|
+
const owes = Number(d?.balance) > 0;
|
|
310
|
+
cell.classList.toggle('is-bad', owes && !ym);
|
|
311
|
+
cell.textContent = !owes ? 'paid off' : ym ? monthName(ym, true) : 'not in sight';
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function onDebtInput(e) {
|
|
316
|
+
const row = e.target.closest('tr[data-id]');
|
|
317
|
+
const field = e.target.dataset.field;
|
|
318
|
+
if (!row || !field) return;
|
|
319
|
+
const d = state.debts.find((x) => x.id === row.dataset.id);
|
|
320
|
+
if (field === 'name' || field === 'promoEnd') d[field] = e.target.value;
|
|
321
|
+
else if (field === 'payInFull') d.payInFull = e.target.checked;
|
|
322
|
+
else d[field] = num(e.target.value);
|
|
323
|
+
persist();
|
|
324
|
+
renderNumbers();
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function moveDebt(btn, dir) {
|
|
328
|
+
const order = state.settings.order;
|
|
329
|
+
const i = order.indexOf(btn.closest('tr').dataset.id), j = i + dir;
|
|
330
|
+
if (j < 0 || j >= order.length) return;
|
|
331
|
+
[order[i], order[j]] = [order[j], order[i]];
|
|
332
|
+
persist(); renderDebts(); renderNumbers();
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/* ---------- 7. notes ---------- */
|
|
336
|
+
|
|
337
|
+
function renderNotes() {
|
|
338
|
+
const notes = localInsights(state);
|
|
339
|
+
const p = progressOf(state);
|
|
340
|
+
if (p?.due) notes.unshift({ tone: 'info', text: 'time for a check-in: update your balances so zero can tell whether you’re on track.' });
|
|
341
|
+
else if (p?.status === 'behind') notes.unshift({ tone: 'warn', text: `you’re ${money(-p.diff)} behind the plan you set. new charges on a card you’re paying down are the usual cause.` });
|
|
342
|
+
else if (p?.status === 'ahead') notes.unshift({ tone: 'good', text: `you’re ${money(p.diff)} ahead of the plan you set. keep it there.` });
|
|
343
|
+
$('#local-notes').innerHTML = notes.map((n) => `<li class="${n.tone}">${esc(n.text)}</li>`).join('');
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function askClaude() {
|
|
347
|
+
const box = $('#claude-notes'), btn = $('#ask-claude');
|
|
348
|
+
btn.disabled = true;
|
|
349
|
+
box.innerHTML = '<p class="thinking">claude is reading your numbers </p>';
|
|
350
|
+
try {
|
|
351
|
+
const r = await api.claude('insights', summaryForClaude(state));
|
|
352
|
+
box.innerHTML = `<p class="first">${esc(r.one_thing)}</p>
|
|
353
|
+
<dl>${(r.notes || []).map((n) => `<div><dt>${esc(n.title)}${n.monthly_impact ? ` <span>${money(n.monthly_impact)}/mo</span>` : ''}</dt><dd>${esc(n.body)}</dd></div>`).join('')}</dl>`;
|
|
354
|
+
} catch (err) {
|
|
355
|
+
const fix = /api key/.test(err.message) ? ' <button type="button" class="link" data-cmd="settings">open settings</button>' : '';
|
|
356
|
+
box.innerHTML = `<p class="error">${esc(err.message)}${fix}</p>`;
|
|
357
|
+
} finally {
|
|
358
|
+
btn.disabled = false;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/* ---------- 8. money in / out ---------- */
|
|
363
|
+
|
|
364
|
+
function renderFlow() {
|
|
365
|
+
flowChart($('#flow-chart'), monthlyFlow(state.transactions));
|
|
366
|
+
const cats = byCategory(since(state.transactions, Number($('#window').value))).slice(0, 10);
|
|
367
|
+
const top = cats[0]?.total || 1;
|
|
368
|
+
const list = $('#cats');
|
|
369
|
+
list.innerHTML = cats.length ? cats.map((c) => `<li><span>${esc(c.category)} <span class="count">${c.count}×</span></span><strong>${money(c.total)}</strong><span class="cat-bar"></span></li>`).join('')
|
|
370
|
+
: '<li class="empty">nothing spent in this window.</li>';
|
|
371
|
+
// widths go through the CSSOM so the strict content security policy can forbid inline styles
|
|
372
|
+
list.querySelectorAll('.cat-bar').forEach((b, i) => { b.style.width = `${Math.max(2, (cats[i].total / top) * 100)}%`; });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/* ---------- 9. transactions ---------- */
|
|
376
|
+
|
|
377
|
+
function renderTxFilters() {
|
|
378
|
+
const accounts = [...new Set(state.transactions.map((t) => t.account))].sort();
|
|
379
|
+
const fill = (sel, opts, all) => {
|
|
380
|
+
const v = sel.value;
|
|
381
|
+
sel.innerHTML = `<option value="">${all}</option>` + opts.map((o) => `<option>${esc(o)}</option>`).join('');
|
|
382
|
+
sel.value = opts.includes(v) ? v : '';
|
|
383
|
+
};
|
|
384
|
+
fill($('#tx-account'), accounts, 'all accounts');
|
|
385
|
+
fill($('#tx-category'), CATEGORIES, 'all categories');
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function renderTx() {
|
|
389
|
+
const q = $('#tx-search').value.trim().toLowerCase();
|
|
390
|
+
const acct = $('#tx-account').value, cat = $('#tx-category').value;
|
|
391
|
+
const rows = state.transactions.filter((t) => (!acct || t.account === acct) && (!cat || t.category === cat) &&
|
|
392
|
+
(!q || t.description.toLowerCase().includes(q) || String(Math.abs(t.amount)).includes(q)));
|
|
393
|
+
const options = CATEGORIES.map((c) => `<option>${esc(c)}</option>`).join('');
|
|
394
|
+
$('#tx-rows').innerHTML = rows.slice(0, txShown).map((t) => `
|
|
395
|
+
<tr data-tx="${esc(t.id)}">
|
|
396
|
+
<td class="c-date">${esc(t.date)}</td>
|
|
397
|
+
<td class="c-desc" title="${esc(t.description)}">${esc(t.description)}</td>
|
|
398
|
+
<td class="c-acct">${esc(t.account)}</td>
|
|
399
|
+
<td class="c-cat"><select aria-label="category for ${esc(t.description)}" data-tx-cat>${options}</select></td>
|
|
400
|
+
<td class="num c-amt ${t.amount > 0 ? 'in' : ''}">${t.amount > 0 ? '+' : ''}${money(t.amount, true)}</td>
|
|
401
|
+
<td class="c-act"><span class="row-actions"><button type="button" data-cmd="remove-tx" aria-label="delete ${esc(t.description)}">×</button></span></td>
|
|
402
|
+
</tr>`).join('') || '<tr><td colspan="6" class="empty">no transactions match. press import to add some.</td></tr>';
|
|
403
|
+
$('#tx-rows').querySelectorAll('[data-tx-cat]').forEach((s) => { s.value = state.transactions.find((t) => t.id === s.closest('tr').dataset.tx).category; });
|
|
404
|
+
$('#tx-count').textContent = plural(rows.length, 'transaction');
|
|
405
|
+
$('#tx-more').hidden = rows.length <= txShown;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/* ---------- status bar and banner ---------- */
|
|
409
|
+
|
|
410
|
+
function renderStatus() {
|
|
411
|
+
const info = api.serverInfo();
|
|
412
|
+
const plan = currentPlan();
|
|
413
|
+
const parts = [
|
|
414
|
+
info ? '<span class="ok">local</span>' : '<span>demo</span>',
|
|
415
|
+
`<span class="opt">${info ? `${esc(info.dataDir)}/state.json` : 'browser storage'}</span>`,
|
|
416
|
+
`<span class="${saveStatus.bad ? 'bad' : ''}">${esc(saveStatus.text)}</span>`,
|
|
417
|
+
info ? (info.key.set ? `<span class="opt ok">key ${esc(info.key.hint)}</span>` : '<span class="opt">no api key</span>') : '',
|
|
418
|
+
`<span class="opt">${esc(state.settings.strategy)}</span>`,
|
|
419
|
+
`<span>${money(plan.budget)}/mo</span>`,
|
|
420
|
+
prefs.keys.help ? `<span class="opt">${esc(keyLabel(prefs.keys.help))} shortcuts</span>` : '',
|
|
421
|
+
];
|
|
422
|
+
$('#status').innerHTML = parts.filter(Boolean).join('');
|
|
423
|
+
$('#where').textContent = info ? `zero ${info.version} ${info.dataDir}/` : 'demo: data stays in this browser';
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function renderBanner() {
|
|
427
|
+
const b = $('#banner');
|
|
428
|
+
const info = api.serverInfo();
|
|
429
|
+
const notes = [];
|
|
430
|
+
const repo = document.body.dataset.repo;
|
|
431
|
+
if (!info) notes.push(`demo mode: nothing leaves this browser and claude is off. to use zero for real, run it on your computer${repo ? `: <a href="${esc(repo)}">get it on github</a>` : ' with <code>npm start</code>'}.`);
|
|
432
|
+
if (state.sample) notes.push(`these are sample numbers. <button type="button" class="link" data-cmd="import">import a statement</button><button type="button" class="link" data-cmd="start-empty">start empty</button>`);
|
|
433
|
+
if (prefWarnings.length) notes.push(`settings.json: ${esc(prefWarnings.join('; '))}`);
|
|
434
|
+
for (const msg of Object.values(blocked)) notes.unshift(`<span class="error">${esc(msg)}</span> <button type="button" class="link" data-cmd="reload">reload</button>`);
|
|
435
|
+
b.hidden = !notes.length;
|
|
436
|
+
b.innerHTML = notes.join('<br>');
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** Everything driven by numbers, without rebuilding inputs you may be typing in. */
|
|
440
|
+
function renderNumbers() {
|
|
441
|
+
renderPayoff(); renderProgress(); renderMath(); renderGoneBy(); renderNotes(); renderStatus();
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function renderAll() {
|
|
445
|
+
if (!state) return;
|
|
446
|
+
renderBanner(); renderPlan(); renderDebts(); renderPayoff(); renderProgress(); renderNotes();
|
|
447
|
+
renderFlow(); renderTxFilters(); renderTx(); renderStatus();
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/* ---------- 10. import ---------- */
|
|
451
|
+
|
|
452
|
+
const STATEMENT_TYPES = ['application/pdf', 'image/png', 'image/jpeg', 'image/webp'];
|
|
453
|
+
|
|
454
|
+
function openImport() {
|
|
455
|
+
pending = null;
|
|
456
|
+
$('#import-preview').innerHTML = '';
|
|
457
|
+
$('#import-error').textContent = '';
|
|
458
|
+
$('#import-file').value = '';
|
|
459
|
+
$('#import-confirm').disabled = true;
|
|
460
|
+
$('#import-confirm').textContent = 'add transactions';
|
|
461
|
+
$('#import-dialog').showModal();
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function handleImportFile(file) {
|
|
465
|
+
pending = null;
|
|
466
|
+
const err = $('#import-error'), preview = $('#import-preview');
|
|
467
|
+
err.textContent = '';
|
|
468
|
+
$('#import-confirm').disabled = true;
|
|
469
|
+
if (!file) return;
|
|
470
|
+
if (file.size > 9 * 1024 * 1024) { err.textContent = 'that file is over 9 MB. export a shorter date range.'; return; }
|
|
471
|
+
|
|
472
|
+
if (STATEMENT_TYPES.includes(file.type)) {
|
|
473
|
+
preview.innerHTML = '<p class="thinking">claude is reading the statement </p>';
|
|
474
|
+
try {
|
|
475
|
+
const r = await api.claude('extract', { mediaType: file.type, data: await fileToBase64(file) });
|
|
476
|
+
const rows = (r.transactions || [])
|
|
477
|
+
.map((t) => ({ date: parseDate(t.date), description: String(t.description || '').slice(0, 120), amount: Number(t.amount) }))
|
|
478
|
+
.filter((t) => t.date && Number.isFinite(t.amount));
|
|
479
|
+
pending = { rows, account: r.account_name || file.name, source: 'claude', skipped: r.skipped || [], debt: r.debt };
|
|
480
|
+
renderPreview();
|
|
481
|
+
} catch (e) { preview.innerHTML = ''; err.textContent = e.message; }
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const text = await file.text();
|
|
486
|
+
|
|
487
|
+
// OFX / QFX: the bank's own download format, with ids that make re-imports safe
|
|
488
|
+
if (/\.(ofx|qfx)$/i.test(file.name) || isOFX(text)) {
|
|
489
|
+
const o = parseOFX(text);
|
|
490
|
+
if (!o.rows.length) { preview.innerHTML = ''; err.textContent = 'no transactions found in that OFX file.'; return; }
|
|
491
|
+
const owed = o.isCard && Number.isFinite(o.balance) && o.balance < 0 ? -o.balance : null;
|
|
492
|
+
pending = { rows: o.rows, account: o.account, source: 'ofx', errors: o.errors, debt: owed ? { balance: owed, apr: null, promo_apr: null, promo_end: null, minimum_payment: null } : null };
|
|
493
|
+
renderPreview();
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// a backup: by extension, type, or because it's a JSON object (some browsers drop both)
|
|
498
|
+
if (/\.json$/i.test(file.name) || file.type === 'application/json' || text.trimStart().startsWith('{')) {
|
|
499
|
+
try {
|
|
500
|
+
const restored = parseBackup(text);
|
|
501
|
+
pending = { backup: restored };
|
|
502
|
+
preview.innerHTML = `<p>a zero backup with ${plural(restored.debts.length, 'debt')} and ${plural(restored.transactions.length, 'transaction')}. it replaces everything here.</p>`;
|
|
503
|
+
$('#import-confirm').disabled = false;
|
|
504
|
+
$('#import-confirm').textContent = 'replace with backup';
|
|
505
|
+
} catch (e) { err.textContent = e.message; }
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const parsed = importCSV(text);
|
|
510
|
+
if (!parsed.rows.length) { preview.innerHTML = ''; err.textContent = 'no transactions found. is this a csv export from your bank?'; return; }
|
|
511
|
+
pending = { text, ...parsed, account: parsed.preset?.account || file.name.replace(/\.csv$/i, ''), flip: false, source: 'csv' };
|
|
512
|
+
renderPreview();
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** The debt a statement most likely belongs to: shares a distinctive word with its name. */
|
|
516
|
+
function guessDebt(account) {
|
|
517
|
+
const generic = new Set(['card', 'bank', 'credit', 'visa', 'mastercard', 'checking', 'savings', 'account', 'the']);
|
|
518
|
+
const words = (s) => new Set(String(s).toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !generic.has(w)));
|
|
519
|
+
const mine = words(account);
|
|
520
|
+
return state.debts.find((d) => [...words(d.name)].some((w) => mine.has(w))) || null;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function renderPreview() {
|
|
524
|
+
const p = pending;
|
|
525
|
+
const accounts = [...new Set([...state.transactions.map((t) => t.account), ...state.debts.map((d) => d.name)])];
|
|
526
|
+
const cols = (k) => p.header.map((h, i) => `<option value="${i}" ${p.mapping[k] === i ? 'selected' : ''}>${esc(h)}</option>`).join('');
|
|
527
|
+
const match = p.debt ? guessDebt(p.account) : null;
|
|
528
|
+
|
|
529
|
+
$('#import-preview').innerHTML = `
|
|
530
|
+
<div class="preview">
|
|
531
|
+
<div class="preview-meta">
|
|
532
|
+
<span>${p.source === 'claude' ? 'read by claude' : p.source === 'ofx' ? 'format: OFX / QFX' : p.preset ? `format: ${esc(p.preset.label)}` : 'format not recognized, check the columns'}</span>
|
|
533
|
+
<label>account <input type="text" id="import-account" list="account-list" value="${esc(p.account)}"></label>
|
|
534
|
+
<datalist id="account-list">${accounts.map((a) => `<option value="${esc(a)}">`).join('')}</datalist>
|
|
535
|
+
${p.source === 'csv' ? `<label><input type="checkbox" id="import-flip" ${p.flip ? 'checked' : ''}> flip signs</label>` : ''}
|
|
536
|
+
</div>
|
|
537
|
+
${p.mapping ? `<div class="mapping">
|
|
538
|
+
<label>date <select data-map="date">${cols('date')}</select></label>
|
|
539
|
+
<label>description <select data-map="description">${cols('description')}</select></label>
|
|
540
|
+
<label>amount <select data-map="amount"><option value="-1">debit / credit columns</option>${cols('amount')}</select></label>
|
|
541
|
+
</div>` : ''}
|
|
542
|
+
<div class="table-wrap"><table>
|
|
543
|
+
<thead><tr><th>date</th><th>description</th><th>category</th><th class="num">amount</th></tr></thead>
|
|
544
|
+
<tbody>${p.rows.slice(0, 80).map((r) => `<tr><td>${esc(r.date)}</td><td>${esc(r.description)}</td><td>${esc(categorize(r.description, r.amount, state.learned))}</td><td class="num">${money(r.amount, true)}</td></tr>`).join('')}</tbody>
|
|
545
|
+
</table></div>
|
|
546
|
+
<p class="hint">${plural(p.rows.length, 'transaction')}${p.rows.length > 80 ? ', first 80 shown' : ''}. money in is positive, money out is negative${p.source === 'csv' ? '. if that’s backwards, flip signs' : ''}.
|
|
547
|
+
${p.skipped?.length ? `<br>skipped: ${esc(p.skipped.join('; '))}` : ''}${p.errors?.length ? `<br>${plural(p.errors.length, 'line')} couldn’t be read.` : ''}</p>
|
|
548
|
+
${p.debt?.balance ? `<label class="debt-offer">statement balance ${money(p.debt.balance, true)}${p.debt.apr != null ? `, ${esc(p.debt.apr)}%` : ''}${p.debt.promo_end ? `, ${esc(p.debt.promo_apr ?? 0)}% until ${esc(p.debt.promo_end)}` : ''}${p.debt.minimum_payment != null ? `, minimum ${money(p.debt.minimum_payment)}` : ''}:
|
|
549
|
+
<select id="import-debt" aria-label="what to do with the statement balance">
|
|
550
|
+
<option value="">leave my debts alone</option>
|
|
551
|
+
<option value="new" ${match ? '' : 'selected'}>add it as a new debt</option>
|
|
552
|
+
${state.debts.map((d) => `<option value="${esc(d.id)}" ${match?.id === d.id ? 'selected' : ''}>update ${esc(d.name)}</option>`).join('')}
|
|
553
|
+
</select></label>` : ''}
|
|
554
|
+
</div>`;
|
|
555
|
+
$('#import-confirm').disabled = !p.rows.length;
|
|
556
|
+
$('#import-confirm').textContent = `add ${plural(p.rows.length, 'transaction')}`;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function onPreviewChange(e) {
|
|
560
|
+
if (!pending?.rows) return;
|
|
561
|
+
if (e.target.id === 'import-account') { pending.account = e.target.value; return; }
|
|
562
|
+
if (e.target.id === 'import-flip' || e.target.dataset.map !== undefined) {
|
|
563
|
+
const mapping = pending.mapping ? { ...pending.mapping } : null;
|
|
564
|
+
if (e.target.dataset.map) mapping[e.target.dataset.map] = Number(e.target.value);
|
|
565
|
+
const flip = $('#import-flip')?.checked || false;
|
|
566
|
+
pending = { ...pending, ...importCSV(pending.text, { mapping, flip }), preset: mapping ? null : pending.preset, flip };
|
|
567
|
+
if (mapping) pending.mapping = mapping;
|
|
568
|
+
renderPreview();
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function confirmImport() {
|
|
573
|
+
if (!pending) return;
|
|
574
|
+
if (pending.backup) {
|
|
575
|
+
state = pending.backup;
|
|
576
|
+
$('#import-dialog').close();
|
|
577
|
+
persist(); animateNext = true; renderAll();
|
|
578
|
+
toast(`restored ${plural(state.debts.length, 'debt')} and ${plural(state.transactions.length, 'transaction')}`);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
const account = ($('#import-account')?.value || pending.account || 'imported').trim();
|
|
582
|
+
const { added, skipped } = addTransactions(state, pending.rows, account);
|
|
583
|
+
const choice = $('#import-debt')?.value;
|
|
584
|
+
if (pending.debt?.balance && choice) {
|
|
585
|
+
let d = state.debts.find((x) => x.id === choice);
|
|
586
|
+
if (!d) { d = { id: newDebtId(state), name: account, min: 0, apr: 0, promoApr: '', promoEnd: '' }; state.debts.push(d); }
|
|
587
|
+
d.balance = Number(pending.debt.balance);
|
|
588
|
+
if (pending.debt.apr != null) d.apr = Number(pending.debt.apr);
|
|
589
|
+
if (pending.debt.promo_end) { d.promoEnd = parseDate(pending.debt.promo_end) || ''; d.promoApr = Number(pending.debt.promo_apr ?? 0); }
|
|
590
|
+
if (pending.debt.minimum_payment != null) d.min = Number(pending.debt.minimum_payment);
|
|
591
|
+
}
|
|
592
|
+
state.sample = false;
|
|
593
|
+
persist();
|
|
594
|
+
$('#import-dialog').close();
|
|
595
|
+
pending = null;
|
|
596
|
+
toast(`added ${plural(added, 'transaction')}${skipped ? `, skipped ${skipped} already here` : ''}`);
|
|
597
|
+
renderAll();
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function exportBackup() {
|
|
601
|
+
const blob = new Blob([JSON.stringify(state, null, 2)], { type: 'application/json' });
|
|
602
|
+
const a = document.createElement('a');
|
|
603
|
+
a.href = URL.createObjectURL(blob);
|
|
604
|
+
a.download = `zero-backup-${new Date().toISOString().slice(0, 10)}.json`;
|
|
605
|
+
a.click();
|
|
606
|
+
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
|
607
|
+
toast('backup downloaded');
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/* ---------- 11. settings dialog ---------- */
|
|
611
|
+
|
|
612
|
+
function field(labelText, control) { return `<div class="field"><span>${labelText}</span><div class="row">${control}</div></div>`; }
|
|
613
|
+
const opt = (value, text, current) => `<option value="${esc(value)}" ${String(value) === String(current) ? 'selected' : ''}>${esc(text)}</option>`;
|
|
614
|
+
|
|
615
|
+
function renderSettings() {
|
|
616
|
+
const info = api.serverInfo();
|
|
617
|
+
const t = activeTheme(prefs);
|
|
618
|
+
const fontChoice = FONTS[prefs.font] ? prefs.font : 'custom';
|
|
619
|
+
$('#settings-body').innerHTML = `
|
|
620
|
+
<section aria-labelledby="s-look"><h3 id="s-look">appearance</h3>
|
|
621
|
+
${field('theme', `<select data-pref="theme">${opt('system', 'system (graph / ink)', prefs.theme)}${Object.entries(THEMES).map(([k, v]) => opt(k, v.label, prefs.theme)).join('')}</select>`)}
|
|
622
|
+
${field('colors', `<div class="swatches">${COLOR_KEYS.map((k) => `<label><input type="color" data-color="${k}" value="${t[k]}"> ${k}</label>`).join('')}</div>
|
|
623
|
+
<button type="button" class="quiet" data-cmd="reset-colors" ${Object.keys(prefs.colors).length ? '' : 'disabled'}>reset colors</button>`)}
|
|
624
|
+
${field('font', `<select data-pref="fontChoice">${opt('mono', 'JetBrains Mono', fontChoice)}${opt('sans', 'Hanken Grotesk', fontChoice)}${opt('custom', 'a font on this computer…', fontChoice)}</select>
|
|
625
|
+
<input type="text" data-pref="fontCustom" placeholder="e.g. Berkeley Mono" value="${fontChoice === 'custom' ? esc(prefs.font) : ''}" ${fontChoice === 'custom' ? '' : 'hidden'} aria-label="custom font name">`)}
|
|
626
|
+
${field('text size', `<input type="range" min="11" max="20" step="1" data-pref="fontSize" value="${prefs.fontSize}" aria-label="text size"><output>${prefs.fontSize}px</output>`)}
|
|
627
|
+
${field('density', `<select data-pref="density">${opt('comfortable', 'comfortable', prefs.density)}${opt('compact', 'compact', prefs.density)}</select>`)}
|
|
628
|
+
${field('dates', `<select data-pref="dates">${opt('iso', '2027-03', prefs.dates)}${opt('words', 'march 2027', prefs.dates)}</select>`)}
|
|
629
|
+
${field('money', `<input type="text" data-pref="locale" value="${esc(prefs.locale)}" aria-label="locale" size="8"><input type="text" data-pref="currency" value="${esc(prefs.currency)}" aria-label="currency code" size="4">`)}
|
|
630
|
+
</section>
|
|
631
|
+
|
|
632
|
+
<section aria-labelledby="s-layout"><h3 id="s-layout">layout</h3>
|
|
633
|
+
${field('columns', `<select data-pref="columns">${opt(1, 'one', prefs.columns)}${opt(2, 'two', prefs.columns)}</select>`)}
|
|
634
|
+
${field('panes', `<ol class="pane-list">${[...prefs.panes, ...Object.keys(PANES).filter((p) => !prefs.panes.includes(p))].map((id) => {
|
|
635
|
+
const on = prefs.panes.includes(id), i = prefs.panes.indexOf(id);
|
|
636
|
+
return `<li data-pane-id="${id}"><span>${esc(PANES[id])}</span>
|
|
637
|
+
<label><input type="checkbox" data-pane-show ${on ? 'checked' : ''}> show</label>
|
|
638
|
+
<label><input type="checkbox" data-pane-wide ${prefs.wide.includes(id) ? 'checked' : ''}> full width</label>
|
|
639
|
+
<span class="row-actions"><button type="button" data-cmd="pane-up" aria-label="move ${esc(PANES[id])} up" ${!on || i === 0 ? 'disabled' : ''}>↑</button><button type="button" data-cmd="pane-down" aria-label="move ${esc(PANES[id])} down" ${!on || i === prefs.panes.length - 1 ? 'disabled' : ''}>↓</button></span></li>`;
|
|
640
|
+
}).join('')}</ol>`)}
|
|
641
|
+
${field('chart', `<label><input type="checkbox" data-chart="animate" ${prefs.chart.animate ? 'checked' : ''}> draw-in</label>
|
|
642
|
+
<label><input type="checkbox" data-chart="minimums" ${prefs.chart.minimums ? 'checked' : ''}> minimums-only line</label>
|
|
643
|
+
<label><input type="checkbox" data-chart="promos" ${prefs.chart.promos ? 'checked' : ''}> promo deadlines</label>`)}
|
|
644
|
+
</section>
|
|
645
|
+
|
|
646
|
+
<section aria-labelledby="s-keys"><h3 id="s-keys">keyboard</h3>
|
|
647
|
+
<div class="keylist">${Object.entries(prefs.keys).map(([k, v]) => `<label>${esc(k)} <input type="text" data-keybind="${k}" value="${esc(v)}" spellcheck="false"></label>`).join('')}</div>
|
|
648
|
+
<p class="hint">one key (“i”) or one chord (“mod+k”, “alt+s”). mod is ⌘ on mac, ctrl elsewhere. leave empty to turn a shortcut off. 1–9 jump to panes.</p>
|
|
649
|
+
</section>
|
|
650
|
+
|
|
651
|
+
<section aria-labelledby="s-claude"><h3 id="s-claude">claude</h3>
|
|
652
|
+
${info ? `
|
|
653
|
+
${field('api key', info.key.set
|
|
654
|
+
? `<span class="key-state ok">saved ${esc(info.key.hint)}${info.key.status === 'unverified' ? ' (not verified, you were offline)' : ''}${info.key.source === 'env' ? ' from ANTHROPIC_API_KEY' : ''}</span>
|
|
655
|
+
${info.key.source === 'env' ? '' : '<button type="button" class="quiet" data-cmd="remove-key">remove</button>'}`
|
|
656
|
+
: '<span class="key-state">none yet</span>')}
|
|
657
|
+
${info.key.source === 'env' ? '' : field(info.key.set ? 'replace key' : 'add key', `<input type="password" id="key-input" placeholder="sk-ant-…" autocomplete="off" spellcheck="false" size="28" aria-label="anthropic api key">
|
|
658
|
+
<button type="button" data-cmd="save-key">save key</button>`)}
|
|
659
|
+
<p class="hint">the key is checked with anthropic, then saved to ${esc(info.dataDir)}/secrets.json on this computer with owner-only permissions. the page never sees it again. get one at console.anthropic.com.</p>
|
|
660
|
+
<p class="error" id="key-error" role="alert"></p>
|
|
661
|
+
${field('model', `<input type="text" data-pref="model" value="${esc(prefs.model)}" list="models" spellcheck="false" aria-label="claude model">
|
|
662
|
+
<datalist id="models"><option value="claude-sonnet-5-5"><option value="claude-haiku-5-5"><option value="claude-opus-5-5"></datalist>`)}`
|
|
663
|
+
: '<p class="hint">claude needs the local server, so your api key never touches the browser. run <code>npm start</code> and open http://localhost:4321.</p>'}
|
|
664
|
+
</section>
|
|
665
|
+
|
|
666
|
+
<section aria-labelledby="s-data"><h3 id="s-data">data</h3>
|
|
667
|
+
${field('stored in', info ? `<code>${esc(info.dataDir)}/state.json</code>, <code>settings.json</code>` : 'this browser (demo mode)')}
|
|
668
|
+
${field('backup', '<button type="button" class="quiet" data-cmd="export">download backup</button><button type="button" class="quiet" data-cmd="import">restore or import…</button>')}
|
|
669
|
+
${field('start over', '<button type="button" class="quiet" data-cmd="load-sample">load sample numbers</button><button type="button" class="quiet" data-cmd="start-empty">start empty</button><button type="button" class="danger" data-cmd="erase">erase everything</button>')}
|
|
670
|
+
</section>
|
|
671
|
+
|
|
672
|
+
<section aria-labelledby="s-json"><h3 id="s-json">settings.json</h3>
|
|
673
|
+
<p class="hint">every option above, as text. only values that differ from the defaults are saved.</p>
|
|
674
|
+
<textarea class="json-editor" id="json-editor" spellcheck="false" aria-label="settings.json">${esc(JSON.stringify(diff(prefs), null, 2))}</textarea>
|
|
675
|
+
<div class="row"><button type="button" data-cmd="apply-json">apply</button><button type="button" class="quiet" data-cmd="show-defaults">show all defaults</button></div>
|
|
676
|
+
<p class="error" id="json-error" role="alert"></p>
|
|
677
|
+
</section>`;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function openSettings(focus) {
|
|
681
|
+
renderSettings();
|
|
682
|
+
$('#settings-dialog').showModal();
|
|
683
|
+
if (focus) $(focus)?.focus();
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function onSettingsInput(e) {
|
|
687
|
+
const el = e.target;
|
|
688
|
+
if (el.dataset.pref === 'fontChoice') {
|
|
689
|
+
if (el.value === 'custom') { el.nextElementSibling.hidden = false; el.nextElementSibling.focus(); return; }
|
|
690
|
+
return setPrefs({ font: el.value });
|
|
691
|
+
}
|
|
692
|
+
if (el.dataset.pref === 'fontCustom') { if (el.value.trim()) setPrefs({ font: el.value }); return; }
|
|
693
|
+
if (el.dataset.pref === 'fontSize') { el.nextElementSibling.textContent = `${el.value}px`; return setPrefs({ fontSize: Number(el.value) }); }
|
|
694
|
+
if (el.dataset.pref === 'columns') return setPrefs({ columns: Number(el.value) });
|
|
695
|
+
if (el.dataset.pref) return setPrefs({ [el.dataset.pref]: el.value });
|
|
696
|
+
if (el.dataset.color) return setPrefs({ colors: { ...prefs.colors, [el.dataset.color]: el.value } });
|
|
697
|
+
if (el.dataset.chart) return setPrefs({ chart: { ...prefs.chart, [el.dataset.chart]: el.checked } });
|
|
698
|
+
if (el.dataset.keybind) return setPrefs({ keys: { ...prefs.keys, [el.dataset.keybind]: el.value.trim() } });
|
|
699
|
+
const li = el.closest('[data-pane-id]');
|
|
700
|
+
if (li && el.matches('[data-pane-show]')) {
|
|
701
|
+
const id = li.dataset.paneId;
|
|
702
|
+
setPrefs({ panes: el.checked ? [...prefs.panes, id] : prefs.panes.filter((p) => p !== id) });
|
|
703
|
+
return renderSettings();
|
|
704
|
+
}
|
|
705
|
+
if (li && el.matches('[data-pane-wide]')) {
|
|
706
|
+
const id = li.dataset.paneId;
|
|
707
|
+
return setPrefs({ wide: el.checked ? [...prefs.wide, id] : prefs.wide.filter((p) => p !== id) });
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function movePane(btn, dir) {
|
|
712
|
+
const id = btn.closest('[data-pane-id]').dataset.paneId;
|
|
713
|
+
const panes = [...prefs.panes];
|
|
714
|
+
const i = panes.indexOf(id), j = i + dir;
|
|
715
|
+
if (i < 0 || j < 0 || j >= panes.length) return;
|
|
716
|
+
[panes[i], panes[j]] = [panes[j], panes[i]];
|
|
717
|
+
setPrefs({ panes });
|
|
718
|
+
renderSettings();
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
async function saveKey() {
|
|
722
|
+
const input = $('#key-input'), err = $('#key-error'), btn = document.querySelector('[data-cmd=save-key]');
|
|
723
|
+
err.textContent = '';
|
|
724
|
+
btn.disabled = true; btn.textContent = 'checking…';
|
|
725
|
+
try {
|
|
726
|
+
const r = await api.saveKey(input.value);
|
|
727
|
+
input.value = '';
|
|
728
|
+
toast(r.status === 'valid' ? `key ${r.hint} verified and saved` : `key ${r.hint} saved (couldn’t verify offline)`);
|
|
729
|
+
renderSettings(); renderStatus();
|
|
730
|
+
} catch (e) {
|
|
731
|
+
err.textContent = e.message;
|
|
732
|
+
btn.disabled = false; btn.textContent = 'save key';
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function applyJson() {
|
|
737
|
+
const err = $('#json-error');
|
|
738
|
+
try {
|
|
739
|
+
const parsed = JSON.parse($('#json-editor').value);
|
|
740
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('settings.json must be an object: { … }');
|
|
741
|
+
const next = resolve(parsed);
|
|
742
|
+
prefs = next.settings; prefWarnings = next.warnings;
|
|
743
|
+
applyPrefs(); writePrefs(); renderSettings();
|
|
744
|
+
$('#json-error').textContent = prefWarnings.join('; ');
|
|
745
|
+
if (!prefWarnings.length) toast('settings applied');
|
|
746
|
+
} catch (e) {
|
|
747
|
+
err.textContent = e instanceof SyntaxError ? `not valid JSON: ${e.message}` : e.message;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/* ---------- 12. commands, keys, boot ---------- */
|
|
752
|
+
|
|
753
|
+
const ACTIONS = {
|
|
754
|
+
palette: () => palette.open(),
|
|
755
|
+
import: openImport,
|
|
756
|
+
settings: () => openSettings(),
|
|
757
|
+
'close-settings': () => $('#settings-dialog').close(),
|
|
758
|
+
ask: askClaude,
|
|
759
|
+
student: () => { state.settings.studentMode = !state.settings.studentMode; persist(); renderPlan(); renderNumbers(); toast(`student mode ${state.settings.studentMode ? 'on' : 'off'}`); },
|
|
760
|
+
search: () => { if (prefs.panes.includes('transactions')) { $('#tx-search').focus(); $('#tx-search').scrollIntoView({ block: 'center' }); } },
|
|
761
|
+
help: () => { renderHelp(); $('#help-dialog').showModal(); },
|
|
762
|
+
'confirm-import': confirmImport,
|
|
763
|
+
export: exportBackup,
|
|
764
|
+
'add-debt': () => {
|
|
765
|
+
const id = newDebtId(state);
|
|
766
|
+
state.debts.push({ id, name: 'new debt', balance: 0, apr: 0, promoApr: '', promoEnd: '', min: 0 });
|
|
767
|
+
state.sample = false;
|
|
768
|
+
persist(); renderDebts(); renderBanner();
|
|
769
|
+
document.getElementById(`n-${id}`)?.select();
|
|
770
|
+
},
|
|
771
|
+
'remove-debt': (btn) => {
|
|
772
|
+
if (!armed(btn, 'sure?')) return;
|
|
773
|
+
const id = btn.closest('tr').dataset.id;
|
|
774
|
+
state.debts = state.debts.filter((x) => x.id !== id);
|
|
775
|
+
persist(); renderDebts(); renderNumbers();
|
|
776
|
+
},
|
|
777
|
+
'debt-up': (btn) => moveDebt(btn, -1),
|
|
778
|
+
'debt-down': (btn) => moveDebt(btn, 1),
|
|
779
|
+
'remove-tx': (btn) => {
|
|
780
|
+
const id = btn.closest('tr').dataset.tx;
|
|
781
|
+
state.transactions = state.transactions.filter((t) => t.id !== id);
|
|
782
|
+
persist(); renderTx(); renderFlow(); renderNotes();
|
|
783
|
+
},
|
|
784
|
+
'more-tx': () => { txShown += 100; renderTx(); },
|
|
785
|
+
checkin: openCheckin,
|
|
786
|
+
'save-checkin': saveCheckin,
|
|
787
|
+
'set-plan': setPlan,
|
|
788
|
+
reload: () => location.reload(),
|
|
789
|
+
'load-sample': () => { state = sample(); persist(); animateNext = true; renderAll(); toast('sample numbers loaded'); },
|
|
790
|
+
'start-empty': () => { state = empty(); persist(); renderAll(); toast('cleared. add a debt or import a statement.'); },
|
|
791
|
+
erase: async (btn) => {
|
|
792
|
+
if (!armed(btn, 'tap again to erase')) return;
|
|
793
|
+
state = empty();
|
|
794
|
+
persist();
|
|
795
|
+
if (!api.isLocal()) await api.eraseLocal();
|
|
796
|
+
renderAll(); toast('erased');
|
|
797
|
+
},
|
|
798
|
+
'save-key': saveKey,
|
|
799
|
+
'remove-key': async (btn) => {
|
|
800
|
+
if (!armed(btn, 'sure?')) return;
|
|
801
|
+
try { await api.removeKey(); toast('key removed'); } catch (e) { toast(e.message); }
|
|
802
|
+
renderSettings(); renderStatus();
|
|
803
|
+
},
|
|
804
|
+
'reset-colors': () => { setPrefs({ colors: {} }); renderSettings(); },
|
|
805
|
+
'pane-up': (btn) => movePane(btn, -1),
|
|
806
|
+
'pane-down': (btn) => movePane(btn, 1),
|
|
807
|
+
'apply-json': applyJson,
|
|
808
|
+
'show-defaults': () => { $('#json-editor').value = JSON.stringify(prefs, null, 2); },
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
/** Everything the palette can run. Titles read as "group: action". */
|
|
812
|
+
function commands() {
|
|
813
|
+
const k = (name) => (prefs.keys[name] ? keyLabel(prefs.keys[name]) : '');
|
|
814
|
+
const list = [
|
|
815
|
+
{ title: 'import a file', hint: k('import'), run: openImport },
|
|
816
|
+
{ title: 'progress: check in with today’s balances', hint: k('checkin'), run: openCheckin },
|
|
817
|
+
{ title: 'progress: set my plan from today’s forecast', run: () => setPlan(null) },
|
|
818
|
+
{ title: 'ask claude for notes', hint: k('ask'), run: askClaude },
|
|
819
|
+
{ title: `student mode: turn ${state.settings.studentMode ? 'off' : 'on'}`, hint: k('student'), run: ACTIONS.student },
|
|
820
|
+
{ title: 'debts: add a debt', run: ACTIONS['add-debt'] },
|
|
821
|
+
{ title: 'transactions: search', hint: k('search'), run: ACTIONS.search },
|
|
822
|
+
{ title: 'settings: open', hint: k('settings'), run: () => openSettings() },
|
|
823
|
+
{ title: 'settings: edit settings.json', run: () => openSettings('#json-editor') },
|
|
824
|
+
{ title: 'settings: api key', run: () => openSettings('#key-input') },
|
|
825
|
+
{ title: 'data: download backup', run: exportBackup },
|
|
826
|
+
{ title: 'data: load sample numbers', run: ACTIONS['load-sample'] },
|
|
827
|
+
{ title: 'data: start empty', run: ACTIONS['start-empty'] },
|
|
828
|
+
{ title: 'keyboard shortcuts', hint: k('help'), run: ACTIONS.help },
|
|
829
|
+
];
|
|
830
|
+
for (const [id, name] of [['avalanche', 'highest rate first'], ['snowball', 'smallest balance first'], ['custom', 'my own order']]) {
|
|
831
|
+
list.push({ title: `strategy: ${name}`, run: () => { state.settings.strategy = id; persist(); renderPlan(); renderDebts(); renderNumbers(); } });
|
|
832
|
+
}
|
|
833
|
+
prefs.panes.forEach((id, i) => list.push({ title: `go to: ${PANES[id]}`, hint: i < 9 ? String(i + 1) : '', run: () => jumpTo(id) }));
|
|
834
|
+
for (const id of Object.keys(PANES)) {
|
|
835
|
+
const on = prefs.panes.includes(id);
|
|
836
|
+
list.push({ title: `pane: ${on ? 'hide' : 'show'} ${PANES[id]}`, run: () => setPrefs({ panes: on ? prefs.panes.filter((p) => p !== id) : [...prefs.panes, id] }) });
|
|
837
|
+
}
|
|
838
|
+
list.push({ title: 'theme: system', run: () => setPrefs({ theme: 'system' }) });
|
|
839
|
+
for (const [id, t] of Object.entries(THEMES)) list.push({ title: `theme: ${t.label}`, run: () => setPrefs({ theme: id }) });
|
|
840
|
+
list.push(
|
|
841
|
+
{ title: 'font: JetBrains Mono', run: () => setPrefs({ font: 'mono' }) },
|
|
842
|
+
{ title: 'font: Hanken Grotesk', run: () => setPrefs({ font: 'sans' }) },
|
|
843
|
+
{ title: `layout: ${prefs.columns === 2 ? 'one column' : 'two columns'}`, run: () => setPrefs({ columns: prefs.columns === 2 ? 1 : 2 }) },
|
|
844
|
+
{ title: `layout: ${prefs.density === 'compact' ? 'comfortable' : 'compact'}`, run: () => setPrefs({ density: prefs.density === 'compact' ? 'comfortable' : 'compact' }) },
|
|
845
|
+
{ title: `dates: ${prefs.dates === 'iso' ? 'march 2027' : '2027-03'}`, run: () => setPrefs({ dates: prefs.dates === 'iso' ? 'words' : 'iso' }) },
|
|
846
|
+
);
|
|
847
|
+
return list;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function jumpTo(id) {
|
|
851
|
+
const pane = document.querySelector(`[data-pane="${id}"]`);
|
|
852
|
+
if (!pane || pane.hidden) return;
|
|
853
|
+
pane.scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
|
|
854
|
+
pane.querySelector('input, select, button')?.focus({ preventScroll: true });
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
function renderHelp() {
|
|
858
|
+
const names = { palette: 'commands', settings: 'settings', import: 'import', checkin: 'check in', ask: 'ask claude', student: 'student mode', search: 'search transactions', help: 'this list' };
|
|
859
|
+
$('#shortcuts').innerHTML = Object.entries(prefs.keys).filter(([, v]) => v)
|
|
860
|
+
.map(([k, v]) => `<dt><kbd>${esc(keyLabel(v))}</kbd></dt><dd>${esc(names[k] || k)}</dd>`).join('') +
|
|
861
|
+
'<dt><kbd>1</kbd>–<kbd>9</kbd></dt><dd>jump to a pane</dd><dt><kbd>esc</kbd></dt><dd>close a dialog</dd>';
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
const palette = createPalette($('#palette'), commands);
|
|
865
|
+
|
|
866
|
+
function bind() {
|
|
867
|
+
document.addEventListener('click', (e) => {
|
|
868
|
+
const btn = e.target.closest('[data-cmd]');
|
|
869
|
+
if (btn && ACTIONS[btn.dataset.cmd]) ACTIONS[btn.dataset.cmd](btn);
|
|
870
|
+
});
|
|
871
|
+
|
|
872
|
+
listen(() => prefs.keys, ACTIONS, (e) => {
|
|
873
|
+
// number keys jump to panes, unless you're typing
|
|
874
|
+
if (/^[1-9]$/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey && !/^(input|textarea|select)$/i.test(document.activeElement?.tagName || '') && !document.querySelector('dialog[open]')) {
|
|
875
|
+
const id = prefs.panes[Number(e.key) - 1];
|
|
876
|
+
if (id) { e.preventDefault(); jumpTo(id); }
|
|
877
|
+
return true;
|
|
878
|
+
}
|
|
879
|
+
return false;
|
|
880
|
+
});
|
|
881
|
+
|
|
882
|
+
document.querySelectorAll('input[name=strategy]').forEach((r) => r.addEventListener('change', () => {
|
|
883
|
+
state.settings.strategy = r.value; persist(); renderPlan(); renderDebts(); renderNumbers();
|
|
884
|
+
}));
|
|
885
|
+
const setMoney = (key, value) => { state.settings[key] = value; persist(); renderPlan(); renderNumbers(); };
|
|
886
|
+
$('#student-mode').addEventListener('change', (e) => setMoney('studentMode', e.target.checked));
|
|
887
|
+
$('#extra-hours').addEventListener('input', (e) => setMoney('extraHours', Number(e.target.value)));
|
|
888
|
+
$('#extra-monthly').addEventListener('input', (e) => setMoney('extraMonthly', Number(e.target.value)));
|
|
889
|
+
$('#lump-amount').addEventListener('change', (e) => setMoney('lump', { ...state.settings.lump, amount: Number(e.target.value) || 0 }));
|
|
890
|
+
$('#lump-month').addEventListener('change', (e) => setMoney('lump', { ...state.settings.lump, month: e.target.value }));
|
|
891
|
+
document.querySelectorAll('[data-money]').forEach((i) => i.addEventListener('input', () => setMoney(i.dataset.money, Number(i.value) || 0)));
|
|
892
|
+
|
|
893
|
+
$('#debt-rows').addEventListener('input', onDebtInput);
|
|
894
|
+
$('#debt-rows').addEventListener('change', (e) => { if (e.target.type === 'checkbox') onDebtInput(e); });
|
|
895
|
+
|
|
896
|
+
$('#window').addEventListener('change', renderFlow);
|
|
897
|
+
$('#tx-search').addEventListener('input', () => { txShown = 60; renderTx(); });
|
|
898
|
+
$('#tx-account').addEventListener('change', () => { txShown = 60; renderTx(); });
|
|
899
|
+
$('#tx-category').addEventListener('change', () => { txShown = 60; renderTx(); });
|
|
900
|
+
$('#tx-rows').addEventListener('change', (e) => {
|
|
901
|
+
if (!e.target.matches('[data-tx-cat]')) return;
|
|
902
|
+
const n = recategorize(state, e.target.closest('tr').dataset.tx, e.target.value);
|
|
903
|
+
persist(); renderTx(); renderFlow(); renderNotes();
|
|
904
|
+
toast(n > 1 ? `moved ${n} from this merchant to ${e.target.value}` : `set to ${e.target.value}`);
|
|
905
|
+
});
|
|
906
|
+
|
|
907
|
+
$('#import-file').addEventListener('change', (e) => handleImportFile(e.target.files[0]));
|
|
908
|
+
$('#import-preview').addEventListener('change', onPreviewChange);
|
|
909
|
+
$('#import-preview').addEventListener('input', (e) => { if (e.target.id === 'import-account' && pending) pending.account = e.target.value; });
|
|
910
|
+
const drop = $('#drop');
|
|
911
|
+
['dragenter', 'dragover'].forEach((t) => drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.add('over'); }));
|
|
912
|
+
['dragleave', 'drop'].forEach((t) => drop.addEventListener(t, () => drop.classList.remove('over')));
|
|
913
|
+
drop.addEventListener('drop', (e) => { e.preventDefault(); handleImportFile(e.dataTransfer.files[0]); });
|
|
914
|
+
|
|
915
|
+
$('#checkin-rows').addEventListener('input', updateCheckinTotal);
|
|
916
|
+
$('#checkin-form').addEventListener('keydown', (e) => { if (e.key === 'Enter' && e.target.matches('input')) { e.preventDefault(); saveCheckin(); } });
|
|
917
|
+
$('#settings-body').addEventListener('change', onSettingsInput);
|
|
918
|
+
$('#settings-body').addEventListener('input', (e) => { if (e.target.type === 'range' || e.target.type === 'color') onSettingsInput(e); });
|
|
919
|
+
$('#settings-body').addEventListener('keydown', (e) => { if (e.target.id === 'key-input' && e.key === 'Enter') { e.preventDefault(); saveKey(); } });
|
|
920
|
+
|
|
921
|
+
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (prefs.theme === 'system') applyPrefs(); });
|
|
922
|
+
let resizeTimer;
|
|
923
|
+
window.addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { renderPayoff(); renderProgress(); renderFlow(); }, 150); });
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/** Reads a data file; if it's broken on disk, remembers that so zero never overwrites it. */
|
|
927
|
+
async function readOrBlock(name) {
|
|
928
|
+
try { return await api.readFile(name); } catch (err) {
|
|
929
|
+
blocked[name] = err.message;
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
async function boot() {
|
|
935
|
+
await api.connect();
|
|
936
|
+
const [savedState, savedPrefs] = await Promise.all([readOrBlock('state'), readOrBlock('settings')]);
|
|
937
|
+
document.getElementById('boot-note')?.remove();
|
|
938
|
+
state = fromSaved(savedState);
|
|
939
|
+
saveStatus = blocked.state ? { text: 'not saving', bad: true } : { text: savedState ? 'loaded' : 'not saved yet', bad: false };
|
|
940
|
+
const r = resolve(savedPrefs || {});
|
|
941
|
+
prefs = r.settings; prefWarnings = r.warnings;
|
|
942
|
+
bind();
|
|
943
|
+
applyPrefs();
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
boot();
|