From c01d3040c56c14becb12b70c6636d4e4b26a80e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 21:15:40 +0000 Subject: [PATCH 1/4] =?UTF-8?q?Add=20Settings=20=E2=86=92=20Database=20tab?= =?UTF-8?q?=20(DB=20Inspector,=20DB=20Schema);=20v1.10.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New db-tools view in views-db.js, shown as the last Settings tab, with DB Inspector and DB Schema sub-tabs. Both views still open on their own with showView(). - Settings hides a tab whose view isn't registered instead of throwing. - DB Inspector re-reads the store on every visit (was showing stale rows and a blank count line), keeping the chosen store, search and page. - README tips point to Settings → Import / Categories; CLAUDE.md §3, §12, §19 and the version strings updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YNVUix2HCeCPauBy4BHxFp --- CHANGELOG.md | 15 +++++++++++++++ CLAUDE.md | 16 +++++++++------- README.md | 12 +++++++----- index.html | 2 +- js/views-db.js | 44 ++++++++++++++++++++++++++++++++++++-------- js/views-settings.js | 8 ++++++-- 6 files changed, 74 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3be6dd..4446714 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.10.0] — 2026-10-25 + +### Added (Settings) +- **Settings → 🗄️ Database tab.** DB Inspector and DB Schema are back in the UI. Since the sidebar's Database section was removed, they could only be opened with `showView()` from DevTools. The tab has two sub-tabs, **DB Inspector** and **DB Schema**, and remembers which one was open for the rest of the session. It's the new `db-tools` view in `views-db.js`, which renders the existing `db-inspector` and `db-schema` views. Both still open on their own with `showView()`. +- **A Settings tab whose file failed to load is now hidden** instead of throwing when Settings opens. The Database tab lives in `views-db.js`, which v1.9.4 showed can stop loading partway through. The tab's code sits above the embedded changelog for the same reason. + +### Fixed (DB Inspector) +- **Coming back to DB Inspector showed old data.** On a second visit it redrew the rows from the first load without reading the database again, so anything imported or cleared since then was missing, and the record count line was blank. It now re-reads the selected store on every visit and keeps the chosen store, search and page. + +### Docs +- **README:** Tips now point to **Settings → Import** and **Settings → Categories** instead of the old Database sidebar section, and mention the new tab. +- **CLAUDE.md §3, §12, §19:** the Settings tab list, view registrations and file descriptions include the Database tab. + +--- + ## [1.9.5] — 2026-10-25 ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index 75d7828..3f38bfa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,7 @@ Until then, this section is the rule. 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.9.5 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.10.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. @@ -118,7 +118,7 @@ FinLens/ ├── views-data.js ← Import, Accounts, Credit Cards, Categories (Settings tabs) + Import Logs ├── 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-db.js ← DB Schema diagram, DB Inspector, Settings → Database tab, Changelog view ├── 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 ``` @@ -599,8 +599,9 @@ 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 · Data & Reset - (General holds Display and Anthropic API Key; all clearing/reset lives in Data & Reset) + └─ Settings page has internal tabs: General · Import · Accounts · Credit Cards · Categories · Data & Reset · Database + (General holds Display and Anthropic API Key; all clearing/reset lives in Data & Reset; + Database has sub-tabs: DB Inspector · DB Schema) ``` View registrations by file: @@ -612,7 +613,8 @@ View registrations by file: - `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) +- `views-db.js` — db-tools (Settings → Database tab: renders db-inspector or db-schema as sub-tabs), db-inspector, db-schema, changelog. Only db-tools is reachable from the UI; the other three also open with `showView()` from DevTools. +- A Settings tab whose view isn't registered (its file failed to load) is hidden instead of throwing. 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). @@ -785,11 +787,11 @@ Multiple Chase card files can be loaded simultaneously. Each gets a unique `acco --- -*Last updated: v1.9.5 — 2026-10-25 (§7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §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)* +*Last updated: v1.10.0 — 2026-10-25 (§3, §12 Settings → Database tab; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §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)* --- -## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1) +## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1, in Settings since v1.10.0) The full IndexedDB implementation is live. See **`docs/archive/INDEXEDDB_PLAN.md`** for the original spec. diff --git a/README.md b/README.md index c825f15..e9055f0 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.9.5  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.10.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -200,7 +200,7 @@ FinLens/ ├── views-data.js ← Database section: Import, Accounts, Categories, Import Logs ├── 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 + ├── views-db.js ← Settings → Database (DB Inspector, DB Schema diagram), Changelog view └── init.js ← App boot and event wiring ``` @@ -210,9 +210,9 @@ FinLens/ ## Tips -**Refreshing data** — FinLens auto-reloads your CSVs on page refresh if it still has permission to the folder you picked. You can also click **↻ Reload** in **Database → Import** to force a re-read. +**Refreshing data** — FinLens auto-reloads your CSVs on page refresh if it still has permission to the folder you picked. You can also click **↻ Reload** in **Settings → Import** to force a re-read. -**Category rules** — go to **Spending → Category Rules** to teach FinLens your merchants. Rules apply across all future imports. Your category list is managed under **Database → Categories**. +**Category rules** — go to **Spending → Category Rules** to teach FinLens your merchants. Rules apply across all future imports. Your category list is managed under **Settings → Categories**. **Multiple Chase cards** — load as many Chase CSV files as you want. Each gets its own account card and can be filtered independently. @@ -223,6 +223,8 @@ FinLens/ - **Disconnect the folder.** - **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. +**Looking at the raw data** — **Settings → 🗄️ Database** has two sub-tabs: **DB Inspector** browses what is stored in each IndexedDB store (read-only, searchable), and **DB Schema** diagrams the stores and how they relate. + **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. @@ -235,4 +237,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.9.5 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.10.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index 7e87f88..36919e8 100644 --- a/index.html +++ b/index.html @@ -326,7 +326,7 @@
⚙️ Settings
diff --git a/js/views-db.js b/js/views-db.js index 3901e2b..e2522c1 100644 --- a/js/views-db.js +++ b/js/views-db.js @@ -1,6 +1,6 @@ /* ================================================================ FINLENS — views-db.js - Database views: Schema Diagram, DB Inspector, Changelog + Database views: Schema Diagram, DB Inspector, Settings → Database tab, Changelog ================================================================ */ /* ══════════════════════════════════════════════════════════════ @@ -429,9 +429,10 @@ registerView('db-inspector', 'DB Inspector', (root) => { } function _renderPage() { + const totalPages = Math.ceil(_inspectorRows.length / INSPECTOR_PAGE_SIZE); + _inspectorPage = Math.max(0, Math.min(_inspectorPage, totalPages - 1)); // store may have shrunk const start = _inspectorPage * INSPECTOR_PAGE_SIZE; const pageRows = _inspectorRows.slice(start, start + INSPECTOR_PAGE_SIZE); - const totalPages = Math.ceil(_inspectorRows.length / INSPECTOR_PAGE_SIZE); const pageInfo = document.getElementById('inspPageInfo'); if (pageInfo) pageInfo.textContent = _inspectorRows.length @@ -505,16 +506,43 @@ registerView('db-inspector', 'DB Inspector', (root) => { _renderPage(); }; - // Auto-load on render if we have previous data - setTimeout(async () => { - if (_inspectorRows.length) { _renderPage(); return; } - await loadStore(); - }, 0); + // Auto-load on every render. Re-read the store rather than reusing the rows from the + // last visit, which may be stale (an import since then) and left the count line blank. + // Keeps the chosen store, search and page. + setTimeout(_fetchAndRender, 0); +}); + + +/* ══════════════════════════════════════════════════════════════ + 3. SETTINGS → DATABASE TAB + Shows DB Inspector and DB Schema as sub-tabs inside Settings. + Both are still registered as views of their own, so + showView('db-inspector') and showView('db-schema') keep working. + Kept above the Changelog block so this tab still registers if + that block ever throws (see v1.9.4). +══════════════════════════════════════════════════════════════ */ + +const DB_TOOLS_TABS = [ + ['db-inspector', 'DB Inspector'], + ['db-schema', 'DB Schema'], +]; +let dbToolsTab = 'db-inspector'; + +registerView('db-tools', 'Database', (root) => { + const tabBar = document.createElement('div'); + tabBar.style.cssText = 'display:flex;gap:6px;flex-wrap:wrap;margin-bottom:16px'; + tabBar.innerHTML = DB_TOOLS_TABS.map(([k, l]) => + `` + ).join(''); + root.appendChild(tabBar); + tabBar.querySelectorAll('[data-db-tab]').forEach(btn => btn.onclick = () => { dbToolsTab = btn.dataset.dbTab; renderActive(); }); + + VIEWS[dbToolsTab].render(root); }); /* ══════════════════════════════════════════════════════════════ - 3. CHANGELOG + 4. CHANGELOG Content embedded directly — no fetch() needed, works on file:// UPDATE THIS BLOCK whenever CHANGELOG.md changes. ══════════════════════════════════════════════════════════════ */ diff --git a/js/views-settings.js b/js/views-settings.js index 338309c..c531725 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -13,12 +13,16 @@ const SETTINGS_TABS=[ ['credit-cards','💳 Credit Cards'], ['categories','🏷️ Categories'], ['data-cleanup','🧹 Data & Reset'], + ['db-tools', '🗄️ Database'], // views-db.js: DB Inspector + DB Schema ]; registerView('settings','Settings',(root)=>{ + // Tabs live in other files. If one failed to load, hide its tab instead of throwing. + const tabs=SETTINGS_TABS.filter(([k])=>k==='general'||VIEWS[k]); + if (!tabs.some(([k])=>k===settingsTab)) settingsTab='general'; const tabBar=document.createElement('div'); tabBar.style.cssText='display:flex;gap:6px;flex-wrap:wrap;margin-bottom:16px'; - tabBar.innerHTML=SETTINGS_TABS.map(([k,l])=> + tabBar.innerHTML=tabs.map(([k,l])=> `` ).join(''); root.appendChild(tabBar); @@ -49,7 +53,7 @@ function _renderGeneralSettings(root) { -
FinLens v1.9.5 ·${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
`; +
FinLens v1.10.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 e56b4874dc438bd53595d7b4b558392af53ffeba Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 02:30:39 +0000 Subject: [PATCH 2/4] Re-version to v1.11.0 so AI Eval (#6) keeps v1.10.0 and merges first; README views-data.js line --- CHANGELOG.md | 4 ++-- CLAUDE.md | 6 +++--- README.md | 6 +++--- index.html | 2 +- js/views-settings.js | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e64a054..8685a29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- -## [1.10.0] — 2026-10-25 +## [1.11.0] — 2026-10-25 ### Added (Settings) - **Settings → 🗄️ Database tab.** DB Inspector and DB Schema are back in the UI. Since the sidebar's Database section was removed, they could only be opened with `showView()` from DevTools. The tab has two sub-tabs, **DB Inspector** and **DB Schema**, and remembers which one was open for the rest of the session. It's the new `db-tools` view in `views-db.js`, which renders the existing `db-inspector` and `db-schema` views. Both still open on their own with `showView()`. @@ -15,7 +15,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - **Coming back to DB Inspector showed old data.** On a second visit it redrew the rows from the first load without reading the database again, so anything imported or cleared since then was missing, and the record count line was blank. It now re-reads the selected store on every visit and keeps the chosen store, search and page. ### Docs -- **README:** Tips now point to **Settings → Import** and **Settings → Categories** instead of the old Database sidebar section, and mention the new tab. +- **README:** Tips now point to **Settings → Import** and **Settings → Categories** instead of the old Database sidebar section, and mention the new tab. The Project Structure line for `views-data.js` no longer calls it the Database section. - **CLAUDE.md §3, §12, §19:** the Settings tab list, view registrations and file descriptions include the Database tab. --- diff --git a/CLAUDE.md b/CLAUDE.md index 7f01d85..1b555bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,7 @@ Until then, this section is the rule. 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.10.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.11.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. @@ -787,11 +787,11 @@ Multiple Chase card files can be loaded simultaneously. Each gets a unique `acco --- -*Last updated: v1.10.0 — 2026-10-25 (§3, §12 Settings → Database tab; v1.9.6: §14 folder access lasts until the last tab closes, not one page load; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §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)* +*Last updated: v1.11.0 — 2026-10-25 (§3, §12 Settings → Database tab; v1.9.6: §14 folder access lasts until the last tab closes, not one page load; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §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)* --- -## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1, in Settings since v1.10.0) +## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1, in Settings since v1.11.0) The full IndexedDB implementation is live. See **`docs/archive/INDEXEDDB_PLAN.md`** for the original spec. diff --git a/README.md b/README.md index e9055f0..5b16d3d 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.10.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.11.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -197,7 +197,7 @@ FinLens/ ├── views-invest.js ← Investing Ideas ├── 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-data.js ← Settings → Import, Accounts, Credit Cards, Categories; Import Logs ├── views-settings.js ← Settings shell + General tab (theme, API key) ├── views-cleanup.js ← Settings → Data & Reset (clean up data, start over) ├── views-db.js ← Settings → Database (DB Inspector, DB Schema diagram), Changelog view @@ -237,4 +237,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.10.0 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.11.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index 36919e8..8fd985e 100644 --- a/index.html +++ b/index.html @@ -326,7 +326,7 @@
⚙️ Settings
diff --git a/js/views-settings.js b/js/views-settings.js index c531725..e6ef004 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -53,7 +53,7 @@ function _renderGeneralSettings(root) { -
FinLens v1.10.0 ·${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
`; +
FinLens v1.11.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 fc957bfd8f4bffa465b479444f56f135c82aeb5e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 09:43:13 +0000 Subject: [PATCH 3/4] =?UTF-8?q?Settings=20=E2=86=92=20Database=20tab=20reb?= =?UTF-8?q?uilt=20on=20Clarity=20(v1.17.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebuilds PR #10's tab on the Clarity redesign. Its v1.11.0 version predated the redesign and was never released; its CHANGELOG entry and version strings are gone, replaced by one 1.17.0 entry. - Settings: a seventh tab, Database, last, in plain text; part of the tablist (arrow keys, Home, End). A tab whose view isn't registered is hidden instead of throwing (#10's guard). On a phone the tab bar scrolls the selected tab into view on each render. - db-tools view: DB Inspector / DB Schema as a .seg.tabs-seg tablist, like Forecast, rendering the chosen view into one tabpanel. The choice is remembered for the session only (dbToolsTab). - DB Inspector: Clarity panel and .tbl table with the Transactions pager. Re-reads the store on every visit, keeping store, search and page (clamped if the store shrank). Store change reads at once; the search filters as you type; Load -> Refresh; Clear -> Clear search. The API key in app_state is shown as hidden and skipped by the search. State moves to one DBInspector object. - DB Schema: one panel titled "Database schema" (was "Database Schema & Inspector"). The SVG takes its colors from .sch-* classes (theme tokens); no hex, rgba(), white, legacy aliases or faded text. 872px wide to fit Settings; labels in the gaps; scrolls in its box on phones. app_state key list and accounts.kind brought up to date. - README tip and Settings line; CLAUDE.md §1, §3, §6, §12, §19 and Last updated; version 1.17.0 in all four places. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Z8iBXzUjiQbYziDZ8CZft --- CHANGELOG.md | 29 ++ CLAUDE.md | 34 +- README.md | 10 +- index.html | 48 ++- js/views-db.js | 838 ++++++++++++++++++------------------------- js/views-settings.js | 19 +- 6 files changed, 472 insertions(+), 506 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01d5240..3fae084 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,35 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.17.0] — 2026-11-02 + +### Settings → Database +DB Inspector and DB Schema are back in the UI, as a seventh Settings tab. Since the sidebar's Database section was removed, they could only be opened with `showView()` from DevTools. This is PR #10's tab rebuilt on the Clarity redesign; its v1.11.0 version predates the redesign and was never released. + +- **Tab:** **Database**, last in the Settings tab bar, in plain text. It is part of the Settings tablist, so arrow keys, Home and End reach it, and it uses the same 1000px page as the other tabs. +- **Sub-tabs:** **DB Inspector** (opens first) and **DB Schema**, as a segmented tab control like Forecast's Savings / Investments (`.seg.tabs-seg`, `role="tab"`, `aria-selected`; arrow keys, Home and End). The one you picked is remembered for the session (`dbToolsTab`); nothing is saved. +- **How it's built:** the tab is the `db-tools` view in `views-db.js`. It renders the existing `db-inspector` or `db-schema` view into one `role="tabpanel"`. Both still open on their own with `showView()`, and so does `showView('changelog')`. +- **A Settings tab whose view isn't registered is hidden** instead of throwing when Settings opens. The Database tab lives in `views-db.js`, which v1.9.4 showed can stop loading partway through. The tab's code sits above the embedded changelog for the same reason. +- **Phones:** the Settings tab bar now scrolls the selected tab into view. Before, every render scrolled it back to the start, so a selected Data & reset or Database tab was off-screen at 390px. + +### DB Inspector +- **Clarity layout:** a panel with the store picker, search, **Clear search**, **Refresh** and the record count ("257 records found (257 total in store)"). Below it, the records in a `.tbl` table that scrolls sideways, with the Transactions screen's pager. The store's key is the first column; field names keep their case. Values are colored by type through `.dv-*` classes (dates, numbers, lists, true/false, null) instead of hard-coded legacy colors. +- **Re-reads the store on every visit.** Before, a second visit redrew the rows cached from the first load, so imports or clears made in between didn't show, and the count line was blank. It keeps the chosen store, search and page, and moves back to the last page if the store got smaller. +- **Picking a store reads it right away, and the search filters as you type.** **Load** is now **Refresh** (read the store again). **Clear** is now **Clear search**: it shows the whole store again instead of emptying the table. +- **The API key isn't shown.** Its `app_state` row says "Hidden: an API key is saved", and the search ignores its value, so typing can't reveal it. Before, the inspector printed the key in full (CLAUDE.md §13: never expose it). + +### DB Schema +- **One Clarity panel titled "Database schema".** It was titled "Database Schema & Inspector", from when one card held both; the inspector is its own sub-tab now. The legend is a `.legend` row in the same panel. +- **Colors come from the theme.** Each store's lines and text use a `.sch-*` class that reads the tokens (`--teal-2`/`--teal-text`, `--warn`/`--warn-text`, `--sky`/`--sky-text`, `--violet`/`--violet-text`). No hex, `rgba()`, `white` or legacy aliases, and no text faded with opacity. The diagram follows light and dark without a redraw. +- **Fits the 1000px Settings page** (872px wide). The relationship labels sit in the gaps between boxes, on a background, instead of over the boxes. The `app_state` key list wraps inside its box. Below 900px the diagram scrolls sideways inside its panel, and a note says so. +- **Text corrected:** the `app_state` key list matches the keys the code writes (`catRules`, not `categoryRules`; adds `recurring`, `cardDetails`, `sampleData`, `lastFolderName` and `csvAutoImportPaused`). `accounts.kind` gives the current kinds (`bank_checking|credit_card|…`). + +### Docs +- **README:** a Tip for **Settings → Database**; the Project Structure line for `views-db.js`. +- **CLAUDE.md:** §1 version; §3 file roles; §6 the Database classes; §12 the seventh Settings tab, its sub-tabs, the hidden-tab guard and view registrations; §19 the database views. + +--- + ## [1.16.0] — 2026-11-02 ### Insights, Settings and the Welcome — Clarity redesign, part 4 diff --git a/CLAUDE.md b/CLAUDE.md index 99c135c..57848ba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,7 @@ Until then, this section is the rule. 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.16.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.17.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). **What it does:** Imports CSV exports from a bank (checking + savings) and 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. @@ -122,7 +122,7 @@ FinLens/ ├── views-data.js ← Settings tabs Import, Accounts, Credit cards, Categories; folder + sync badge; sample data; Import Logs ├── views-settings.js ← Settings shell (tab bar) + General tab (display, Anthropic API key) ├── views-cleanup.js ← Settings → Data & reset: what's stored, clean up, JSON export/import, start over (§20) - ├── views-db.js ← DB Schema diagram, DB Inspector, Changelog views (developer only) + ├── views-db.js ← Settings → Database tab (DB Inspector, DB Schema sub-tabs); Changelog view (developer only) ├── views-eval.js ← AI Eval: grounding eval for AI Analysis (developer only, §21) ├── 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 @@ -444,6 +444,15 @@ Dark mode is applied by setting `data-theme="dark"` on `` (`applyTheme()`, body[data-view="settings"], body.first-run — Settings and the Welcome are 1000px wide; a first run hides the app bar's nav and tools ``` +**Settings → Database (v1.17.0)** adds: + +``` +.tbl.db-tbl .insp-store .dv-null/.dv-hidden/.dv-date/.dv-arr/.dv-num/.dv-obj/.dv-true/.dv-false — DB Inspector's raw table and its values by type +.sch (the schema SVG) .sch-teal/.sch-warn/.sch-sky/.sch-violet/.sch-neutral (set --c for lines and --ct for text; warn uses --warn-strong-text) + .box-bg .box .band .rule .stripe .st-name .st-kind .f-name .f-type .f-note .st-note .badge(.pk) .badge-t(.pk) .rel .rel-head .rel-bg .rel-t — its shapes and text +.sch-scroll .sch-hint .sch-legend .key-badge(.pk) .sch-opt — the diagram's scroll box, its phone note and legend +``` + Prefer these over inline styles. Keep touch targets ≥ 44px where feasible (`@media (pointer:coarse)` raises pills and remove buttons). --- @@ -773,8 +782,9 @@ FinLens · Overview · Transactions · Plan ▾ · Trends · AI Analysis [S Transactions has filter pills: All · Income · Spending · Bills · Payments · Transfers (All and Payments filter the list; the other four open registered views — see below) Forecast has sub-tabs: Savings · Investments -Gear → Settings, with tabs: General · Import · Accounts · Credit cards · Categories · Data & reset - (General holds Display — including Theme — and Anthropic API key; all clearing/reset lives in Data & reset) +Gear → Settings, with tabs: General · Import · Accounts · Credit cards · Categories · Data & reset · Database + (General holds Display — including Theme — and Anthropic API key; all clearing/reset lives in Data & reset; + Database has sub-tabs: DB Inspector · DB Schema) ``` - **Right side:** the sync badge, then the date-range and accounts icon buttons (each opens a popover), then the Settings gear. There is no theme button. @@ -784,6 +794,8 @@ Gear → Settings, with tabs: General · Import · Accounts · Credit cards · C - **Page title:** the shell renders it (`#pageTitle` from the registered title, `#rangeLabel` the range). Views never render their own H1. On screens that ignore the date range (`NO_RANGE_VIEWS`: the five Plan screens, Trends and Settings) `showView()` hides `#rangeLabel` (v1.15.0, v1.16.0). The Welcome rewords the title with `shellHero()` instead of adding an H1. - **The Welcome (v1.16.0)** is the Overview with no transactions (`renderWelcome()` in views-main.js). On a true first run (`isFirstRun()`: no folder, plans, AI history or key) the app bar shows only the brand. Its buttons call the existing import paths from their click: `pickDataFolder()` (`reloadDataFiles()` when a folder is connected), `loadSampleData()`, and `#filePick`. - **Settings (v1.16.0)** is a `role="tablist"` (arrow keys, Home, End) and one `role="tabpanel"`; each tab is a registered view rendered into it. Fields save when you leave them (`change`) and report in a `.status-line`; destructive buttons ask for a second click. A screen's buttons and one-line note go in a `.page-actions` row at the top (`pageActions()` in views-main.js). + - **A tab whose view isn't registered is hidden** (its file failed to load) instead of throwing; Settings falls back to General. On a phone the tab bar scrolls the selected tab into view on every render (v1.17.0). + - **Database (v1.17.0)** is the `db-tools` view: a `.seg.tabs-seg` tablist (DB Inspector · DB Schema; arrow keys, Home, End) and one `role="tabpanel"` that the `db-inspector` or `db-schema` view renders into. `dbToolsTab` remembers the choice for the session only, like `forecastTab`. **Transactions pills (v1.14.0).** `renderTxPills(root, current)` draws the row on all five screens. **All** and **Payments** set `txPillFilter` and show the `transactions` view, which lists one or the other. **Income**, **Spending**, **Bills** and **Transfers** set `txPillFilter` and open the registered views `income`, `spending`, `bills`, `transfers` (titles "Income", "Spending", "Bills & subscriptions", "Transfers"). The Transactions view treats any other `txPillFilter` as All, so the app bar link always lands on the list. `TX_VIEWS` (ui.js) keeps Transactions underlined on all five. @@ -796,7 +808,7 @@ View registrations by file: - `views-data.js` — import, accounts, credit-cards, categories (Settings tabs); db-logs (Import Logs, not in nav) - `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) +- `views-db.js` — db-tools (Settings → Database tab), db-inspector, db-schema, changelog. Only db-tools is reachable from the UI; all four also open with `showView()` from DevTools. - `views-eval.js` — ai-eval (not in nav; developer only — `showView('ai-eval')` from DevTools, §21) ### Nav label and icon rule (replaces the emoji rule, v1.13.0) @@ -964,11 +976,11 @@ Multiple credit card files can be loaded simultaneously. Each gets a unique `acc --- -*Last updated: v1.16.0 — 2026-11-02 (Trends, AI Analysis, Settings and the Welcome rebuilt: §3 file roles; §4.1 `cardDetails`, `sampleData`, AI history `model`; §6 tile tokens and Insights/Settings/Welcome components; §7 rule 7 covers Trends; §8 `loadFiles()` sample option; §9 `shellHero()`, `NO_RANGE_VIEWS`, ☰ → ×, JSON export/import buttons; §12 Settings tabs renamed, the Welcome, range label hidden on Trends and Settings; §13 quick analyses, tab state, history; §20 new fields, Use my own files, Export/Import JSON; §21 quick analyses send `AI_PROMPTS`; v1.15.0: Plan screens rebuilt: §3 file roles; §4.1 `debtPlan` and the Budget / Bucket / Debt / Scenario shapes; §6 `--teal-text` and Plan components; §7 rule 7 covers the Plan charts; §8 plan helpers (`payoffPlan()`, `growthByYear()` …); §9 plan form helpers, `simulatePayoff()` kept unused; §12 Plan titles, Forecast tabs, range label hidden on Plan screens; §13 debt balances in the summary; §20 Clear forecast scenarios / investment mix, Clear debts resets `debtPlan`; v1.14.0: Finances screens rebuilt: §4.1 Bill shape and `recurringConfirmed`; §6 new tokens and Finances components; §7 rule 7 inline SVG charts; §8 new aggregation helpers; §9 drawer, `TX_VIEWS`, SVG/heatmap/format helpers, bill helpers, removed renderers; §11 keywords re-run detection, `transferPairs()`, card payments; §12 page actions and Transactions pills; §20 Clear bills also clears spotted-charge choices; v1.13.0: Clarity redesign — §6 tokens and components; §9 theme, chart colors and app bar helpers; §12 app bar navigation replaces the sidebar and the emoji rule; §17 footer; §20 Data & Reset; v1.12.0: bank-neutral account codes, names, samples and docs; §22 `migrate.js` added; §3, §4, §5, §10, §18, §21 updated; v1.10.2: §13 summary states its dates; §21 per-month derivations; v1.10.1: §13 `AI_MAX_TOKENS`, thinking and cut-off answers; v1.10.0: §21 AI Eval added; §13 `callClaude()` raw mode; v1.9.6: §14 folder access lasts until the last tab closes, not one page load; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §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)* +*Last updated: v1.17.0 — 2026-11-02 (Settings → Database tab, DB Inspector and DB Schema rebuilt on Clarity: §1 version; §3 views-db.js role; §6 Database classes; §12 seventh Settings tab, its sub-tabs, the hidden-tab guard, the tab bar scrolling to the selected tab, view registrations; §19 database views; v1.16.0: Trends, AI Analysis, Settings and the Welcome rebuilt: §3 file roles; §4.1 `cardDetails`, `sampleData`, AI history `model`; §6 tile tokens and Insights/Settings/Welcome components; §7 rule 7 covers Trends; §8 `loadFiles()` sample option; §9 `shellHero()`, `NO_RANGE_VIEWS`, ☰ → ×, JSON export/import buttons; §12 Settings tabs renamed, the Welcome, range label hidden on Trends and Settings; §13 quick analyses, tab state, history; §20 new fields, Use my own files, Export/Import JSON; §21 quick analyses send `AI_PROMPTS`; v1.15.0: Plan screens rebuilt: §3 file roles; §4.1 `debtPlan` and the Budget / Bucket / Debt / Scenario shapes; §6 `--teal-text` and Plan components; §7 rule 7 covers the Plan charts; §8 plan helpers (`payoffPlan()`, `growthByYear()` …); §9 plan form helpers, `simulatePayoff()` kept unused; §12 Plan titles, Forecast tabs, range label hidden on Plan screens; §13 debt balances in the summary; §20 Clear forecast scenarios / investment mix, Clear debts resets `debtPlan`; v1.14.0: Finances screens rebuilt: §4.1 Bill shape and `recurringConfirmed`; §6 new tokens and Finances components; §7 rule 7 inline SVG charts; §8 new aggregation helpers; §9 drawer, `TX_VIEWS`, SVG/heatmap/format helpers, bill helpers, removed renderers; §11 keywords re-run detection, `transferPairs()`, card payments; §12 page actions and Transactions pills; §20 Clear bills also clears spotted-charge choices; v1.13.0: Clarity redesign — §6 tokens and components; §9 theme, chart colors and app bar helpers; §12 app bar navigation replaces the sidebar and the emoji rule; §17 footer; §20 Data & Reset; v1.12.0: bank-neutral account codes, names, samples and docs; §22 `migrate.js` added; §3, §4, §5, §10, §18, §21 updated; v1.10.2: §13 summary states its dates; §21 per-month derivations; v1.10.1: §13 `AI_MAX_TOKENS`, thinking and cut-off answers; v1.10.0: §21 AI Eval added; §13 `callClaude()` raw mode; v1.9.6: §14 folder access lasts until the last tab closes, not one page load; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §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)* --- -## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1) +## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1, in Settings → Database since v1.17.0) The full IndexedDB implementation is live. See **`docs/archive/INDEXEDDB_PLAN.md`** for the original spec. @@ -984,6 +996,14 @@ The full IndexedDB implementation is live. See **`docs/archive/INDEXEDDB_PLAN.md ### Adding a new bank Add a new object to `BANK_SCHEMAS` in `core.js`. No other code changes needed if the bank follows standard column conventions (`date`, `amount`, `description`). For non-standard conventions use: `amountSign: 'inverted'`, custom `columns` map, `dateFormat` (`'YYYY-MM-DD'` | `'MM/DD/YYYY'` | `'DD/MM/YYYY'`), and `postDateFormat` if the post-date column uses a different format than the primary date column (see the `credit_card` schema). +### Database views (views-db.js, Settings → Database since v1.17.0) +- **DB Inspector** (`db-inspector`) reads one store with `getAll()` and shows it 50 records a page, the store's keyPath first. Its state lives on the `DBInspector` object, in memory only: store, search, page and the records last read. + - **It re-reads the store on every render**, keeping the store, search and page; a page past the end moves back to the last one. The read runs after the render (`setTimeout`), and it looks its elements up again afterwards, because the view may have been left. + - **Read-only.** Picking a store reads it; the search matches each record's JSON as you type; Refresh reads the store again. + - **The API key is never shown.** Its `app_state` row says it's hidden, and the search skips its value (`DBInspector.isSecret()`, §13). +- **DB Schema** (`db-schema`) draws the five stores as inline SVG, 872px wide so it fits Settings' 1000px page. Colors come from `.sch-*` classes in `index.html` (§6), never from the script. The field lists and the `app_state` key list are written by hand: when a store or a saved key changes, update them. +- **The embedded changelog** (`changelog` view, `CHANGELOG_MD`) still stops at v1.4.1. Refreshing it is a separate cleanup. + ### 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). diff --git a/README.md b/README.md index d4b7908..342fa10 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.16.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.17.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -143,7 +143,7 @@ Reference lists for learning, not financial advice. Type your own % next to nine Ask Claude about your finances: eight quick analyses (a monthly spending review, where to cut back, a subscription audit, a savings-rate check, a debt payoff plan, budget suggestions, a 12-month forecast and a summary) or your own question. Claude receives a text summary of your balances, income, spending by category, debts and subscriptions for the dates on screen, never your CSV files. Answers can be copied or saved as Markdown, and a cut-off answer says so. History keeps up to 50 answers in your browser; open any of them again, or export them all as Markdown. Requires your own [Anthropic API key](https://console.anthropic.com). ### Settings -Six tabs: **General** (theme and your API key), **Import** (your CSV folder, how each file is read and the import log), **Accounts** (names, display order and starting balances), **Credit cards** (balance, credit limit, APR and payment due day), **Categories** (add or delete; deleting moves a category's transactions to Other) and **Data & reset** (what's stored, clean up, JSON export and import, start over). +Seven tabs: **General** (theme and your API key), **Import** (your CSV folder, how each file is read and the import log), **Accounts** (names, display order and starting balances), **Credit cards** (balance, credit limit, APR and payment due day), **Categories** (add or delete; deleting moves a category's transactions to Other), **Data & reset** (what's stored, clean up, JSON export and import, start over) and **Database** (DB Inspector and DB Schema, for looking at the raw data). --- @@ -226,7 +226,7 @@ FinLens/ ├── views-data.js ← Settings tabs Import, Accounts, Credit cards, Categories; sample data; Import Logs ├── views-settings.js ← Settings shell + General tab (theme, API key) ├── views-cleanup.js ← Settings → Data & reset (clean up data, export/import JSON, start over) - ├── views-db.js ← DB Inspector, DB Schema diagram, Changelog views + ├── views-db.js ← Settings → Database (DB Inspector, DB Schema diagram); Changelog view ├── views-eval.js ← AI Eval: grounding eval for AI Analysis (developer view) └── init.js ← App boot and event wiring ``` @@ -251,6 +251,8 @@ FinLens/ - **Export or import JSON:** your plans, edits, balances, categories and AI history in one file (no transactions, no API key). - **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. +**Looking at the raw data** — **Settings → Database** has two sub-tabs. **DB Inspector** browses each IndexedDB store, read-only and searchable; your API key is never shown. **DB Schema** diagrams the five stores and how they link. + **Dark mode** — go to **Settings → General → Theme** and pick **Dark**, or **Match system** to follow your computer. Light is the default. **Exporting** — the Transactions screen has an **Export CSV** button: it exports every transaction in the current date range and accounts. AI answers can be saved as Markdown from the AI Analysis tab, one at a time or the whole history. @@ -263,4 +265,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.16.0 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.17.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index d1e2044..c13e6d2 100644 --- a/index.html +++ b/index.html @@ -1040,6 +1040,52 @@ .radio-set label{display:flex;align-items:center;gap:10px;min-height:36px;font-size:14px;cursor:pointer;overflow-wrap:anywhere} .radio-set input{width:18px;height:18px;margin:0;flex-shrink:0;accent-color:var(--accent)} .field .input.reset-in{width:200px;font-weight:600;letter-spacing:.08em} +/* Settings → Database (v1.17.0): DB Inspector table, DB Schema diagram */ +.tbl.db-tbl{font-size:13px} +.tbl.db-tbl th,.tbl.db-tbl td{max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:10px;text-transform:none;letter-spacing:0} +.form-row .field.insp-store{flex:0 1 200px} +.tbl.db-tbl thead th{text-transform:none;letter-spacing:0;font:500 12px 'DM Mono',ui-monospace,monospace;color:var(--text-2)} +.tbl.db-tbl tbody th{font:500 12.5px 'DM Mono',ui-monospace,monospace;color:var(--text);text-align:left;border-bottom:1px solid var(--divider)} +.tbl.db-tbl tr:hover th{background:var(--surface-2)} +.tbl.db-tbl tbody tr:last-child>*{border-bottom:0} +.tbl.db-tbl th:first-child,.tbl.db-tbl td:first-child{padding-left:24px} +.tbl.db-tbl th:last-child,.tbl.db-tbl td:last-child{padding-right:24px} +.dv-null,.dv-hidden{color:var(--text-3);font-style:italic} +.dv-date{color:var(--teal-text)} .dv-arr{color:var(--violet-text)} .dv-num{color:var(--sky-text);font-variant-numeric:tabular-nums} +.dv-obj{color:var(--text-2);font:12px 'DM Mono',ui-monospace,monospace} +.dv-true{color:var(--good-text)} .dv-false{color:var(--text-3)} +/* the schema: each store's .sch-* sets --c (lines, fills) and --ct (text) from the theme */ +.sch-teal{--c:var(--teal-2);--ct:var(--teal-text)} .sch-warn{--c:var(--warn);--ct:var(--warn-strong-text)} +.sch-sky{--c:var(--sky);--ct:var(--sky-text)} .sch-violet{--c:var(--violet);--ct:var(--violet-text)} +.sch-neutral{--c:var(--text-3);--ct:var(--text-2)} +.sch-scroll{border-radius:var(--radius-sm)} +.sch-scroll:focus-visible{outline:2px solid var(--accent-border);outline-offset:2px} +svg.sch{display:block;font-family:'DM Mono',ui-monospace,Menlo,monospace} +.sch .box-bg{fill:var(--surface)} +.sch .box{fill:none;stroke:var(--c);stroke-width:1.5} +.sch .band{fill:color-mix(in srgb,var(--c) 12%,var(--surface))} +.sch .rule{stroke:var(--c);stroke-opacity:.5} +.sch .stripe{fill:var(--surface-2)} +.sch .st-name{fill:var(--ct);font-size:13px;font-weight:500} +.sch .st-kind{fill:var(--text-3);font-size:10px} +.sch .f-name{fill:var(--text);font-size:12px} +.sch .f-type{fill:var(--text-3);font-size:10.5px;font-style:italic} +.sch .f-note{fill:var(--ct);font-size:10px} +.sch .st-note{fill:var(--text-3);font-size:10px;font-style:italic} +.sch .badge{fill:var(--muted)} +.sch .badge.pk{fill:color-mix(in srgb,var(--c) 16%,var(--surface));stroke:var(--c)} +.sch .badge-t{fill:var(--text-2);font:700 9px 'Inter',system-ui,sans-serif} +.sch .badge-t.pk{fill:var(--ct)} +.sch .rel{fill:none;stroke:var(--c);stroke-width:1.5;stroke-dasharray:5 3} +.sch .rel-head{fill:var(--c)} +.sch .rel-bg{fill:var(--surface)} +.sch .rel-t{fill:var(--ct);font-size:10px} +.key-badge{display:inline-block;padding:1px 6px;border:1px solid transparent;border-radius:4px;background:var(--muted);color:var(--text-2);font-size:10px;font-weight:700;line-height:14px} +.key-badge.pk{background:color-mix(in srgb,var(--c) 16%,var(--surface));border-color:var(--c);color:var(--ct)} +.sch-opt{font:italic 11px 'DM Mono',ui-monospace,monospace;color:var(--text-3)} +.sch-hint{display:none} +@media (max-width:900px){.panel .sub.sch-hint{display:block;margin:0}} +@media (max-width:720px){.tbl.db-tbl th:first-child,.tbl.db-tbl td:first-child{padding-left:16px} .tbl.db-tbl th:last-child,.tbl.db-tbl td:last-child{padding-right:16px}} /* Welcome */ .welcome{display:flex;flex-direction:column;align-items:center;gap:16px;text-align:center} .welcome .lead{margin:0;max-width:620px;font-size:18px;line-height:1.55;color:var(--text-2)} @@ -1202,7 +1248,7 @@
-
v1.16.0 · FinLens
+
v1.17.0 · FinLens
diff --git a/js/views-db.js b/js/views-db.js index f281c55..abe56c9 100644 --- a/js/views-db.js +++ b/js/views-db.js @@ -1,543 +1,401 @@ /* ================================================================ FINLENS — views-db.js - Database views: Schema Diagram, DB Inspector, Settings → Database tab, Changelog + Database views: the DB Schema diagram and DB Inspector, the + Settings → Database tab that shows them as sub-tabs (Clarity, + v1.17.0), and the Changelog. + Colors come from CSS classes in index.html (.sch-*, .dv-*), which + read the theme tokens, so nothing here names a color. ================================================================ */ /* ══════════════════════════════════════════════════════════════ 1. DB SCHEMA DIAGRAM - Visual ERD of all 5 IndexedDB stores with fields and relationships + The 5 IndexedDB object stores in finlens_db, their fields and how + they link, as an inline SVG. ══════════════════════════════════════════════════════════════ */ registerView('db-schema', 'DB Schema', (root) => { - - const card = document.createElement('div'); - card.className = 'card'; - card.innerHTML = ` -

Database Schema & Inspector

-

- All data stored locally in your browser. No server, no cloud. Five object stores with relationships shown below. -

`; - root.appendChild(card); - - const diagramCard = document.createElement('div'); - diagramCard.className = 'card'; - diagramCard.style.padding = '0'; - diagramCard.style.overflow = 'hidden'; - - // Build the diagram as an SVG embedded in HTML - diagramCard.innerHTML = `
`; - root.appendChild(diagramCard); - - setTimeout(() => { - const holder = document.getElementById('dbDiagram'); - if (!holder) return; - - // ── Store definitions ────────────────────────────────────── - const stores = [ - { - id: 'transactions', - label: 'transactions', - color: 'var(--teal)', - colorSoft: 'var(--teal-soft)', - fields: [ - { name: 'id', type: 'string', key: 'PK', note: 'deterministic hash' }, - { name: 'date', type: 'Date', key: 'IDX' }, - { name: 'yearMonth', type: 'string', key: 'IDX', note: 'YYYY-MM' }, - { name: 'account', type: 'string', key: 'IDX', note: '→ accounts.id' }, - { name: 'type', type: 'string', key: 'IDX', note: 'debit|credit|transfer' }, - { name: 'schemaId', type: 'string', key: 'IDX', note: '→ BANK_SCHEMAS.id' }, - { name: 'description', type: 'string', key: '' }, - { name: 'amount', type: 'number', key: '' }, - { name: 'categories', type: 'string[]', key: '' }, - { name: 'isRecurring', type: 'boolean', key: '' }, - { name: 'isBill', type: 'boolean', key: '' }, - { name: 'isSubscription',type: 'boolean', key: '' }, - { name: '_originalDesc', type: 'string', key: '' }, - ], - }, - { - id: 'tx_overrides', - label: 'tx_overrides', - color: 'var(--amber)', - colorSoft: 'var(--amber-soft)', - fields: [ - { name: 'txId', type: 'string', key: 'PK', note: '→ transactions.id' }, - { name: 'description', type: 'string?', key: '' }, - { name: 'categories', type: 'string[]?', key: '' }, - { name: 'type', type: 'string?', key: '' }, - { name: 'notes', type: 'string?', key: '' }, - { name: 'isRecurring', type: 'boolean?', key: '' }, - { name: 'isBill', type: 'boolean?', key: '' }, - { name: 'isSubscription',type: 'boolean?', key: '' }, - { name: 'accountOverride',type:'string?', key: '' }, - { name: 'link', type: 'object?', key: '', note: '{type,idx}' }, - { name: 'modifiedAt', type: 'Date', key: '' }, - ], - }, - { - id: 'accounts', - label: 'accounts', - color: 'var(--blue)', - colorSoft: 'rgba(59,130,246,.08)', - fields: [ - { name: 'id', type: 'string', key: 'PK', note: 'e.g. bank_checking' }, - { name: 'name', type: 'string', key: '' }, - { name: 'kind', type: 'string', key: '', note: 'checking|savings|credit|…' }, - { name: 'schemaId', type: 'string', key: '' }, - { name: 'sourceFile', type: 'string', key: '' }, - { name: 'displayOrder', type: 'number', key: '' }, - { name: 'manualBalance', type: 'number?', key: '' }, - { name: 'creditLimit', type: 'number?', key: '' }, - { name: 'initialBalance',type: 'number?', key: '' }, - { name: 'dataRangeMin', type: 'Date?', key: '', note: 'coverage tracking' }, - { name: 'dataRangeMax', type: 'Date?', key: '', note: 'coverage tracking' }, - { name: 'txCount', type: 'number', key: '', note: 'coverage tracking' }, - ], - }, - { - id: 'import_log', - label: 'import_log', - color: 'var(--purple)', - colorSoft: 'rgba(139,92,246,.08)', - fields: [ - { name: 'id', type: 'number', key: 'PK', note: 'auto-increment' }, - { name: 'timestamp', type: 'Date', key: '' }, - { name: 'filename', type: 'string', key: '' }, - { name: 'accountId', type: 'string', key: '', note: '→ accounts.id' }, - { name: 'schemaId', type: 'string', key: '' }, - { name: 'rowsFound', type: 'number', key: '' }, - { name: 'rowsInserted', type: 'number', key: '' }, - { name: 'rowsSkipped', type: 'number', key: '' }, - { name: 'dateRangeMin', type: 'Date', key: '' }, - { name: 'dateRangeMax', type: 'Date', key: '' }, - ], - }, - { - id: 'app_state', - label: 'app_state', - color: 'var(--text-2)', - colorSoft: 'var(--surface-2)', - fields: [ - { name: 'key', type: 'string', key: 'PK', note: 'lsSet() key' }, - { name: 'value', type: 'any', key: '', note: 'JSON-serializable' }, - ], - note: 'budgets · bills · debts · buckets · categories · apiKey · aiHistory · scenarios · investAlloc · debtPlan · manualBalances · txOverrides · accountOrder · accountLabels · categoryRules · txRules · transferKeywords · customSchemas · fileAssignments · theme', - }, - ]; - - // ── Layout: 3-column grid ────────────────────────────────── - // Col 0: transactions (tall) - // Col 1: tx_overrides, accounts - // Col 2: import_log, app_state - const COL_W = 260; - const COL_GAP = 80; - const ROW_H = 28; - const HDR_H = 40; - const FIELD_PAD = 8; - - function storeHeight(s) { - return HDR_H + s.fields.length * ROW_H + FIELD_PAD * 2 + (s.note ? 32 : 0); - } - - const layout = { - transactions: { col: 0, row: 0 }, - tx_overrides: { col: 1, row: 0 }, - accounts: { col: 1, row: 1 }, - import_log: { col: 2, row: 0 }, - app_state: { col: 2, row: 1 }, - }; - - // Compute X positions - const colX = [0, COL_W + COL_GAP, (COL_W + COL_GAP) * 2]; - - // Compute Y positions per (col, row) - const colRowY = { '1_0': 0, '1_1': 0, '2_0': 0, '2_1': 0 }; - const txH = storeHeight(stores[0]); - colRowY['1_0'] = 0; - colRowY['1_1'] = storeHeight(stores[1]) + 32; - colRowY['2_0'] = 0; - colRowY['2_1'] = storeHeight(stores[3]) + 32; - - function boxPos(storeId) { - const l = layout[storeId]; - const x = colX[l.col]; - let y = 0; - if (l.col === 0) y = 0; - else y = colRowY[`${l.col}_${l.row}`]; - return { x, y }; - } - - const totalW = COL_W * 3 + COL_GAP * 2; - const totalH = Math.max( - storeHeight(stores[0]), - storeHeight(stores[1]) + 32 + storeHeight(stores[2]), - storeHeight(stores[3]) + 32 + storeHeight(stores[4]) - ); - - // ── SVG builder ────────────────────────────────────────────── - let svg = ``; - - // Draw each store box - stores.forEach(s => { - const { x, y } = boxPos(s.id); - const h = storeHeight(s); - - // Box shadow / background - svg += ``; - - // Header band - svg += ``; - // Mask bottom corners of header - svg += ``; - - // Header divider - svg += ``; - - // Store name - svg += `${s.label}`; - svg += `IndexedDB Object Store`; - - // Fields - s.fields.forEach((f, i) => { - const fy = y + HDR_H + FIELD_PAD + i * ROW_H; - const isKey = f.key === 'PK' || f.key === 'IDX'; - - // Row hover band (every other) - if (i % 2 === 0) { - svg += ``; - } - - // Key badge - if (f.key) { - const badgeColor = f.key === 'PK' ? s.color : 'var(--text-3)'; - svg += ``; - svg += `${f.key}`; - } - - const nameX = f.key ? x + 14 + (f.key.length * 7 + 14) : x + 14; - svg += `${f.name}`; - - // Type (right-aligned) - const typeStr = f.type + (f.note ? '' : ''); - svg += `${typeStr}`; - - // Note tooltip (small below type) - if (f.note) { - svg += `${f.note}`; - } - }); - - // Store note (description of keys) - if (s.note) { - const noteY = y + HDR_H + FIELD_PAD + s.fields.length * ROW_H + 6; - // Wrap note text - const words = s.note.split(' · '); - const line1 = words.slice(0, Math.ceil(words.length / 2)).join(' · '); - const line2 = words.slice(Math.ceil(words.length / 2)).join(' · '); - svg += `${escapeHtml(line1)}`; - svg += `${escapeHtml(line2)}`; - } - }); - - // ── Relationship arrows ────────────────────────────────────── - // transactions.id ←→ tx_overrides.txId + // hue: a .sch-* class (index.html) that sets --c (lines) and --ct (text) from the theme. + const stores = [ { - const from = boxPos('transactions'); - const to = boxPos('tx_overrides'); - // transactions right edge, vertically at 'id' field - const x1 = from.x + COL_W; - const y1 = from.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const x2 = to.x; - const y2 = to.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const mx = (x1 + x2) / 2; - svg += ``; - // Arrow head - svg += ``; - // Label - svg += `1:N id → txId`; - } - - // transactions.account → accounts.id + id: 'transactions', hue: 'teal', + fields: [ + { name: 'id', type: 'string', key: 'PK', note: 'deterministic hash' }, + { name: 'date', type: 'Date', key: 'IDX' }, + { name: 'yearMonth', type: 'string', key: 'IDX', note: 'YYYY-MM' }, + { name: 'account', type: 'string', key: 'IDX', note: '→ accounts.id' }, + { name: 'type', type: 'string', key: 'IDX', note: 'debit|credit|transfer' }, + { name: 'schemaId', type: 'string', key: 'IDX', note: '→ BANK_SCHEMAS.id' }, + { name: 'description', type: 'string', key: '' }, + { name: 'amount', type: 'number', key: '' }, + { name: 'categories', type: 'string[]', key: '' }, + { name: 'isRecurring', type: 'boolean', key: '' }, + { name: 'isBill', type: 'boolean', key: '' }, + { name: 'isSubscription',type: 'boolean', key: '' }, + { name: '_originalDesc', type: 'string', key: '' }, + ], + }, { - const from = boxPos('transactions'); - const to = boxPos('accounts'); - const accountFieldIdx = stores[0].fields.findIndex(f => f.name === 'account'); - const x1 = from.x + COL_W; - const y1 = from.y + HDR_H + FIELD_PAD + accountFieldIdx * ROW_H + 14; - const x2 = to.x; - const y2 = to.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const mx = (x1 + x2) / 2; - svg += ``; - svg += ``; - svg += `N:1 account → id`; - } - - // import_log.accountId → accounts.id + id: 'tx_overrides', hue: 'warn', + fields: [ + { name: 'txId', type: 'string', key: 'PK', note: '→ transactions.id' }, + { name: 'description', type: 'string?', key: '' }, + { name: 'categories', type: 'string[]?', key: '' }, + { name: 'type', type: 'string?', key: '' }, + { name: 'notes', type: 'string?', key: '' }, + { name: 'isRecurring', type: 'boolean?', key: '' }, + { name: 'isBill', type: 'boolean?', key: '' }, + { name: 'isSubscription',type: 'boolean?', key: '' }, + { name: 'accountOverride',type:'string?', key: '' }, + { name: 'link', type: 'object?', key: '', note: '{type,idx}' }, + { name: 'modifiedAt', type: 'Date', key: '' }, + ], + }, { - const from = boxPos('import_log'); - const to = boxPos('accounts'); - const acctFieldIdx = stores[3].fields.findIndex(f => f.name === 'accountId'); - const x1 = from.x; - const y1 = from.y + HDR_H + FIELD_PAD + acctFieldIdx * ROW_H + 14; - const x2 = to.x + COL_W; - const y2 = to.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const mx = (x1 + x2) / 2; - svg += ``; - svg += ``; - svg += `N:1 accountId → id`; - } - - svg += ``; - holder.innerHTML = svg; - - // ── Legend card ────────────────────────────────────────────── - const legend = document.createElement('div'); - legend.className = 'card'; - legend.style.marginTop = '0'; - legend.innerHTML = ` -

Legend

-
-
- PK - Primary Key (keyPath) -
-
- IDX - Indexed field (fast queries) -
-
- - Foreign key relationship -
-
- type? - Optional field (may be null) -
-
-
- Database: finlens_db · Version: 1 · Storage: IndexedDB (browser-native) · All data stays on your device. -
`; - root.appendChild(legend); - }, 0); + id: 'accounts', hue: 'sky', + fields: [ + { name: 'id', type: 'string', key: 'PK', note: 'e.g. bank_checking' }, + { name: 'name', type: 'string', key: '' }, + { name: 'kind', type: 'string', key: '', note: 'bank_checking|credit_card|…' }, + { name: 'schemaId', type: 'string', key: '' }, + { name: 'sourceFile', type: 'string', key: '' }, + { name: 'displayOrder', type: 'number', key: '' }, + { name: 'manualBalance', type: 'number?', key: '' }, + { name: 'creditLimit', type: 'number?', key: '' }, + { name: 'initialBalance',type: 'number?', key: '' }, + { name: 'dataRangeMin', type: 'Date?', key: '', note: 'coverage tracking' }, + { name: 'dataRangeMax', type: 'Date?', key: '', note: 'coverage tracking' }, + { name: 'txCount', type: 'number', key: '', note: 'coverage tracking' }, + ], + }, + { + id: 'import_log', hue: 'violet', + fields: [ + { name: 'id', type: 'number', key: 'PK', note: 'auto-increment' }, + { name: 'timestamp', type: 'Date', key: '' }, + { name: 'filename', type: 'string', key: '' }, + { name: 'accountId', type: 'string', key: '', note: '→ accounts.id' }, + { name: 'schemaId', type: 'string', key: '' }, + { name: 'rowsFound', type: 'number', key: '' }, + { name: 'rowsInserted', type: 'number', key: '' }, + { name: 'rowsSkipped', type: 'number', key: '' }, + { name: 'dateRangeMin', type: 'Date', key: '' }, + { name: 'dateRangeMax', type: 'Date', key: '' }, + ], + }, + { + id: 'app_state', hue: 'neutral', + fields: [ + { name: 'key', type: 'string', key: 'PK', note: 'lsSet() key' }, + { name: 'value', type: 'any', key: '', note: 'JSON-serializable' }, + ], + // The lsSet() keys the code writes (and customSchemas, which it reads). + note: 'budgets · bills · recurring · debts · debtPlan · buckets · categories · catRules · txRules · apiKey · aiHistory · scenarios · investAlloc · manualBalances · cardDetails · txOverrides · accountOrder · accountLabels · transferKeywords · customSchemas · fileAssignments · lastFolderName · csvAutoImportPaused · sampleData · theme', + }, + ]; + + // ── Layout: three columns ──────────────────────────────────── + // transactions | tx_overrides over accounts | import_log over app_state + // 3 × 228 + 2 × 94 = 872px: fits Settings' 1000px page inside a panel. The gaps hold + // the relationship labels. Text is DM Mono, about 0.6em a character. + const W = 228, GAP = 94, ROW_H = 30, HDR_H = 44, PAD = 8, STACK = 28, NOTE_LH = 13; + const byId = Object.fromEntries(stores.map(s => [s.id, s])); + // Wrap a store's note into lines that fit the box (10px text ≈ 6px a character). + const perLine = Math.floor((W - 24) / 6); + stores.forEach(s => { + s.lines = []; + if (!s.note) return; + let line = ''; + s.note.split(' · ').forEach(w => { + const next = line ? line + ' · ' + w : w; + if (next.length > perLine && line) { s.lines.push(line + ' ·'); line = w; } else line = next; + }); + if (line) s.lines.push(line); + }); + const height = (s) => HDR_H + s.fields.length * ROW_H + PAD * 2 + (s.lines.length ? s.lines.length * NOTE_LH + 8 : 0); + const at = { + transactions: { x: 0, y: 0 }, + tx_overrides: { x: W + GAP, y: 0 }, + accounts: { x: W + GAP, y: height(byId.tx_overrides) + STACK }, + import_log: { x: (W + GAP) * 2, y: 0 }, + app_state: { x: (W + GAP) * 2, y: height(byId.import_log) + STACK }, + }; + const totalW = W * 3 + GAP * 2; + const totalH = Math.max(...stores.map(s => at[s.id].y + height(s))) + 2; + const fieldY = (id, name) => at[id].y + HDR_H + PAD + byId[id].fields.findIndex(f => f.name === name) * ROW_H + ROW_H / 2; + const esc = escapeHtml; + + let svg = ''; + stores.forEach(s => { + const { x, y } = at[s.id]; + const h = height(s), r = 10; + svg += ``; + svg += ``; + // header band: rounded at the top only + svg += ``; + svg += ``; + svg += `${esc(s.id)}`; + svg += `IndexedDB object store`; + s.fields.forEach((f, i) => { + const fy = y + HDR_H + PAD + i * ROW_H; + if (i % 2 === 0) svg += ``; + let nameX = x + 12; + if (f.key) { + const bw = f.key.length * 6.5 + 8, pk = f.key === 'PK' ? ' pk' : ''; + svg += ``; + svg += `${f.key}`; + nameX += bw + 7; + } + svg += `${esc(f.name)}`; + svg += `${esc(f.type)}`; + if (f.note) svg += `${esc(f.note)}`; + }); + const ny = y + HDR_H + PAD + s.fields.length * ROW_H + 8; + s.lines.forEach((l, i) => { svg += `${esc(l)}`; }); + svg += ``; // outline on top of the band + svg += ``; + }); + + // ── Relationships: a dashed curve from the field to the key it points at ── + // [from store, field, to store, field, hue, label lines, label position 'above' | 'mid'] + const rels = [ + ['transactions', 'id', 'tx_overrides', 'txId', 'teal', ['1:N', 'id → txId'], 'above'], + ['transactions', 'account', 'accounts', 'id', 'sky', ['N:1', 'account → id'], 'mid'], + ['import_log', 'accountId', 'accounts', 'id', 'violet', ['N:1', 'accountId → id'], 'mid'], + ]; + rels.forEach(([fs, ff, ts, tf, hue, label, pos]) => { + const leftToRight = at[fs].x < at[ts].x; + const x1 = leftToRight ? at[fs].x + W : at[fs].x, y1 = fieldY(fs, ff); + const x2 = leftToRight ? at[ts].x : at[ts].x + W, y2 = fieldY(ts, tf); + const mx = (x1 + x2) / 2, d = leftToRight ? -8 : 8; + svg += ``; + svg += ``; + svg += ``; + const ly = pos === 'above' ? Math.min(y1, y2) - 30 : (y1 + y2) / 2 - 13; + const lw = Math.max(...label.map(l => l.length)) * 6 + 10; + svg += ``; + label.forEach((l, i) => { svg += `${esc(l)}`; }); + svg += ``; + }); + + const desc = 'Diagram of the five IndexedDB object stores and their fields: transactions, tx_overrides, accounts, import_log and app_state. ' + + 'transactions.id links to tx_overrides.txId (one transaction, many edits); transactions.account and import_log.accountId each point at accounts.id.'; + appendHtml(root, `
+

Database schema

+

The five object stores FinLens keeps in this browser's IndexedDB database, their fields, and how they link. No server, no cloud.

+

Scroll sideways to see the whole diagram.

+
+ ${svg} +
+
+ PKPrimary key (the store's keyPath) + IDXIndexed field (fast queries) + Link between stores + type?Optional field (may be missing) +
+

Database finlens_db · version 1 · IndexedDB in this browser. Your data stays on this device.

+
`); }); /* ══════════════════════════════════════════════════════════════ 2. DB INSPECTOR - Browse any IndexedDB store — select store, search, paginate + Browse any IndexedDB store: pick a store, search, page through. + Read-only. Re-reads the store on every visit, keeping the store, + search and page (a page past the end moves back to the last one). ══════════════════════════════════════════════════════════════ */ const DB_INSPECTOR_STORES = ['transactions', 'tx_overrides', 'accounts', 'import_log', 'app_state']; - -let _inspectorStore = 'transactions'; -let _inspectorPage = 0; -let _inspectorSearch = ''; -let _inspectorRows = []; const INSPECTOR_PAGE_SIZE = 50; +// Session memory (nothing is saved): the chosen store, search and page, and the records last read. +const DBInspector = { + store: 'transactions', + search: '', // as typed; matched case-insensitively against each record's JSON + page: 0, // 0-based + all: [], // the store's records, as last read + rows: [], // …those that match the search + keyPath: 'id', // the store's key, shown first + // The API key is in app_state (CLAUDE.md §13). Show that it's there, never its value, and + // leave its value out of the search so typing can't reveal it a character at a time. + isSecret: (r) => DBInspector.store === 'app_state' && r && r.key === 'apiKey', + matches(r, q) { + const v = this.isSecret(r) ? { key: r.key } : r; + return JSON.stringify(v).toLowerCase().includes(q); + }, +}; registerView('db-inspector', 'DB Inspector', (root) => { - - const ctrl = document.createElement('div'); - ctrl.className = 'card'; - ctrl.innerHTML = ` -

DB Inspector

-

Browse the raw contents of any IndexedDB store. Read-only.

-
-
- - -
-
- - -
-
- - -
+ const I = DBInspector; + appendHtml(root, `
+

DB Inspector

Read-only
+

The raw records in this browser's database, one store at a time. Nothing here can be changed.

+
+ + + +
-
`; - root.appendChild(ctrl); - - const tableCard = document.createElement('div'); - tableCard.className = 'card'; - tableCard.innerHTML = `

Select a store and click Load.

`; - root.appendChild(tableCard); - - const pagCtrl = document.createElement('div'); - pagCtrl.style.display = 'flex'; - pagCtrl.style.gap = '8px'; - pagCtrl.style.alignItems = 'center'; - pagCtrl.style.flexWrap = 'wrap'; - pagCtrl.innerHTML = ` - - - `; - root.appendChild(pagCtrl); - - // Load data - async function loadStore() { - _inspectorStore = $('#inspStoreSelect').value; - _inspectorSearch = ($('#inspSearch').value||'').trim().toLowerCase(); - _inspectorPage = 0; - await _fetchAndRender(); - } - - async function _fetchAndRender() { - if (typeof DB === 'undefined' || !DB._db) { - $('#inspTable').innerHTML = '
IndexedDB not available.
'; +

+
+
+

Reading the store…

+
+
`); + + // Read the selected store, then draw. Runs after the render (renders stay synchronous, + // CLAUDE.md §15) and looks its elements up again afterwards: the view may have been left. + async function fetchAndRender() { + const store = I.store; + let rows = null; + try { + if (typeof DB !== 'undefined' && DB._db) { + rows = await new Promise((res) => { + const os = DB._db.transaction(store, 'readonly').objectStore(store); + I.keyPath = typeof os.keyPath === 'string' ? os.keyPath : 'id'; + const req = os.getAll(); + req.onsuccess = () => res(req.result || []); + req.onerror = () => res(null); + }); + } + } catch (e) { rows = null; } + if (store !== I.store) return; // another store was picked meanwhile + const tbl = $('#inspTable'); + if (!tbl) return; + if (!rows) { + I.all = []; I.rows = []; + tbl.innerHTML = `
${callout('warn', 'The browser database isn\'t available, so there is nothing to show.')}
`; + const meta = $('#inspMeta'); if (meta) meta.textContent = ''; + const pi = $('#inspPageInfo'); if (pi) pi.textContent = ''; + const pg = $('#inspPager'); if (pg) pg.innerHTML = ''; return; } - const store = _inspectorStore; - const rows = await new Promise(res => { - const req = DB._db.transaction(store, 'readonly').objectStore(store).getAll(); - req.onsuccess = () => res(req.result || []); - req.onerror = () => res([]); - }); - - // Filter - _inspectorRows = _inspectorSearch - ? rows.filter(r => JSON.stringify(r).toLowerCase().includes(_inspectorSearch)) - : rows; - - const meta = document.getElementById('inspMeta'); - if (meta) meta.textContent = `${_inspectorRows.length.toLocaleString()} record${_inspectorRows.length!==1?'s':''} found (${rows.length.toLocaleString()} total in store)`; - - _renderPage(); + I.all = rows; + applySearch(); } - function _renderPage() { - const totalPages = Math.ceil(_inspectorRows.length / INSPECTOR_PAGE_SIZE); - _inspectorPage = Math.max(0, Math.min(_inspectorPage, totalPages - 1)); // store may have shrunk - const start = _inspectorPage * INSPECTOR_PAGE_SIZE; - const pageRows = _inspectorRows.slice(start, start + INSPECTOR_PAGE_SIZE); - - const pageInfo = document.getElementById('inspPageInfo'); - if (pageInfo) pageInfo.textContent = _inspectorRows.length - ? `Page ${_inspectorPage + 1} of ${totalPages} (${start + 1}–${Math.min(start + INSPECTOR_PAGE_SIZE, _inspectorRows.length)} of ${_inspectorRows.length})` - : ''; + function applySearch() { + const q = I.search.trim().toLowerCase(); + I.rows = q ? I.all.filter(r => I.matches(r, q)) : I.all; + const meta = $('#inspMeta'); + if (meta) meta.textContent = `${plural(I.rows.length, 'record')} found (${I.all.length.toLocaleString()} total in store)`; + renderPage(); + } - const prev = document.getElementById('inspPrev'); - const next = document.getElementById('inspNext'); - if (prev) prev.disabled = _inspectorPage === 0; - if (next) next.disabled = _inspectorPage >= totalPages - 1; + // One cell. Strings are escaped; long values are cut, with the full value (up to 500 + // characters) in the cell's title. + function cell(r, k) { + const v = r[k]; + if (I.isSecret(r) && k === 'value') return `Hidden: an API key is saved`; + let disp, full; + if (v === null || v === undefined) disp = 'null'; + else if (v instanceof Date || (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v))) { + const d = dayjs(v); + disp = `${d.isValid() ? d.format('MMM D YYYY, h:mm A') : escapeHtml(String(v))}`; + full = v instanceof Date ? v.toISOString() : v; + } else if (Array.isArray(v)) { + full = '[' + v.map(x => typeof x === 'object' ? JSON.stringify(x) : String(x)).join(', ') + ']'; + disp = `${escapeHtml(full.slice(0, 100))}`; + } else if (typeof v === 'object') { + full = JSON.stringify(v); + disp = `${escapeHtml(full.slice(0, 80))}`; + } else if (typeof v === 'boolean') disp = `${v}`; + else if (typeof v === 'number') disp = `${v.toLocaleString()}`; + else { full = String(v); disp = escapeHtml(full.slice(0, 100)); } + const title = full && full.length > 20 ? ` title="${escapeHtml(full.slice(0, 500))}"` : ''; + return `${disp}`; + } - const tbl = document.getElementById('inspTable'); + function renderPage() { + const pages = Math.max(1, Math.ceil(I.rows.length / INSPECTOR_PAGE_SIZE)); + I.page = Math.max(0, Math.min(I.page, pages - 1)); // the store may have shrunk + const start = I.page * INSPECTOR_PAGE_SIZE; + const pageRows = I.rows.slice(start, start + INSPECTOR_PAGE_SIZE); + const tbl = $('#inspTable'), info = $('#inspPageInfo'), pager = $('#inspPager'); if (!tbl) return; - + if (info) info.textContent = I.rows.length + ? `Page ${I.page + 1} of ${pages} · ${(start + 1).toLocaleString()}–${Math.min(start + INSPECTOR_PAGE_SIZE, I.rows.length).toLocaleString()} of ${I.rows.length.toLocaleString()}` + : ''; + if (pager) { + const nums = []; + for (let p = 0; p < pages; p++) if (p === 0 || p === pages - 1 || Math.abs(p - I.page) <= 1) nums.push(p); else if (nums[nums.length - 1] !== '…') nums.push('…'); + pager.innerHTML = pages > 1 ? ` + ${nums.map(p => p === '…' ? '' : ``).join('')} + ` : ''; + $$('[data-page]', pager).forEach(b => b.onclick = () => { + I.page = +b.dataset.page; renderPage(); + const cur = $('#inspPager [aria-current="page"]'); if (cur) cur.focus({ preventScroll: true }); + }); + } if (!pageRows.length) { - tbl.innerHTML = '

No records found.

'; + const q = I.search.trim(); + tbl.innerHTML = `

${q ? `No records in ${escapeHtml(I.store)} match “${escapeHtml(q)}”.` : `${escapeHtml(I.store)} is empty.`}

`; return; } - - // Collect all keys across all rows for columns - const allKeys = []; - const keySeen = new Set(); - pageRows.forEach(r => Object.keys(r).forEach(k => { if (!keySeen.has(k)){ keySeen.add(k); allKeys.push(k); } })); - - const thead = `${allKeys.map(k => `${escapeHtml(k)}`).join('')}`; - const tbody = `${pageRows.map(r => `${allKeys.map(k => { - const v = r[k]; - let disp; - if (v === null || v === undefined) disp = 'null'; - else if (v instanceof Date || (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v))) - disp = `${dayjs(v).format('MMM D YYYY, h:mm A')}`; - else if (Array.isArray(v)) - disp = `[${v.map(x=>escapeHtml(String(x))).join(', ')}]`; - else if (typeof v === 'object') - disp = `${escapeHtml(JSON.stringify(v).slice(0,80))}`; - else if (typeof v === 'boolean') - disp = v ? 'true' : 'false'; - else if (typeof v === 'number') - disp = `${v.toLocaleString()}`; - else disp = escapeHtml(String(v).slice(0, 100)); - return `${disp}`; - }).join('')}`).join('')}`; - - tbl.innerHTML = `
${thead}${tbody}
`; + // Columns: the store's key first, then every other key on this page, in first-seen order. + const keys = [I.keyPath]; + pageRows.forEach(r => Object.keys(r).forEach(k => { if (!keys.includes(k)) keys.push(k); })); + const head = `${keys.map(k => `${escapeHtml(k)}`).join('')}`; + const body = `${pageRows.map(r => { + const id = r[I.keyPath]; + return `${escapeHtml(String(id ?? ''))}${keys.slice(1).map(k => cell(r, k)).join('')}`; + }).join('')}`; + tbl.innerHTML = `${head}${body}
${escapeHtml(I.store)}, page ${I.page + 1} of ${pages}
`; } - // Wire events after DOM is ready - const loadBtn = document.getElementById('inspLoad'); - const clearBtn = document.getElementById('inspClear'); - const prevBtn = document.getElementById('inspPrev'); - const nextBtn = document.getElementById('inspNext'); - - if (loadBtn) loadBtn.onclick = loadStore; - if (clearBtn) { - clearBtn.onclick = () => { - const si = document.getElementById('inspSearch'); - if (si) si.value = ''; - _inspectorSearch = ''; - _inspectorPage = 0; - _inspectorRows = []; - const tbl = document.getElementById('inspTable'); - if (tbl) tbl.innerHTML = '

Select a store and click Load.

'; - const meta = document.getElementById('inspMeta'); - if (meta) meta.textContent = ''; - }; - } - if (prevBtn) prevBtn.onclick = () => { _inspectorPage = Math.max(0, _inspectorPage - 1); _renderPage(); }; - if (nextBtn) nextBtn.onclick = () => { - const totalPages = Math.ceil(_inspectorRows.length / INSPECTOR_PAGE_SIZE); - _inspectorPage = Math.min(totalPages - 1, _inspectorPage + 1); - _renderPage(); - }; + // Picking a store reads it; the search filters as you type (no re-read). + $('#inspStoreSelect').onchange = (e) => { I.store = e.target.value; I.page = 0; I.all = []; I.rows = []; fetchAndRender(); }; + $('#inspSearch').oninput = debounce((e) => { I.search = e.target.value; I.page = 0; applySearch(); }, 200); + $('#inspSearch').onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); I.search = e.target.value; I.page = 0; applySearch(); } }; + $('#inspClear').onclick = () => { const s = $('#inspSearch'); s.value = ''; I.search = ''; I.page = 0; applySearch(); s.focus(); }; + $('#inspLoad').onclick = () => fetchAndRender(); - // Auto-load on every render. Re-read the store rather than reusing the rows from the - // last visit, which may be stale (an import since then) and left the count line blank. - // Keeps the chosen store, search and page. - setTimeout(_fetchAndRender, 0); + // Every visit reads the store again: rows from the last visit may be stale (an import + // or a clear since then). The store, search and page are kept. + setTimeout(fetchAndRender, 0); }); /* ══════════════════════════════════════════════════════════════ - 3. SETTINGS → DATABASE TAB - Shows DB Inspector and DB Schema as sub-tabs inside Settings. - Both are still registered as views of their own, so + 3. SETTINGS → DATABASE TAB (v1.17.0) + DB Inspector and DB Schema as sub-tabs: a segmented tab control, + as on Forecast (Savings / Investments), and one tabpanel the chosen + view renders into. Both are still views of their own, so showView('db-inspector') and showView('db-schema') keep working. Kept above the Changelog block so this tab still registers if that block ever throws (see v1.9.4). ══════════════════════════════════════════════════════════════ */ const DB_TOOLS_TABS = [ - ['db-inspector', 'DB Inspector'], - ['db-schema', 'DB Schema'], + ['db-inspector', 'DB Inspector', 'dbTabInsp'], + ['db-schema', 'DB Schema', 'dbTabSchema'], ]; -let dbToolsTab = 'db-inspector'; +let dbToolsTab = 'db-inspector'; // remembered for the session only, like forecastTab registerView('db-tools', 'Database', (root) => { - const tabBar = document.createElement('div'); - tabBar.style.cssText = 'display:flex;gap:6px;flex-wrap:wrap;margin-bottom:16px'; - tabBar.innerHTML = DB_TOOLS_TABS.map(([k, l]) => - `` - ).join(''); - root.appendChild(tabBar); - tabBar.querySelectorAll('[data-db-tab]').forEach(btn => btn.onclick = () => { dbToolsTab = btn.dataset.dbTab; renderActive(); }); - - VIEWS[dbToolsTab].render(root); + const tabs = DB_TOOLS_TABS.filter(([k]) => VIEWS[k]); + if (!tabs.length) return; + if (!tabs.some(([k]) => k === dbToolsTab)) dbToolsTab = tabs[0][0]; + appendHtml(root, `
${tabs.map(([k, l, id]) => + ``).join('')}
`); + // Arrow keys, Home and End move between the sub-tabs; focus follows. + const pick = (k) => { dbToolsTab = k; renderActive(); const t = $(`[role="tab"][data-db-tab="${k}"]`); if (t) t.focus(); }; + const btns = $$('[data-db-tab]', root); + btns.forEach((b, i) => { + b.onclick = () => pick(b.dataset.dbTab); + b.onkeydown = (e) => { + const n = e.key === 'ArrowRight' ? i + 1 : e.key === 'ArrowLeft' ? i - 1 : e.key === 'Home' ? 0 : e.key === 'End' ? btns.length - 1 : null; + if (n == null) return; + e.preventDefault(); e.stopPropagation(); pick(btns[(n + btns.length) % btns.length].dataset.dbTab); + }; + }); + const panel = document.createElement('div'); + panel.id = 'dbPanel'; + panel.className = 'tab-panel'; + panel.setAttribute('role', 'tabpanel'); + panel.setAttribute('aria-labelledby', tabs.find(([k]) => k === dbToolsTab)[2]); + root.appendChild(panel); + VIEWS[dbToolsTab].render(panel); }); diff --git a/js/views-settings.js b/js/views-settings.js index 76ec5f0..5d37847 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -2,7 +2,8 @@ FINLENS — views-settings.js Settings shell (tab bar) + General tab: Display, Anthropic API key. The other tabs are views of their own: Import, Accounts, Credit cards and - Categories in views-data.js, Data & reset in views-cleanup.js (Clarity, v1.16.0). + Categories in views-data.js, Data & reset in views-cleanup.js (Clarity, v1.16.0), + Database (DB Inspector and DB Schema) in views-db.js (v1.17.0). ================================================================ */ let settingsTab='general'; @@ -14,19 +15,29 @@ const SETTINGS_TABS=[ ['credit-cards','Credit cards'], ['categories','Categories'], ['data-cleanup','Data & reset'], + ['db-tools', 'Database'], // views-db.js: DB Inspector and DB Schema sub-tabs ]; registerView('settings','Settings',(root)=>{ - if (!SETTINGS_TABS.some(t=>t[0]===settingsTab)) settingsTab='general'; + // Tabs live in other files. If one failed to load, hide its tab instead of throwing. + const shown=SETTINGS_TABS.filter(([k])=>k==='general'||VIEWS[k]); + if (!shown.some(t=>t[0]===settingsTab)) settingsTab='general'; pageActions(root,'Everything here stays on this computer',''); const tabBar=document.createElement('div'); tabBar.className='tabs'; tabBar.setAttribute('role','tablist'); tabBar.setAttribute('aria-label','Settings sections'); - tabBar.innerHTML=SETTINGS_TABS.map(([k,l])=> + tabBar.innerHTML=shown.map(([k,l])=> `` ).join(''); root.appendChild(tabBar); + // On a phone the tab bar scrolls sideways, and each render starts it at the left. Bring the + // selected tab into view (the last ones, Data & reset and Database, were off-screen). + const selTab=$('[aria-selected="true"]',tabBar); + if (selTab) { + const b=tabBar.getBoundingClientRect(), s=selTab.getBoundingClientRect(); + if (s.right>b.right||s.left{ settingsTab=k; renderActive(); const t=$(`#setTab-${k}`); if (t) t.focus(); }; const tabs=$$('[role="tab"]',tabBar); @@ -60,7 +71,7 @@ function _renderGeneralSettings(root) { ``).join('')}
-
VersionFinLens v1.16.0
+
VersionFinLens v1.17.0
`); const opts=$$('[data-theme-opt]',root); opts.forEach((b,i)=>{ From 6b101f64ceab4f5f53ccfb61d9191ad16ea056c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 09:45:34 +0000 Subject: [PATCH 4/4] DB Schema: list import_log.rowsRemoved Import log records have had rowsRemoved (leftover duplicate copies removed) since v1.8.1; the diagram didn't list it. Found by comparing the diagram's fields with the keys of real records from samples/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Z8iBXzUjiQbYziDZ8CZft --- CHANGELOG.md | 2 +- js/views-db.js | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fae084..989adee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,7 @@ DB Inspector and DB Schema are back in the UI, as a seventh Settings tab. Since - **One Clarity panel titled "Database schema".** It was titled "Database Schema & Inspector", from when one card held both; the inspector is its own sub-tab now. The legend is a `.legend` row in the same panel. - **Colors come from the theme.** Each store's lines and text use a `.sch-*` class that reads the tokens (`--teal-2`/`--teal-text`, `--warn`/`--warn-text`, `--sky`/`--sky-text`, `--violet`/`--violet-text`). No hex, `rgba()`, `white` or legacy aliases, and no text faded with opacity. The diagram follows light and dark without a redraw. - **Fits the 1000px Settings page** (872px wide). The relationship labels sit in the gaps between boxes, on a background, instead of over the boxes. The `app_state` key list wraps inside its box. Below 900px the diagram scrolls sideways inside its panel, and a note says so. -- **Text corrected:** the `app_state` key list matches the keys the code writes (`catRules`, not `categoryRules`; adds `recurring`, `cardDetails`, `sampleData`, `lastFolderName` and `csvAutoImportPaused`). `accounts.kind` gives the current kinds (`bank_checking|credit_card|…`). +- **Text corrected:** the `app_state` key list matches the keys the code writes (`catRules`, not `categoryRules`; adds `recurring`, `cardDetails`, `sampleData`, `lastFolderName` and `csvAutoImportPaused`). `accounts.kind` gives the current kinds (`bank_checking|credit_card|…`). `import_log` lists `rowsRemoved` (leftover duplicate copies removed, since v1.8.1), which its records have. ### Docs - **README:** a Tip for **Settings → Database**; the Project Structure line for `views-db.js`. diff --git a/js/views-db.js b/js/views-db.js index abe56c9..45ce5fe 100644 --- a/js/views-db.js +++ b/js/views-db.js @@ -78,6 +78,7 @@ registerView('db-schema', 'DB Schema', (root) => { { name: 'rowsFound', type: 'number', key: '' }, { name: 'rowsInserted', type: 'number', key: '' }, { name: 'rowsSkipped', type: 'number', key: '' }, + { name: 'rowsRemoved', type: 'number', key: '', note: 'leftover duplicates' }, { name: 'dateRangeMin', type: 'Date', key: '' }, { name: 'dateRangeMax', type: 'Date', key: '' }, ],