From 2bcf358611b17531245e1ea533b236668d5fde44 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 03:25:27 +0000 Subject: [PATCH 1/7] Fix 'Pick CSV Files' landing on Overview handleFilePick() showed the non-existent 'db-import' view, so showView() fell back to Overview and the file-assignment card was never seen. Open Settings -> Import instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AT1Bh6Sscb8ogzzuf8U3Jc --- js/views-data.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/js/views-data.js b/js/views-data.js index 0fba906..239b242 100644 --- a/js/views-data.js +++ b/js/views-data.js @@ -425,7 +425,10 @@ function handleFilePick(fileList) { lsSet('lastFolderName',folderName); } pendingFileObjects=csvs; - showView('db-import'); + // The Import view is a Settings tab ('db-import' no longer exists, so this used to + // fall back to Overview and hide the file-assignment card). + settingsTab='import'; + showView('settings'); } /* ---- Database > Accounts subtab ---- */ From f7e52a9ab8b649805b4fdff4671125612c838c63 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 03:25:27 +0000 Subject: [PATCH 2/7] Add DB and file primitives for cleanup and reset - DB: STORES, counts(), clearStores(), destroy(); release the connection on versionchange so another tab can't block a reset. - core.js: lsClearAll(), deleteIndexedDB(), folderWithWriteAccess(), saveStateNow(), retireStateFile() (archive with key stripped, or delete), forgetDataFolder(); saveStateToFile() is a no-op while a reset is running. - idbGet/idbSet/idbDel close their connections so finlens_fs can be deleted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AT1Bh6Sscb8ogzzuf8U3Jc --- js/core.js | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- js/db.js | 40 ++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 3 deletions(-) diff --git a/js/core.js b/js/core.js index f761429..3ce6db3 100644 --- a/js/core.js +++ b/js/core.js @@ -34,6 +34,10 @@ const lsSet = (k, v) => { // Auto-save full State to filesystem (debounced) if (typeof _saveStateDebounced !== 'undefined') _saveStateDebounced(State); }; +// Removes every finlens_* key from localStorage. Only "Start over" should call this. +const lsClearAll = () => { + Object.keys(localStorage).filter(k => k.startsWith('finlens_')).forEach(k => localStorage.removeItem(k)); +}; const debounce = (fn, ms=300) => { let t; return (...a)=>{ clearTimeout(t); t=setTimeout(()=>fn(...a),ms); }; }; const today = () => new Date(new Date().toDateString()); const startOfMonth = (d=new Date()) => new Date(d.getFullYear(),d.getMonth(),1); @@ -121,6 +125,9 @@ async function loadStateFromFile() { // Save state to finlens-state.json in the backup folder async function saveStateToFile(state) { + // "Start over" sets this so a pending debounced save can't re-create the file + // between the reset and the page reload. + if (State._resetInProgress) return false; try { const dirHandle = await idbGet('csvDirHandle'); if (!dirHandle) { @@ -171,6 +178,72 @@ const _saveStateDebounced = debounce(async (state) => { await saveStateToFile(state); }, 5000); +/* ---------- Folder + state-file maintenance (Settings → Data & Reset) ---------- */ +// Browsers only show a file-permission prompt during a user gesture, so the +// functions that may need write access must be called from a click handler. + +// Returns the connected folder handle with read-write access, or null when no folder +// is connected or access was refused. +async function folderWithWriteAccess() { + const dir = await idbGet('csvDirHandle'); + if (!dir) return null; + try { + let perm = await dir.queryPermission({ mode: 'readwrite' }); + if (perm !== 'granted') perm = await dir.requestPermission({ mode: 'readwrite' }); + return perm === 'granted' ? dir : null; + } catch(e) { return null; } +} + +// Writes finlens-state.json right away, e.g. after clearing data, so the next page +// load can't restore what was just cleared from an older file. +// Returns 'saved', 'no-folder' or 'denied'. +async function saveStateNow() { + if (!(await idbGet('csvDirHandle'))) return 'no-folder'; + if (!(await folderWithWriteAccess())) return 'denied'; + return (await saveStateToFile(State)) ? 'saved' : 'denied'; +} + +// Used by "Start over": retires finlens-state.json so reconnecting the same folder +// later doesn't bring the old state back. 'archive' renames it to +// finlens-state.backup-.json (API key stripped); 'delete' removes it. +// CSV files are never touched. +// Returns { status: 'archived'|'deleted'|'none'|'no-folder'|'denied'|'error', name? }. +async function retireStateFile(mode) { + if (!(await idbGet('csvDirHandle'))) return { status: 'no-folder' }; + const dir = await folderWithWriteAccess(); + if (!dir) return { status: 'denied' }; + let fh; + try { fh = await dir.getFileHandle('finlens-state.json'); } + catch(e) { return { status: e.name === 'NotFoundError' ? 'none' : 'error' }; } + try { + let name; + if (mode === 'archive') { + const text = await (await fh.getFile()).text(); + let out = text; + try { const obj = JSON.parse(text); delete obj.apiKey; out = JSON.stringify(obj, null, 2); } catch(e) { /* keep raw text */ } + name = `finlens-state.backup-${dayjs().format('YYYYMMDD-HHmmss')}.json`; + const w = await (await dir.getFileHandle(name, { create: true })).createWritable(); + await w.write(out); + await w.close(); + } + await dir.removeEntry('finlens-state.json'); + return { status: mode === 'archive' ? 'archived' : 'deleted', name }; + } catch(e) { + console.warn('[FinLens] retireStateFile:', e.message); + return { status: 'error' }; + } +} + +// Disconnects the CSV folder: FinLens forgets the stored handle, so it stops +// auto-importing that folder's CSVs and writing finlens-state.json there. +// Nothing on disk is changed. +async function forgetDataFolder() { + await idbDel('csvDirHandle'); + State.lastFolderName = ''; + State._csvNeedsReconnect = false; + lsSet('lastFolderName', ''); +} + /* ---------- IndexedDB helpers (for persisting FileSystemDirectoryHandle) ---------- */ function _idbOpen() { return new Promise((res, rej) => { @@ -180,18 +253,30 @@ function _idbOpen() { req.onerror = () => rej(req.error); }); } +// Each helper opens its own short-lived connection and closes it when done +// (close() waits for the transaction), so finlens_fs can be deleted on reset. async function idbGet(key) { - try { const db=await _idbOpen(); return await new Promise(r=>{ const q=db.transaction('kv','readonly').objectStore('kv').get(key); q.onsuccess=()=>r(q.result??null); q.onerror=()=>r(null); }); } + try { const db=await _idbOpen(); return await new Promise(r=>{ const q=db.transaction('kv','readonly').objectStore('kv').get(key); q.onsuccess=()=>r(q.result??null); q.onerror=()=>r(null); db.close(); }); } catch(e){ return null; } } async function idbSet(key, val) { - try { const db=await _idbOpen(); await new Promise(r=>{ const q=db.transaction('kv','readwrite').objectStore('kv').put(val,key); q.onsuccess=()=>r(); q.onerror=()=>r(); }); } + try { const db=await _idbOpen(); await new Promise(r=>{ const q=db.transaction('kv','readwrite').objectStore('kv').put(val,key); q.onsuccess=()=>r(); q.onerror=()=>r(); db.close(); }); } catch(e){} } async function idbDel(key) { - try { const db=await _idbOpen(); await new Promise(r=>{ const q=db.transaction('kv','readwrite').objectStore('kv').delete(key); q.onsuccess=()=>r(); q.onerror=()=>r(); }); } + try { const db=await _idbOpen(); await new Promise(r=>{ const q=db.transaction('kv','readwrite').objectStore('kv').delete(key); q.onsuccess=()=>r(); q.onerror=()=>r(); db.close(); }); } catch(e){} } +// Deletes a whole IndexedDB database. Resolves 'deleted', 'blocked' (another open +// connection — the delete then completes once it closes) or 'error'. +function deleteIndexedDB(name) { + return new Promise((res) => { + const req = indexedDB.deleteDatabase(name); + req.onsuccess = () => res('deleted'); + req.onerror = () => res('error'); + req.onblocked = () => res('blocked'); + }); +} /* ---------- AppState ---------- */ diff --git a/js/db.js b/js/db.js index bd1f7f3..36cc197 100644 --- a/js/db.js +++ b/js/db.js @@ -62,6 +62,9 @@ const DB = { req.onsuccess = (e) => { this._db = e.target.result; this._db.onerror = (ev) => console.error('DB error:', ev.target.error); + // Another tab is deleting or upgrading the database (e.g. "Start over"): + // let go so it isn't blocked. This tab then keeps working from memory. + this._db.onversionchange = () => { this._db.close(); this._db = null; }; res(); }; @@ -497,4 +500,41 @@ const DB = { req.onerror = () => res([]); }); }, + + /* ── Cleanup & reset (used by Settings → Data & Reset, views-cleanup.js) ── */ + + /** Every object store in finlens_db. Keep in sync with open() → onupgradeneeded. */ + STORES: ['transactions', 'tx_overrides', 'accounts', 'import_log', 'app_state'], + + /** Returns { [storeName]: recordCount } (null for a store that couldn't be read). */ + async counts() { + const out = {}; + if (!this._db) return out; + for (const name of this.STORES) { + try { out[name] = await this._req(this._getStore(name).count()); } + catch(e) { out[name] = null; } + } + return out; + }, + + /** Empties the given object stores in a single transaction. Resolves true once committed. */ + clearStores(names) { + if (!this._db || !names.length) return Promise.resolve(false); + return new Promise((res) => { + const t = this._db.transaction(names, 'readwrite'); + names.forEach(n => t.objectStore(n).clear()); + t.oncomplete = () => res(true); + t.onerror = t.onabort = () => res(false); + }); + }, + + /** + * Closes this tab's connection and deletes finlens_db entirely. + * Resolves 'deleted', 'blocked' (another FinLens tab still has it open — the + * delete finishes when that tab closes or reloads) or 'error'. + */ + destroy() { + if (this._db) { this._db.close(); this._db = null; } + return deleteIndexedDB(this.DB_NAME); + }, }; From a2ee30c6b02ffb303bb36ed51f9f5595abd839e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 03:25:27 +0000 Subject: [PATCH 3/7] Add Settings -> Data & Reset tab; make Clear All Data actually reset New views-cleanup.js (DataCleanup namespace): - Clear imported transactions & accounts, the import log, or transaction edits; clear budgets, bills, buckets, debts or AI history individually. - Rebuild from folder: clear imported data + log, then re-import every CSV. - Disconnect the CSV folder (nothing on disk changes). - Start over (type RESET): retire finlens-state.json (rename to a backup or delete), delete both IndexedDB databases and all finlens_* keys, reload. - After clearing, finlens-state.json is rewritten immediately so a reload can't restore the cleared data. - Two-step confirm buttons keep a fresh user gesture for permission prompts. The Danger Zone moves out of General. clearAllData() now runs the full reset; before, it only cleared localStorage and IndexedDB restored everything. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AT1Bh6Sscb8ogzzuf8U3Jc --- .gitignore | 4 +- index.html | 2 + js/ui.js | 6 +- js/views-cleanup.js | 285 +++++++++++++++++++++++++++++++++++++++++++ js/views-settings.js | 96 ++------------- 5 files changed, 305 insertions(+), 88 deletions(-) create mode 100644 js/views-cleanup.js diff --git a/.gitignore b/.gitignore index 4f39355..0dfee09 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,10 @@ # Financial data — never commit real transaction exports or backups data/ finlens-data.json -# State backup (all transactions + settings) — ignored wherever the CSV folder lives +# State backup (all transactions + settings), plus copies archived by "Start over" — +# ignored wherever the CSV folder lives finlens-state.json +finlens-state.backup-*.json # Settings exports and saved AI analyses finlens-export-*.json finlens-analysis-*.md diff --git a/index.html b/index.html index f1e77f8..34fe65a 100644 --- a/index.html +++ b/index.html @@ -148,6 +148,7 @@ .btn.ghost:hover{background:var(--surface-2)} .btn.danger{background:var(--red);color:#fff} .btn.sm{padding:5px 10px;font-size:12px} +.btn:disabled{opacity:.45;cursor:not-allowed;filter:none} table.tbl{width:100%;border-collapse:collapse;font-size:13px} table.tbl th{text-align:left;color:var(--text-2);font-weight:500;font-size:11.5px;text-transform:uppercase;letter-spacing:.5px;padding:8px 10px;border-bottom:1px solid var(--border)} @@ -394,6 +395,7 @@

Transaction Detail

+ diff --git a/js/ui.js b/js/ui.js index 480b7a4..e813e75 100644 --- a/js/ui.js +++ b/js/ui.js @@ -370,7 +370,9 @@ function importJsonFile(ev) { }; reader.readAsText(file); } +// Erase everything and reload. Clearing only localStorage (as ≤v1.8.1 did) was undone on +// reload by IndexedDB and finlens-state.json, so this delegates to the full reset in +// views-cleanup.js. Call it from a click handler (it may need folder write access). function clearAllData() { - Object.keys(localStorage).filter(k=>k.startsWith('finlens_')).forEach(k=>localStorage.removeItem(k)); - location.reload(); + return DataCleanup.startOver('archive'); } diff --git a/js/views-cleanup.js b/js/views-cleanup.js new file mode 100644 index 0000000..fe87940 --- /dev/null +++ b/js/views-cleanup.js @@ -0,0 +1,285 @@ +/* ================================================================ + FINLENS — views-cleanup.js + Settings → Data & Reset: clean up imported data, the database and + logs, clear plans, disconnect the CSV folder, or start over. + Loaded after views-settings.js, before views-db.js. + + Where FinLens keeps data (keep in sync with CLAUDE.md §20): + - memory State + - localStorage finlens_* keys (lsSet / lsGet) + - IndexedDB finlens_db (DB.STORES) and finlens_fs (CSV folder handle) + - disk finlens-state.json in the connected CSV folder + (CSV files themselves are never modified) +================================================================ */ + +const DataCleanup = { + lastMessage: null, // { kind: 'good'|'warn'|'bad', text } shown once at the top of the tab + + // Plans and history the user created: [State key (= lsSet key), label] + PLAN_ITEMS: [ + ['budgets', 'Budgets'], + ['bills', 'Bills'], + ['buckets', 'Savings buckets'], + ['debts', 'Debts'], + ['aiHistory', 'AI history'], + ], + + /* ---------- actions ---------- */ + + async clearImported() { + this._dropImported(); + await DB.clearStores(['transactions', 'accounts']); + buildAccountFilter(); + await this._finish('Imported transactions and accounts cleared.'); + }, + + async clearImportLog() { + await DB.clearStores(['import_log']); + _importLogCache = []; + this._done('good', 'Import log cleared.'); + }, + + async clearEdits() { + State.txOverrides = {}; + lsSet('txOverrides', {}); + await DB.clearStores(['tx_overrides']); + // Rebuild the loaded transactions without overrides so the change shows now. + if (DB._db && State.transactions.length) { + const raw = await DB._getAllTransactions(); + State.transactions = raw.map(r => reconstituteTx(r, {})).sort((a, b) => b.date - a.date); + detectTransfers(); + } + await this._finish('Transaction edits cleared.'); + }, + + async clearPlan(key) { + const item = this.PLAN_ITEMS.find(i => i[0] === key); + if (!item) return; + State[key] = []; + lsSet(key, []); + await this._finish(`${item[1]} cleared.`); + }, + + async rebuildFromFolder() { + const handle = await idbGet('csvDirHandle'); + if (!handle) return this._done('bad', 'No CSV folder is connected.'); + // Ask for access now, while still inside the click: read-write also lets the + // backup file be updated afterwards; read is the minimum needed to re-import. + let canRead = !!(await folderWithWriteAccess()); + if (!canRead) { + try { + canRead = (await handle.queryPermission({ mode: 'read' })) === 'granted' + || (await handle.requestPermission({ mode: 'read' })) === 'granted'; + } catch(e) { canRead = false; } + } + if (!canRead) return this._done('bad', `FinLens doesn't have access to “${State.lastFolderName}”. Nothing was cleared.`); + + this._dropImported(); + _importLogCache = []; + await DB.clearStores(['transactions', 'accounts', 'import_log']); + await reloadFromDirHandle(handle); // re-imports every CSV, detects transfers, renders + await this._finish(`Rebuilt from “${State.lastFolderName}”: ${State.transactions.length.toLocaleString()} transactions re-imported.`); + }, + + async disconnectFolder() { + const name = State.lastFolderName || 'the folder'; + await forgetDataFolder(); + buildAccountFilter(); + this._done('good', `Disconnected “${name}”. FinLens no longer reads CSVs from it or saves finlens-state.json there. Nothing on disk was changed.`); + }, + + /** + * Erase everything FinLens stores, then reload. Must run from a click: it may + * need write access to the folder to retire finlens-state.json. + * stateFile: 'archive' (rename to finlens-state.backup-.json) | 'delete' + */ + async startOver(stateFile = 'archive') { + State._resetInProgress = true; // blocks pending/future auto-saves until the reload + const file = await retireStateFile(stateFile); + await idbDel('csvDirHandle'); + const dbStatus = await DB.destroy(); + const fsStatus = await deleteIndexedDB('finlens_fs'); + lsClearAll(); + + const lines = ['FinLens has been reset and will now reload with no data.']; + if (file.status === 'archived') lines.push(`Your old backup file was renamed to ${file.name} (API key removed).`); + if (file.status === 'deleted') lines.push('finlens-state.json was deleted.'); + if (file.status === 'denied' || file.status === 'error') { + lines.push(`Couldn't ${stateFile === 'archive' ? 'rename' : 'delete'} finlens-state.json, so it's still in the folder. If you reconnect that folder, rename or delete the file first, or your old data will come back.`); + } + if (dbStatus === 'blocked' || fsStatus === 'blocked') { + lines.push('Another FinLens tab is still open. Close it so the database can finish erasing.'); + } + alert(lines.join('\n\n')); + location.reload(); + }, + + /* ---------- helpers ---------- */ + + // Forget imported data in memory (the caller clears the matching DB stores). + _dropImported() { + State.transactions = []; + State.accounts = {}; + State.fileMeta = []; + State.selectedAccounts = 'all'; + State.lastRefresh = null; + _lastImportResults = []; + _coverageCache = {}; + }, + + // After clearing data that finlens-state.json also holds: rewrite the file now, + // so the next page load can't restore what was just cleared. + async _finish(text) { + const file = await saveStateNow(); + if (file === 'denied') { + this._done('warn', `${text} But FinLens couldn't update finlens-state.json in “${State.lastFolderName}” (no write access), so reloading may bring the cleared data back. Allow access when asked, or disconnect the folder.`); + } else { + this._done('good', text + (file === 'saved' ? ' Backup file updated.' : '')); + } + }, + + _done(kind, text) { + this.lastMessage = { kind, text }; + renderActive(); + }, +}; + +/* ---------- view ---------- */ + +const DC_ROW_STYLE = 'display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 14px;border:1px solid var(--border);border-radius:var(--radius-sm)'; + +registerView('data-cleanup', 'Data & Reset', (root) => { + const msg = DataCleanup.lastMessage; + DataCleanup.lastMessage = null; + if (msg) { + const banner = document.createElement('div'); + banner.className = 'insight' + (msg.kind === 'good' ? '' : ' ' + msg.kind); + banner.style.marginBottom = '2px'; + banner.textContent = msg.text; + root.appendChild(banner); + } + + const folder = State.lastFolderName; + const n = (x) => Number(x || 0).toLocaleString(); + const plural = (x, one, many) => `${n(x)} ${x === 1 ? one : many}`; + // A two-step button: first click arms it, second click runs the action. + const btn = (action, label, arg = '', cls = 'btn danger sm') => + ``; + const row = (title, count, desc, button) => ` +
+
+
${title} ${count}
+
${desc}
+
+ ${button} +
`; + + /* ---- Imported data & database ---- */ + const imported = document.createElement('div'); imported.className = 'card'; + imported.innerHTML = ` +

Imported data & database

+

Data that came from your CSV files. Clearing it keeps your plans, account names, balances and settings.

+
+ ${row('Transactions & accounts', + `${plural(State.transactions.length, 'transaction', 'transactions')} loaded · … in database · …`, + 'Removes every imported transaction and account record from this browser.', + btn('clearImported', 'Clear'))} + ${row('Import log', '…', + 'The history of CSV imports shown under Settings → Import.', + btn('clearImportLog', 'Clear'))} + ${row('Transaction edits', plural(Object.keys(State.txOverrides || {}).length, 'edit', 'edits'), + 'Your changes to descriptions, categories, notes and flags. Edits are kept when you clear or re-import transactions, so they re-apply automatically.', + btn('clearEdits', 'Clear'))} + ${folder ? `
${row('Rebuild from folder', `📁 ${escapeHtml(folder)}`, + 'Clears imported transactions, accounts and the import log, then re-imports every CSV in the folder. Fixes a messy database without touching your plans.', + btn('rebuildFromFolder', 'Rebuild', '', 'btn sm'))}
` : ''} +
+ ${folder ? `
“${escapeHtml(folder)}” is connected, so FinLens re-imports its CSVs the next time the page loads with no transactions. To keep cleared transactions gone, disconnect the folder below.
` : ''}`; + root.appendChild(imported); + + /* ---- Plans & history ---- */ + const plans = document.createElement('div'); plans.className = 'card'; + plans.innerHTML = ` +

Your plans & history

+

Things you created in FinLens. Clearing one can't be undone.

+
+ ${DataCleanup.PLAN_ITEMS.map(([key, label]) => { + const len = (State[key] || []).length; + return row(label, key === 'aiHistory' ? plural(len, 'entry', 'entries') : n(len), '', btn('clearPlan', 'Clear', key)); + }).join('')} +
`; + root.appendChild(plans); + + /* ---- CSV folder & backup file ---- */ + const files = document.createElement('div'); files.className = 'card'; + files.innerHTML = ` +

CSV folder & backup file

+ ${folder + ? `
+ ${row(`📁 ${escapeHtml(folder)}`, + State.lastFsyncTime ? '· backup saved ' + dayjs(State.lastFsyncTime).format('MMM D, h:mm A') : '', + 'FinLens reads your CSVs from this folder and saves finlens-state.json there. Disconnecting stops both; nothing on disk is changed.', + btn('disconnectFolder', 'Disconnect', '', 'btn ghost sm'))} +
` + : `

No CSV folder is connected, so nothing is saved to disk. Connect one under Settings → Import.

`}`; + root.appendChild(files); + + /* ---- Start over ---- */ + const reset = document.createElement('div'); reset.className = 'card'; + reset.style.borderColor = 'var(--red)'; + reset.innerHTML = ` +

Start over from scratch

+

Erases everything FinLens keeps in this browser — transactions, accounts, import log, edits, budgets, bills, buckets, debts, AI history, settings and your API key — and disconnects your CSV folder. Your CSV files are never touched.

+ ${folder ? ` +
+
Backup file in “${escapeHtml(folder)}”
+ + +
Either way, reconnecting this folder later starts fresh. FinLens may ask for permission to change the folder.
+
` : ''} + +
+ + +
`; + root.appendChild(reset); + + /* ---- wiring ---- */ + root.querySelectorAll('[data-dc-action]').forEach(b => b.addEventListener('click', async () => { + if (b.dataset.armed !== '1') { + // First click arms the button; the second click (a fresh user gesture, which + // file-permission prompts require) runs the action. + b.dataset.armed = '1'; + b.textContent = 'Click again to confirm'; + setTimeout(() => { if (b.isConnected && b.dataset.armed === '1') { b.dataset.armed = ''; b.textContent = b.dataset.dcLabel; } }, 4000); + return; + } + b.dataset.armed = ''; + b.disabled = true; + b.textContent = 'Working…'; + try { await DataCleanup[b.dataset.dcAction](b.dataset.dcArg); } + catch(e) { console.error('[FinLens] cleanup:', e); DataCleanup._done('bad', 'Something went wrong: ' + (e.message || e)); } + })); + + const confirmInput = $('#dcResetConfirm'); + const resetBtn = $('#dcResetBtn'); + confirmInput.addEventListener('input', () => { resetBtn.disabled = confirmInput.value.trim() !== 'RESET'; }); + resetBtn.addEventListener('click', () => { + if (confirmInput.value.trim() !== 'RESET') return; + resetBtn.disabled = true; + resetBtn.textContent = 'Erasing…'; + const choice = $('input[name="dcStateFile"]:checked'); + DataCleanup.startOver(choice ? choice.value : 'archive'); + }); + + // Database counts load asynchronously (renders stay synchronous — CLAUDE.md §15). + setTimeout(async () => { + const c = typeof DB !== 'undefined' ? await DB.counts() : {}; + const set = (id, text) => { const el = $('#' + id); if (el) el.textContent = text; }; + set('dcDbTx', c.transactions == null ? '—' : n(c.transactions)); + set('dcDbAcct', c.accounts == null ? '—' : plural(c.accounts, 'account', 'accounts')); + set('dcDbLog', c.import_log == null ? '—' : plural(c.import_log, 'entry', 'entries')); + // A folder name without a stored handle (legacy file input) can't be re-read. + if (!(await idbGet('csvDirHandle'))) $$('[data-needs-handle]').forEach(el => el.remove()); + }, 0); +}); diff --git a/js/views-settings.js b/js/views-settings.js index 776ddcc..18cace0 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -1,6 +1,7 @@ /* ================================================================ FINLENS — views-settings.js - Settings tab — Display, Anthropic API Key, Import, Accounts, Categories, Danger Zone + Settings shell (tab bar) + General tab: Display, Anthropic API Key. + Clearing data and starting over live in the Data & Reset tab (views-cleanup.js). ================================================================ */ let settingsTab='general'; @@ -11,6 +12,7 @@ const SETTINGS_TABS=[ ['accounts', '🏦 Accounts'], ['credit-cards','💳 Credit Cards'], ['categories','🏷️ Categories'], + ['data-cleanup','🧹 Data & Reset'], ]; registerView('settings','Settings',(root)=>{ @@ -67,59 +69,14 @@ function _renderGeneralSettings(root) { $('#apiKeyInput').addEventListener('keydown',e=>{ if (e.key==='Enter') saveApiKey(); }); if ($('#apiKeyRemove')) $('#apiKeyRemove').addEventListener('click',()=>{ if (confirm('Remove the saved API key from this browser?')) removeApiKey(); }); - /* ---- Danger Zone ---- */ - const dangerCard=document.createElement('div'); dangerCard.className='card'; - dangerCard.innerHTML=` -

Danger Zone

-

Permanently erase data from this browser. This cannot be undone.

-
-
-
-
Transactions
-
${State.transactions.length.toLocaleString()} transactions
-
- -
-
-
-
Budgets
-
${State.budgets.length} budget${State.budgets.length!==1?'s':''}
-
- -
-
-
-
Bills
-
${State.bills.length} bill${State.bills.length!==1?'s':''}
-
- -
-
-
-
Savings Buckets
-
${State.buckets.length} bucket${State.buckets.length!==1?'s':''}
-
- -
-
-
-
Debts
-
${State.debts.length} debt${State.debts.length!==1?'s':''}
-
- -
-
-
-
Transaction Edits
-
${Object.keys(State.txOverrides).length} override${Object.keys(State.txOverrides).length!==1?'s':''}
-
- -
-
- -
-
`; - root.appendChild(dangerCard); + /* ---- Pointer to Data & Reset (the old Danger Zone moved there in v1.9.0) ---- */ + const dataCard=document.createElement('div'); dataCard.className='card'; + dataCard.innerHTML=` +

Clear data or start over

+

Clean up imported transactions, the database and import log, clear budgets or bills, or erase everything and start from scratch.

+ `; + root.appendChild(dataCard); + $('#openDataReset').addEventListener('click',()=>{ settingsTab='data-cleanup'; renderActive(); }); } /* ---- API key (browser storage only — saveStateToFile() excludes it) ---- */ @@ -141,37 +98,6 @@ function saveCurrency(val) { // TODO: future — convert currency symbol in formatters } -/* ---- Clear an individual dataset ---- */ -function clearDataset(key) { - const defaults = { - transactions: [], - budgets: [], - bills: [], - buckets: [], - debts: [], - txOverrides: {}, - }; - if (!(key in defaults)) return; - State[key] = defaults[key]; - lsSet(key, defaults[key]); - // Also wipe from IndexedDB if available - if (typeof DB !== 'undefined' && DB._db) { - if (key === 'transactions') { - // Clear transactions store in IndexedDB - DB._db.transaction('transactions','readwrite').objectStore('transactions').clear(); - State.accounts = {}; - lsSet('accounts', {}); - State.fileMeta = []; - lsSet('fileMeta', []); - State.accountOrder = []; - lsSet('accountOrder', []); - } else { - DB.setState(key, defaults[key]); - } - } - renderActive(); -} - /* Transfer keyword helpers (renderKwChipsTransfers, addTransferKeywordTransfers, deleteTransferKeywordFromTransfers, reapplyTransferKeywords) live in views-main.js alongside the Transfers tab that owns the keyword editor. */ From 4b59df6ee173b752939f85b45280f816ad5d051c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 03:25:28 +0000 Subject: [PATCH 4/7] =?UTF-8?q?Release=20v1.9.0:=20changelog,=20version=20?= =?UTF-8?q?strings,=20CLAUDE.md=20=C2=A720,=20README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AT1Bh6Sscb8ogzzuf8U3Jc --- CHANGELOG.md | 36 +++++++++++++++++++++++ CLAUDE.md | 69 ++++++++++++++++++++++++++++++++++++++------ README.md | 14 +++++++-- index.html | 2 +- js/views-settings.js | 2 +- 5 files changed, 109 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 357f408..d4e1fd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,42 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.9.0] — 2026-10-23 + +### Settings → 🧹 Data & Reset (new tab, `views-cleanup.js`) +- **One place for all cleanup.** The Danger Zone moved here from General, which now keeps Display and the API key plus a link to the new tab. +- **Imported data & database:** + - Clear imported transactions & accounts (memory + `transactions`/`accounts` stores). Plans, edits, account names and balances are kept. + - Clear the import log. + - Clear transaction edits (also rebuilds the loaded transactions without overrides). + - Each row shows live counts from memory and IndexedDB. +- **Rebuild from folder** — clears imported transactions, accounts and the import log, then re-imports every CSV in the connected folder. It fixes a messy database without touching plans. +- **Plans & history** — clear budgets, bills, savings buckets, debts or AI history individually. +- **CSV folder & backup file** — disconnect the folder (FinLens forgets the handle; nothing on disk changes). +- **Start over from scratch:** + - Type `RESET` to erase everything: both IndexedDB databases, all `finlens_*` localStorage keys (including the API key), the folder connection, then reload. + - `finlens-state.json` is either renamed to `finlens-state.backup-.json` (API key stripped) or deleted, so reconnecting the folder later starts fresh. + - CSV files are never touched. +- **Safer confirmations** — destructive buttons use click-again-to-confirm, so the folder-permission prompt that may follow gets a fresh user gesture. An alert can't outlast the browser's activation window. + +### Fixed +- **"Clear All Data" didn't clear anything.** `clearAllData()` only removed localStorage keys, so on reload `DB.loadAll()` (and `finlens-state.json`) restored every transaction, budget and setting. It now runs the full Start over. +- **Cleared data could come back on reload.** The state file is loaded first at boot but was only rewritten by the 5-second debounced save, so a quick reload restored it. Clearing now writes it immediately via `saveStateNow()`, and warns if write access is refused. +- **Clearing transactions left empty account cards.** The `accounts` store is now cleared too, and the account filter is rebuilt. +- **"Pick CSV Files" landed on Overview.** `handleFilePick()` showed the non-existent `db-import` view, which hid the file-assignment card. It now opens Settings → Import. +- **`finlens_fs` connections were never closed.** `idbGet`/`idbSet`/`idbDel` now close them, so the database can be deleted. +- **Other tabs could block a reset.** `DB.open()` now releases the connection on `versionchange`. + +### Technical +- **New `DB` methods:** `STORES`, `counts()`, `clearStores(names)`, `destroy()`. +- **New `core.js` helpers:** `lsClearAll()`, `deleteIndexedDB()`, `folderWithWriteAccess()`, `saveStateNow()`, `retireStateFile()`, `forgetDataFolder()`. +- **Auto-save guard:** `saveStateToFile()` does nothing while `State._resetInProgress` is set. +- **Disabled-button style:** new `.btn:disabled` rule. +- **`.gitignore`:** also ignores `finlens-state.backup-*.json`. +- **Docs:** CLAUDE.md §20 documents where data lives and the cleanup rules; README tip on cleaning up and starting over. + +--- + ## [1.8.1] — 2026-10-23 ### Fixed (Technical) diff --git a/CLAUDE.md b/CLAUDE.md index 64cbbcc..da364b7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ FinLens is a **single-origin, zero-build, vanilla JavaScript personal finance dashboard** that runs entirely in the browser. There is no server, no npm, no bundler, no framework, and no TypeScript. The entry point is `index.html`; everything else is a plain `.js` file in the `js/` folder. -**Current version:** v1.8.1 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.9.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). **What it does:** Imports CSV exports from Ally Bank (Checking + Savings) and Chase credit cards, parses and normalizes them into a unified transaction model, and renders a multi-tab financial dashboard with budgeting, debt tracking, savings forecasting, investment planning, and Claude-powered AI analysis. @@ -65,7 +65,8 @@ FinLens/ ├── views-forecast.js ← Forecast Savings + Forecast Investments tabs ├── views-ai.js ← AI Analysis tab (Claude integration) ├── views-data.js ← Import, Accounts, Credit Cards, Categories (Settings tabs) + Import Logs - ├── views-settings.js ← Settings shell + General tab (display, Anthropic API key, danger zone) + ├── views-settings.js ← Settings shell (tab bar) + General tab (display, Anthropic API key) + ├── views-cleanup.js ← Settings → Data & Reset: clean up imported data, DB, logs; start over (§20) ├── views-db.js ← DB Schema diagram, DB Inspector, Changelog views (developer only) ├── views-database.js ← Unused — not loaded by index.html; retained for reference └── init.js ← App boot IIFE — event wiring, DB.open(), DB.loadAll(), first render @@ -76,7 +77,7 @@ FinLens/ ``` core.js → aggregation.js → db.js → ui.js → views-main.js → views-plan.js → views-invest.js → views-forecast.js → views-ai.js → views-data.js - → views-settings.js → views-db.js → init.js + → views-settings.js → views-cleanup.js → views-db.js → init.js ``` All scripts share the **global `window` scope**. A function defined in `core.js` is callable in any `views-*.js` without import statements. @@ -352,6 +353,14 @@ hash(str) // Deterministic 'tx' + base36 hash for transaction I escapeHtml(str) // Escape HTML entities for safe innerHTML insertion escapeAttr(str) // Escape for use in HTML attribute strings renderMarkdown(md) // marked → DOMPurify (no images/styles/forms) → safe HTML string; escaped-text fallback +lsClearAll() // Remove every finlens_* localStorage key — only "Start over" should call it +deleteIndexedDB(name) // Delete a whole IndexedDB database → 'deleted' | 'blocked' | 'error' + +// Folder + state-file maintenance (call from a click handler — permission prompts need a user gesture) +folderWithWriteAccess() // Connected folder handle with read-write access, or null +saveStateNow() // Write finlens-state.json immediately → 'saved' | 'no-folder' | 'denied' +retireStateFile(mode) // 'archive' (→ finlens-state.backup-.json, key stripped) | 'delete' +forgetDataFolder() // Forget the folder handle + name; nothing on disk changes downloadFile(name, content, mime) // Trigger browser file download debounce(fn, ms) // Returns debounced function parseDate(s) // Parse date string/object → Date | null @@ -394,7 +403,8 @@ editBucket(i), saveBucket(i), deleteBucket(i) editDebt(i), saveDebt(i), deleteDebt(i), simulatePayoff(debts, extra) confirmRecurring(...), dismissRecurring(key) addCatRule(), delCatRule(i), recategorizeAll() -exportAllData(), importJsonFile(ev), clearAllData() +exportAllData(), importJsonFile(ev) +clearAllData() // = DataCleanup.startOver('archive') — full reset + reload (§20) ``` --- @@ -534,8 +544,8 @@ Plan: budgets, buckets, debt, investments, forecast └─ Forecast has sub-tabs: Savings · Investments Insights: trends, ai ⚙️ Settings ← standalone nav link, no section wrapper, no sub-items in sidebar - └─ Settings page has internal tabs: General · Import · Accounts · Credit Cards · Categories - (General holds Display, Anthropic API Key and Danger Zone) + └─ Settings page has internal tabs: General · Import · Accounts · Credit Cards · Categories · Data & Reset + (General holds Display and Anthropic API Key; all clearing/reset lives in Data & Reset) ``` View registrations by file: @@ -546,6 +556,7 @@ View registrations by file: - `views-ai.js` — ai - `views-data.js` — import, accounts, credit-cards, categories - `views-settings.js` — settings (internal use only, not in nav) +- `views-cleanup.js` — data-cleanup (Settings → Data & Reset tab) - `views-db.js` — db-inspector, db-schema, changelog (not in nav; developer reference only) The `data-section` attribute values are `finances`, `plan`, `insights` — the toggle JS derives section IDs as `ns-{data-section}`. Settings is a standalone `` link at the bottom of the sidebar (no section wrapper, no sub-items). @@ -625,7 +636,9 @@ The handle lives in a separate `finlens_fs` database (distinct from `finlens_db` - **Do not create new global variables** — use `const`/`let` at module scope where possible, or attach to an existing namespace object. - **Do not write secrets to disk** — `apiKey` must never appear in `finlens-state.json`, exports, or logs. - **Do not call `marked.parse()` directly** — use `renderMarkdown()`. -- **Do not commit real financial data** — use `samples/` (synthetic) for demos; `data/`, `finlens-state.json` and exports are git-ignored. +- **Do not commit real financial data** — use `samples/` (synthetic) for demos; `data/`, `finlens-state.json` (and its `.backup-*` copies) and exports are git-ignored. +- **Do not add a new place that stores data without updating §20** — "Start over" must erase it, or a reset silently leaves data behind. +- **Do not modify the user's CSV files** — cleanup and reset only ever touch FinLens's own storage and `finlens-state.json`. --- @@ -685,7 +698,7 @@ Bump the patch version for bug fixes, minor version for new features, major vers **On every version bump, all four of these must be updated — no exceptions:** 1. `CHANGELOG.md` — new entry at the top with the new version number and date. -2. `index.html` — version string in the sidebar footer (search for `· FinLens`); currently on line ~325: +2. `index.html` — version string in the sidebar footer (search for `· FinLens`); currently on line ~326: ```html
vX.Y.Z · FinLens
``` @@ -709,7 +722,7 @@ Multiple Chase card files can be loaded simultaneously. Each gets a unique `acco --- -*Last updated: v1.8.1 — 2026-10-23 (§10 re-upload dedup rewritten for the occurrence-suffix fix; v1.8.0: AI Analysis restored with API-key and output hardening; `renderMarkdown()` added; `samples/` added; §1–3, §13, §14, §17 corrected to match the code)* +*Last updated: v1.9.0 — 2026-10-23 (§20 Data & Reset added; v1.8.1: §10 re-upload dedup rewritten for the occurrence-suffix fix; v1.8.0: AI Analysis restored with API-key and output hardening; `renderMarkdown()` added; `samples/` added; §1–3, §13, §14, §17 corrected to match the code)* --- @@ -732,3 +745,41 @@ Add a new object to `BANK_SCHEMAS` in `core.js`. No other code changes needed if ### Deferred - Column Mapping UI for truly unknown CSV formats (show a modal when `detectSchema()` returns null). - Forecast Savings account-driven inputs (see §4 in INDEXEDDB_PLAN.md — separate task). + +--- + +## 20. Data Cleanup & Reset (views-cleanup.js) + +**Settings → 🧹 Data & Reset** is the only place that clears data. All actions live on the `DataCleanup` namespace object. + +### Where FinLens keeps data + +| Place | What | Cleared by | +|---|---|---| +| Memory | `State` | every action (then `renderActive()`) | +| `localStorage` | `finlens_*` keys via `lsSet`/`lsGet` (plus `finlens_navCollapsed`) | per-item `lsSet(key, [])`; Start over → `lsClearAll()` | +| IndexedDB `finlens_db` | `DB.STORES`: transactions, tx_overrides, accounts, import_log, app_state | `DB.clearStores([...])`; Start over → `DB.destroy()` | +| IndexedDB `finlens_fs` | `csvDirHandle` (the connected folder) | Disconnect → `forgetDataFolder()`; Start over → `deleteIndexedDB('finlens_fs')` | +| Disk | `finlens-state.json` in the connected folder | rewritten by `saveStateNow()` after clears; Start over → `retireStateFile()` | + +CSV files on disk are **never** modified. + +### Actions + +| Action | Does | Keeps | +|---|---|---| +| Clear transactions & accounts | Empties memory + `transactions`/`accounts` stores | Plans, edits, account labels/balances, settings | +| Clear import log | Empties `import_log` | Everything else | +| Clear transaction edits | `txOverrides` + `tx_overrides` store; rebuilds loaded transactions with `reconstituteTx(raw, {})` | — | +| Clear budgets / bills / buckets / debts / AI history | `State[key] = []` + `lsSet` | — | +| Rebuild from folder | Clears transactions, accounts, import log, then `reloadFromDirHandle()` | Plans, edits, settings | +| Disconnect folder | `forgetDataFolder()` — stops CSV auto-reload and state-file writes | Files on disk | +| Start over | `retireStateFile()` → forget handle → `DB.destroy()` → delete `finlens_fs` → `lsClearAll()` → alert → reload | CSV files (and a backup copy of the state file, if chosen) | + +### Rules + +- **Rewrite the state file after clearing anything it holds.** `finlens-state.json` is the first thing loaded at boot, so a stale file would restore cleared data. `_finish()` calls `saveStateNow()` and warns if write access was refused. +- **A connected folder re-imports its CSVs** at boot whenever no transactions are loaded (§14). Clearing transactions without disconnecting is effectively "re-import on next load"; the tab says so. +- **Permission prompts need a fresh user gesture.** Destructive buttons use click-again-to-confirm (no `confirm()` dialog, which can outlast the ~5 s activation window), and actions ask for folder access before doing slow work. +- **Start over must leave nothing behind.** It sets `State._resetInProgress` so a pending debounced save can't re-create the file, and `DB.open()` registers `onversionchange` so other tabs release the database. `idbGet`/`idbSet`/`idbDel` close their connections so `finlens_fs` can be deleted. +- `clearAllData()` is kept as a wrapper for `DataCleanup.startOver('archive')`. Up to v1.8.1 it only cleared `localStorage`, which IndexedDB and the state file then restored on reload. diff --git a/README.md b/README.md index 55a718e..98c8151 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > A zero-install, browser-native finance dashboard. Drop in your bank CSVs, get instant clarity on your money. -**Version:** v1.8.1  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.9.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -198,7 +198,8 @@ FinLens/ ├── views-forecast.js ← Forecast Savings + Forecast Investments ├── views-ai.js ← AI Analysis (Claude integration) ├── views-data.js ← Database section: Import, Accounts, Categories, Import Logs - ├── views-settings.js ← Settings tab (API key, theme, danger zone) + ├── views-settings.js ← Settings shell + General tab (theme, API key) + ├── views-cleanup.js ← Settings → Data & Reset (clean up data, start over) ├── views-db.js ← DB Inspector, DB Schema diagram, Changelog views └── init.js ← App boot and event wiring ``` @@ -215,6 +216,13 @@ FinLens/ **Multiple Chase cards** — load as many Chase CSV files as you want. Each gets its own account card and can be filtered independently. +**Cleaning up or starting over** — **Settings → 🧹 Data & Reset** shows what FinLens has stored and lets you: +- **Clean up imported data:** clear imported transactions, the import log or your transaction edits. +- **Rebuild from your CSV folder:** fixes a messy database without touching your plans. +- **Clear individual plans:** budgets, bills, buckets, debts or AI history. +- **Disconnect the folder.** +- **Start over from scratch:** type `RESET` to erase everything and reload. Your backup file is kept as a renamed copy or deleted, your choice. Your CSV files are never touched. + **Dark mode** — click the **◐** button in the top-right corner of the topbar. **Exporting** — the Transactions tab has an **Export CSV** button for the currently filtered view. AI responses can be saved as Markdown from the AI Analysis tab. @@ -227,4 +235,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.8.1 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.9.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index 34fe65a..0c52e72 100644 --- a/index.html +++ b/index.html @@ -323,7 +323,7 @@
⚙️ Settings
diff --git a/js/views-settings.js b/js/views-settings.js index 18cace0..3411b8a 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -49,7 +49,7 @@ function _renderGeneralSettings(root) { -
FinLens v1.8.1 ·${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
`; +
FinLens v1.9.0 ·${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
`; root.appendChild(displayCard); /* ---- Anthropic API Key ---- */ From 724c0b213faec499471253d0bef1ae7c2b848e13 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 03:53:07 +0000 Subject: [PATCH 5/7] Start over: name the backup finlens-state-backup-DDMMYYYY.json MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Requested in review. A second reset on the same day gets -2, -3, … so an earlier copy is never overwritten. Updated .gitignore, the radio label (now shows the real name), CLAUDE.md, README and CHANGELOG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AT1Bh6Sscb8ogzzuf8U3Jc --- .gitignore | 2 +- CHANGELOG.md | 4 ++-- CLAUDE.md | 4 ++-- README.md | 2 +- js/core.js | 8 ++++++-- js/views-cleanup.js | 4 ++-- 6 files changed, 14 insertions(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index 0dfee09..b6a3318 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ finlens-data.json # State backup (all transactions + settings), plus copies archived by "Start over" — # ignored wherever the CSV folder lives finlens-state.json -finlens-state.backup-*.json +finlens-state-backup-*.json # Settings exports and saved AI analyses finlens-export-*.json finlens-analysis-*.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 5507dd4..219781a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - **CSV folder & backup file** — disconnect the folder (FinLens forgets the handle; nothing on disk changes). - **Start over from scratch:** - Type `RESET` to erase everything: both IndexedDB databases, all `finlens_*` localStorage keys (including the API key), the folder connection, then reload. - - `finlens-state.json` is either renamed to `finlens-state.backup-.json` (API key stripped) or deleted, so reconnecting the folder later starts fresh. + - `finlens-state.json` is either renamed to `finlens-state-backup-DDMMYYYY.json` (API key stripped; a second reset the same day gets `-2`, `-3`, … so no copy is overwritten) or deleted, so reconnecting the folder later starts fresh. - CSV files are never touched. - **Safer confirmations** — destructive buttons use click-again-to-confirm, so the folder-permission prompt that may follow gets a fresh user gesture. An alert can't outlast the browser's activation window. @@ -36,7 +36,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - **New `core.js` helpers:** `lsClearAll()`, `deleteIndexedDB()`, `folderWithWriteAccess()`, `saveStateNow()`, `retireStateFile()`, `forgetDataFolder()`. - **Auto-save guard:** `saveStateToFile()` does nothing while `State._resetInProgress` is set. - **Disabled-button style:** new `.btn:disabled` rule. -- **`.gitignore`:** also ignores `finlens-state.backup-*.json`. +- **`.gitignore`:** also ignores `finlens-state-backup-*.json`. - **Docs:** CLAUDE.md §20 documents where data lives and the cleanup rules; README tip on cleaning up and starting over. --- diff --git a/CLAUDE.md b/CLAUDE.md index da364b7..41331cb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -359,7 +359,7 @@ deleteIndexedDB(name) // Delete a whole IndexedDB database → 'deleted' | // Folder + state-file maintenance (call from a click handler — permission prompts need a user gesture) folderWithWriteAccess() // Connected folder handle with read-write access, or null saveStateNow() // Write finlens-state.json immediately → 'saved' | 'no-folder' | 'denied' -retireStateFile(mode) // 'archive' (→ finlens-state.backup-.json, key stripped) | 'delete' +retireStateFile(mode) // 'archive' (→ finlens-state-backup-DDMMYYYY[-n].json, key stripped) | 'delete' forgetDataFolder() // Forget the folder handle + name; nothing on disk changes downloadFile(name, content, mime) // Trigger browser file download debounce(fn, ms) // Returns debounced function @@ -636,7 +636,7 @@ The handle lives in a separate `finlens_fs` database (distinct from `finlens_db` - **Do not create new global variables** — use `const`/`let` at module scope where possible, or attach to an existing namespace object. - **Do not write secrets to disk** — `apiKey` must never appear in `finlens-state.json`, exports, or logs. - **Do not call `marked.parse()` directly** — use `renderMarkdown()`. -- **Do not commit real financial data** — use `samples/` (synthetic) for demos; `data/`, `finlens-state.json` (and its `.backup-*` copies) and exports are git-ignored. +- **Do not commit real financial data** — use `samples/` (synthetic) for demos; `data/`, `finlens-state.json` (and its `finlens-state-backup-*` copies) and exports are git-ignored. - **Do not add a new place that stores data without updating §20** — "Start over" must erase it, or a reset silently leaves data behind. - **Do not modify the user's CSV files** — cleanup and reset only ever touch FinLens's own storage and `finlens-state.json`. diff --git a/README.md b/README.md index 98c8151..db15b89 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ FinLens/ - **Rebuild from your CSV folder:** fixes a messy database without touching your plans. - **Clear individual plans:** budgets, bills, buckets, debts or AI history. - **Disconnect the folder.** -- **Start over from scratch:** type `RESET` to erase everything and reload. Your backup file is kept as a renamed copy or deleted, your choice. Your CSV files are never touched. +- **Start over from scratch:** type `RESET` to erase everything and reload. Your backup file is either kept as `finlens-state-backup-DDMMYYYY.json` or deleted, your choice. Your CSV files are never touched. **Dark mode** — click the **◐** button in the top-right corner of the topbar. diff --git a/js/core.js b/js/core.js index 3ce6db3..c431e56 100644 --- a/js/core.js +++ b/js/core.js @@ -205,7 +205,8 @@ async function saveStateNow() { // Used by "Start over": retires finlens-state.json so reconnecting the same folder // later doesn't bring the old state back. 'archive' renames it to -// finlens-state.backup-.json (API key stripped); 'delete' removes it. +// finlens-state-backup-DDMMYYYY.json (API key stripped; a second reset on the same +// day gets -2, -3, … so an earlier copy is never overwritten); 'delete' removes it. // CSV files are never touched. // Returns { status: 'archived'|'deleted'|'none'|'no-folder'|'denied'|'error', name? }. async function retireStateFile(mode) { @@ -221,7 +222,10 @@ async function retireStateFile(mode) { const text = await (await fh.getFile()).text(); let out = text; try { const obj = JSON.parse(text); delete obj.apiKey; out = JSON.stringify(obj, null, 2); } catch(e) { /* keep raw text */ } - name = `finlens-state.backup-${dayjs().format('YYYYMMDD-HHmmss')}.json`; + const exists = async (nm) => { try { await dir.getFileHandle(nm); return true; } catch(e) { return false; } }; + const stamp = dayjs().format('DDMMYYYY'); + name = `finlens-state-backup-${stamp}.json`; + for (let n = 2; await exists(name); n++) name = `finlens-state-backup-${stamp}-${n}.json`; const w = await (await dir.getFileHandle(name, { create: true })).createWritable(); await w.write(out); await w.close(); diff --git a/js/views-cleanup.js b/js/views-cleanup.js index fe87940..80a3a72 100644 --- a/js/views-cleanup.js +++ b/js/views-cleanup.js @@ -91,7 +91,7 @@ const DataCleanup = { /** * Erase everything FinLens stores, then reload. Must run from a click: it may * need write access to the folder to retire finlens-state.json. - * stateFile: 'archive' (rename to finlens-state.backup-.json) | 'delete' + * stateFile: 'archive' (rename to finlens-state-backup-DDMMYYYY.json) | 'delete' */ async startOver(stateFile = 'archive') { State._resetInProgress = true; // blocks pending/future auto-saves until the reload @@ -233,7 +233,7 @@ registerView('data-cleanup', 'Data & Reset', (root) => { ${folder ? `
Backup file in “${escapeHtml(folder)}”
- +
Either way, reconnecting this folder later starts fresh. FinLens may ask for permission to change the folder.
` : ''} From b01fd0ecd3e17991a0ee9d0f2130bff502d508ef Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 02:38:06 +0000 Subject: [PATCH 6/7] Raise contrast of gray secondary text (light, dark, sidebar, charts) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review feedback on #3: gray-on-white text was hard to read. - --text-3 #94A3B8 -> #5B6B80 (light) and #64748B -> #8190A6 (dark). Was 2.3-2.6:1 on light surfaces and 3.3-3.9:1 on dark; now at least 4.7:1 everywhere (WCAG AA). Used by .muted, .footnote and ~20 inline styles, so the fix reaches every tab. - Sidebar group headers, brand subtitle and footer: hard-coded #475569/#64748b (2.3-3.6:1) -> new --sidebar-muted token (6.7:1). - applyTheme() sets Chart.defaults.color to --text-2, replacing Chart.js's #666 (hard to read in dark mode). - CHANGELOG (1.9.0) and CLAUDE.md §6 contrast rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QoR1wxcaDjVVk3xmd5rRCt --- CHANGELOG.md | 5 +++++ CLAUDE.md | 4 +++- index.html | 13 +++++++------ js/ui.js | 5 +++++ 4 files changed, 20 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 219781a..b9df1cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,11 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - CSV files are never touched. - **Safer confirmations** — destructive buttons use click-again-to-confirm, so the folder-permission prompt that may follow gets a fresh user gesture. An alert can't outlast the browser's activation window. +### Display — readable secondary text (all views) +- **Darker gray text.** `--text-3` (descriptions, counts, footnotes, `.muted`) was `#94A3B8` on white, about 2.5:1 contrast. It's now `#5B6B80` in light mode and `#8190A6` in dark mode, at least 4.7:1 on every surface (WCAG AA). One token change, so it applies to every tab. +- **Sidebar.** Group headers, the brand subtitle and the version footer used hard-coded `#475569`/`#64748b` (2.3–3.6:1 on the sidebar). They now share a new `--sidebar-muted` token (`#94A3B8`, 6.7:1). +- **Charts.** Axis labels and legends used Chart.js's default `#666`, which was hard to read in dark mode. `applyTheme()` now sets `Chart.defaults.color` to `--text-2`. + ### Fixed - **"Clear All Data" didn't clear anything.** `clearAllData()` only removed localStorage keys, so on reload `DB.loadAll()` (and `finlens-state.json`) restored every transaction, budget and setting. It now runs the full Start over. - **Cleared data could come back on reload.** The state file is loaded first at boot but was only rewritten by the 5-second debounced save, so a quick reload restored it. Clearing now writes it immediately via `saveStateNow()`, and warns if write access is refused. diff --git a/CLAUDE.md b/CLAUDE.md index 41331cb..d197f5b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -245,7 +245,7 @@ All CSS lives in a single `