From c4a100e3290124d61930373f0198675af19cbe69 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 06:44:30 +0000 Subject: [PATCH 1/4] Clarity redesign, part 4: Trends, AI Analysis, Settings, Welcome (v1.16.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Trends: KPIs (average saved, savings rate, fastest-growing category, steadiest month), income/spending/savings bars, savings rate with a 3-month average and a note from the numbers, account balance sparklines, top categories × months as shaded tiles. No Chart.js; range label hidden. - AI Analysis: quick analyses with the mockup's labels (each sends an existing AI_PROMPTS question unchanged), your own question, an aria-live answer area, history (open again, export as Markdown), key pill. The request is byte-identical to v1.15.0's. - Settings: six tabs in the mockup's words with arrow keys; General, Import (folder card, files, import log), Accounts (order, names, starting balances), Credit cards (balance, limit, new APR and due day), Categories (delete moves transactions to Other), Data & reset (stored data, clean up with confirm, JSON export/import, start over). - Welcome: the Overview with no data; brand-only app bar on a true first run; "Try it with sample data" imports samples/ and your own files replace them. - New stored fields: State.cardDetails, State.sampleData. - Phone: the ☰ button shows × while the menu is open. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Z8iBXzUjiQbYziDZ8CZft --- CHANGELOG.md | 63 +++ CLAUDE.md | 71 +++- README.md | 32 +- index.html | 253 ++++++++++-- js/aggregation.js | 2 +- js/core.js | 20 +- js/db.js | 2 + js/init.js | 3 + js/ui.js | 39 +- js/views-ai.js | 232 ++++++++--- js/views-cleanup.js | 211 +++++----- js/views-data.js | 903 +++++++++++++++++++++++++------------------ js/views-main.js | 51 ++- js/views-plan.js | 264 +++++++++---- js/views-settings.js | 136 ++++--- 15 files changed, 1521 insertions(+), 761 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29d6177..01d5240 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,69 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.16.0] — 2026-11-02 + +### Insights, Settings and the Welcome — Clarity redesign, part 4 +Trends, AI Analysis, the six Settings tabs and the first-run Welcome now match the Clarity mockups. This is the last part of the redesign. Every number is computed from your data; none come from the mockups. The mockups name banks; the app still names none. + +- **Shared:** each screen opens with its note in the `.page-actions` row; panels, KPI tiles, rows, pills and the drawer reuse the Finances and Plan classes, plus a few new ones in `index.html`. Charts are inline SVG or plain boxes with a text description (`role="img"`); Trends no longer uses Chart.js. +- **The date range label is hidden on Trends and Settings** (`NO_RANGE_VIEWS` in `ui.js`), as on the Plan screens. Neither uses the range. +- **Settings and the Welcome are 1000px wide,** as in the mockups (`body[data-view]`, set by `showView()`). +- **Phones:** grids fold to one column; nothing scrolls sideways at 390px. The **☰** button turns into **×** ("Close menu") while the menu is open, as in the phone mockup. + +### Trends +Always your latest six months with data, across every account. It ignores the date range and the accounts filter, as before. +- **KPIs:** average saved a month (income minus spending), savings rate (the average of the monthly rates), fastest-growing category (the biggest rise in the latest month, among categories with at least $25 the month before) and steadiest month (lowest spending; an unfinished latest month doesn't count). +- **Income, spending and savings:** three bars a month, with what you saved under each month. +- **Savings rate:** each month's rate and a dashed 3-month average, with a note written from the numbers: the best and worst months, the category that pulled the worst one down, and where the latest month stands. +- **Account balances:** a sparkline per account, how it moved ("Up about $426 a month", "Swings between …", "Paid down around the 6th") and its balance (`balanceAt()`, as the Overview cards). +- **Top categories over time:** the top 6 categories × 6 months as shaded tiles (darker = that category's most expensive months) and 6-month totals. +- **Dropped to match the mockup:** income month-over-month, income stability, the current month's savings rate, the this-month-vs-last category table, the rolling-spending and savings-rate Chart.js charts, most visited merchants and the auto-generated insights (`generateInsights()` removed). + +### AI Analysis +- **Layout:** Quick analyses and History on the left; Ask your own question and the answer on the right. A pill says whether a key is saved. +- **Quick analyses** use the mockup's labels. Each sends one of the existing `AI_PROMPTS` questions, unchanged (`AI_QUICK` maps them), so the request is exactly what the eval measures. The label shown and kept in history is the new one. +- **Ask your own question:** Ask is disabled until you type; Ctrl/⌘+Enter asks. A note says what Claude gets (a summary for the dates it covers, never your CSV files). +- **The answer** is an `aria-live="polite"` region: "Claude is reading your summary…" while waiting (`aria-busy`), then "You asked", Copy, Save as Markdown, the answer and "Answered just now · model". The cut-off warning now sits above the answer; the no-answer message is unchanged in substance. +- **History:** every saved answer (up to 50), newest first, "N of 50 kept"; cut-off answers are marked. Clicking one shows it again (nothing is sent). **Export history as Markdown** downloads all of them. New answers also store the model that wrote them. +- **No key:** the screen says so first and links to Settings → General; history stays readable. +- **Unchanged (the published eval depends on them):** `AI_MODEL`, `AI_MAX_TOKENS`, `AI_PROMPTS`, the system prompt, `buildFinancialSummary()`, the `` wrapping and the one request path (`send()` inside `callClaude()`, raw mode included). The test suite checks that each quick analysis and a custom question send a request byte-identical to v1.15.0's. +- **Left out of the mockup:** "Unusual transactions". The summary sent to Claude has no single transactions, so it couldn't be answered without changing the request. "Summarize my finances" takes its place, so all eight eval prompts stay reachable. +- **Dropped:** the alert-based copy confirmation (an inline status replaces it). + +### Settings +- **Tabs** in the mockup's words (General · Import · Accounts · Credit cards · Categories · Data & reset), with `role="tab"`; arrow keys, Home and End move between them, as on Forecast. +- **General:** Display (theme: Light / Dark / Match system, arrow keys move the choice; version) and the API key (Save key, Remove with a second click instead of `confirm()`). **Dropped:** the currency menu (it saved a value nothing used), the transactions-loaded line and the pointer card to Data & Reset. +- **Import:** the folder card (name, access, CSVs last read, backup last saved, auto-save; Save now, Reload CSVs, Change folder, or Reconnect when access lapsed, or Pick a folder / Choose CSV files with none), files waiting for "Read as" (kept), the last import's results (kept), **Files in the folder** (how each file is read, rows, dates; changing "Read as" saves the choice for the next reload), the **Import log** (always shown, one line per import) and the Safari / Firefox card. **Dropped:** the per-file rename list (renaming is on Accounts), "Add individual CSV files" (the Safari / Firefox card does it) and **Add Manual Account** (its accounts were never saved, so they vanished on reload). +- **Accounts:** one row per account: ▲▼ order, display name, the starting balance (bank accounts; labelled with the day before the first row) or the balance owed (cards), rows and dates. Each field saves when you leave it. An old current-balance override on a bank account is shown with a button to drop it. **Dropped:** the two tables and the Save button. +- **Credit cards:** per card: current balance, credit limit, **APR** and **payment due day** (new), and how much of the limit is used, which follows what you type. A debt in the Debt tracker linked to the card shares its APR and due day; a new debt started from the card takes them. +- **Categories:** chips with each category's transaction count (your list plus categories your transactions use), Add category, and a link to the rules on Spending. **Deleting a category now moves its transactions to Other** (saved as transaction edits) and points its rules at Other; before, it only took the name off the list. Other, Transfer in and Transfer out can't be deleted. +- **Data & reset:** What FinLens has stored (database counts, settings, the folder), **Clean up** (every action as a row: click, then "Click again to confirm", then "Cleared"), **Export and import** (JSON; these buttons are new — the functions existed but nothing on screen called them) and **Start over** (type RESET). **Kept:** every action, including forecast scenarios and the investment mix, which the mockup predates. + +### Welcome (first run) +- **With no transactions, the Overview is the Welcome:** "Your money in one view, on your own computer", Pick your CSV folder, Try it with sample data, choose the files, three steps and three notes. The headline is the shell's title (`shellHero()`), so there is still one H1. +- **On a true first run** (nothing saved at all) the app bar shows only the brand, as in the mockup. With a folder, plans, AI history or a key saved, it keeps its menus. +- **The buttons use the existing import paths** from their click: `pickDataFolder()` (or `reloadDataFiles()` when a folder is already connected), and the `#filePick` file picker. +- **Try it with sample data** imports the three files in `samples/` through the normal import: fetched over HTTP, or from a file picker when FinLens is opened as a file. A banner says it's sample data, with **Use my own files**. Importing your own files replaces the samples instead of mixing them into the same accounts (`loadFiles(…, { sample })`). +- **Dropped:** the old "Welcome to FinLens 👋" card and its "Go to Data Tab" button. + +### Technical +- **New stored data:** + - `State.cardDetails` `{ [cardAccountId]: { apr, dueDay } }`: localStorage, IndexedDB `app_state` (`DB.loadAll()`), `finlens-state.json`, JSON export and import. Kept by Clear transactions (like balances); Start over erases it. + - `State.sampleData` (boolean): the same places except the JSON export. Cleared by importing your own files, Clear transactions and accounts, Use my own files, and Start over. + - Inside existing records: AI history entries get `model`. +- **`ui.js`:** `shellHero()`, `NO_RANGE_VIEWS`, `body[data-view]` and `first-run`; `editDebt()` pre-fills APR and due day from `cardDetails`; the drawer note says "Credit cards". +- **`views-data.js`:** `loadSampleData()`, `handleSamplePick()`, `setAccountName()`, `setAccountMoney()`, `setCardDetail()`, `deleteCategory(name)`, `addCategory(name)`, `renderImportLogList()`; `moveAccount()` works from the order shown. `renderImportLog()` and the Import Logs view are unchanged, so #18 still applies. +- **`views-cleanup.js`:** `DataCleanup.clearSampleData()`, `PLAN_ROWS`, `lastDone`. +- **Tokens:** `--t0`…`--t5`, `--t-ink`, `--t-ink-hi` (Trends tiles; `--t4` is a little darker than the mockup's so white text reaches 4.5:1) and `--border-dash`, light and dark. +- **Removed CSS** no longer used: the old AI panel, file list, account group and pending-file row, `.kbd`. + +### Docs +- **README** — getting started with the Welcome and sample data; Trends, AI Analysis and Settings as they are now. +- **CLAUDE.md** — §1 version; §3 file roles; §4.1 `cardDetails`, `sampleData`; §6 new tokens and components; §7 Trends charts; §8 `loadFiles()` option; §9 shell helpers; §12 Settings tabs, the Welcome, page titles; §13 the AI tab's quick analyses and history; §20 the new fields and Use my own files; §21 quick analyses vs `AI_PROMPTS`. + +--- + ## [1.15.0] — 2026-11-02 ### Plan screens — Clarity redesign, part 3 diff --git a/CLAUDE.md b/CLAUDE.md index bca5400..99c135c 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.15.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.16.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. @@ -115,13 +115,13 @@ FinLens/ ├── migrate.js ← Rewrites data saved by older versions: account codes (§22) ├── ui.js ← View registry, drawer, theme, chart helpers, CRUD helpers ├── views-main.js ← Overview, Transactions, Income, Bills, Spending, Transfers - ├── views-plan.js ← Budget, Savings buckets, Debt tracker (Plan, v1.15.0); Trends + ├── views-plan.js ← Budget, Savings buckets, Debt tracker (Plan, v1.15.0); Trends (v1.16.0) ├── views-invest.js ← Investing ideas + the Forecast → Investments tab (_renderForecastInvest) ├── views-forecast.js ← Forecast: Savings and Investments tabs, saved scenarios - ├── views-ai.js ← AI Analysis tab (Claude integration) - ├── views-data.js ← Import, Accounts, Credit Cards, Categories (Settings tabs) + Import Logs + ├── views-ai.js ← AI Analysis tab (Claude integration): quick analyses, your own question, history + ├── 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: clean up imported data, DB, logs; start over (§20) + ├── 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-eval.js ← AI Eval: grounding eval for AI Analysis (developer only, §21) ├── views-database.js ← Unused — not loaded by index.html; retained for reference @@ -160,10 +160,12 @@ const State = { categoryRules: [], // { contains: string, category: string }[] categories: [], // string[] — user-editable category list apiKey: '', // Anthropic API key - aiHistory: [], // { timestamp, question, response }[] + aiHistory: [], // { timestamp, question, response, truncated?, model? }[] — model since v1.16.0 scenarios: [], // Scenario[] — Forecast → Savings, up to 10 (shape below) investAlloc: {}, // { [ticker]: userPct } — Investing ideas "My %" (0 / missing = not in the mix) debtPlan: { strategy, extra }, // Debt payoff plan: 'avalanche' | 'snowball' | 'minimum', extra $ a month (v1.15.0) + cardDetails: {}, // { [cardAccountId]: { apr, dueDay } } — Settings → Credit cards (v1.16.0); a linked debt's own apr/dueDay win + sampleData: false, // true while the transactions are the samples/ files ("Try it with sample data", v1.16.0) range: { mode, start, end }, // Active date range selectedAccounts: 'all', // 'all' | string[] theme: 'light', // 'light' | 'dark' | 'system' (follow the OS) — Settings → General @@ -356,12 +358,13 @@ The visual system is **Clarity** (v1.13.0): indigo accent, Inter type, white car /* hues */ --teal-2, --teal-text (v1.15.0), --sky, --sky-text, --violet, --violet-text, --pink, --card, --card-soft, --card-border /* charts */ --chart-in, --chart-out, --chart-save, --chart-debt, --chart-card, --chart-neutral, --chart-grid /* heatmap */ --heat-1 … --heat-5 +/* tiles */ --t0 … --t5, --t-ink (on t0–t3), --t-ink-hi (on t4–t5) — Trends' category tiles (v1.16.0); --border-dash (a dashed panel) /* shape */ --shadow (none), --popover-shadow, --radius (16px), --radius-sm (10px) /* legacy */ --teal, --teal-soft, --amber, --amber-soft, --red, --red-soft, --blue, --purple — aliases kept so pre-v1.13.0 inline styles keep working; new code uses the names above ``` -Dark mode is applied by setting `data-theme="dark"` on `` (`applyTheme()`, §9). **Never hard-code colors** — always use a CSS variable. Chart.js can't read variables, so it calls `chartColor('--token', alpha?)` when it draws (§7, §9). Inline SVG built by FinLens (the Finances screens' charts, v1.14.0) colors its shapes through CSS classes instead (`.lc-*`, `.spark`, `.hue-*`), which read the tokens directly and follow the theme without a redraw. +Dark mode is applied by setting `data-theme="dark"` on `` (`applyTheme()`, §9). **Never hard-code colors** — always use a CSS variable. Chart.js can't read variables, so it calls `chartColor('--token', alpha?)` when it draws (§7, §9). Inline SVG built by FinLens (the Finances, Plan and Trends charts, v1.14.0–v1.16.0) colors its shapes through CSS classes instead (`.lc-*`, `.spark`, `.hue-*`), which read the tokens directly and follow the theme without a redraw. **In dark mode, fills get lighter and the text on them gets darker.** `--accent-solid` and `--danger` are light tints in dark mode, and `--on-solid` is near-black, because white on those tints fails AA. Use `--on-solid` for text on any solid fill, never `#fff`. @@ -426,6 +429,21 @@ Dark mode is applied by setting `data-theme="dark"` on `` (`applyTheme()`, .strong .c-bad .c-warn .c-dim .c-teal .axis-ends .sw.dash .mw-640 .mw-720 ``` +**Insights, Settings and the Welcome (v1.16.0)** add: + +``` +.status-line(.good/.bad/.warn) — a one-line result under a form (role="status"; takes no space while empty) +.head-row .icon-tile.lg .panel h2.lg — a panel header with a 48px icon tile (the folder, a credit card) +.panel.dashed .panel.row-panel(.grow .acts) .panel.danger-panel(.body) — dashed / one-row / Start over panels +.cols-2 .cols-3.top .col-stack — two columns; three with tops aligned; a column of panels +.btn.xl .btn.danger-outline .inline-link — the Welcome's 52px buttons; Remove key; a button that looks like a link +.bars.wide-gap .hue-teal-text .sw.line .lc-line.avg .bal-rows/.bal-row .heat-tbl .ht.l0…l5 — Trends +.key-pill(.ok/.off) .quick[aria-pressed] .hist-list/.hist-row .ask-box .ask-foot .ai-answer .ans-head .ai-md .ans-foot .thinking .skel .err-detail — AI Analysis +.tab-panel .set-row(.line) .info-tiles .fname .lg-row .acct-rows/.acct-row .order-btns .acct-meta .row-note .cc-grid .util-line .cat-chips/.cat-chip .kv-rows .clean-rows/.clean-row .clean-btn(.armed/.done) .radio-set .reset-in — Settings +.welcome(.lead .hint) .hero-acts .steps .step-num .features — the Welcome; .pagebar.hero — its centered headline +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 +``` + Prefer these over inline styles. Keep touch targets ≥ 44px where feasible (`@media (pointer:coarse)` raises pills and remove buttons). --- @@ -440,7 +458,7 @@ These rules exist because Chart.js will cause infinite layout loops if violated. 4. **Always** destroy a chart before recreating it on the same canvas — or use a unique canvas ID per render. `ui.js` enforces this: `Chart` is a guard subclass that destroys any chart already on the canvas, and any chart whose canvas has left the page, before drawing. Keep it. Without it, two renders in a row throw "Canvas is already in use" and every render leaks its charts. 5. **Never** let a chart container have `height: auto` — always an explicit pixel height. 6. **Colors come from the theme:** `chartColor('--chart-in')`, `chartColor('--chart-out', .12)` and so on, read when the chart is created, never hex literals. `setTheme()` re-renders, so charts recolor when the theme changes. `CHART_PALETTE` is for multi-series charts with no meaning per color. -7. **The Finances and Plan screens don't use Chart.js (v1.14.0, v1.15.0).** The Plan screens' budget, debt and forecast bars are plain boxes (`.bud-hist`, `.mini-bars`, `.ybars`). Their line charts, sparklines, bars and heatmap are inline SVG or plain boxes (`svgLineChart()`, `sparkSvg()`, `dailyHeatmapHtml()` in `ui.js`; `.bars` in CSS). Give each one `role="img"` and an `aria-label` that says what it shows. `svgLineChart()` takes the width it should draw at: measure the holder (`clientWidth`, the view is already in the page when it renders) so its 11px labels stay 11px. +7. **The Finances, Plan and Trends screens don't use Chart.js (v1.14.0–v1.16.0).** Trends' bars are `.bars` boxes, its savings-rate chart is inline SVG (`rateChartSvg()` in views-plan.js, two series: the rate and a dashed 3-month average), its balances are `sparkSvg()` and its category grid is a table of tiles (`.heat-tbl`). The Plan screens' budget, debt and forecast bars are plain boxes (`.bud-hist`, `.mini-bars`, `.ybars`). Their line charts, sparklines, bars and heatmap are inline SVG or plain boxes (`svgLineChart()`, `sparkSvg()`, `dailyHeatmapHtml()` in `ui.js`; `.bars` in CSS). Give each one `role="img"` and an `aria-label` that says what it shows. `svgLineChart()` takes the width it should draw at: measure the holder (`clientWidth`, the view is already in the page when it renders) so its 11px labels stay 11px. ```js // Correct pattern @@ -539,6 +557,7 @@ debounce(fn, ms) // Returns debounced function parseDate(s) // Parse date string/object → Date | null monthKey(d) // 'YYYY-MM' string describeRange() // Human-readable date range label +loadFiles(files, assignments, { sample }?) // the import; without `sample`, it first clears sample data (State.sampleData) so your files replace it ``` --- @@ -550,6 +569,9 @@ describeRange() // Human-readable date range label registerView(id, title, renderFn) // Register a view (called at module load time) showView(id) // Navigate to a view — re-renders from scratch renderActive() // Re-render current view (call after state mutations) +shellHero(title, firstRun) // The Welcome: rewords the shell's title as a centered headline; firstRun hides the app bar's + // nav and tools (body.first-run). showView() undoes both (v1.16.0) +NO_RANGE_VIEWS // PLAN_VIEWS + trends + settings: showView() hides #rangeLabel there // Drawer (single shared drawer #txDrawer: title row, scrolling body, optional pinned footer, scrim) openDrawer(bodyHtml, { title, footer }?) // A body starting with

(older forms) uses it as the title @@ -568,7 +590,7 @@ chartColor('--token', alpha?) // Same, as rgba() when alpha is given — PLAN_VIEWS // The views under the Plan menu; #planBtn is underlined on them TX_VIEWS // transactions + its pill screens; the Transactions link stays underlined // (aria-current="true") on income, spending, bills and transfers -toggleAppBarPopup(btn, panel) // Open/close the Plan menu, a filter popover or the ☰ menu +toggleAppBarPopup(btn, panel) // Open/close the Plan menu, a filter popover or the ☰ menu (☰ shows × and "Close menu" while open) closeAppBarPopups(focusBtn?) // Close whatever is open (Escape returns focus to its button) updateRangeUI(), updateAcctUI() // Sync the date / accounts popovers, their dots and tooltips updateSyncBadge() // (views-data.js) "Synced" / "Not synced" from State._folderLinked, @@ -601,7 +623,7 @@ simulatePayoff(debts, extra) // older payoff model, kept unchanged and u // deleteBudget/Bucket/Debt no longer confirm(): the drawer's Delete asks for a second click confirmRecurring(r), dismissRecurring(key), undoDismissRecurring(key) // r: a detectRecurring() entry addCatRule(), delCatRule(i), recategorizeAll() -exportAllData(), importJsonFile(ev) +exportAllData(), importJsonFile(ev) // Settings → Data & reset → Export / Import JSON (v1.16.0; before, no button called them) clearAllData() // = DataCleanup.startOver('archive') — full reset + reload (§20) ``` @@ -751,27 +773,29 @@ 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 + (General holds Display — including Theme — and Anthropic API key; all clearing/reset lives in Data & reset) ``` - **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. - **Below 1000px** the nav moves into the **☰** menu (`#mobileMenu`), with the same grouping. **Below 720px** the gear moves into it too. - **Links** are ``; `init.js` wires every `.appbar [data-view]`, and `showView()` marks the current one (`.active` + `aria-current`). -- **Page title:** the shell renders it (`#pageTitle` from the registered title, `#rangeLabel` the range). Views never render their own H1. On the five Plan screens (`PLAN_VIEWS`) `showView()` hides `#rangeLabel`: none of them use the date range (v1.15.0). A screen's buttons and one-line note go in a `.page-actions` row at the top (`pageActions()` in views-main.js). +- **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). **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. View registrations by file: - `views-main.js` — overview, transactions (All / Payments), income, spending, bills, transfers -- `views-plan.js` — budgets, buckets, debt (titles "Budget", "Savings buckets", "Debt tracker"), trends +- `views-plan.js` — budgets, buckets, debt (titles "Budget", "Savings buckets", "Debt tracker"), trends ("Trends") - `views-invest.js` — investments ("Investing ideas"; `_renderForecastInvest` is a helper, not a registered view) - `views-forecast.js` — forecast: a `role="tablist"` with Savings / Investments (`forecastTab`, arrow keys move between them), one `role="tabpanel"` filled by `_renderForecastSavings` / `_renderForecastInvest` - `views-ai.js` — ai -- `views-data.js` — import, accounts, credit-cards, categories +- `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-cleanup.js` — data-cleanup (Settings → Data & reset tab) - `views-db.js` — db-inspector, db-schema, changelog (not in nav; developer reference only) - `views-eval.js` — ai-eval (not in nav; developer only — `showView('ai-eval')` from DevTools, §21) @@ -811,7 +835,9 @@ Views build a fresh DOM on every `showView()` call. This is intentional. Do not Without them the model guessed the period length (6, 6.5 or even 9 months) to work out monthly figures, so the same data gave different answers. Never send totals without the dates they cover. - The summary is sent inside `` tags, and the system prompt tells the model to treat that content as data, not instructions (account names and merchant descriptions come from CSVs and are untrusted). - Responses are read from every `text` content block (don't assume `content[0]` is text) and rendered with `renderMarkdown()` — never `marked.parse()`. -- AI history is capped at 50 entries (`State.aiHistory`). +- AI history is capped at 50 entries (`State.aiHistory`). Entries keep the model that answered (`model`, v1.16.0); the tab lists them newest first, opens one again without sending anything, and exports them all as Markdown. +- **Quick analyses (v1.16.0).** The tab shows `AI_QUICK`: the mockup's labels, each pointing at an `AI_PROMPTS` entry whose question it sends unchanged. Only the label (shown, and kept in history) differs. **Leave `AI_PROMPTS` as it is:** the eval runs it and matches published results by its labels and questions (§21). The mockup's "Unusual transactions" isn't offered: the summary has no single transactions. +- **The tab's state lives in the module** (`aiPhase`, `aiCurrent`, `aiError`, `aiSel`, `aiDraft`) and `aiPaint()` updates the open tab in place, so an answer that arrives while you're on another screen shows when you come back. The answer area is `aria-live="polite"` with `aria-busy` while waiting. - **Output budget and cut-off answers (v1.10.1).** `max_tokens` is `AI_MAX_TOKENS` (4,096). It caps the model's thinking *and* the answer combined. Sonnet 5.5 thinks by default (effort `high`), and thinking counts toward `max_tokens` even though FinLens shows only the text. At 1,500, thinking took ~750 tokens and 15 of 24 eval answers were cut off. Asking the model in the prompt to think less doesn't reliably work; raise the budget or set `output_config.effort` instead. `send()` returns `truncated` when `stop_reason` is `max_tokens` or `model_context_window_exceeded`. The AI tab then shows a warning, and the answer is saved to history with `truncated: true` and copied or saved with `AI_CUT_OFF_NOTE`. If it was cut off before any text (the text is `AI_NO_TEXT`; `aiNoAnswer()`), the tab says no answer was written and nothing goes to history. Never show a cut-off answer as if it were complete. - **Raw mode:** `callClaude(question, label, { raw:true, summary })` sends the identical request through the same inner `send()` but touches no DOM, busy flag or history; it resolves to `{ text, stopReason, truncated, usage, model }` or throws (`.status`/`.detail` on HTTP errors). The AI Eval (§21) depends on it — keep one request path for both, so the eval measures what the AI tab actually sends. - If updating the Claude model string, update `AI_MODEL` in `views-ai.js` and mention it in CHANGELOG.md. Changing the model, the system prompt or `buildFinancialSummary()` changes what the eval measures — re-run it and replace `docs/EVAL.md`. @@ -938,7 +964,7 @@ Multiple credit card files can be loaded simultaneously. Each gets a unique `acc --- -*Last updated: v1.15.0 — 2026-11-02 (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.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)* --- @@ -966,7 +992,7 @@ Add a new object to `BANK_SCHEMAS` in `core.js`. No other code changes needed if ## 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. +**Settings → Data & reset** is the only place that clears data (plus **Use my own files** on the sample-data banner, `DataCleanup.clearSampleData()`). All actions live on the `DataCleanup` namespace object. ### Where FinLens keeps data @@ -984,12 +1010,14 @@ CSV files on disk are **never** modified. | Action | Does | Keeps | |---|---|---| -| Clear transactions & accounts | Empties memory + `transactions`/`accounts` stores; with a folder connected, sets `csvAutoImportPaused` | Plans, edits, account labels/balances, settings | +| Clear transactions & accounts | Empties memory + `transactions`/`accounts` stores; turns `sampleData` off; with a folder connected, sets `csvAutoImportPaused` | Plans, edits, account labels/balances, `cardDetails`, 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 / forecast scenarios / investment mix / AI history | `State[key] = []` (`{}` for `investAlloc`; the empty value is `PLAN_ITEMS[i][2]`) + `lsSet`. Bills also resets `recurringConfirmed` (confirmed/dismissed spotted charges); Debts also resets `debtPlan` (`PLAN_ALSO`) | — | | 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 | +| Use my own files (sample banner) | `clearSampleData()`: transactions, accounts and import log (memory + stores), `sampleData` off, state file rewritten, back to the Welcome | Plans made while trying it | +| Export / Import JSON | `exportAllData()` / `importJsonFile()` — not a clear; listed because it lives here | — | | 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 @@ -1000,6 +1028,7 @@ CSV files on disk are **never** modified. - **Browser storage only:** it lives in localStorage and IndexedDB `app_state`, never in `finlens-state.json`. Saves are debounced, so a backup file written before the pause ended could otherwise switch it back on. If browser storage is wiped, the folder re-imports as a recovery. - **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. +- **Fields added in v1.16.0:** `cardDetails` and `sampleData` live in localStorage, IndexedDB `app_state` (`DB.loadAll()`) and `finlens-state.json`; Start over erases both with everything else. `cardDetails` is also in the JSON export. Importing your own files turns `sampleData` off after clearing the samples (`loadFiles()`). - `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. --- @@ -1013,7 +1042,7 @@ A developer-only view (`showView('ai-eval')`) that measures how well AI Analysis - **Samples only, never real data.** The eval reads only the three files in `samples/`, and only if their SHA-256 (after normalizing line endings) matches `AIEval.SAMPLES`. If you change a sample file on purpose, update its hash there (the error message shows the new one), add the old hash to that sample's `earlier` list so published results still load (results files are matched by hash, not file name), and re-run the eval. - **Sandbox, synchronously.** `_withSampleState(fn)` swaps a fresh, sample-only set of `State` keys in, runs `fn`, and restores every key in `finally`. `fn` must be synchronous — no `await` — so no render, `lsSet()` or debounced save can run while sample data is in `State`. If `buildFinancialSummary()`, `normalizeRow()`, `mkTx()` or `detectTransfers()` start reading a new `State` key, add it to the sandbox or the user's value will leak into the eval. - **Same parsing as an import.** `buildDataset()` mirrors `parseCsvFile()` (schema detection, account ids, occurrence suffixes) without touching IndexedDB. If `parseCsvFile()` changes, mirror it here; the sandbox summary must equal what a normal import of `samples/` produces. -- **Same request as the AI tab** — `callClaude()` raw mode (§13). Never build a second request path. +- **Same request as the AI tab** — `callClaude()` raw mode (§13). Never build a second request path. The tab's quick analyses (`AI_QUICK`) send `AI_PROMPTS` questions unchanged, so every prompt the eval runs is one the tab sends. - **Each run records** `meta.maxTokens` and every call's `usage` (including `output_tokens_details.thinking_tokens`), and EVAL.md reports cut-off answers and thinking per answer. Runs from before v1.10.1 didn't record `maxTokens`, so it is inferred from the size the cut-off answers stopped at. - **Nothing persisted.** Results live in memory only and leave via the download buttons, so §20 needs no entry. Don't add `lsSet()` calls here. The API key is never put in results, exports or logs. - **A summary loaded from a results JSON is never sent.** It can be re-scored locally (`loadResults()` sets `dataset.fromFile`), but Run stays disabled until samples are reloaded and verified. diff --git a/README.md b/README.md index 0319a74..d4b7908 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.15.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.16.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -39,7 +39,7 @@ No server. No install. No `npm install`. Just open the file. **2. Load your data** -Go to **Settings → Import** and click **Pick a Folder**. Point it at a folder containing your bank's CSV exports (usually under the account's transactions or activity page → Download / Export → CSV): +The first time you open FinLens, the Welcome screen offers **Pick your CSV folder** (you can also do it later in **Settings → Import**). Point it at a folder containing your bank's CSV exports (usually under the account's transactions or activity page → Download / Export → CSV): | Account | Columns in the CSV | |---|---| @@ -49,7 +49,7 @@ Go to **Settings → Import** and click **Pick a Folder**. Point it at a folder FinLens auto-detects which file is which based on filename and column headers. Checking and savings exports have the same columns, so keep `checking` or `savings` in their file names (or assign them manually on import). -**No bank exports handy?** Pick the [`samples/`](samples/) folder instead — three synthetic CSVs (fake data) covering May–Oct 2026. Set the date range to **All Time** to see everything. +**No bank exports handy?** Click **Try it with sample data** on the Welcome screen: it loads the three synthetic CSVs in [`samples/`](samples/) (fake data, May–Oct 2026) and sets the date range to **All time**. If FinLens is opened as a file, your browser asks you to choose those three files. A banner says you're looking at sample data; **Use my own files** removes it, and importing your own files replaces it. **3. Explore** @@ -131,7 +131,7 @@ Split your savings into goals. Each bucket has a target, what's saved, a date, a Enter your debts, or take a credit card's balance and limit straight from your CSVs. Total debt, minimums (and their share of take-home pay), average APR and card utilization. The **payoff plan** compares avalanche (highest rate first), snowball (smallest balance first) and paying only the minimums for any extra amount a month: when you'd be debt-free, the interest you'd pay, the payoff order and the first 6 months. Interest is added monthly at APR ÷ 12; a paid-off debt's minimum moves on to the next one. ### Trends -Monthly income/expense/savings bar chart, rolling savings rate line, top category ranking over time, and account balance trends. +Your latest six months, across every account: average saved a month, savings rate, the fastest-growing category and the steadiest month. Income, spending and savings by month; the savings rate with a 3-month average and a note on what moved it; each account's balance over the six months; and your top six categories month by month, shaded so each category's most expensive months stand out. ### Investing ideas Reference lists for learning, not financial advice. Type your own % next to nine index funds and ETFs (or use the balanced 40/20/20/10/5/5 preset) and see your mix, and its stock / bond / real estate split, update as you type. Six well-known stocks are listed to read about. Your mix is saved with your other plans. @@ -140,7 +140,10 @@ Reference lists for learning, not financial advice. Type your own % next to nine **Savings:** start from your checking, savings and debt, add what you save each month, and pick an interest rate (APY) and the tax on it, for 1–30 years. Save up to 10 scenarios and load them back. **Investments:** a starting amount, monthly additions, 1–40 years and a yearly return (5%, 8%, 11% or your own), shown in future and in today's dollars, year by year. Growth compounds monthly so that a yearly rate compounds to exactly that rate. ### AI Analysis -Ask Claude anything about your finances. Eight preset quick-analysis prompts or a free-form custom question. Claude receives a structured summary of your current financial state (balances, income, spending by category, debts, subscriptions) as context. Requires your own [Anthropic API key](https://console.anthropic.com). History is saved locally (up to 50 entries) and exportable as Markdown. +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). --- @@ -164,7 +167,7 @@ Ask Claude anything about your finances. Eight preset quick-analysis prompts or FinLens uses `claude-sonnet-5-5`. **How the AI feature is secured:** -- **Key storage** — the key is stored only in your browser (localStorage + IndexedDB). It is never written to `finlens-state.json`. Versions up to 1.7.0 did save it there; v1.8.0 moves it into browser storage on load and rewrites the file without it on the next save (click **Save Now** in **Settings → Import** to force it). For a personal, local-only app this is a deliberate trade-off; a multi-user deployment would proxy calls through a server holding the key in a secrets vault. +- **Key storage** — the key is stored only in your browser (localStorage + IndexedDB). It is never written to `finlens-state.json`. Versions up to 1.7.0 did save it there; v1.8.0 moves it into browser storage on load and rewrites the file without it on the next save (click **Save now** in **Settings → Import** to force it). For a personal, local-only app this is a deliberate trade-off; a multi-user deployment would proxy calls through a server holding the key in a secrets vault. - **Prompt injection** — your financial summary is sent inside `` tags, and the system prompt tells Claude to treat that content as data, never as instructions (merchant descriptions come straight from bank CSVs). - **Output rendering** — Claude's Markdown is converted with marked and sanitized with DOMPurify before it touches the page (`renderMarkdown()` in `core.js`). Scripts, event handlers and images are stripped, so injected text can't run code or exfiltrate data through image URLs. Both libraries are version-pinned with SRI hashes. @@ -220,9 +223,9 @@ FinLens/ ├── views-invest.js ← Investing ideas + the Forecast → Investments tab ├── views-forecast.js ← Forecast (Savings and Investments tabs) ├── views-ai.js ← AI Analysis (Claude integration) - ├── views-data.js ← Database section: Import, Accounts, Categories, Import Logs + ├── 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, start over) + ├── 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-eval.js ← AI Eval: grounding eval for AI Analysis (developer view) └── init.js ← App boot and event wiring @@ -234,22 +237,23 @@ 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 CSVs** in **Settings → Import** to force a re-read. -**Category rules** — go to **Transactions → 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 **Transactions → Spending → Category rules** to teach FinLens your merchants. Rules apply across all future imports. Your category list is managed under **Settings → Categories**. **Multiple credit cards** — load as many credit card 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: +**Cleaning up or starting over** — **Settings → Data & reset** shows what FinLens has stored and lets you (each button asks for a second click): - **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. +- **Clear individual plans:** budgets, bills, buckets, debts, forecast scenarios, the investment mix or AI history. - **Disconnect the folder.** +- **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. **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 responses can be saved as Markdown from the AI Analysis tab. +**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. --- @@ -259,4 +263,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.15.0 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.16.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index aa6db0b..d1e2044 100644 --- a/index.html +++ b/index.html @@ -69,6 +69,11 @@ --chart-grid:#eef1f4; /* spending heatmap, light → heavy */ --heat-1:#e0e7ff; --heat-2:#c7d2fe; --heat-3:#a5b4fc; --heat-4:#6366f1; --heat-5:#3730a3; + /* Trends → Top categories over time: six tile shades, light → heavy, and their text + (--t-ink on t0–t3, --t-ink-hi on t4–t5; each pair ≥ 4.5:1). --t4 is a touch darker than + the mockup's #6366f1, which gave white text 4.47:1. */ + --t0:#eef2ff; --t1:#e0e7ff; --t2:#c7d2fe; --t3:#a5b4fc; --t4:#5f62f0; --t5:#4338ca; --t-ink:#1e1b4b; --t-ink-hi:#ffffff; + --border-dash:#c3cad5; /* a dashed panel's border */ /* shape */ --shadow:none; --popover-shadow:0 12px 32px rgba(15,23,42,.14); @@ -114,6 +119,8 @@ --chart-neutral:#5b6678; --chart-grid:#1d2535; --heat-1:#272d5c; --heat-2:#2f3878; --heat-3:#3f4aa8; --heat-4:#6d78f0; --heat-5:#c7d2fe; + --t0:#1a2040; --t1:#232a55; --t2:#2f3878; --t3:#4651b0; --t4:#7a84f5; --t5:#c7d2fe; --t-ink:#e0e7ff; --t-ink-hi:#0b0f17; + --border-dash:#44516a; --popover-shadow:0 12px 32px rgba(0,0,0,.5); } *{box-sizing:border-box} @@ -183,6 +190,7 @@ .pop .custom{display:grid;grid-template-columns:1fr 1fr;gap:8px;padding:6px 10px 8px} .pop .custom label{font-size:12px;font-weight:600;color:var(--text-2)} .menu-btn{display:none} +.menu-btn[aria-expanded="true"] .i-open,.menu-btn:not([aria-expanded="true"]) .i-close{display:none} /* ☰ becomes × while the menu is open */ .mobile-menu{position:absolute;top:100%;left:0;right:0;z-index:45;background:var(--surface);border-bottom:1px solid var(--border);box-shadow:var(--popover-shadow);padding:8px 12px 14px;display:flex;flex-direction:column;max-height:calc(100vh - 64px);overflow-y:auto} .mobile-menu[hidden]{display:none} .mobile-menu a{display:flex;align-items:center;min-height:46px;padding:0 12px;border-radius:10px;color:var(--text);text-decoration:none;font-size:15px;font-weight:500;cursor:pointer} @@ -199,7 +207,7 @@ .pagebar h1{font-size:28px;font-weight:700;letter-spacing:-.02em;margin:0} .pagebar .sub{font-size:14px;color:var(--text-2)} .content{padding:20px 0 0;display:flex;flex-direction:column;gap:20px} -.folder-banner-wrap{padding:16px 0 0} +.folder-banner-wrap{padding:16px 0 0;display:flex;flex-direction:column;gap:10px} .folder-banner{display:flex;align-items:center;gap:12px;flex-wrap:wrap} .appfoot{max-width:1200px;margin:0 auto;padding:28px 32px 36px;font-size:12px;color:var(--text-3)} section.view{display:none;flex-direction:column;gap:20px;animation:fade .2s ease} @@ -281,7 +289,6 @@ .empty{border:2px dashed var(--border-strong);border-radius:var(--radius);padding:40px;text-align:center;color:var(--text-2);background:var(--surface)} .empty h4{margin:0 0 8px;color:var(--text)} -.kbd{font-family:'DM Mono',ui-monospace,monospace;font-size:11px;background:var(--muted);padding:2px 6px;border-radius:5px;border:1px solid var(--border)} .dot{display:inline-block;width:8px;height:8px;border-radius:99px;background:var(--accent)} .dot.amber{background:var(--warn)} .dot.red{background:var(--danger)} @@ -339,22 +346,6 @@ .spark-wrap{position:relative;height:64px;width:100%;margin-top:10px} .spark-wrap canvas{display:block} -/* file list */ -.filelist{display:flex;flex-direction:column;gap:6px} -.filerow{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid var(--border);border-radius:10px;background:var(--surface-2);font-size:13px} -.filerow .meta{margin-left:auto;color:var(--text-3);font-size:12px} - -/* ai panel */ -.ai-grid{display:grid;grid-template-columns:280px 1fr;gap:20px} -@media (max-width:900px){.ai-grid{grid-template-columns:1fr}} -.ai-prompts button{display:block;width:100%;text-align:left;min-height:44px;padding:10px 14px;border:1px solid var(--border);background:var(--surface);color:var(--text);border-radius:10px;margin-bottom:6px;font-size:14px;font-weight:500} -.ai-prompts button:hover{background:var(--surface-2)} -.ai-response{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:22px 26px;min-height:280px;overflow-y:auto;max-height:70vh;line-height:1.65} -.ai-response h1,.ai-response h2,.ai-response h3{font-weight:700} -.ai-response h2{font-size:17px} -.ai-response code{background:var(--muted);padding:2px 5px;border-radius:4px;font-size:13px} -.ai-response ul{padding-left:20px} - /* checkbox / check */ .check{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--text-2);cursor:pointer} .check input{accent-color:var(--accent)} @@ -379,18 +370,9 @@ th.sortable{cursor:pointer;user-select:none} th.sortable .arr{color:var(--text-3);font-size:10px;margin-left:4px} -/* account group */ -.acct-group{border:1px solid var(--border);border-radius:var(--radius-sm);padding:16px;margin-bottom:12px;background:var(--surface-2)} -.acct-group .acct-head{font-weight:600;font-size:14px;margin-bottom:10px;display:flex;align-items:center;gap:8px} -.acct-group .acct-kind{font-size:12px;color:var(--text-3);font-weight:400} - /* multi-category chips in table */ .cat-chips{display:flex;flex-wrap:wrap;gap:4px} -/* pending file assignment */ -.file-assign-row{display:grid;grid-template-columns:1fr 180px;gap:8px;align-items:center;padding:10px 12px;border:1px solid var(--border);border-radius:10px;background:var(--surface);margin-bottom:6px} -.file-assign-row .fname{font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} - /* allocation input */ .alloc-input{width:72px;text-align:right;padding:6px 8px;border:1px solid var(--border-strong);border-radius:8px;background:var(--surface);color:var(--text);font-size:13px} @@ -896,12 +878,223 @@ .seg.tabs-seg{align-self:stretch} .seg.tabs-seg button{flex:1} } +/* =============== INSIGHTS & SETTINGS (v1.16.0): Trends, AI Analysis, Settings, Welcome =============== */ +/* shell: Settings and the Welcome are narrower; on a true first run the app bar shows only the brand */ +body[data-view="settings"] .main,body.first-run .main,body[data-view="settings"] .appfoot,body.first-run .appfoot{max-width:1000px} +body.first-run .mainnav,body.first-run .appbar-tools{display:none !important} +.pagebar.hero{flex-direction:column;align-items:center;text-align:center;gap:0;padding-top:56px} +.pagebar.hero h1{font-size:44px;line-height:1.1;letter-spacing:-.03em;max-width:720px;text-wrap:balance} +/* a one-line result under a form or action; takes no space while empty (it stays a live region) */ +.status-line{margin:0;font-size:13px;font-weight:600;color:var(--text-2);overflow-wrap:anywhere} +.status-line:empty{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)} +.status-line.good{color:var(--good-strong-text)} .status-line.bad{color:var(--danger-text)} .status-line.warn{color:var(--warn-text)} +.btn.xl{min-height:52px;padding:0 24px;border-radius:12px;font-size:16px} +.btn.danger-outline{border-color:var(--danger-border)} +.panel h2.lg{font-size:17px;font-weight:700;overflow-wrap:anywhere} +.panel.dashed{border-style:dashed;border-color:var(--border-dash)} +.panel.row-panel{flex-direction:row;flex-wrap:wrap;align-items:center;gap:16px} +.row-panel .grow{flex:1 1 360px;min-width:0} +.row-panel .acts{display:flex;flex-wrap:wrap;gap:10px} +.panel-head.center{align-items:center} +.form-row.center{align-items:center} +.form-row .field.grow{flex:1 1 260px} +.cols-2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px} +.cols-3.top{align-items:start} +.col-stack{display:flex;flex-direction:column;gap:20px;min-width:0} +.icon-tile.lg{width:48px;height:48px;border-radius:12px} +.head-row{display:flex;align-items:center;gap:14px;flex-wrap:wrap} +.head-row .who{flex:1 1 240px;min-width:0} +.head-row .sub{margin:2px 0 0;color:var(--text-2)} +/* Trends */ +.bars.wide-gap,.bars-x.wide-gap{gap:28px} +.bars.wide-gap .grp{gap:4px} +.bars.wide-gap .bar{border-radius:4px 4px 0 0} +.hue-teal-text{--c:var(--teal-text)} +.bars-x .v.c-teal{color:var(--teal-text)} .bars-x .v.c-bad{color:var(--danger-text)} +.sw.line{width:16px;height:3px;border-radius:2px} +.lc-line.avg{stroke:var(--text);stroke-width:2;stroke-dasharray:6 5} +.bal-rows{display:flex;flex-direction:column} +.bal-row{display:grid;grid-template-columns:180px minmax(0,1fr) auto;gap:14px;align-items:center;padding:14px 0;border-top:1px solid var(--divider)} +.bal-row:first-child{border-top:0;padding-top:0} +.bal-row .n{font-weight:600;font-size:14px;overflow-wrap:break-word} +.bal-row .d{font-size:12px;color:var(--text-3)} +.bal-row .spark{height:48px} +.bal-row .v{text-align:right;font-weight:700;white-space:nowrap} +.bal-row .v small{font-size:12px;font-weight:500;color:var(--text-3)} +.heat-tbl{width:100%;min-width:720px;border-collapse:separate;border-spacing:6px;font-size:13px} +.heat-tbl th{padding:2px 0;font-size:12px;font-weight:600;color:var(--text-3);text-transform:uppercase;letter-spacing:.06em;text-align:center} +.heat-tbl thead th:first-child{width:150px;text-align:left} +.heat-tbl tbody th{font-size:14px;color:var(--text);text-transform:none;letter-spacing:0;text-align:left;overflow-wrap:anywhere} +.heat-tbl .r{text-align:right} +.heat-tbl td.r{width:100px;font-size:14px;font-weight:700;white-space:nowrap} +.ht{display:flex;align-items:center;justify-content:center;height:42px;border-radius:8px;font-weight:600;color:var(--t-ink);white-space:nowrap} +.ht.l0{background:var(--t0)} .ht.l1{background:var(--t1)} .ht.l2{background:var(--t2)} .ht.l3{background:var(--t3)} +.ht.l4{background:var(--t4);color:var(--t-ink-hi)} .ht.l5{background:var(--t5);color:var(--t-ink-hi)} +/* AI Analysis */ +.key-pill{height:36px;display:inline-flex;align-items:center;gap:8px;padding:0 12px;border-radius:999px;font-size:13px;font-weight:600;white-space:nowrap} +.key-pill .sdot{width:8px;height:8px;border-radius:50%;flex-shrink:0} +.key-pill.ok{background:var(--good-soft);color:var(--good-strong-text)} .key-pill.ok .sdot{background:var(--good-dot)} +.key-pill.off{background:var(--warn-soft);color:var(--warn-strong-text)} .key-pill.off .sdot{background:var(--warn)} +.quick-list{display:flex;flex-direction:column;gap:6px} +.quick{min-height:44px;padding:10px 14px;border:1px solid var(--border);background:var(--surface);border-radius:10px;color:var(--text);font-size:14px;font-weight:500;text-align:left} +.quick:hover{background:var(--surface-2)} +.quick[aria-pressed="true"]{background:var(--accent-soft);border-color:var(--accent-border)} +.quick:disabled{background:var(--surface-2);color:var(--text-3);cursor:not-allowed} +.hist-list{display:flex;flex-direction:column;max-height:360px;overflow-y:auto} +.hist-row{display:flex;align-items:center;gap:8px;min-height:44px;padding:8px 0;border:0;border-bottom:1px solid var(--divider);background:transparent;color:var(--text);font-size:14px;text-align:left} +.hist-row:last-child{border-bottom:0} +.hist-row .t{flex:1;min-width:0;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.hist-row .d{flex-shrink:0;font-size:13px;color:var(--text-3);white-space:nowrap} +.hist-row:hover .t,.hist-row[aria-current="true"] .t{color:var(--accent-text)} +.hist-row[aria-current="true"] .t{font-weight:600} +.ask-box{min-height:0;padding:12px 14px;border-radius:12px;font-size:15px;line-height:1.5} +.ask-foot{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px} +.ask-foot .note{flex:1 1 380px;margin:0;font-size:12px;line-height:1.5;color:var(--text-3)} +.panel.ai-answer{padding:26px 30px;gap:16px} +.ans-head{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:12px} +.ans-head .who{min-width:0;flex:1 1 280px} +.ans-head h2{margin:4px 0 0;font-size:18px;font-weight:700;overflow-wrap:anywhere} +.ans-head h2:focus{outline:none} +.ans-head .acts{display:flex;flex-wrap:wrap;gap:8px} +.ai-md{font-size:15px;line-height:1.65;color:var(--text-body);overflow-wrap:anywhere;min-width:0} +.ai-md>:first-child{margin-top:0} .ai-md>:last-child{margin-bottom:0} +.ai-md h1,.ai-md h2,.ai-md h3,.ai-md h4{margin:18px 0 8px;font-size:16px;font-weight:700;color:var(--text)} +.ai-md p{margin:0 0 12px} +.ai-md ul,.ai-md ol{margin:0 0 12px;padding-left:22px} +.ai-md li{margin:0 0 6px} +.ai-md strong{color:var(--text)} +.ai-md code{background:var(--muted);padding:2px 5px;border-radius:4px;font-size:13px} +.ai-md pre{background:var(--surface-2);padding:12px 14px;border-radius:10px;overflow-x:auto} +.ai-md table{display:block;max-width:100%;overflow-x:auto;border-collapse:collapse;margin:0 0 12px;font-size:14px} +.ai-md th,.ai-md td{padding:6px 12px 6px 0;border-bottom:1px solid var(--divider);text-align:left} +.ai-md hr{border:0;border-top:1px solid var(--divider);margin:16px 0} +.ai-md blockquote{margin:0 0 12px;padding-left:12px;border-left:3px solid var(--border-strong);color:var(--text-2)} +.ans-foot{margin:0;padding-top:14px;border-top:1px solid var(--divider);font-size:12px;color:var(--text-3)} +.thinking{display:flex;flex-direction:column;gap:12px} +.thinking .lead{font-size:14px;font-weight:600;color:var(--accent-text)} +.skel{display:block;height:12px;background:var(--track);border-radius:6px} +@media (prefers-reduced-motion:no-preference){.skel{animation:skel 1.4s ease-in-out infinite}} +@keyframes skel{50%{opacity:.5}} +.err-detail{margin:6px 0 0;white-space:pre-wrap;font:12px 'DM Mono',ui-monospace,monospace} +/* Settings */ +.tab-panel{display:flex;flex-direction:column;gap:20px} +.set-row{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px} +.set-row .t{font-size:14px;font-weight:600} +.set-row .d{font-size:13px;color:var(--text-3)} +.set-row.line{padding-top:14px;border-top:1px solid var(--divider);font-size:14px} +.set-row .v{color:var(--text-2)} +.info-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;font-size:13px} +.info-tiles>div{display:flex;flex-direction:column;gap:2px;padding:12px 14px;background:var(--surface-2);border-radius:10px;min-width:0} +.info-tiles .l{color:var(--text-3)} +.info-tiles b{font-weight:600} +.tbl .w-read{width:200px} +.tbl td .select{min-height:40px} +.fname{font:13px 'DM Mono',ui-monospace,monospace;color:var(--text);overflow-wrap:anywhere} +.rows>.r.wrap{flex-wrap:wrap} +.rows>.r.wrap .t{flex:1 1 280px;white-space:normal} +.rows .t .s2{display:block;margin-top:2px;font-size:12px;font-weight:400;color:var(--text-3)} +.rows>.r.wrap .callout{flex-basis:100%} +.log-list{display:flex;flex-direction:column;font-size:14px} +.lg-row{display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px;padding:11px 0;border-bottom:1px solid var(--divider)} +.lg-row:last-of-type{border-bottom:0} +.lg-row .w{width:150px;color:var(--text-2)} +.lg-row .t{flex:1 1 180px;min-width:0} +.lg-row .d{color:var(--text-2)} +.log-list>.btn{align-self:flex-start;margin-top:6px} +.acct-rows{display:flex;flex-direction:column} +.acct-row{display:grid;grid-template-columns:44px minmax(0,1fr) 200px 130px;gap:8px 14px;align-items:center;padding:14px 0;border-top:1px solid var(--divider)} +.acct-row .field{font-size:12px;color:var(--text-3)} +.field .input.strong{font-weight:600} +.order-btns{display:flex;flex-direction:column;gap:4px} +.order-btns .icon-btn{width:40px;height:30px;border-color:var(--border);border-radius:7px;color:var(--text-body)} +.acct-meta{display:flex;flex-direction:column;font-size:12px;line-height:1.5;color:var(--text-3)} +.acct-meta b{font-size:14px;font-weight:600;color:var(--text)} +.row-note{grid-column:2/-1;margin:0;font-size:13px;color:var(--text-2)} +.cc-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px} +.util-line{display:flex;flex-direction:column;gap:6px} +.util-line .sub{margin:0;font-size:13px;color:var(--text-2)} +.cat-chips{list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:8px} +.cat-chip{display:inline-flex;align-items:center;gap:6px;min-height:38px;padding:0 4px 0 14px;border:1px solid var(--border);border-radius:999px;font-size:14px;font-weight:500} +.cat-chip:not(:has(button)){padding-right:14px} +.cat-chip .c{font-size:12px;color:var(--text-3)} +.cat-chip button{width:30px;height:30px;border:0;background:transparent;border-radius:50%;color:var(--text-3);font-size:16px;line-height:1} +.cat-chip button:hover{background:var(--surface-2);color:var(--danger-text)} +.kv-rows{display:flex;flex-direction:column;font-size:14px} +.kv-rows>div{display:grid;grid-template-columns:200px minmax(0,1fr);gap:12px;padding:11px 0;border-bottom:1px solid var(--divider)} +.kv-rows>div:last-child{border-bottom:0} +.kv-rows .k{font-weight:600} +.kv-rows .v{color:var(--text-2);overflow-wrap:anywhere} +.clean-rows{display:flex;flex-direction:column} +.clean-row{display:flex;flex-wrap:wrap;align-items:center;gap:10px 14px;padding:12px 0;border-top:1px solid var(--divider)} +.clean-row .who{flex:1 1 320px;min-width:0} +.clean-row .t{font-size:14px;font-weight:600} +.clean-row .d{font-size:13px;color:var(--text-3)} +.clean-btn{min-width:150px} +.clean-btn.armed,.clean-btn.armed:hover{background:var(--danger);border-color:var(--danger);color:var(--on-solid)} +.clean-btn.done,.clean-btn.done:disabled{background:var(--good-soft);border-color:var(--good-border);color:var(--good-strong-text);opacity:1;cursor:default} +.panel.danger-panel{border-color:var(--danger-border)} +.danger-panel h2{font-weight:700;color:var(--danger-strong-text)} +.danger-panel .body{margin:0;font-size:14px;line-height:1.5;color:var(--text-body)} +.radio-set{border:0;padding:0;margin:0;display:flex;flex-direction:column;gap:4px;min-width:0} +.radio-set legend{padding:0;margin-bottom:8px;font-size:13px;font-weight:600;color:var(--text-body)} +.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} +/* 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)} +.hero-acts{display:flex;flex-wrap:wrap;justify-content:center;gap:12px;margin-top:8px} +.welcome .hint{margin:0;font-size:13px;color:var(--text-2)} +.inline-link{border:0;background:none;padding:0;font:inherit;color:var(--accent-text);text-decoration:underline;cursor:pointer} +.inline-link:hover{color:var(--accent-hover)} +.steps{margin:20px 0 0;padding:0;list-style:none;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px} +.steps li{display:flex;flex-direction:column;gap:10px;padding:24px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius)} +.step-num{width:32px;height:32px;border-radius:50%;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent-strong-text);font-weight:700} +.steps h2{margin:0;font-size:16px;font-weight:700} +.steps p{margin:0;font-size:14px;line-height:1.55;color:var(--text-2)} +.features{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px;margin-top:20px;padding-top:8px;border-top:1px solid var(--border)} +.features>div{display:flex;gap:12px;padding-top:20px} +.features svg{flex-shrink:0;color:var(--accent)} +.features .t{font-size:14px;font-weight:600} +.features .d{margin-top:2px;font-size:13px;line-height:1.5;color:var(--text-2)} +@media (max-width:1000px){.cols-2{grid-template-columns:minmax(0,1fr)}} +@media (max-width:900px){.cc-grid{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media (max-width:720px){ + .panel.ai-answer{padding:18px} + .steps,.features{grid-template-columns:minmax(0,1fr)} + .features>div{padding-top:12px} + .acct-row{grid-template-columns:44px minmax(0,1fr)} + .acct-row .order-btns{grid-row:span 3;align-self:start} + .acct-row>.field,.acct-row .acct-meta{grid-column:2} + .acct-meta{flex-direction:row;gap:8px;flex-wrap:wrap} + .bars.wide-gap,.bars-x.wide-gap{gap:8px} + .bars.wide-gap .grp{gap:2px} +} +@media (max-width:600px){ + .pagebar.hero{padding-top:28px} + .pagebar.hero h1{font-size:30px} + .welcome .lead{font-size:16px} + .info-tiles{grid-template-columns:minmax(0,1fr)} + .kv-rows>div{grid-template-columns:minmax(0,1fr);gap:2px} + .lg-row .w{width:auto;flex-basis:100%;font-size:13px} + .files-tbl.fit-sm .w-read{width:150px} + .files-tbl .select{width:100%;min-width:0;padding:6px 8px} + .tbl.fit-sm td code{overflow-wrap:anywhere} + .bal-row{grid-template-columns:minmax(0,1fr) auto} + .bal-row .spark{grid-column:1/-1;grid-row:2} + .hero-acts .btn{flex:1 1 100%} + .clean-row .who{flex:1 1 170px} + .clean-btn{min-width:104px} +} +@media (max-width:480px){.cc-grid{grid-template-columns:minmax(0,1fr)}} /* bigger touch targets on touch screens */ @media (pointer:coarse){ .fpill,.seg button{min-height:44px} .kw{height:44px} .kw button{width:40px;height:40px} .icon-x{width:44px;height:44px} + .cat-chip button{width:40px;height:40px} + .order-btns .icon-btn{height:36px} } @@ -979,7 +1172,8 @@ @@ -1008,7 +1202,7 @@
-
v1.15.0 · FinLens
+
v1.16.0 · FinLens
@@ -1024,6 +1218,7 @@

Details

+ diff --git a/js/aggregation.js b/js/aggregation.js index 80e55aa..9264b95 100644 --- a/js/aggregation.js +++ b/js/aggregation.js @@ -378,7 +378,7 @@ function savingsPace(txs=State.transactions) { /* ---------- DEBTS (v1.15.0) ---------- */ // A debt can take its balance from a credit card account in your CSVs (debt.account). Its -// limit then comes from that account's credit limit (Settings → Credit Cards). Without a +// limit then comes from that account's credit limit (Settings → Credit cards). Without a // linked account, or once it's gone, the debt's own fields count. function debtLinked(d) { return !!(d&&d.account&&State.accounts[d.account]); } function debtIsCard(d) { return debtLinked(d)?State.accounts[d.account].kind==='credit_card':d.type==='Credit Card'; } diff --git a/js/core.js b/js/core.js index dafa4b6..90e7bcc 100644 --- a/js/core.js +++ b/js/core.js @@ -198,6 +198,8 @@ async function saveStateToFile(state) { scenarios: state.scenarios, investAlloc: state.investAlloc, debtPlan: state.debtPlan, + cardDetails: state.cardDetails, + sampleData: state.sampleData, theme: state.theme, fileAssignments: state.fileAssignments, accountOrder: state.accountOrder, @@ -364,6 +366,12 @@ const State = { scenarios: lsGet('scenarios', []), // Forecast → Savings scenarios (CLAUDE.md §4.1) investAlloc: lsGet('investAlloc', {}), // ticker -> user % debtPlan: lsGet('debtPlan', { strategy:'avalanche', extra:0 }), // Debt payoff plan: 'avalanche'|'snowball'|'minimum', extra $/mo + // Settings → Credit cards (v1.16.0): { [cardAccountId]: { apr: number|null, dueDay: number|null } }. + // A debt linked to the card (State.debts[].account) holds its own APR and due day, which win. + cardDetails: lsGet('cardDetails', {}), + // true while the loaded transactions are the synthetic samples/ files ("Try it with sample + // data" on the Welcome). The next import of your own files clears them first (loadFiles()). + sampleData: lsGet('sampleData', false), range: { mode:'month', start:null, end:null }, selectedAccounts: 'all', theme: lsGet('theme', 'light'), @@ -727,13 +735,23 @@ function parseCsvFile(file, forcedKind) { }); } -async function loadFiles(fileList, assignments) { +async function loadFiles(fileList, assignments, opts = {}) { // assignments: { filename -> kind } (optional; if not provided, auto-detect) + // opts.sample: these are the synthetic samples/ files (loadSampleData() in views-data.js) const csvs = Array.from(fileList).filter(f=>f.name.toLowerCase().endsWith('.csv')); if (!csvs.length) { alert('No CSV files found.'); return; } // Any import (Reload, Reconnect, Rebuild, picking a folder or files) ends the pause // set by "Clear transactions & accounts". Boot never gets here while paused. if (State.csvAutoImportPaused) { State.csvAutoImportPaused = false; lsSet('csvAutoImportPaused', false); } + // Your own files replace the sample data instead of being mixed into its accounts + // (the samples use the same account ids as real checking and savings exports). + if (State.sampleData && !opts.sample) { + State.accounts = {}; + State.selectedAccounts = 'all'; + if (typeof DB !== 'undefined' && DB._db) await DB.clearStores(['transactions', 'accounts', 'import_log']); + State.sampleData = false; lsSet('sampleData', false); + if (typeof updateFolderBanner === 'function') updateFolderBanner(); + } State.fileMeta = []; State.transactions = []; for (const f of csvs) { diff --git a/js/db.js b/js/db.js index 7e46aa6..e7fd719 100644 --- a/js/db.js +++ b/js/db.js @@ -323,6 +323,8 @@ const DB = { ['scenarios', 'scenarios', []], ['investAlloc', 'investAlloc', {}], ['debtPlan', 'debtPlan', null], + ['cardDetails', 'cardDetails', {}], + ['sampleData', 'sampleData', false], ['fileAssignments', 'fileAssignments', {}], ['lastFolderName', 'lastFolderName', ''], ['theme', 'theme', 'light'], diff --git a/js/init.js b/js/init.js index 0c0d76f..fea2b28 100644 --- a/js/init.js +++ b/js/init.js @@ -86,6 +86,9 @@ const filePick = $('#filePick'); if (folderPick) folderPick.addEventListener('change', e => { if (e.target.files.length) handleFilePick(e.target.files); folderPick.value=''; }); if (filePick) filePick.addEventListener('change', e => { if (e.target.files.length) handleFilePick(e.target.files); filePick.value=''; }); + // The Welcome's "Try it with sample data" when FinLens is opened as a file (views-data.js) + const samplePick = $('#samplePick'); + if (samplePick) samplePick.addEventListener('change', e => { if (e.target.files.length) handleSamplePick(e.target.files); samplePick.value=''; }); /* ---- Escape closes an open app bar menu first, then the drawer ---- */ document.addEventListener('keydown', e => { diff --git a/js/ui.js b/js/ui.js index 1e06ae2..aacc575 100644 --- a/js/ui.js +++ b/js/ui.js @@ -29,9 +29,16 @@ function showView(id) { }); const pb=$('#planBtn'); if (pb) pb.classList.toggle('active',PLAN_VIEWS.includes(id)); const gear=$('.appbar .gear'); if (gear) gear.classList.toggle('on',id==='settings'); + // The shell's title row. A view may reword it while it renders (shellHero(), the Welcome). const pt=$('#pageTitle'); if (pt) pt.textContent=VIEWS[id].title; - // The Plan screens don't use the date range (Budget has its own month), so its label hides there. - const rl=$('#rangeLabel'); if (rl) rl.hidden=PLAN_VIEWS.includes(id); + const bar=$('.pagebar'); if (bar) bar.classList.remove('hero'); + // Screens that don't use the date range hide its label: the Plan screens (Budget has its + // own month), Trends (always the latest six months) and Settings. + const rl=$('#rangeLabel'); if (rl) rl.hidden=NO_RANGE_VIEWS.includes(id); + // body[data-view] lets CSS size the page per screen (Settings is narrower); first-run is + // set again by the Welcome if it shows. + document.body.dataset.view=id; + document.body.classList.remove('first-run'); if (typeof updateSyncBadge==='function') updateSyncBadge(); const c=$('#content'); if (!c) return; c.innerHTML=''; @@ -45,6 +52,16 @@ function showView(id) { function renderActive() { showView(State.currentView||'overview'); } +// The Welcome (no data yet) rewords the shell's title as its headline and centers it. +// With firstRun, the app bar shows only the brand, as in the mockup: there is nothing to +// navigate to yet. showView() undoes both before the next render. +function shellHero(title, firstRun) { + const pt=$('#pageTitle'); if (pt) pt.textContent=title; + const bar=$('.pagebar'); if (bar) bar.classList.add('hero'); + const rl=$('#rangeLabel'); if (rl) rl.hidden=true; + document.body.classList.toggle('first-run', !!firstRun); +} + /* ---------- DRAWER ---------- */ // One shared side panel (#txDrawer in index.html) with a title row, a scrolling body and // an optional footer pinned at the bottom: @@ -130,6 +147,8 @@ function chartColor(name, alpha) { /* ---------- APP BAR: Plan menu, filter popovers, ☰ menu ---------- */ const PLAN_VIEWS = ['budgets','buckets','debt','investments','forecast']; +// Screens that ignore the date range: the shell hides its label there (v1.15.0, v1.16.0). +const NO_RANGE_VIEWS = [...PLAN_VIEWS, 'trends', 'settings']; let _appBarOpen = null; // { btn, panel } of the menu or popover that's open function openAppBarPopup(btn, panel) { @@ -137,7 +156,7 @@ function openAppBarPopup(btn, panel) { panel.hidden = false; btn.setAttribute('aria-expanded','true'); btn.classList.add('open'); - if (panel.id === 'mobileMenu') { const s=$('#menuScrim'); if (s) s.hidden=false; } + if (panel.id === 'mobileMenu') { const s=$('#menuScrim'); if (s) s.hidden=false; btn.setAttribute('aria-label','Close menu'); } _appBarOpen = { btn, panel }; } function closeAppBarPopups(focusBtn) { @@ -147,6 +166,7 @@ function closeAppBarPopups(focusBtn) { btn.setAttribute('aria-expanded','false'); btn.classList.remove('open'); const s=$('#menuScrim'); if (s) s.hidden=true; + if (panel.id === 'mobileMenu') btn.setAttribute('aria-label','Open menu'); _appBarOpen = null; if (focusBtn) btn.focus(); } @@ -639,7 +659,9 @@ function debtCardChoices(current) { } // Edit debt i in the drawer, or add one (i < 0); `account` links a new one to a card. function editDebt(i, account) { - const d=i>=0?State.debts[i]:{name:account?acctName(account):'',type:'Credit Card',balance:'',apr:'',minPayment:'',limit:'',dueDay:'',account:account||''}; + // A new debt started from a card takes the APR and due day entered in Settings → Credit cards. + const cd=(account&&State.cardDetails&&State.cardDetails[account])||{}; + const d=i>=0?State.debts[i]:{name:account?acctName(account):'',type:'Credit Card',balance:'',apr:cd.apr??'',minPayment:'',limit:'',dueDay:cd.dueDay??'',account:account||''}; const acct=debtLinked(d)?d.account:''; const cards=debtCardChoices(acct); const limit=acct?(State.manualBalances[acct+'_limit']??''):(d.limit||''); @@ -651,7 +673,7 @@ function editDebt(i, account) { -

The balance comes from the card's transactions (or the balance you set in Settings → Credit Cards) and updates when you import.

+

The balance comes from the card's transactions (or the balance you set in Settings → Credit cards) and updates when you import.

@@ -673,6 +695,9 @@ function editDebt(i, account) { $('#dtType').value='Credit Card'; if (!name.value.trim()||cards.some(a=>acctName(a.id)===name.value)) name.value=acctName(id); const l=State.manualBalances[id+'_limit']; $('#dtLim').value=l==null||l===''?'':l; + const c=(State.cardDetails||{})[id]||{}; + if (!$('#dtApr').value&&c.apr!=null) $('#dtApr').value=c.apr; + if (!$('#dtDue').value&&c.dueDay!=null) $('#dtDue').value=c.dueDay; } }; $('#dtSave').onclick=()=>saveDebt(i); @@ -743,7 +768,7 @@ function exportAllData() { categoryRules:State.categoryRules, categories:State.categories, aiHistory:State.aiHistory, scenarios:State.scenarios, recurringConfirmed:State.recurringConfirmed, investAlloc:State.investAlloc, - debtPlan:State.debtPlan, + debtPlan:State.debtPlan, cardDetails:State.cardDetails, }; downloadFile(`finlens-export-${dayjs().format('YYYYMMDD')}.json`, JSON.stringify(data,null,2),'application/json'); } @@ -755,7 +780,7 @@ function importJsonFile(ev) { const d=JSON.parse(e.target.result); // Exports from before v1.12.0 use the old account codes (migrate.js) IdMigration.migrateState(d); - ['budgets','buckets','debts','bills','txOverrides','manualBalances','categoryRules','categories','aiHistory','scenarios','recurringConfirmed','investAlloc','debtPlan'].forEach(k=>{ + ['budgets','buckets','debts','bills','txOverrides','manualBalances','categoryRules','categories','aiHistory','scenarios','recurringConfirmed','investAlloc','debtPlan','cardDetails'].forEach(k=>{ if (d[k]!==undefined){ State[k]=d[k]; lsSet(k,d[k]); } }); if (IdMigration.adoptOverrides(State.transactions).size) lsSet('txOverrides',State.txOverrides); diff --git a/js/views-ai.js b/js/views-ai.js index 04e3a5f..5253c4c 100644 --- a/js/views-ai.js +++ b/js/views-ai.js @@ -71,57 +71,135 @@ function buildFinancialSummary() { return lines.join('\n'); } -let aiCurrentResponse=''; -registerView('ai','AI Analysis',(root)=>{ - if (!State.apiKey) { - const setup=document.createElement('div'); setup.className='card'; - setup.innerHTML=`

AI Analysis Powered by Claude

-

Add your Anthropic API key in Settings → General to enable Claude-powered analysis.

-
Your key is stored only in this browser (localStorage + IndexedDB) and is never written to finlens-state.json. Get one at console.anthropic.com.
`; - root.appendChild(setup); return; - } +// The quick analyses on the AI tab (v1.16.0), with the mockup's labels. Each sends one of +// the AI_PROMPTS questions, unchanged, so the request is exactly what the AI Eval measures; +// only the label shown here and kept in history differs. AI_PROMPTS stays as it was: the +// published eval results are matched against its labels and questions (views-eval.js). +// The mockup's "Unusual transactions" isn't here: the summary FinLens sends has no single +// transactions to look at, and adding them would change the request. +const AI_QUICK=[ + ['Monthly spending review', 4], // "This month vs last month" + ['Where can I cut back?', 1], // "Where am I overspending?" + ['Subscription audit', 6], // "Subscriptions to cancel" + ['Savings rate check', 2], // "Am I on track with savings?" + ['Debt payoff plan', 3], // "Debt payoff strategy" + ['Budget suggestions', 5], // "Realistic budget suggestion" + ['12-month forecast', 7], // "12-month net worth prediction" + ['Summarize my finances', 0], +]; - const grid=document.createElement('div'); grid.className='ai-grid'; - grid.innerHTML=` -
-
-

Quick Analyses

-
- ${AI_PROMPTS.map(([label],i)=>``).join('')} -
-
-
-

Custom Question

- - -
- ${(State.aiHistory||[]).length?`
-

History

-
- ${State.aiHistory.slice().reverse().map((h,i)=>`
-
${dayjs(h.timestamp).format('MMM D, h:mm A')}
-
${escapeHtml(h.question.slice(0,50))}${h.question.length>50?'…':''}
-
`).join('')} -
-
`:''} +// What the answer area shows. Kept between renders, so leaving the tab and coming back +// (or an answer arriving while you're elsewhere) shows the latest state. +let aiCurrentResponse=''; // the answer as Markdown, for Copy and Save as Markdown +let aiCurrent=null; // { question, text, truncated, at, model, hist? } — the answer on screen +let aiError=null; // { title, detail } — the last request's error +let aiPhase='idle'; // 'idle' | 'thinking' | 'done' | 'error' +let aiAsking=''; // the question being asked while thinking +let aiSel=-1; // the quick analysis last used (index into AI_QUICK); -1 = your own question +let aiDraft=''; // the text in "Ask your own question" + +registerView('ai','AI Analysis',(root)=>{ + wireLinks(root); + const has=!!State.apiKey; + pageActions(root,'Ask Claude about your finances, using a summary of the numbers on your screen', + has?'API key saved in this browser' + :'No API key saved'); + const span=dataSpan(filteredTx()); + const period=span?spanText(span.first,span.last):rangeText(); + // Without a key, the way to add one comes first (above the columns, so phones see it first). + if (!has) appendHtml(root,`
+

Add your API key to ask Claude

+

AI Analysis uses your own Anthropic API key. Add it in Settings → General. It's kept in this browser only and never written to finlens-state.json, exports or logs. Get one at console.anthropic.com.

+ Add API key +
`); + appendHtml(root,`
+
+

Quick analyses

+
${AI_QUICK.map(([l],i)=>``).join('')}
+
+
+

History

+
+ +
-
-
-
-
✦
-
Pick a quick analysis or ask your own question.
Claude will analyze your financial data in detail.
+
+ ${has?`

Ask your own question

+ +
+

Claude gets a text summary of your balances, income, spending by category, debts and subscriptions for ${escapeHtml(period)}. Never your CSV files. The request goes from your browser straight to Anthropic using your key.

+
-
-
- - -
-
`; - root.appendChild(grid); + `:''} +
+
+
`); + + $$('[data-quick]',root).forEach(b=>b.onclick=()=>askQuick(+b.dataset.quick)); + const box=$('#aiCustom'), ask=$('#aiAsk'); + if (box) { + box.addEventListener('input',()=>{ aiDraft=box.value; aiPaint(); }); + box.addEventListener('keydown',e=>{ if (e.key==='Enter'&&(e.ctrlKey||e.metaKey)) { e.preventDefault(); askAICustom(); } }); + ask.onclick=askAICustom; + } + $('#aiHistExport').onclick=exportAIHistory; + aiPaint(); }); +// A quick analysis: the AI_PROMPTS question it stands for, sent as askAI() sends it. +function askQuick(i){ const q=AI_QUICK[i]; if (!q) return; aiSel=i; callClaude(AI_PROMPTS[q[1]][1], q[0]); } function askAI(i){ callClaude(AI_PROMPTS[i][1],AI_PROMPTS[i][0]); } -function askAICustom(){ const q=$('#aiCustom').value.trim(); if (!q){ alert('Type a question first.'); return; } callClaude(q,q); } +function askAICustom(){ const el=$('#aiCustom'); const q=(el?el.value:aiDraft).trim(); if (!q){ if (el) el.focus(); return; } aiSel=-1; callClaude(q,q); } + +// Brings the open AI tab up to date: the answer area, the buttons and the history list. +// Does nothing when the tab isn't showing (the next render shows the same state). +function aiPaint() { + const resp=$('#aiResponse'); + if (!resp) return; + const busy=aiPhase==='thinking'; + const sec=$('#answer'); if (sec) sec.setAttribute('aria-busy',String(busy)); + const box=$('#aiCustom'), ask=$('#aiAsk'); + if (ask) { + ask.disabled=busy||!(box&&box.value.trim()); + ask.querySelector('span').textContent=busy?'Asking…':'Ask Claude'; + } + $$('[data-quick]').forEach(b=>{ if (State.apiKey) b.disabled=busy; b.setAttribute('aria-pressed',String(+b.dataset.quick===aiSel)); }); + + if (busy) { + resp.innerHTML=`

Answer

+
Claude is reading your summary…
+

You asked: ${escapeHtml(aiAsking)}

`; + } else if (aiPhase==='error'&&aiError) { + resp.innerHTML=`

Answer

+ `; + } else if (aiCurrent) { + const c=aiCurrent, none=aiNoAnswer(c.text, c.truncated); + resp.innerHTML=`
+
You asked

${escapeHtml(c.question)}

+ ${none?'':`
`} +
+ ${aiAnswerHtml(c.text, c.truncated)} +

Answered ${c.fresh&&Date.now()-c.at<60000?'just now':escapeHtml(dayjs(c.at).format('MMM D, h:mm A'))} · ${escapeHtml(c.model||AI_MODEL)} · AI can make mistakes, so check figures against your Spending and Budget pages.

+

`; + const cp=$('#aiCopy'), sv=$('#aiSave'); + if (cp) cp.onclick=copyAIResponse; + if (sv) sv.onclick=saveAINote; + } else { + resp.innerHTML=`

Answer

${State.apiKey?'Pick a quick analysis or ask your own question. The answer appears here.':'Answers appear here once your API key is saved. Your history stays readable without it.'}

`; + } + + const hist=State.aiHistory||[]; + const cnt=$('#aiHistCount'); if (cnt) cnt.textContent=`${hist.length} of 50 kept`; + const list=$('#aiHist'); + if (list) { + list.innerHTML=hist.length?hist.map((e,i)=>({e,i})).reverse().map(({e,i})=> + ``).join('') + :'

Your answers are kept here, up to 50.

'; + $$('[data-hist]',list).forEach(b=>b.onclick=()=>loadAIHistory(+b.dataset.hist)); + } + const ex=$('#aiHistExport'); if (ex) ex.disabled=!hist.length; +} let aiBusy=false; // ignore clicks while a request is in flight const AI_TIMEOUT_MS=90000; // give up (and say so) instead of spinning forever @@ -143,10 +221,12 @@ const AI_NO_TEXT='(no response)'; // no answer at all — nothing to show, copy, save or keep in history. function aiNoAnswer(text, truncated) { return truncated && text===AI_NO_TEXT; } -// An answer as HTML, with a visible warning when it was cut off. +// An answer as HTML: a warning first when it was cut off, then the Markdown (sanitized by +// renderMarkdown()). Cut off before any text: only the warning. function aiAnswerHtml(text, truncated) { - if (aiNoAnswer(text, truncated)) return '
No answer was written. Claude reached the length limit while it was still thinking, before it started the answer. Ask again, or ask a narrower question.
'; - return renderMarkdown(text)+(truncated?'
This answer was cut off. It reached the length limit, so the end is missing. Ask again, or ask a narrower question.
':''); + if (aiNoAnswer(text, truncated)) return `
${ICON_ALERT}No answer was written. Claude reached the length limit while it was still thinking, before it started the answer. Ask again, or ask a narrower question.
`; + return (truncated?`
${ICON_ALERT}This answer was cut off before it finished. It reached the length limit, so the end is missing, and it's saved to history marked as cut off. Ask again, or ask a narrower question.
`:'') + +`
${renderMarkdown(text)}
`; } // Every failure path ends in a visible message on the page — never a silent no-op. @@ -159,14 +239,13 @@ async function callClaude(question, label, opts={}) { if (opts.raw) return send(opts.summary!=null?opts.summary:buildFinancialSummary()); if (!State.apiKey){ alert('Set your Anthropic API key in Settings first.'); return; } - const respEl=$('#aiResponse'); - if (!respEl || aiBusy) return; - const showError=(title, detail)=>{ - respEl.innerHTML=`
${escapeHtml(title)}${detail?`
${escapeHtml(detail)}
`:''}
`; - }; + if (aiBusy) return; + const asked=label||question; + const showError=(title, detail)=>{ aiError={ title, detail:detail||'' }; aiPhase='error'; }; aiBusy=true; - respEl.innerHTML='
Analyzing
'; + aiPhase='thinking'; aiAsking=asked; aiError=null; aiCurrentResponse=''; + aiPaint(); let summary; try { @@ -175,19 +254,23 @@ async function callClaude(question, label, opts={}) { console.error('[FinLens] buildFinancialSummary failed:', err); showError("Couldn't prepare your financial summary, so nothing was sent to Claude.", err.message||String(err)); aiBusy=false; + aiPaint(); return; } try { - const { text, truncated }=await send(summary); - respEl.innerHTML=aiAnswerHtml(text, truncated); + const { text, truncated, model }=await send(summary); + const at=Date.now(); + aiCurrent={ question:asked, text, truncated, at, model, fresh:true }; + aiPhase='done'; if (aiNoAnswer(text, truncated)) return; // nothing to copy or keep (finally clears aiBusy) // A cut-off answer says so on screen, in copies and saved notes, and in history. aiCurrentResponse=truncated?`${text}\n\n${AI_CUT_OFF_NOTE}`:text; State.aiHistory=State.aiHistory||[]; - State.aiHistory.push({timestamp:Date.now(),question:label||question,response:text,...(truncated?{truncated:true}:{})}); + State.aiHistory.push({timestamp:at,question:asked,response:text,...(truncated?{truncated:true}:{}),model}); if (State.aiHistory.length>50) State.aiHistory=State.aiHistory.slice(-50); lsSet('aiHistory',State.aiHistory); + aiCurrent.hist=State.aiHistory.length-1; } catch(err) { console.error('[FinLens] Claude request failed:', err); if (err.status){ @@ -199,6 +282,7 @@ async function callClaude(question, label, opts={}) { else showError("Something went wrong handling Claude's answer.", err.message||String(err)); } finally { aiBusy=false; + aiPaint(); } // One Messages API request. Throws on failure; HTTP errors get .status and .detail @@ -236,6 +320,34 @@ async function callClaude(question, label, opts={}) { } } } -function loadAIHistory(idx){ const h=State.aiHistory[idx]; if (!h) return; aiCurrentResponse=h.truncated?`${h.response}\n\n${AI_CUT_OFF_NOTE}`:h.response; $('#aiResponse').innerHTML=`
${dayjs(h.timestamp).format('MMM D, h:mm A')} · ${escapeHtml(h.question)}
`+aiAnswerHtml(h.response, !!h.truncated); } -function copyAIResponse(){ if (!aiCurrentResponse){ alert('Nothing to copy.'); return; } navigator.clipboard.writeText(aiCurrentResponse).then(()=>alert('Copied!')); } -function saveAINote(){ if (!aiCurrentResponse) return; const blob=new Blob([aiCurrentResponse],{type:'text/markdown'}); const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download=`finlens-analysis-${dayjs().format('YYYYMMDD-HHmm')}.md`; a.click(); } +// Show a saved answer from History (it stays saved; nothing is sent). +function loadAIHistory(idx){ + const h=(State.aiHistory||[])[idx]; if (!h) return; + aiCurrentResponse=h.truncated?`${h.response}\n\n${AI_CUT_OFF_NOTE}`:h.response; + aiCurrent={ question:h.question, text:h.response, truncated:!!h.truncated, at:h.timestamp, model:h.model, hist:idx }; + aiPhase='done'; aiError=null; + aiPaint(); + const head=$('#ansH'); if (head) { head.focus({preventScroll:true}); head.scrollIntoView({block:'nearest'}); } +} +function aiSay(text, kind) { const el=$('#aiCopyMsg'); if (el) { el.className='status-line '+(kind||'good'); el.textContent=text; } } +function copyAIResponse(){ + if (!aiCurrentResponse){ aiSay('Nothing to copy yet.','bad'); return; } + const done=()=>aiSay('Copied to the clipboard.'), fail=()=>aiSay('Your browser didn\'t allow copying. Select the text and copy it instead.','bad'); + try { navigator.clipboard.writeText(aiCurrentResponse).then(done,fail); } catch(e) { fail(); } +} +function saveAINote(){ + if (!aiCurrentResponse) return; + downloadFile(`finlens-analysis-${dayjs().format('YYYYMMDD-HHmm')}.md`, aiCurrentResponse, 'text/markdown'); + aiSay('Saved as a Markdown file.'); +} +// Every saved answer, newest first, as one Markdown file. +function exportAIHistory(){ + const h=State.aiHistory||[]; + if (!h.length) return; + const md=['# FinLens AI history','',`Exported ${dayjs().format('MMM D, YYYY h:mm A')} · ${h.length} answer${h.length===1?'':'s'}`,'']; + h.slice().reverse().forEach(e=>{ + md.push('---','',`## ${e.question}`,'',`*${dayjs(e.timestamp).format('MMM D, YYYY h:mm A')}${e.model?' · '+e.model:''}*`,'',e.response,''); + if (e.truncated) md.push(AI_CUT_OFF_NOTE,''); + }); + downloadFile(`finlens-ai-history-${dayjs().format('YYYYMMDD')}.md`, md.join('\n'), 'text/markdown'); +} diff --git a/js/views-cleanup.js b/js/views-cleanup.js index 59bd61e..6430403 100644 --- a/js/views-cleanup.js +++ b/js/views-cleanup.js @@ -14,6 +14,7 @@ const DataCleanup = { lastMessage: null, // { kind: 'good'|'warn'|'bad', text } shown once at the top of the tab + lastDone: null, // 'action|arg' of the action that just ran: its button shows "Cleared" once // Plans and history the user created: [State key (= lsSet key), label, empty value (default [])] PLAN_ITEMS: [ @@ -30,6 +31,16 @@ const DataCleanup = { bills: [['recurringConfirmed', 'recurring', {}, 'Also forgets which spotted recurring charges you confirmed or dismissed.']], debts: [['debtPlan', 'debtPlan', { strategy: 'avalanche', extra: 0 }, 'Also resets the payoff plan (strategy and extra payment).']], }, + // Each plan item's row in Clean up: [title, what it holds (count → text)] + PLAN_ROWS: { + budgets: ['Clear budgets', n => plural(n, 'budget')], + bills: ['Clear bills', n => plural(n, 'bill')], + buckets: ['Clear buckets', n => plural(n, 'savings goal')], + debts: ['Clear debts', n => plural(n, 'debt')], + scenarios: ['Clear forecast scenarios', n => plural(n, 'saved scenario')], + investAlloc: ['Clear investment mix', n => plural(n, 'fund')], + aiHistory: ['Clear AI history', n => plural(n, 'saved answer')], + }, // How many entries a plan item holds (the investment mix: tickers with a share above 0) _planCount(key) { const v = State[key]; @@ -41,6 +52,7 @@ const DataCleanup = { async clearImported() { this._dropImported(); + if (State.sampleData) { State.sampleData = false; lsSet('sampleData', false); updateFolderBanner(); } await DB.clearStores(['transactions', 'accounts']); buildAccountFilter(); // With a folder connected, boot would re-import its CSVs into the now-empty @@ -49,7 +61,7 @@ const DataCleanup = { const paused = !!(await idbGet('csvDirHandle')); if (paused) { State.csvAutoImportPaused = true; lsSet('csvAutoImportPaused', true); } await this._finish('Imported transactions and accounts cleared.' + (paused - ? ` They stay cleared after a reload: “${State.lastFolderName}” won't re-import until you click Rebuild here or Reload under Settings → Import.` + ? ` They stay cleared after a reload: “${State.lastFolderName}” won't re-import until you click Rebuild here or Reload CSVs under Settings → Import.` : '')); }, @@ -103,6 +115,20 @@ const DataCleanup = { await this._finish(`Rebuilt from “${State.lastFolderName}”: ${State.transactions.length.toLocaleString()} transactions re-imported.`); }, + // "Use my own files" on the sample-data banner: removes the samples (transactions, + // accounts, their import log) and goes back to the Welcome. Plans made meanwhile stay. + // Runs from a click: with a folder connected it rewrites finlens-state.json. + async clearSampleData() { + this._dropImported(); + _importLogCache = []; + await DB.clearStores(['transactions', 'accounts', 'import_log']); + State.sampleData = false; lsSet('sampleData', false); + buildAccountFilter(); + updateFolderBanner(); + if (await idbGet('csvDirHandle')) await saveStateNow(); + showView('overview'); + }, + async disconnectFolder() { const name = State.lastFolderName || 'the folder'; await forgetDataFolder(); @@ -164,113 +190,94 @@ const DataCleanup = { _done(kind, text) { this.lastMessage = { kind, text }; + if (kind === 'bad') this.lastDone = null; 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)'; +/* ---------- view (Clarity, v1.16.0) ---------- */ -registerView('data-cleanup', 'Data & Reset', (root) => { +registerView('data-cleanup', 'Data & reset', (root) => { + wireLinks(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 done = DataCleanup.lastDone; + DataCleanup.lastDone = null; + if (msg) appendHtml(root, callout(msg.kind === 'good' ? 'good' : msg.kind, escapeHtml(msg.text))); const folder = State.lastFolderName; + const f = escapeHtml(folder || ''); 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} -
`; + const edits = Object.keys(State.txOverrides || {}).length; + const paused = State.csvAutoImportPaused && !State.transactions.length; - /* ---- 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'))}
` : ''} + /* ---- What FinLens has stored ---- */ + const count = (k) => DataCleanup._planCount(k); + const settingsLine = [plural(count('budgets'), 'budget'), plural(count('bills'), 'bill'), plural(count('buckets'), 'bucket'), + plural(count('debts'), 'debt'), plural(count('aiHistory'), 'AI answer')] + .concat(count('scenarios') ? [plural(count('scenarios'), 'forecast scenario')] : []) + .concat(count('investAlloc') ? ['your investment mix'] : []) + .concat([State.apiKey ? 'API key' : 'no API key']).join(' · '); + appendHtml(root, `
+

What FinLens has stored

+
+
This browser's database… · … · … · ${plural(edits, 'transaction edit')}
+
This browser's settings${settingsLine}
+
Your folder${folder ? `“${f}”: finlens-state.json (everything above except the API key). Your CSV files are never changed.` : 'No folder connected, so nothing is saved to disk. Connect one in Import.'}
- ${folder ? `
${State.csvAutoImportPaused && !State.transactions.length - ? `Automatic import from “${escapeHtml(folder)}” is paused because you cleared your transactions. Click Rebuild, or Reload under Settings → Import, to bring them back.` - : `Clearing transactions pauses the automatic import from “${escapeHtml(folder)}”, so they stay cleared after a reload until you click Rebuild or Reload.`}
` : ''}`; - 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 = DataCleanup._planCount(key); - const also = (DataCleanup.PLAN_ALSO[key] || []).map(a => a[3]).join(' '); - const count = key === 'aiHistory' ? plural(len, 'entry', 'entries') : key === 'investAlloc' ? plural(len, 'fund', 'funds') : n(len); - return row(label, count, also, btn('clearPlan', 'Clear', key)); - }).join('')} -
`; - root.appendChild(plans); + /* ---- Clean up ---- */ + // [action, arg, title, what it does, button label, label once done, needs a stored folder handle] + const rows = [ + ['clearImported', '', 'Clear transactions and accounts', + paused ? `Automatic import from “${f}” is paused because you cleared your transactions. Rebuild, or Reload CSVs in Import, brings them back.` + : folder ? `Keeps your plans, edits and settings. “${f}” won't re-import its CSVs until you reload them.` : 'Keeps your plans, edits, account names, balances and settings.', + 'Clear', 'Cleared'], + ['clearImportLog', '', 'Clear import log', '…', 'Clear', 'Cleared'], + ['clearEdits', '', 'Clear transaction edits', + edits ? `${plural(edits, 'renamed, re-categorized or flagged transaction')} go${edits === 1 ? 'es' : ''} back to ${edits === 1 ? 'its' : 'their'} CSV values` : 'No edits yet', 'Clear', 'Cleared'], + ]; + if (folder) rows.push(['rebuildFromFolder', '', 'Rebuild from your folder', 'Re-reads every CSV from scratch. Plans and edits are kept.', 'Rebuild', 'Rebuilt', true]); + DataCleanup.PLAN_ITEMS.forEach(([key]) => { + const [title, what] = DataCleanup.PLAN_ROWS[key]; + const also = (DataCleanup.PLAN_ALSO[key] || []).map(a => a[3]).join(' '); + rows.push(['clearPlan', key, title, what(count(key)) + (also ? '. ' + also : ''), 'Clear', 'Cleared']); + }); + if (folder) rows.push(['disconnectFolder', '', 'Disconnect folder', 'Stops auto-reload and backups. Files on disk stay as they are.', 'Disconnect', 'Disconnected']); + appendHtml(root, `
+

Clean up

Each button asks you to click again to confirm.

+
${rows.map(([act, arg, title, desc, label, doneLabel, needsHandle]) => { + const isDone = done === act + '|' + arg; + return `
+
${title}
${desc}
+ +
`; + }).join('')}
+
`); - /* ---- 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); + /* ---- Export and import (JSON) ---- */ + appendHtml(root, `
+

Export and import

+

Download your plans, transaction edits, balances, categories and AI history as a JSON file, or load one you exported. Transactions and your API key aren't in it; your CSVs bring the transactions back.

+
+ +
+
`); /* ---- 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 and the payoff plan, forecast scenarios, your investment mix, 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); + appendHtml(root, `
+

Start over

+

Erases everything FinLens has stored in this browser, forgets the folder and reloads the app. Your CSV files are not touched.

+ ${folder ? `
Your backup file + + +
` : ''} +
+ + +
+
`); /* ---- wiring ---- */ root.querySelectorAll('[data-dc-action]').forEach(b => b.addEventListener('click', async () => { @@ -278,17 +285,25 @@ registerView('data-cleanup', 'Data & Reset', (root) => { // 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.classList.add('armed'); b.textContent = 'Click again to confirm'; - setTimeout(() => { if (b.isConnected && b.dataset.armed === '1') { b.dataset.armed = ''; b.textContent = b.dataset.dcLabel; } }, 4000); + setTimeout(() => { if (b.isConnected && b.dataset.armed === '1') { b.dataset.armed = ''; b.classList.remove('armed'); b.textContent = b.dataset.dcLabel; } }, 4000); return; } b.dataset.armed = ''; + b.classList.remove('armed'); b.disabled = true; b.textContent = 'Working…'; + DataCleanup.lastDone = b.dataset.dcAction + '|' + b.dataset.dcArg; 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)); } })); + $('#dcExport').onclick = () => exportAllData(); + const jf = $('#dcImportFile'); + $('#dcImport').onclick = () => jf.click(); + jf.onchange = (e) => { if (jf.files.length) importJsonFile(e); setTimeout(() => { jf.value = ''; }, 0); }; + const confirmInput = $('#dcResetConfirm'); const resetBtn = $('#dcResetBtn'); confirmInput.addEventListener('input', () => { resetBtn.disabled = confirmInput.value.trim() !== 'RESET'; }); @@ -303,10 +318,12 @@ registerView('data-cleanup', 'Data & Reset', (root) => { // 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')); + const text = { + transactions: c.transactions == null ? 'transactions: —' : plural(c.transactions, 'transaction'), + accounts: c.accounts == null ? 'accounts: —' : plural(c.accounts, 'account'), + import_log: c.import_log == null ? 'import log: —' : plural(c.import_log, 'import log entry', 'import log entries'), + }; + $$('[data-count]').forEach(el => { el.textContent = text[el.dataset.count] || '—'; }); // 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-data.js b/js/views-data.js index 013e92a..55af0df 100644 --- a/js/views-data.js +++ b/js/views-data.js @@ -1,6 +1,10 @@ /* ================================================================ FINLENS — views-data.js - Database > Import subtab — file loading, account management, manual balances + Settings tabs Import, Accounts, Credit cards and Categories (Clarity, + v1.16.0), the CSV folder (pick, reload, reconnect, save now), the sync + badge and folder banner, sample data, and the Import Logs view. + Shared pieces (pageActions, appendHtml, wireLinks, ICON, plural …) are in + views-main.js; meterHtml() is in views-plan.js. ================================================================ */ /* ---------- pending file handling ---------- */ @@ -13,184 +17,227 @@ let _importLogCache = []; // cached import log (refreshed on view render) let _coverageCache = {}; // cached coverage (refreshed on view render) let _saveNowMsg = null; // { kind, text } — result of the last Save Now click let _folderBannerMsg = null; // { kind, text } — result of the last Reconnect click +let _settingsMsg = null; // { tab, kind, text } — a Settings tab's one-time status line +let _importLogShowAll = false; + +const ICON_FOLDER=_svg('',22); +const ICON_UP=_svg(''); +const ICON_DOWN=_svg(''); +// How a CSV file can be read ("Read as"): the import kinds, as words. +const READ_AS=[['bank_checking','Checking'],['bank_savings','Savings'],['credit_card','Credit card'],['other','Other CSV']]; +// The three synthetic files in samples/ (fake data) behind "Try it with sample data". +const SAMPLE_FILES=['checking_sample.csv','savings_sample.csv','credit_card_sample.csv']; + +// "Today, 2:01 PM", "Yesterday, 9:12 AM", "Oct 21, 9:12 AM"; '' for no date. +function whenText(d) { + if (!d) return ''; + const x=dayjs(d), t=dayjs(); + if (x.isSame(t,'day')) return 'Today, '+x.format('h:mm A'); + if (x.isSame(t.subtract(1,'day'),'day')) return 'Yesterday, '+x.format('h:mm A'); + return x.format(x.year()===t.year()?'MMM D, h:mm A':'MMM D, YYYY'); +} +// "May 1 – Oct 18" (the year once, at the end, when it isn't this year) +function spanText(a, b) { + if (!a||!b) return '—'; + const y=dayjs(b).year()!==dayjs().year()?', '+dayjs(b).year():''; + return `${dayjs(a).format('MMM D')} – ${dayjs(b).format('MMM D')}${y}`; +} +// A Settings tab's status line: shown once, after the action that set it. +function takeSettingsMsg(tab) { + const m=_settingsMsg&&_settingsMsg.tab===tab?_settingsMsg:null; + if (m) _settingsMsg=null; + return m; +} +function statusLine(id, m) { + return `

${m?escapeHtml(m.text):''}

`; +} +// Money typed in a field: "1,284.50", "$1284.5" → 1284.5; '' → null; anything else → NaN. +function parseMoneyInput(raw) { + const s=String(raw||'').replace(/[$,\s]/g,''); + if (s==='') return null; + return /^-?\d*\.?\d+$/.test(s)?parseFloat(s):NaN; +} +// Files FinLens has imported, one per account that came from a CSV. +function importedFiles() { + return orderedAccounts().filter(a=>a.sourceFile&&a.sourceFile!=='manual').map(a=>{ + const own=State.transactions.filter(t=>t.account===a.id); + const r=accountDateRange(a.id); + return { name:a.sourceFile, acct:a, rows:own.length, min:r.min, max:r.max }; + }); +} +function readAsOptions(sel, extra) { + return READ_AS.concat(extra||[]).map(([k,l])=>``).join(''); +} +/* =================== SETTINGS → IMPORT =================== */ registerView('import','Import',(root)=>{ - - /* ---- File Loader ---- */ - const fl=document.createElement('div'); fl.className='card'; - const hasSavedFolder=!!State.lastFolderName; - const needsReconnect=!!State._csvNeedsReconnect; - fl.innerHTML=` -

Data Source

- ${hasSavedFolder - ? `
-
-
📁 ${escapeHtml(State.lastFolderName)}
-
${State.transactions.length?'✓ '+State.transactions.length+' transactions loaded':(State.csvAutoImportPaused?(needsReconnect||State._folderNeedsAccess?'Transactions cleared — automatic import is paused. Reconnect turns backups back on without re-importing.':'Transactions cleared — automatic import is paused. Click Reload to import again.'):(needsReconnect?'⚠ Permission needed — click Reconnect':'No data loaded yet'))}
-
- ${needsReconnect||State._folderNeedsAccess - ? `` - : ``} - -
` - : `

Pick your .CSV files and assign each one to an account before importing.

-
- - -
`} -
- ${hasSavedFolder?``:''} -
- ${State.lastRefresh?`
Last refresh: ${dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A')}
`:''}`; - root.appendChild(fl); - - /* ---- Auto-Backup Status ---- */ - const backupCard=document.createElement('div'); backupCard.className='card'; - const hasBackupFolder=!!State.lastFolderName; // Uses same folder as CSV files - const lastSync=State.lastFsyncTime?dayjs(State.lastFsyncTime).format('MMM D, YYYY h:mm A'):'Never'; - const paused=!!State._folderNeedsAccess; - const saveMsg=_saveNowMsg; _saveNowMsg=null; // shown once, after the click that produced it - backupCard.innerHTML=` -

📦 Auto-Backup to Disk

-

Your dashboard state is automatically saved to finlens-state.json in your folder every 5 seconds (when you make changes). This survives browser cache clearing.

- ${hasBackupFolder - ? `
-
${paused?'⚠ Backup paused — FinLens needs permission to write to this folder again':'✓ Backup enabled'}
-
Folder: ${escapeHtml(State.lastFolderName)}
-
Last saved: ${lastSync}
-
-
- -
- ${saveMsg?`
${escapeHtml(saveMsg.text)}
`:''}` - : `
-
⚠ Backup disabled
-
Pick a folder above (under "Data Source") to enable automatic backups.
-
`} - `; - root.appendChild(backupCard); - const saveNowBtn=backupCard.querySelector('#saveNowBtn'); - if (saveNowBtn) saveNowBtn.onclick=saveNowClick; - - /* ---- Pending file assignment ---- */ - if (pendingFileObjects.length) { - const assignCard=document.createElement('div'); assignCard.className='card'; - assignCard.innerHTML=` -

Assign Files to Accounts

-

Select the account type for each file, then click Import.

-
-
- - -
`; - root.appendChild(assignCard); - renderFileAssignList(); - } - - /* ---- Loaded Files (with rename) ---- */ - if (State.fileMeta&&State.fileMeta.length) { - const loadedCard=document.createElement('div'); loadedCard.className='card'; - loadedCard.innerHTML=` -

- Loaded Files - -

-

Rename any dataset — the new name appears everywhere in the dashboard.

-
-
- + wireLinks(root); + const folder=State.lastFolderName; + const linked=!!State._folderLinked; + const needs=!!(State._csvNeedsReconnect||State._folderNeedsAccess); + const files=importedFiles(); + + /* ---- the folder ---- */ + const saveMsg=_saveNowMsg; _saveNowMsg=null; // shown once, after the click that produced it + const paused=State.csvAutoImportPaused&&!State.transactions.length; + if (folder) { + const pill=!linked?'Not connected' + :needs?'Needs your permission' + :'Read and write access'; + const sub=linked?`${plural(files.length,'CSV file')} · backup file finlens-state.json` + :`${plural(files.length,'CSV file')} · chosen with the file picker, so FinLens can't save to it`; + const acts=!linked + ?`` + :needs + ?`` + :``; + const okMsg=saveMsg&&saveMsg.kind==='good'; + appendHtml(root,`
+
+ ${ICON_FOLDER} +

${escapeHtml(folder)}

${sub}

+ ${pill}
-
${State.fileMeta.length} file${State.fileMeta.length!==1?'s':''} loaded · ${State.transactions.length.toLocaleString()} transactions
`; - root.appendChild(loadedCard); - renderFileMetaList(); - } - - /* ---- Add Account ---- */ - const addCard=document.createElement('div'); addCard.className='card'; - addCard.innerHTML=` -

Add Manual Account

-

Add an account without a CSV file (e.g., a brokerage, cash on hand).

-
-
-
- - + ${needs&&linked?'

Your browser asks again after it has been closed. Changes are kept in this browser until you reconnect.

':''} + ${paused?`
${ICON_ALERT}You cleared your transactions, so automatic import from this folder is paused. ${linked&&!needs?'Click Reload CSVs to import again.':'Reconnect, then reload to import again.'}
`:''} +
+
CSVs last read${State.lastRefresh?whenText(State.lastRefresh):'Not since this page opened'}
+
Backup last saved${!linked?'Off':State.lastFsyncTime?whenText(State.lastFsyncTime):'Not since this page opened'}
+
Auto-save${linked&&!needs?'5 seconds after a change':'Paused'}
-
- +
${acts} +

${saveMsg?(okMsg?'✓ ':'')+escapeHtml(saveMsg.text):''}

+
`); + } else { + appendHtml(root,`
+
+ ${ICON_FOLDER} +

No folder connected

Pick the folder that holds your CSV exports. FinLens reads them and saves your plans and edits there as finlens-state.json, so clearing the browser loses nothing.

-
`; - root.appendChild(addCard); +
+
+ `); + } + const on=(id,fn)=>{ const b=$('#'+id,root); if (b) b.onclick=fn; }; + on('saveNowBtn',saveNowClick); + on('impReload',()=>reloadDataFiles()); + on('impChange',()=>pickDataFolder()); + on('impPick',()=>pickDataFolder()); + on('impChoose2',()=>$('#filePick').click()); + $$('[data-reconnect-btn]',root).forEach(b=>b.onclick=reconnectFolderClick); + + /* ---- files waiting for "Read as" (picked with the file chooser) ---- */ + if (pendingFileObjects.length) { + const n=pendingFileObjects.length; + appendHtml(root,`
+

Choose how to read ${n===1?'this file':'these files'}

FinLens guessed from the file names. Change any that are wrong, then import.

+
+ + ${pendingFileObjects.map((f,i)=>{ + const saved=State.fileAssignments[f.name]||guessKind(f.name); + return ` + `; + }).join('')}
FileRead as
${escapeHtml(f.name)}
+
+
`); + on('impAssign',()=>importAssignedFiles()); + on('impCancel',()=>{ pendingFileObjects=[]; renderActive(); }); + } - /* ---- Post-Upload Result card (shown after each import) ---- */ + /* ---- the last import's results ---- */ if (_lastImportResults.length) { - const resCard=document.createElement('div'); resCard.className='card'; - resCard.innerHTML=`

Last Import Results

`; - root.appendChild(resCard); - const body=resCard.querySelector('#importResultsBody'); - body.innerHTML=_lastImportResults.map(r=>{ - const ir=r.importResult; - if (!ir) return `
- 📄 ${escapeHtml(r.filename)} — imported (DB not ready for stats)
`; - const fmtD=d=>d?dayjs(d).format('MMM D, YYYY'):'—'; - const coverage=_coverageCache[r.accountId]; - const gapHtml=ir.gapWarning?` -
- ⚠️ Gap detected: no data for ${fmtD(ir.gapWarning.from)} → ${fmtD(ir.gapWarning.to)}. - Upload a file covering this period to fill it. -
`:''; - const nextUpload=ir.dateRangeMax?dayjs(ir.dateRangeMax).add(1,'day').format('MMM D, YYYY'):'—'; - return `
-
✓ ${escapeHtml(r.account)}
-
📄 ${escapeHtml(r.filename)}
-
- ${ir.inserted.toLocaleString()} new transaction${ir.inserted!==1?'s':''} imported - · ${ir.skipped.toLocaleString()} duplicate${ir.skipped!==1?'s':''} skipped - ${ir.removed?`· ${ir.removed.toLocaleString()} leftover duplicate cop${ir.removed!==1?'ies':'y'} removed`:''} -
-
File covered: ${fmtD(ir.dateRangeMin)} → ${fmtD(ir.dateRangeMax)}
- ${coverage?`
Total in DB: ${fmtD(coverage.min)} → ${fmtD(coverage.max)} (${coverage.count.toLocaleString()} transactions)
`:''} -
Next upload: start from ${nextUpload}
- ${gapHtml} -
`; - }).join(''); + const fmtD=d=>d?dayjs(d).format('MMM D, YYYY'):'—'; + appendHtml(root,`
+

Last import

${State.lastRefresh?`${escapeHtml(whenText(State.lastRefresh))}`:''}
+
${_lastImportResults.map(r=>{ + const ir=r.importResult; + if (!ir) return `
${escapeHtml(r.account)}${escapeHtml(r.filename)} · imported (the browser database wasn't ready, so no counts)
`; + const cov=_coverageCache[r.accountId]; + const next=ir.dateRangeMax?dayjs(ir.dateRangeMax).add(1,'day').format('MMM D, YYYY'):'—'; + return `
${escapeHtml(r.account)} + ${escapeHtml(r.filename)} · covers ${fmtD(ir.dateRangeMin)} – ${fmtD(ir.dateRangeMax)}${cov?` · ${cov.count.toLocaleString()} in FinLens`:''} · start the next export on ${next}
+ ${ir.inserted.toLocaleString()} new · ${ir.skipped.toLocaleString()} already imported${ir.removed?` · ${ir.removed.toLocaleString()} leftover duplicate cop${ir.removed!==1?'ies':'y'} removed`:''} + ${ir.gapWarning?callout('warn',`No data for ${fmtD(ir.gapWarning.from)} – ${fmtD(ir.gapWarning.to)}. Import a file that covers those dates to fill the gap.`):''}
`; + }).join('')}
+
`); } - /* ---- Import Log card (collapsible history) ---- */ - const logCard=document.createElement('div'); logCard.className='card'; - logCard.innerHTML=` -

- Import Log - ▶ Show -

- `; - root.appendChild(logCard); - const logToggle=logCard.querySelector('#importLogToggle'); - const logBody=logCard.querySelector('#importLogBody'); - const logChev=logCard.querySelector('#importLogChevron'); - logToggle.onclick=async()=>{ - if (logBody.style.display==='none') { - logBody.style.display='block'; - logChev.textContent='▼ Hide'; - if (typeof DB!=='undefined'&&DB._db) { - _importLogCache=await DB.getImportLog(); - renderImportLog(logBody); - } else { - logBody.innerHTML='
IndexedDB not available.
'; - } - } else { - logBody.style.display='none'; - logChev.textContent='▶ Show'; - } - }; + /* ---- files in the folder ---- */ + if (files.length) { + const m=takeSettingsMsg('import'); + appendHtml(root,`
+

${linked?'Files in the folder':'Imported files'}

FinLens works out each account from the filename and columns. Change it if it guessed wrong.

+
+ + ${files.map(f=>{ + const sel=State.fileAssignments[f.name]||(f.acct.kind==='unknown'?'other':f.acct.kind); + return ` + + `; + }).join('')}
FileRead asRowsDates
${escapeHtml(f.name)}
${spanText(f.min,f.max)}
${f.rows.toLocaleString()}${spanText(f.min,f.max)}
+ ${statusLine('readAsMsg',m)} +
`); + $$('[data-read-as]',root).forEach(s=>s.onchange=()=>{ + const name=s.dataset.readAs; + State.fileAssignments[name]=s.value; + lsSet('fileAssignments',State.fileAssignments); + const label=(READ_AS.find(r=>r[0]===s.value)||[])[1]||s.value; + const msg=$('#readAsMsg'); + if (msg) { msg.className='status-line good'; msg.textContent=`Saved. FinLens reads ${name} as ${label} from the next reload. To re-read the rows already imported, use Rebuild in Data & reset.`; } + }); + } + + /* ---- import log (fills in from IndexedDB after the render) ---- */ + appendHtml(root,`
+

Import log

+

Loading…

+
`); + // As in #18's fix for Import Logs: look the element up again after the database read, + // and stop if the view was left in the meantime. + setTimeout(async()=>{ + if (!$('#impLog')) return; + const log=(typeof DB!=='undefined'&&DB._db)?await DB.getImportLog():null; + const el=$('#impLog'); + if (!el) return; + if (log) _importLogCache=log; + renderImportLogList(el, log); + const lr=$('#impLastRead'); + if (lr&&!State.lastRefresh&&log&&log.length) lr.textContent=whenText(log[0].timestamp); + },0); + + /* ---- Safari and Firefox ---- */ + appendHtml(root,`
+

Using Safari or Firefox?

+

These browsers can't keep a folder connected. Choose your CSV files each time you have new exports; your data stays saved in the browser between visits.

+ +
`); + on('impChoose',()=>$('#filePick').click()); }); +// Settings → Import → Import log: one line per import (files imported together are one +// line), newest first. `log` is DB.getImportLog() (null when IndexedDB isn't available). +function renderImportLogList(el, log) { + if (!log) { el.innerHTML='

The browser database isn\'t available, so there is no log.

'; return; } + if (!log.length) { el.innerHTML='

No imports yet.

'; return; } + const groups=[]; + for (const e of log) { + const g=groups[groups.length-1]; + const t=new Date(e.timestamp).getTime(); + if (g&&Math.abs(g.t-t)<10000) g.items.push(e); else groups.push({ t, items:[e] }); + } + const shown=_importLogShowAll?groups:groups.slice(0,8); + el.innerHTML=shown.map(g=>{ + const sum=(k)=>g.items.reduce((s,e)=>s+(e[k]||0),0); + const names=g.items.map(e=>e.filename||'').reverse(); + const what=g.items.length===1?`${escapeHtml(names[0])}`:`${plural(g.items.length,'file')}`; + const removed=sum('rowsRemoved'); + return `
${escapeHtml(whenText(g.t))}${what} + ${sum('rowsInserted').toLocaleString()} new · ${sum('rowsSkipped').toLocaleString()} already imported${removed?` · ${removed.toLocaleString()} duplicates removed`:''}
`; + }).join('')+(groups.length>8?``:''); + const all=el.querySelector('#impLogAll'); + if (all) all.onclick=()=>{ _importLogShowAll=!_importLogShowAll; renderImportLogList(el, log); const b=el.querySelector('#impLogAll'); if (b) b.focus(); }; +} + /* ---- Render import log table ---- */ function renderImportLog(container) { if (!_importLogCache.length) { @@ -219,42 +266,12 @@ function renderImportLog(container) {
`; } -/* ---- Render loaded file list with editable name inputs + reorder buttons ---- */ -function renderFileMetaList() { - const el=$('#fileMetaList'); if (!el) return; - // Show files in account display order so drag matches what the user sees in Overview - const ordered=orderedAccounts() - .map(a=>State.fileMeta.find(f=>f.name===a.sourceFile||f.account===a.name)) - .filter(Boolean); - // Append any fileMeta entries not yet matched (manual accounts, etc.) - State.fileMeta.forEach(f=>{ if (!ordered.includes(f)) ordered.push(f); }); - - el.innerHTML=ordered.map((f,i)=>{ - const acct=Object.values(State.accounts).find(a=>a.sourceFile===f.name||a.name===f.account); - const acctId=acct?.id||''; - const origIdx=State.fileMeta.indexOf(f); - return ` -
-
- - -
-
- - -
-
- 📄 ${escapeHtml(f.name)} - ${f.rows} rows${f.dateRange?' · '+dayjs(f.dateRange[0]).format('MMM D YYYY')+' → '+dayjs(f.dateRange[1]).format('MMM D YYYY'):''} -
-
`; - }).join(''); -} - /* ---- Move an account up (-1) or down (+1) in the display order ---- */ +// Works from the order as shown, so accounts missing from State.accountOrder (loaded from +// the browser database) move too. function moveAccount(accountId, direction) { if (!accountId) return; - const order=[...State.accountOrder]; + const order=orderedAccounts().map(a=>a.id); const idx=order.indexOf(accountId); if (idx===-1) return; const newIdx=idx+direction; @@ -262,64 +279,97 @@ function moveAccount(accountId, direction) { [order[idx],order[newIdx]]=[order[newIdx],order[idx]]; State.accountOrder=order; lsSet('accountOrder',order); + buildAccountFilter(); renderActive(); } -function saveDatasetNames() { - State.fileMeta.forEach((f,i)=>{ - const input=$(`#fname_${i}`); - if (!input) return; - const newName=input.value.trim()||f.account; - const oldName=f.account; - if (newName===oldName) return; - // Update fileMeta display name - f.account=newName; - // Update the account object name that matches this file - const acct=Object.values(State.accounts).find(a=>a.sourceFile===f.name||a.name===oldName); - if (acct) { - acct.name=newName; - // Persist via accountLabels so the name survives future CSV reloads - if (!State.accountLabels) State.accountLabels={}; - State.accountLabels[acct.id]=newName; - } - }); - lsSet('accountLabels', State.accountLabels); +/* ---- Account and card fields (Settings → Accounts, Credit cards): saved as you leave each one ---- */ +// The name you type is kept in State.accountLabels, which wins over the CSV's default +// name everywhere (as renaming on the Overview does). An empty name goes back to it. +function setAccountName(id, raw) { + const a=State.accounts[id]; if (!a) return ''; + const name=String(raw||'').trim(); + if (!State.accountLabels) State.accountLabels={}; + if (name) State.accountLabels[id]=name; else delete State.accountLabels[id]; + a.name=name||a.name; + lsSet('accountLabels',State.accountLabels); buildAccountFilter(); - alert('Dataset names saved.'); - renderActive(); + return acctName(id); } - -/* ---- Save all balance inputs at once (no per-keystroke re-render) ---- */ -function saveAccountBalances() { - $$('[data-acct][data-field]').forEach(input=>{ - const id=input.dataset.acct; - const field=input.dataset.field; - const raw=input.value.trim(); - const val=raw===''?null:parseFloat(raw); - if (field==='balance') State.manualBalances[id]=val; - else if (field==='initial') State.manualBalances[id+'_initial']=val; - else if (field==='limit') State.manualBalances[id+'_limit']=val==null?'':val; - }); +// field: 'balance' (State.manualBalances[id]: today's balance; for a card, what you owe), +// 'initial' (the starting balance before the first transaction) or 'limit' (a card's credit +// limit). Returns false when the value isn't a number. +function setAccountMoney(id, field, raw) { + const v=parseMoneyInput(raw); + if (Number.isNaN(v)) return false; + const key=field==='balance'?id:field==='initial'?id+'_initial':id+'_limit'; + if (field==='limit') State.manualBalances[key]=v==null?'':Math.max(0,v); + else State.manualBalances[key]=v; lsSet('manualBalances',State.manualBalances); - alert('Account balances saved.'); - renderActive(); + return true; +} +// A card's APR (%) or payment due day. A debt linked to the card (Debt tracker) holds +// its own, so it's updated too; State.cardDetails keeps them for a card with no debt yet. +function setCardDetail(id, field, raw) { + const s=String(raw||'').trim().replace('%',''); + let v=null; + if (s!=='') { + v=Number(s); + if (!Number.isFinite(v)) return false; + if (field==='apr' && (v<0||v>100)) return false; + if (field==='dueDay') { if (!Number.isInteger(v)||v<1||v>31) return false; } + } + State.cardDetails=State.cardDetails||{}; + const cd=State.cardDetails[id]={ ...(State.cardDetails[id]||{}), [field]:v }; + lsSet('cardDetails',State.cardDetails); + const debt=(State.debts||[]).find(d=>d.account===id); + if (debt) { + if (field==='apr') debt.apr=v==null?0:v; else if (v!=null) debt.dueDay=v; + lsSet('debts',State.debts); + } + return cd; +} +// What the Credit cards tab shows: the linked debt's values first. +function cardDetail(id, field) { + const debt=(State.debts||[]).find(d=>d.account===id); + if (debt&&debt[field]!=null&&debt[field]!=='') return debt[field]; + const cd=(State.cardDetails||{})[id]||{}; + return cd[field]??''; } -/* ---- File assign list ---- */ -function renderFileAssignList() { - const el=$('#fileAssignList'); if (!el) return; - el.innerHTML=pendingFileObjects.map((f,i)=>{ - const saved=State.fileAssignments[f.name]||guessKind(f.name); - return `
-
📄 ${escapeHtml(f.name)}
- -
`; - }).join(''); +/* ---- Categories (Settings → Categories) ---- */ +// Always there: transactions fall back to Other, and transfers get Transfer in / out. +const FIXED_CATEGORIES=['Other','Transfer in','Transfer out']; +// Deleting a category moves its transactions to Other. The move is saved as a transaction +// edit (State.txOverrides), so it lasts across reloads; Clear transaction edits undoes it. +// Category rules that assigned it now assign Other. Returns { moved, rules }. +function deleteCategory(name) { + if (FIXED_CATEGORIES.includes(name)) return { moved:0, rules:0 }; + State.categories=State.categories.filter(c=>c!==name); + lsSet('categories',State.categories); + let moved=0; + for (const t of State.transactions) { + if (!t.categories.includes(name)) continue; + const next=[...new Set(t.categories.map(c=>c===name?'Other':c))]; + const ov=State.txOverrides[t.id]||{}; + ov.categories=next; State.txOverrides[t.id]=ov; + t.categories=next; moved++; + } + if (moved) lsSet('txOverrides',State.txOverrides); + let rules=0; + (State.categoryRules||[]).forEach(r=>{ if (r.category===name) { r.category='Other'; rules++; } }); + if (rules) lsSet('catRules',State.categoryRules); + return { moved, rules }; +} +// Returns the name added, or '' when it's empty or already there (any capitalization). +function addCategory(raw) { + const val=String(raw||'').trim(); + if (!val) return ''; + const known=[...State.categories, ...State.transactions.flatMap(t=>t.categories)]; + if (known.some(c=>c.toLowerCase()===val.toLowerCase())) return ''; + State.categories.push(val); + lsSet('categories',State.categories); + return val; } function guessKind(filename) { @@ -493,37 +543,45 @@ async function saveNowClick() { const name = State.lastFolderName || 'your folder'; _saveNowMsg = { saved: { kind:'good', text:`Saved to finlens-state.json in “${name}” at ${dayjs().format('h:mm A')}.` }, - 'no-folder':{ kind:'warn', text:'Not saved: no folder is connected. Pick one under Data Source first.' }, - denied: { kind:'bad', text:`Not saved: FinLens doesn't have permission to write to “${name}”. Click Save Now again and choose Allow. If no prompt appears, file access for this site is blocked in your browser's site settings.` }, + 'no-folder':{ kind:'warn', text:'Not saved: no folder is connected. Pick a folder first.' }, + denied: { kind:'bad', text:`Not saved: FinLens doesn't have permission to write to “${name}”. Click Save now again and choose Allow. If no prompt appears, file access for this site is blocked in your browser's site settings.` }, error: { kind:'bad', text:`Not saved: ${State._lastSaveError || 'unknown error'}.` }, }[r]; renderActive(); } // The banner above every view (#folderBanner in index.html). Shown while access to -// the stored folder has lapsed, and briefly after a Reconnect click with its result. +// the stored folder has lapsed, briefly after a Reconnect click with its result, and +// while the sample data is loaded (v1.16.0). function updateFolderBanner() { updateSyncBadge(); const el = $('#folderBanner'); if (!el) return; const msg = _folderBannerMsg; const needs = !!State._folderNeedsAccess; - if (!needs && !msg) { el.hidden = true; el.innerHTML = ''; return; } + const sample = !!State.sampleData && State.transactions.length > 0; + if (!needs && !msg && !sample) { el.hidden = true; el.innerHTML = ''; return; } const name = escapeHtml(State.lastFolderName || 'your folder'); const body = needs ? `Backups paused. FinLens needs your permission again to use “${name}”, so changes aren't being saved to finlens-state.json. Your data is safe in this browser.` : ''; const kind = msg ? msg.kind : 'warn'; el.hidden = false; - el.innerHTML = `
+ el.innerHTML = (needs || msg ? `
${msg ? escapeHtml(msg.text) : body}
${needs ? `` : ''} ${!needs ? `` : ''} -
`; +
` : '') + + (sample ? `
+
You're trying FinLens with sample data. These are made-up transactions from the samples folder. Importing your own files replaces them.
+ +
` : ''); const rb = el.querySelector('[data-reconnect-btn]'); if (rb) rb.onclick = reconnectFolderClick; const cb = el.querySelector('[data-banner-close]'); if (cb) cb.onclick = () => { _folderBannerMsg = null; updateFolderBanner(); }; + const sx = el.querySelector('[data-sample-exit]'); + if (sx) sx.onclick = () => DataCleanup.clearSampleData(); } // The sync badge in the app bar (#syncBadge). "Synced" while finlens-state.json in the @@ -560,14 +618,49 @@ function syncBadgeClick() { showView('settings'); } -function addManualAccount() { - const name=$('#newAcctName').value.trim(); - const kind=$('#newAcctKind').value; - if (!name){ alert('Account name required.'); return; } - const id='manual_'+name.toLowerCase().replace(/[^a-z0-9]+/g,'_'); - State.accounts[id]={id,name,kind,balance:null,limit:null,sourceFile:'manual'}; - alert(`Account "${name}" added.`); - renderActive(); +/* ---- Sample data: "Try it with sample data" on the Welcome ---- */ +// Imports the three synthetic CSVs in samples/ through the normal import (loadFiles), and +// sets State.sampleData so your own files replace them later instead of joining their +// accounts. Served over HTTP the files are fetched; opened as a file (file://) the browser +// won't allow that, so the file picker opens for you to choose them. +// Call it from a click handler (the picker needs the click). +async function loadSampleData(statusEl) { + const say=(t)=>{ if (statusEl) statusEl.textContent=t; }; + if (location.protocol==='file:') { + say('FinLens is open as a file, so your browser won\'t let it read the samples folder by itself. Choose the three CSV files in FinLens\'s samples folder.'); + $('#samplePick').click(); + return; + } + say('Loading the sample files…'); + try { + const files=await Promise.all(SAMPLE_FILES.map(async n=>{ + const res=await fetch('samples/'+n,{ cache:'no-store' }); + if (!res.ok) throw new Error(`samples/${n}: HTTP ${res.status}`); + return new File([await res.text()], n, { type:'text/csv' }); + })); + await importSampleFiles(files); + } catch(e) { + console.warn('[FinLens] sample data:', e.message); + say('Couldn\'t read the samples folder. Choose its three CSV files instead.'); + $('#samplePick').click(); + } +} +// The picker for samples (#samplePick in index.html): only the three sample files are read. +function handleSamplePick(fileList) { + const files=Array.from(fileList).filter(f=>SAMPLE_FILES.includes(f.name)); + if (!files.length) { alert('Those aren\'t the sample files. Choose checking_sample.csv, savings_sample.csv and credit_card_sample.csv in FinLens\'s samples folder.'); return; } + importSampleFiles(files); +} +async function importSampleFiles(files) { + State.sampleData=true; lsSet('sampleData',true); + const assignments={}; + files.forEach(f=>{ assignments[f.name]=guessKind(f.name); }); + await loadFiles(files, assignments, { sample:true }); + // the samples cover May–Oct 2026: show all of it + setRange('all'); + updateFolderBanner(); + showView('overview'); + window.scrollTo(0,0); } /* ---------- hook folder/file pickers ---------- */ @@ -587,135 +680,183 @@ function handleFilePick(fileList) { showView('settings'); } -/* ---- Database > Accounts subtab ---- */ -function _renderAccountsTable(root, title, kinds, emptyMsg) { - const card=document.createElement('div'); card.className='card'; - const BANK_KINDS=['bank_checking','bank_savings','unknown']; - const accts=Object.values(State.accounts).filter(a=>kinds.includes(a.kind)); +/* =================== SETTINGS → ACCOUNTS =================== */ +registerView('accounts','Accounts',(root)=>{ + wireLinks(root); + const accts=orderedAccounts(); if (!accts.length) { - card.innerHTML=`

${title}

${emptyMsg}

`; - root.appendChild(card); + appendHtml(root,`

Accounts

+

No accounts yet. Import your CSV files and each one becomes an account here.

`); return; } - const rows=accts.map(a=>{ - const range=accountDateRange(a.id); - const fmtD=d=>d?dayjs(d).format('MMM D, YYYY'):'—'; - const txCount=State.transactions.filter(t=>t.account===a.id).length; - const bal=State.manualBalances[a.id]; - return ` - ${escapeHtml(a.name)} - ${txCount.toLocaleString()} - ${fmtD(range.min)} - ${fmtD(range.max)} - ${bal!=null?fmt(bal):'—'} - `; - }).join(''); - card.innerHTML=` -

${title}

-
- - - ${rows} -
AccountTransactionsFirstLatestBalance
-
`; - root.appendChild(card); -} - -registerView('accounts','Accounts',(root)=>{ - _renderAccountsTable(root,'Bank Accounts',['bank_checking','bank_savings','unknown'],'No bank accounts loaded yet. Import CSV files in Settings → Import.'); - _renderAccountBalances(root); + const m=takeSettingsMsg('accounts'); + appendHtml(root,`
+

Accounts

Bank exports don't include a running balance, so FinLens adds your transactions to the starting balance you enter here. Use the arrows to set the display order.

+
${accts.map((a,i)=>{ + const id=escapeHtml(a.id), name=acctName(a.id), n=escapeHtml(name); + const own=State.transactions.filter(t=>t.account===a.id).length; + const r=accountDateRange(a.id); + const card=a.kind==='credit_card'; + const field=card?'balance':'initial'; + const val=State.manualBalances[card?a.id:a.id+'_initial']; + const label=card?'Balance owed today ($)':`Starting balance${r.min?', '+dayjs(r.min).subtract(1,'day').format('MMM D'):''} ($)`; + const cur=!card&&State.manualBalances[a.id]!=null&&State.manualBalances[a.id]!==''?Number(State.manualBalances[a.id]):null; + return `
+
+ + +
+ + +
${plural(own,'row')}${spanText(r.min,r.max)}
+ ${cur!=null?`

A current balance of ${fmt(cur)} is set for this account (Settings before v1.16.0), and it takes the place of the starting balance.

`:''} +
`; + }).join('')}
+ ${statusLine('acctMsg',m)} +
`); + const say=(kind,text)=>{ const el=$('#acctMsg'); if (el) { el.className='status-line '+kind; el.textContent=text; } }; + $$('[data-move]',root).forEach(b=>b.onclick=()=>{ + const id=b.dataset.move, dir=+b.dataset.dir; + moveAccount(id,dir); + // keep focus on the same arrow (or the other one at the ends) + const same=$(`[data-move="${CSS.escape(id)}"][data-dir="${dir}"]`), other=$(`[data-move="${CSS.escape(id)}"][data-dir="${-dir}"]`); + (same&&!same.disabled?same:other)?.focus(); + }); + $$('[data-acct-name]',root).forEach(inp=>inp.addEventListener('change',()=>{ + const shown=setAccountName(inp.dataset.acctName, inp.value); + inp.value=shown; + say('good',`Saved the name “${shown}”.`); + })); + $$('[data-acct-money]',root).forEach(inp=>inp.addEventListener('change',()=>{ + if (!setAccountMoney(inp.dataset.acctMoney, inp.dataset.field, inp.value)) { + inp.setAttribute('aria-invalid','true'); say('bad','Enter an amount such as 1500.00.'); return; + } + inp.removeAttribute('aria-invalid'); + say('good',`Saved the ${inp.dataset.field==='initial'?'starting balance':'balance'} for ${acctName(inp.dataset.acctMoney)}.`); + })); + $$('[data-clear-cur]',root).forEach(b=>b.onclick=()=>{ + const id=b.dataset.clearCur; + State.manualBalances[id]=null; lsSet('manualBalances',State.manualBalances); + _settingsMsg={ tab:'accounts', kind:'good', text:`${acctName(id)} now uses its starting balance plus its transactions.` }; + renderActive(); + }); }); -/* ---- Simplified Account Balances card (shown in Accounts tab) ---- */ -function _renderAccountBalances(root) { - const accts=Object.values(State.accounts); - if (!accts.length) return; - - const card=document.createElement('div'); card.className='card'; - card.innerHTML=` -

Account Balances

-

Set current balances and credit limits. Click Save when done.

-
-
- -
`; - root.appendChild(card); - - const list=card.querySelector('#acctBalList'); - accts.forEach(a=>{ - const isCard=a.kind==='credit_card'; - const row=document.createElement('div'); - row.style.cssText='display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius-sm)'; - row.innerHTML=` -
-
${escapeHtml(a.name)}
-
${a.kind.replace('_',' ')}
+/* =================== SETTINGS → CREDIT CARDS =================== */ +registerView('credit-cards','Credit cards',(root)=>{ + wireLinks(root); + const cards=orderedAccounts().filter(a=>a.kind==='credit_card'); + if (!cards.length) { + appendHtml(root,`

Credit cards

+

No credit cards yet. Put a card's CSV export in your folder, or choose it in Import, and it shows up here.

`); + return; + } + const bal=currentBalances(); + cards.forEach(a=>{ + const id=escapeHtml(a.id), name=acctName(a.id); + const own=State.transactions.filter(t=>t.account===a.id).length; + const manual=State.manualBalances[a.id]; + const lim=State.manualBalances[a.id+'_limit']; + const debt=(State.debts||[]).find(d=>d.account===a.id); + const v=(x)=>x==null||x===''?'':escapeHtml(String(x)); + appendHtml(root,`
+
+ ${ICON.card.replace('width="18" height="18"','width="22" height="22"')} +

${escapeHtml(name)}

From ${escapeHtml(a.sourceFile||'your CSV')} · ${plural(own,'transaction')}

-
- - +

Card exports don't include your balance. Enter it from your latest statement or your card's app.${manual==null||manual===''?` Until you do, FinLens uses your transactions: ${fmt(debtOf(bal[a.id]))}.`:''}

+
+ + + +
- ${isCard?` -
- - -
`:''}`; - list.appendChild(row); +
+ ${debt?`

APR and due day are shared with “${escapeHtml(debt.name)}” in the Debt tracker.

`:''} +

+
`); + }); + appendHtml(root,`

Have more than one card? Put each card's CSV in the folder. Each becomes its own card here.

`); + + // The bar under the fields follows the balance and limit as you type. + const drawUtil=(sec)=>{ + const id=sec.dataset.card; + const typed=parseMoneyInput($('[data-cc="balance"]',sec).value); + const owed=typed!=null&&!Number.isNaN(typed)?Math.abs(typed):debtOf(currentBalances()[id]); + const lim=parseMoneyInput($('[data-cc="limit"]',sec).value); + const el=$('[data-util]',sec); + if (!(lim>0)) { el.innerHTML='Add a credit limit to see how much of it you\'re using.'; return; } + const p=owed/lim*100; + el.innerHTML=`${meterHtml(p,'card',`${acctName(id)} credit used`,`${Math.round(p)}% of ${fmt0(lim)} used`,'lg')}${Math.round(p)}% of your limit used · ${fmt(owed)} of ${fmt0(lim)}`; + }; + $$('[data-card]',root).forEach(sec=>{ + drawUtil(sec); + const id=sec.dataset.card, msg=$('[data-cc-msg]',sec); + const say=(kind,text)=>{ msg.className='status-line '+kind; msg.textContent=text; }; + $$('[data-cc]',sec).forEach(inp=>{ + const f=inp.dataset.cc; + if (f==='balance'||f==='limit') inp.addEventListener('input',()=>drawUtil(sec)); + inp.addEventListener('change',()=>{ + const ok=f==='balance'||f==='limit'?setAccountMoney(id,f,inp.value):!!setCardDetail(id,f,inp.value); + if (!ok) { + inp.setAttribute('aria-invalid','true'); + say('bad',f==='dueDay'?'Enter a day from 1 to 31.':f==='apr'?'Enter an APR from 0 to 100.':'Enter an amount such as 1284.50.'); + return; + } + inp.removeAttribute('aria-invalid'); + drawUtil(sec); + say('good',`Saved the ${{balance:'balance',limit:'credit limit',apr:'APR',dueDay:'due day'}[f]}.`); + }); + }); }); -} - -registerView('credit-cards','Credit Cards',(root)=>{ - _renderAccountsTable(root,'Credit Cards',['credit_card'],'No credit card accounts loaded yet. Import a credit card CSV in Settings → Import.'); }); -/* ---- Database > Categories subtab ---- */ +/* =================== SETTINGS → CATEGORIES =================== */ registerView('categories','Categories',(root)=>{ - const card=document.createElement('div'); card.className='card'; - card.innerHTML=` -

Categories

-

Click × to remove a category. Add new ones below.

-
-
-
- -
`; - root.appendChild(card); - renderDbCategories(); + wireLinks(root); + const count={}; + State.transactions.forEach(t=>t.categories.forEach(c=>{ count[c]=(count[c]||0)+1; })); + // Your list, then categories your transactions use that aren't on it (from the card + // export's Category column, say), most used first; the fixed ones last. + const extra=Object.keys(count).filter(c=>!State.categories.includes(c)&&!FIXED_CATEGORIES.includes(c)).sort((a,b)=>count[b]-count[a]||a.localeCompare(b)); + const list=[...State.categories.filter(c=>!FIXED_CATEGORIES.includes(c)), ...extra, ...FIXED_CATEGORIES.filter(c=>State.categories.includes(c)||count[c])]; + const m=takeSettingsMsg('categories'); + appendHtml(root,`
+

Categories

The list used across Transactions, Spending and Budget. Matching rules live on the Spending page.

+
    ${list.map((c,i)=>`
  • ${escapeHtml(c)}${count[c]||0}${FIXED_CATEGORIES.includes(c) + ?'' + :``}
  • `).join('')}
+
+ + +
+

Deleting a category moves its transactions to Other. Other, Transfer in and Transfer out can't be deleted.

+ ${statusLine('catMsg',m)} +
`); + $$('[data-cat-del]',root).forEach(b=>b.onclick=()=>{ + const name=list[+b.dataset.catDel]; + const r=deleteCategory(name); + _settingsMsg={ tab:'categories', kind:'good', text:`Deleted “${name}”.`+(r.moved?` ${plural(r.moved,'transaction')} moved to Other.`:'')+(r.rules?` ${plural(r.rules,'rule')} now ${r.rules===1?'assigns':'assign'} Other.`:'') }; + renderActive(); + const next=$$('[data-cat-del]')[Math.min(+b.dataset.catDel, $$('[data-cat-del]').length-1)]; + (next||$('#newCatInput')).focus(); + }); + const add=()=>{ + const inp=$('#newCatInput'); + const v=addCategory(inp.value); + if (!v) { + inp.setAttribute('aria-invalid','true'); + const el=$('#catMsg'); el.className='status-line bad'; el.textContent=inp.value.trim()?`“${inp.value.trim()}” is already a category.`:'Type a name for the new category.'; + inp.focus(); return; + } + _settingsMsg={ tab:'categories', kind:'good', text:`Added “${v}”.` }; + renderActive(); + $('#newCatInput').focus(); + }; + $('#catAdd').onclick=add; + $('#newCatInput').addEventListener('keydown',e=>{ if (e.key==='Enter') { e.preventDefault(); add(); } }); }); -function renderDbCategories() { - const cont=$('#catChips'); if (!cont) return; - cont.innerHTML=State.categories.map((cat,i)=>` - - ${escapeHtml(cat)} - - `).join(''); -} - -function deleteCategory(i) { - State.categories.splice(i,1); - lsSet('categories', State.categories); - renderDbCategories(); -} - -function addCategory() { - const input=$('#newCatInput'); if (!input) return; - const val=input.value.trim(); - if (!val) return; - if (!State.categories.includes(val)) { - State.categories.push(val); - lsSet('categories', State.categories); - } - renderDbCategories(); - input.value=''; -} - /* ---- Database > Import Logs subtab ---- */ registerView('db-logs','Import Logs',(root)=>{ const card=document.createElement('div'); card.className='card'; diff --git a/js/views-main.js b/js/views-main.js index 276ed04..602ef7c 100644 --- a/js/views-main.js +++ b/js/views-main.js @@ -109,18 +109,7 @@ function rhythmOf(dates) { let nwPeriod='all'; // net worth chart: '1m' | '3m' | 'all' registerView('overview','Overview',(root)=>{ - if (!State.transactions.length) { - root.innerHTML=`
-

Welcome to FinLens 👋

-

Load the CSV exports from your bank to see your dashboard come alive.

-
- -
-

- Supported format: .CSV only — bank checking, bank savings, bank credit card -

`; - return; - } + if (!State.transactions.length) { renderWelcome(root); return; } wireLinks(root); wireTxOpeners(root); pageActions(root, escapeHtml(dayjs().format('dddd, MMMM D')), @@ -293,6 +282,44 @@ registerView('overview','Overview',(root)=>{ } }); +/* =================== WELCOME (no transactions yet, v1.16.0) =================== */ +// What the Overview shows with no transactions. On a true first run (nothing saved at all) +// the app bar shows only the brand, as in the mockup; once you have a folder, plans, AI +// history or a key, it keeps its menus so you can still reach them. +function isFirstRun() { + return !State.transactions.length && !State.lastFolderName && !State.apiKey + && !['budgets','bills','buckets','debts','aiHistory','scenarios'].some(k=>(State[k]||[]).length); +} +function renderWelcome(root) { + shellHero('Your money in one view, on your own computer', isFirstRun()); + const linked=!!(State._folderLinked&&State.lastFolderName); + const folderBtn=linked + ?`` + :``; + const step=(n,t,d)=>`
  • ${t}

    ${d}

  • `; + const feat=(icon,t,d)=>`
    ${_svg(icon,20)}
    ${t}
    ${d}
    `; + appendHtml(root,`
    +

    FinLens reads the CSV files your bank lets you download. Nothing is uploaded, and there's no account to create.

    +
    ${folderBtn}
    +

    Works best in Chrome, Edge, Arc or Brave. In Safari or Firefox you'll each time instead.

    +

    +
    +
      + ${step(1,'Download your CSVs','From your bank\'s website, export checking and savings transactions as CSV, and download each credit card\'s activity as CSV.')} + ${step(2,'Put them in one folder','Any folder works. Drop newer exports in later and FinLens adds only the new rows.')} + ${step(3,'Pick the folder','FinLens saves your budgets, bills and edits back to that folder as finlens-state.json, so clearing the browser loses nothing.')} +
    +
    + ${feat('','No bank login','FinLens never connects to your bank.')} + ${feat('','Stays on this computer','No server and no cloud sync.')} + ${feat('','AI is optional','It uses your own Anthropic key, and only sends a summary.')} +
    `); + // The existing import paths, each from its own click (the folder and file pickers need one). + $('#wcFolder').onclick=()=>linked?reloadDataFiles():pickDataFolder(); + $('#wcSample').onclick=()=>loadSampleData($('#wcStatus')); + $('#wcFiles').onclick=()=>$('#filePick').click(); +} + // One account card on the Overview: balance, a sparkline (cash) or utilization bar (card), // and where the balance comes from. function accountCardHtml(a, bal, seriesEnd, pairsAll) { diff --git a/js/views-plan.js b/js/views-plan.js index 461fcc1..0a2e998 100644 --- a/js/views-plan.js +++ b/js/views-plan.js @@ -2,7 +2,7 @@ FINLENS — views-plan.js The Plan screens (Clarity, v1.15.0): Budget, Savings buckets and Debt tracker. Investing ideas is in views-invest.js, Forecast in - views-forecast.js. Trends (below) is unchanged until its own redesign. + views-forecast.js. Trends (Clarity, v1.16.0) is at the end. Shared pieces (pageActions, kpiTiles, appendHtml, ICON, plural …) are in views-main.js; the forms and their helpers are in ui.js. ================================================================ */ @@ -391,87 +391,189 @@ function payoffPlanHtml(debts, extra, sel, total) {
    `; } -/* =================== TRENDS & INSIGHTS =================== */ -registerView('trends','Trends & Insights',(root)=>{ - if (!State.transactions.length){ root.innerHTML=emptyCard('Load data to see trends.'); return; } - const months=byMonth(State.transactions); - const now=new Date(); - const thisMonthStart=startOfMonth(now), thisMonthEnd=endOfMonth(now); - const lastMonthStart=startOfMonth(new Date(now.getFullYear(),now.getMonth()-1,1)); - const lastMonthEnd=endOfMonth(lastMonthStart); - const catThis=byCategory(State.transactions.filter(t=>t.date>=thisMonthStart&&t.date<=thisMonthEnd),'expense'); - const catLast=byCategory(State.transactions.filter(t=>t.date>=lastMonthStart&&t.date<=lastMonthEnd),'expense'); - const catLastMap=Object.fromEntries(catLast.map(c=>[c.category,c.amount])); - const catChanges=catThis.map(c=>({category:c.category,this:c.amount,last:catLastMap[c.category]||0,pctChange:catLastMap[c.category]?(c.amount-catLastMap[c.category])/catLastMap[c.category]:null})).sort((a,b)=>(b.this-b.last)-(a.this-a.last)); - - const incomeThisMo=months.find(m=>m.month===monthKey(now))?.income||0; - const incomeLastMo=months.find(m=>m.month===monthKey(lastMonthStart))?.income||0; - const incomeChange=incomeLastMo>0?(incomeThisMo-incomeLastMo)/incomeLastMo:null; - const incomes=months.map(m=>m.income).filter(x=>x>0); - const meanInc=incomes.reduce((s,x)=>s+x,0)/Math.max(1,incomes.length); - const stdInc=Math.sqrt(incomes.reduce((s,x)=>s+(x-meanInc)**2,0)/Math.max(1,incomes.length)); - const cov=meanInc>0?stdInc/meanInc:0; - const stability=cov<0.1?'Very stable':cov<0.25?'Stable':cov<0.5?'Variable':'Highly variable'; - const savingsRates=months.map(m=>({month:m.month,rate:m.income>0?(m.income-m.expense)/m.income:0})); - const rollingSpending=months.map((m,i)=>{ const slice=months.slice(Math.max(0,i-2),i+1); return {month:m.month,avg:slice.reduce((s,x)=>s+x.expense,0)/slice.length}; }); - const merchantFreq={}; - State.transactions.filter(t=>t.amount<0&&t.type!=='transfer').forEach(t=>{ const k=(t.description||'').replace(/\d+/g,'').trim().slice(0,30); merchantFreq[k]=(merchantFreq[k]||0)+1; }); - const topFreq=Object.entries(merchantFreq).sort((a,b)=>b[1]-a[1]).slice(0,10); - - const m=document.createElement('div'); m.className='grid grid-3'; - m.innerHTML=` -

    Income MoM

    ${incomeChange==null?'—':pct(incomeChange)}
    ${fmt(incomeThisMo)} vs ${fmt(incomeLastMo)}
    -

    Income Stability

    ${stability}
    CoV ${(cov*100).toFixed(0)}%
    -

    Savings Rate (curr mo)

    ${pct(savingsRates[savingsRates.length-1]?.rate||0)}
    `; - root.appendChild(m); - - const catCard=document.createElement('div'); catCard.className='card'; - catCard.innerHTML=`

    Category Spending: This Month vs Last

    - - ${catChanges.map(c=>{ const delta=c.this-c.last; const cls=delta>0?'amt-neg':'amt-pos'; return ``; }).join('')}
    CategoryThis MonthLast MonthΔ%
    ${c.category}${fmt(c.this)}${fmt(c.last)}${delta>0?'▲':'▼'} ${fmt(Math.abs(delta))}${c.pctChange==null?'—':pct(c.pctChange,0)}
    `; - root.appendChild(catCard); - - const chartsRow=document.createElement('div'); chartsRow.className='grid grid-2'; - chartsRow.innerHTML=` -

    3-Month Rolling Avg Spending

    -

    Savings Rate Trend

    `; - root.appendChild(chartsRow); - - const freqCard=document.createElement('div'); freqCard.className='card'; - freqCard.innerHTML=`

    Most Visited Merchants

    `; - root.appendChild(freqCard); - - const insights=generateInsights(catChanges,incomeChange,savingsRates,State.transactions); - const insightCard=document.createElement('div'); insightCard.className='card'; - insightCard.innerHTML=`

    Auto-Generated Insights

    -
    ${insights.map(ins=>`
    ${ins.text}
    `).join('')}
    `; - root.appendChild(insightCard); - - setTimeout(()=>{ - new Chart($('#trRoll'),{type:'line',data:{labels:rollingSpending.map(r=>r.month),datasets:[ - {label:'Monthly',data:months.map(m=>m.expense),borderColor:chartColor('--chart-neutral'),borderDash:[4,4],pointRadius:0,tension:.3,fill:false}, - {label:'3-mo Rolling',data:rollingSpending.map(r=>r.avg),borderColor:chartColor('--chart-out'),backgroundColor:chartColor('--chart-out',.12),fill:true,tension:.35,borderWidth:2} - ]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{boxWidth:10,font:{size:11}}}},scales:{y:{ticks:{callback:v=>'$'+v.toLocaleString()}}}}}); - new Chart($('#trSav'),{type:'line',data:{labels:savingsRates.map(r=>r.month),datasets:[{label:'Savings Rate',data:savingsRates.map(r=>r.rate*100),borderColor:chartColor('--chart-in'),backgroundColor:chartColor('--chart-in',.12),fill:true,tension:.35,borderWidth:2,pointRadius:3}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{y:{ticks:{callback:v=>v.toFixed(0)+'%'}}}}}); - new Chart($('#trFreq'),{type:'bar',data:{labels:topFreq.map(t=>t[0].slice(0,28)),datasets:[{label:'Visits',data:topFreq.map(t=>t[1]),backgroundColor:chartColor('--violet'),borderRadius:4}]},options:{responsive:true,maintainAspectRatio:false,indexAxis:'y',plugins:{legend:{display:false}}}}); - },0); +/* =================== TRENDS (Clarity, v1.16.0) =================== */ +// Always the latest six months with transactions, across every account: Trends ignores the +// date range (the shell hides its label) and the accounts filter. +registerView('trends','Trends',(root)=>{ + wireLinks(root); + const all=State.transactions; + if (!all.length) { + pageActions(root,'How your money has moved, month by month',''); + appendHtml(root,`

    No transactions imported yet. Import your CSV files to see your trends.

    `); + return; + } + const span=dataSpan(all); + const months=monthlyFlow(all).slice(-6).map(m=>({ ...m, saved:m.income-m.expense, rate:m.income>0?(m.income-m.expense)/m.income:null })); + const last=months[months.length-1]; + // The latest month is unfinished when the data stops before its last day. + const partial=span.last.getDate()!==endOfMonth(span.last).getDate(); + const mShort=(m)=>dayjs(m.date).format('MMM'), mLong=(m)=>dayjs(m.date).format('MMMM'); + const sameYear=dayjs(months[0].date).year()===dayjs(last.date).year(); + const period=`${dayjs(months[0].date).format(sameYear?'MMMM':'MMMM YYYY')} – ${dayjs(last.date).format('MMMM YYYY')}`; + pageActions(root,`How your money has moved, month by month · ${months.length>1?period:dayjs(last.date).format('MMMM YYYY')}`,''); + + /* ---- KPIs ---- */ + const avgSaved=months.reduce((s,m)=>s+m.saved,0)/months.length; + const rated=months.filter(m=>m.rate!=null); + const avgRate=rated.length?rated.reduce((s,m)=>s+m.rate,0)/rated.length:null; + // Fastest-growing: the category up the most (%) in the latest month on the one before, + // among categories with at least $25 in that month (so a $2 → $20 change doesn't win). + let growth=null; + if (months.length>1) { + const prev=Object.fromEntries(byCategory(months[months.length-2].txs,'expense').map(c=>[c.category,c.amount])); + byCategory(last.txs,'expense').forEach(c=>{ + const p=prev[c.category]; + if (!(p>=25)||c.amount<=p) return; + const g=(c.amount-p)/p; + if (!growth||g>growth.g) growth={ cat:c.category, g }; + }); + } + // Steadiest: the month with the lowest spending, leaving out an unfinished latest month. + const whole=months.length>1&&partial?months.slice(0,-1):months; + const low=whole.reduce((a,m)=>m.expense/mo`,sub:'Income minus spending'}, + {label:'Savings rate',value:avgRate==null?'—':pctStr(avgRate),sub:rated.length>1?`${rated.length}-month average`:'Income minus spending, as a share of income'}, + {label:'Fastest-growing category',value:growth?escapeHtml(growth.cat):'—',sub:growth?`${mLong(last)} up ${Math.round(growth.g*100)}% on ${mLong(months[months.length-2])}`:months.length>1?`No category grew in ${mLong(last)}`:'Needs two months of data'}, + {label:'Steadiest month',value:mLong(low),sub:`Lowest spending, ${fmt0(low.expense)}`}, + ])); + + /* ---- income, spending and savings ---- */ + const max=Math.max(1,...months.map(m=>Math.max(m.income,m.expense))); + const h=(v)=>(Math.max(0,v)/max*100).toFixed(1); + const best=months.reduce((a,m)=>m.saved>a.saved?m:a,months[0]), worst=months.reduce((a,m)=>m.savedm===last&&partial?` (through ${dayjs(span.last).format('MMM D')})`:''; + appendHtml(root,`
    +

    Income, spending and savings

    +
    IncomeSpendingSaved
    + +
    ${months.map(m=>`
    ${mShort(m)}
    ${fmtSigned0(m.saved)}
    `).join('')}
    +
    `); + + /* ---- savings rate + account balances ---- */ + const row=document.createElement('div'); row.className='cols-2'; + row.innerHTML=`
    +

    Savings rate

    +
    Monthly3-month average
    +
    +

    ${escapeHtml(rateStory(months, partial))}

    +
    +

    Account balances

    +
    ${trendAccountRows(months[0].date, span.last)}
    +
    `; + root.appendChild(row); + const holder=$('#trRate'); + holder.innerHTML=rateChartSvg(months, Math.max(300,Math.min(640,Math.round(holder.clientWidth||560)))); + + /* ---- top categories over time ---- */ + const totals={}; + months.forEach(m=>byCategory(m.txs,'expense').forEach(c=>{ totals[c.category]=(totals[c.category]||0)+c.amount; })); + const top=Object.entries(totals).sort((a,b)=>b[1]-a[1]).slice(0,6).map(([c])=>c); + if (top.length) { + const cell=months.map(m=>Object.fromEntries(byCategory(m.txs,'expense').map(c=>[c.category,c.amount]))); + appendHtml(root,`
    +

    Top categories over time

    Darker cells are that category's most expensive months
    +
    + ${months.map(m=>``).join('')} + ${top.map(c=>{ + const vals=cell.map(x=>x[c]||0), lo=Math.min(...vals), hi=Math.max(...vals); + return `${vals.map((v,i)=>{ + const lvl=hi===lo?2:Math.round((v-lo)/(hi-lo)*5); + return ``; + }).join('')}`; + }).join('')}
    Category${mShort(m)}${months.length}-mo total
    ${escapeHtml(c)}${fmt0(v)}${fmt0(totals[c])}
    +
    `); + } }); -function generateInsights(catChanges, incomeChange, savingsRates, allTxs) { - const out=[]; - const big=catChanges.find(c=>c.pctChange!=null&&Math.abs(c.pctChange)>0.3&&c.this>50); - if (big) { - if (big.pctChange>0) out.push({tone:'warn',text:`${big.category} up ${(big.pctChange*100).toFixed(0)}% vs last month — ${fmt(big.this-big.last)} more than usual.`}); - else out.push({tone:'',text:`${big.category} down ${(Math.abs(big.pctChange)*100).toFixed(0)}% vs last month — saved ${fmt(big.last-big.this)}.`}); +// The savings-rate chart: each month's rate and a 3-month average (dashed), as inline SVG +// colored by CSS classes (.lc-*). `w` is the width it's drawn at, so 11px labels stay 11px. +function rateChartSvg(months, w) { + const pts=months.map((m,i)=>{ + const win=months.slice(Math.max(0,i-2),i+1).filter(x=>x.rate!=null); + return { m, r:m.rate, avg:win.length?win.reduce((s,x)=>s+x.rate,0)/win.length:null }; + }); + const vals=pts.flatMap(p=>[p.r,p.avg]).filter(v=>v!=null).map(v=>Math.max(-1,Math.min(1,v))); + if (!vals.length) return '

    No income in these months, so there is no savings rate.

    '; + const step=niceStep(((Math.max(0,...vals)-Math.min(0,...vals))*100)/2||20); + const lo=Math.floor(Math.min(0,...vals)*100/step)*step, hi=Math.max(step,Math.ceil(Math.max(...vals)*100/step-1e-9)*step); + const h=210, L=44, R=16, T=22, B=28, pw=w-L-R, ph=h-T-B; + const X=i=>L+(pts.length<2?pw/2:i*pw/(pts.length-1)), Y=v=>T+(hi-v*100)/(hi-lo)*ph; + const o=[``]; + for (let v=lo; v<=hi+1e-9; v+=step) { + const y=Y(v/100).toFixed(1); + o.push(`${v}%`); } - const biggest=allTxs.filter(t=>t.amount<0&&t.type!=='transfer').sort((a,b)=>a.amount-b.amount)[0]; - if (biggest) out.push({tone:'',text:`Largest single expense: ${fmt(Math.abs(biggest.amount))} at ${escapeHtml(biggest.description)} on ${dayjs(biggest.date).format('MMM D')}.`}); - const recent=savingsRates.slice(-3).map(r=>r.rate); - if (recent.length===3&&recent.every(r=>r>0.2)) out.push({tone:'',text:`Strong savings discipline — savings rate above 20% for the last 3 months.`}); - if (recent.length&&recent[recent.length-1]<0) out.push({tone:'bad',text:`Negative cash flow in the most recent month — spending exceeded income.`}); - if (incomeChange!=null&&Math.abs(incomeChange)>0.1) out.push({tone:incomeChange>0?'':'warn',text:`Income ${incomeChange>0?'increased':'decreased'} ${pct(Math.abs(incomeChange))} vs last month.`}); - const recurring=detectRecurring().filter(r=>r.isSubscription); - if (recurring.length>5) out.push({tone:'warn',text:`You have ${recurring.length} active subscriptions — consider auditing for unused services.`}); - if (!out.length) out.push({tone:'',text:'Not enough data yet for personalized insights — check back after a few more weeks of transactions.'}); - return out; + const line=(key,cls)=>{ const seg=pts.map((p,i)=>p[key]==null?null:`${X(i).toFixed(1)},${Y(Math.max(-1,Math.min(1,p[key]))).toFixed(1)}`).filter(Boolean); return seg.length>1?``:''; }; + o.push(line('avg','lc-line avg'), line('r','lc-line')); + const withRate=pts.map((p,i)=>({p,i})).filter(x=>x.p.r!=null); + withRate.forEach(({p,i})=>o.push(`${dayjs(p.m.date).format('MMMM')}: ${pctStr(p.r)} (3-month average ${pctStr(p.avg)})`)); + // value labels on the first, the lowest and the last month + const lowest=withRate.reduce((a,x)=>x.p.r{ const y=Y(Math.max(-1,Math.min(1,p.r))); const below=p===lowest.p&&p!==withRate[0].p&&p!==withRate[withRate.length-1].p; + o.push(`${pctStr(p.r)}`); }); + pts.forEach((p,i)=>o.push(`${dayjs(p.m.date).format('MMM')}`)); + o.push(''); + return o.join(''); +} + +// A sentence under the savings-rate chart, from the numbers: the best and worst months, +// what pulled the worst one down, and where the latest month stands. +function rateStory(months, partial) { + const r=months.filter(m=>m.rate!=null); + if (r.length<2) return r.length?`${dayjs(r[0].date).format('MMMM')}'s savings rate is ${pctStr(r[0].rate)}.`:'No income in these months yet.'; + const name=m=>dayjs(m.date).format('MMMM'); + const hi=r.reduce((a,m)=>m.rate>a.rate?m:a,r[0]), lo=r.reduce((a,m)=>m.rates+m.rate,0)/r.length; + if (pctStr(hi.rate)===pctStr(lo.rate)) return `Your savings rate was ${pctStr(hi.rate)} every month.`; + const out=[`${name(hi)} had the highest rate (${pctStr(hi.rate)}) and ${name(lo)} the lowest (${pctStr(lo.rate)}).`]; + // the category furthest above its usual level in the lowest month + const others=r.filter(m=>m!==lo); + let push=null; + byCategory(lo.txs,'expense').forEach(c=>{ + const usual=others.reduce((s,m)=>s+(byCategory(m.txs,'expense').find(x=>x.category===c.category)?.amount||0),0)/others.length; + const over=c.amount-usual; + if (over>=50&&(!push||over>push.over)) push={ cat:c.category, amt:c.amount, usual, over }; + }); + if (push) out.push(`${push.cat} spending in ${name(lo)} (${fmt0(push.amt)}, against about ${fmt0(push.usual)} in other months) pulled it down.`); + if (last!==hi&&last!==lo) out.push(`${name(last)}${partial&&last===months[months.length-1]?' so far':''} is at ${pctStr(last.rate)}, ${pctStr(last.rate)===pctStr(avg)?'the same as':last.rate>avg?'above':'below'} the ${r.length}-month average of ${pctStr(avg)}.`); + return out.join(' '); +} + +// Trends → Account balances: one row per account with a sparkline from `from` to `to`, +// a line about how it moved, and its balance at `to` (balanceAt(), as the Overview cards). +function trendAccountRows(from, to) { + const accts=orderedAccounts(); + if (!accts.length) return '

    No accounts yet.

    '; + const end=new Date(to.getFullYear(),to.getMonth(),to.getDate(),23,59,59); + return accts.map(a=>{ + const own=State.transactions.filter(t=>t.account===a.id); + const card=a.kind==='credit_card'; + const first=own.length?Math.max(from.getTime(),dataSpan(own).first.getTime()):from.getTime(); + const vals=[]; + for (let i=0;i<24;i++) { const v=balanceAt(a.id,new Date(first+(end.getTime()-first)*i/23)); vals.push(card?debtOf(v):v); } + const now=vals[vals.length-1], start=vals[0]; + const lo=Math.min(...vals), hiV=Math.max(...vals), months=Math.max(1,(end.getTime()-first)/(30.44*DAY)); + let story; + if (card) { + const pays=own.filter(isCardPayment).map(t=>t.date); + const rh=rhythmOf(pays); + story=rh?`Paid down ${rh.charAt(0).toLowerCase()+rh.slice(1)}`.replace('Paid down monthly, around','Paid down around'):pays.length?`Last paid ${dayjs(pays.sort((x,y)=>y-x)[0]).format('MMM D')}`:'No payments yet'; + } else { + const per=(now-start)/months; + story=(hiV-lo)>2*Math.abs(now-start)&&(hiV-lo)>=200?`Swings between ${fmt0(lo)} and ${fmt0(hiV)}` + :Math.abs(per)<25?'About level':`${per>0?'Up':'Down'} about ${fmt0(Math.abs(per))} a month`; + } + const hue=card?'card':a.kind==='bank_savings'?'teal-text':'accent'; + const name=acctName(a.id); + return `
    +
    ${escapeHtml(name)}
    ${escapeHtml(story)}
    + ${sparkSvg(vals,hue,`${name} ${card?'amount owed':'balance'}, ${dayjs(first).format('MMM D')} to ${dayjs(end).format('MMM D')}: from ${fmt0(start)} to ${fmt0(now)}`)||''} + ${card?`${fmt(now)} owed`:fmt(now)} +
    `; + }).join(''); } diff --git a/js/views-settings.js b/js/views-settings.js index ab713c9..76ec5f0 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -1,7 +1,8 @@ /* ================================================================ FINLENS — views-settings.js - Settings shell (tab bar) + General tab: Display, Anthropic API Key. - Clearing data and starting over live in the Data & Reset tab (views-cleanup.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). ================================================================ */ let settingsTab='general'; @@ -10,100 +11,121 @@ const SETTINGS_TABS=[ ['general', 'General'], ['import', 'Import'], ['accounts', 'Accounts'], - ['credit-cards','Credit Cards'], + ['credit-cards','Credit cards'], ['categories','Categories'], - ['data-cleanup','Data & Reset'], + ['data-cleanup','Data & reset'], ]; registerView('settings','Settings',(root)=>{ + if (!SETTINGS_TABS.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])=> - `` + `` ).join(''); root.appendChild(tabBar); - tabBar.querySelectorAll('[data-tab]').forEach(btn=>btn.onclick=()=>{settingsTab=btn.dataset.tab;renderActive();}); + // Arrow keys, Home and End move between tabs (as on Forecast). + const pick=(k)=>{ settingsTab=k; renderActive(); const t=$(`#setTab-${k}`); if (t) t.focus(); }; + const tabs=$$('[role="tab"]',tabBar); + tabs.forEach((b,i)=>{ + b.onclick=()=>pick(b.dataset.tab); + b.onkeydown=(e)=>{ + const n=e.key==='ArrowRight'?i+1:e.key==='ArrowLeft'?i-1:e.key==='Home'?0:e.key==='End'?tabs.length-1:null; + if (n==null) return; + e.preventDefault(); pick(tabs[(n+tabs.length)%tabs.length].dataset.tab); + }; + }); - if (settingsTab==='general') _renderGeneralSettings(root); - else VIEWS[settingsTab].render(root); + const panel=document.createElement('div'); + panel.id='setPanel'; + panel.className='tab-panel'; + panel.setAttribute('role','tabpanel'); + panel.setAttribute('aria-labelledby',`setTab-${settingsTab}`); + root.appendChild(panel); + if (settingsTab==='general') _renderGeneralSettings(panel); + else VIEWS[settingsTab].render(panel); }); function _renderGeneralSettings(root) { /* ---- Display ---- */ - const displayCard=document.createElement('div'); displayCard.className='card'; - displayCard.innerHTML=` -

    Display

    -
    -
    -
    Theme
    -
    Light is the default. Dark is optional.
    -
    + appendHtml(root,`
    +

    Display

    +
    +
    Theme
    Light is the default. Dark is optional.
    ${[['light','Light'],['dark','Dark'],['system','Match system']].map(([v,l])=> - ``).join('')} -
    -
    -
    -
    - - + ``).join('')}
    -
    FinLens v1.15.0 · ${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
    `; - root.appendChild(displayCard); - displayCard.querySelectorAll('[data-theme-opt]').forEach(b=>b.addEventListener('click',()=>setTheme(b.dataset.themeOpt))); +
    VersionFinLens v1.16.0
    +
    `); + const opts=$$('[data-theme-opt]',root); + opts.forEach((b,i)=>{ + b.addEventListener('click',()=>{ setTheme(b.dataset.themeOpt); const f=$(`[data-theme-opt="${b.dataset.themeOpt}"]`); if (f) f.focus(); }); + // a radio group: arrow keys choose the next option + b.addEventListener('keydown',e=>{ + const n=e.key==='ArrowRight'||e.key==='ArrowDown'?i+1:e.key==='ArrowLeft'||e.key==='ArrowUp'?i-1:null; + if (n==null) return; + e.preventDefault(); + const next=opts[(n+opts.length)%opts.length].dataset.themeOpt; + setTheme(next); const f=$(`[data-theme-opt="${next}"]`); if (f) f.focus(); + }); + }); - /* ---- Anthropic API Key ---- */ + /* ---- Anthropic API key ---- */ // The key value is never rendered back into the DOM; only whether one is saved. - const keyCard=document.createElement('div'); keyCard.className='card'; - keyCard.innerHTML=` -

    Anthropic API Key

    -

    Powers the AI Analysis tab. Stored only in this browser (localStorage + IndexedDB) — never written to finlens-state.json. Get a key at console.anthropic.com.

    -
    - - - ${State.apiKey?'':''} + const has=!!State.apiKey; + const m=takeSettingsMsg('general'); + appendHtml(root,`
    +

    Anthropic API key

    ${has?'Key saved':'No key saved'}
    +

    Needed only for AI Analysis. The key is kept in this browser and is never written to finlens-state.json, exports or logs. Get one at console.anthropic.com.

    +
    + + + ${has?'':''}
    -
    ${State.apiKey?'Key saved in this browser':'No key saved'}
    `; - root.appendChild(keyCard); + ${statusLine('apiKeyMsg',m)} +
    `); $('#apiKeySave').addEventListener('click',saveApiKey); $('#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(); }); - - /* ---- 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(); }); + // Remove asks for a second click, like Data & reset (no confirm() dialog). + const rm=$('#apiKeyRemove'); + if (rm) rm.addEventListener('click',()=>{ + if (rm.dataset.armed!=='1') { + rm.dataset.armed='1'; rm.textContent='Click again to remove'; + setTimeout(()=>{ if (rm.isConnected&&rm.dataset.armed==='1') { rm.dataset.armed=''; rm.textContent='Remove'; } },4000); + return; + } + removeApiKey(); + }); } /* ---- API key (browser storage only — saveStateToFile() excludes it) ---- */ function saveApiKey() { - const v=($('#apiKeyInput')?.value||'').trim(); - if (!v) { alert('Paste your Anthropic API key first.'); return; } + const inp=$('#apiKeyInput'); + const v=(inp?.value||'').trim(); + if (!v) { + const el=$('#apiKeyMsg'); + if (el) { el.className='status-line bad'; el.textContent='Paste your Anthropic API key first.'; } + if (inp) { inp.setAttribute('aria-invalid','true'); inp.focus(); } + return; + } State.apiKey=v; lsSet('apiKey',v); + if (inp) inp.value=''; + _settingsMsg={ tab:'general', kind:'good', text:'Key saved in this browser. AI Analysis is ready.' }; renderActive(); } function removeApiKey() { State.apiKey=''; lsSet('apiKey',''); + _settingsMsg={ tab:'general', kind:'good', text:'Key removed from this browser.' }; renderActive(); } -function saveCurrency(val) { - lsSet('currency',val); - // TODO: future — convert currency symbol in formatters -} - /* Transfer keyword helpers (addTransferKeyword, removeTransferKeyword, reapplyTransferKeywords) live in views-main.js alongside the Transfers screen that owns the keyword editor. */ From ddc8a5fde9612cc50ec4d2f0429acf0d8f586535 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 06:49:08 +0000 Subject: [PATCH 2/4] Trends: tile legend wording works in dark mode In dark mode the most expensive months are the lightest tiles, so "Darker cells" was wrong there. "Stronger shades" is true in both themes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Z8iBXzUjiQbYziDZ8CZft --- js/views-plan.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/views-plan.js b/js/views-plan.js index 0a2e998..380065e 100644 --- a/js/views-plan.js +++ b/js/views-plan.js @@ -475,7 +475,7 @@ registerView('trends','Trends',(root)=>{ if (top.length) { const cell=months.map(m=>Object.fromEntries(byCategory(m.txs,'expense').map(c=>[c.category,c.amount]))); appendHtml(root,`
    -

    Top categories over time

    Darker cells are that category's most expensive months
    +

    Top categories over time

    Stronger shades are that category's most expensive months
    ${months.map(m=>``).join('')}${top.map(c=>{ From 70c7125524f8b59357253e8953957157524e6b74 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 10:51:06 +0000 Subject: [PATCH 3/4] Settings: keep the selected tab in view on a phone At 390px the tab bar scrolls sideways, and every render started it at the left, so Credit cards, Categories and Data & reset were selected but off-screen. Each render now scrolls the selected tab into view. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Z8iBXzUjiQbYziDZ8CZft --- CHANGELOG.md | 2 +- js/views-settings.js | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01d5240..72ec170 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,7 +36,7 @@ Always your latest six months with data, across every account. It ignores the da - **Dropped:** the alert-based copy confirmation (an inline status replaces it). ### Settings -- **Tabs** in the mockup's words (General · Import · Accounts · Credit cards · Categories · Data & reset), with `role="tab"`; arrow keys, Home and End move between them, as on Forecast. +- **Tabs** in the mockup's words (General · Import · Accounts · Credit cards · Categories · Data & reset), with `role="tab"`; arrow keys, Home and End move between them, as on Forecast. On a phone the tab bar scrolls sideways, and each render brings the selected tab into view. - **General:** Display (theme: Light / Dark / Match system, arrow keys move the choice; version) and the API key (Save key, Remove with a second click instead of `confirm()`). **Dropped:** the currency menu (it saved a value nothing used), the transactions-loaded line and the pointer card to Data & Reset. - **Import:** the folder card (name, access, CSVs last read, backup last saved, auto-save; Save now, Reload CSVs, Change folder, or Reconnect when access lapsed, or Pick a folder / Choose CSV files with none), files waiting for "Read as" (kept), the last import's results (kept), **Files in the folder** (how each file is read, rows, dates; changing "Read as" saves the choice for the next reload), the **Import log** (always shown, one line per import) and the Safari / Firefox card. **Dropped:** the per-file rename list (renaming is on Accounts), "Add individual CSV files" (the Safari / Firefox card does it) and **Add Manual Account** (its accounts were never saved, so they vanished on reload). - **Accounts:** one row per account: ▲▼ order, display name, the starting balance (bank accounts; labelled with the day before the first row) or the balance owed (cards), rows and dates. Each field saves when you leave it. An old current-balance override on a bank account is shown with a button to drop it. **Dropped:** the two tables and the Save button. diff --git a/js/views-settings.js b/js/views-settings.js index 76ec5f0..778e905 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -27,6 +27,13 @@ registerView('settings','Settings',(root)=>{ `` ).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 (Data & reset, the last one, was off-screen at 390px). + 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); From 92e8b33b1249843c800f9efe03199bb2ecf86f02 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:40:16 +0000 Subject: [PATCH 4/4] =?UTF-8?q?Settings=20=E2=86=92=20General:=20the=20Dis?= =?UTF-8?q?play=20panel=20only=20holds=20the=20version=20now,=20so=20call?= =?UTF-8?q?=20it=20About?= 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_013Z8iBUZo6LRYpLthSp2PRi --- CLAUDE.md | 4 ++-- js/views-settings.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d851244..d9454c9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -772,7 +772,7 @@ FinLens · Overview · Transactions · Plan ▾ · Trends · AI Analysis [S (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 and Anthropic API key; all clearing/reset lives in Data & reset) + (General holds About (the version) and Anthropic API key; all clearing/reset lives in Data & reset) ``` - **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 or theme setting (light only for now). @@ -944,7 +944,7 @@ Bump the patch version for bug fixes, minor version for new features, major vers
    vX.Y.Z · FinLens
    ``` 3. `README.md` — version string in the header badge and the footer line. -4. `js/views-settings.js` — the `FinLens vX.Y.Z` line in the General tab's Display card. +4. `js/views-settings.js` — the `FinLens vX.Y.Z` line in the General tab's About panel. Also update **Current version** in §1 of this file. Never close out a change without updating all of these. diff --git a/js/views-settings.js b/js/views-settings.js index bb9a53e..59e7dd8 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -1,6 +1,6 @@ /* ================================================================ FINLENS — views-settings.js - Settings shell (tab bar) + General tab: Display, Anthropic API key. + Settings shell (tab bar) + General tab: About (version), 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). ================================================================ */
    Category${mShort(m)}${months.length}-mo total