diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cc2bb8..9086e63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,76 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.14.0] — 2026-11-02 + +### Finances screens — Clarity redesign, part 2 +Overview, Transactions and the screens behind its filter pills (Income, Spending, Bills, Transfers) now match the Clarity mockups. Every number is computed from your data; none come from the mockups. + +- **Shared:** a note and the screen's buttons sit in one row under the page title (`.page-actions`). KPI tiles, panels, tags and lists use new Clarity classes in `index.html` instead of inline styles. Charts on these screens are inline SVG or plain boxes colored by theme tokens, each with a text description for screen readers. +- **Filter pills:** All · Income · Spending · Bills · Payments · Transfers on all five screens. All and Payments filter the list; the other four open their own screens (`income`, `spending`, `bills`, `transfers`, as before). The app bar keeps **Transactions** underlined on all of them (`TX_VIEWS` in `ui.js`). Screen titles: Income, Spending, Bills & subscriptions, Transfers. +- **Phones:** grids fold to one or two columns, wide tables hide secondary columns below 600px, and the transfer diagram stacks. No screen scrolls sideways at 390px. + +### Overview +- **Net worth** with a trend chart: **1M** (daily), **3M** (weekly) or **All** (month ends). A pill shows the change since the end of last month. +- **Latest month:** money in, money out, net, the savings rate as a bar, and the average rate over up to 6 months. It says how far the data runs ("Data runs through Oct 20"). +- **Account cards:** an icon, the number of transactions, a balance sparkline for bank accounts, and for a card how much of its limit is used ("No credit limit set · Add one" without one) and whether it's on autopay. Footnotes say where the balance comes from, or how much savings is assigned to buckets. +- **Cash flow:** 6 months of money in and out as bars, with the net under each month. +- **Upcoming bills:** bills due in the next 3 weeks, plus any overdue, with a "Due today" pill. With no bills yet, it shows the recurring charges FinLens spotted, marked as not confirmed. +- **Largest card purchases** of the latest month. +- **Kept:** double-click an account name to rename it (Enter on a focused name works too). **Added:** Reload CSVs and Ask AI about this buttons. +- **Dropped to match the mockup:** the four KPI cards (Total Cash, Total Debt, Net Worth, Cash Flow), the income/spending/transfers bar chart, Recent Transactions, and the Top Spending Category, Most Frequent Merchant and Top Income Source cards. + +### Transactions +- **KPIs:** transactions, money in, money out, net. On **Payments**: card payments, total paid, average payment, card balance now. +- **Payments** now lists payments to your credit cards, including the card side of an autopay transfer (`isCardPayment()`). Before, those became transfers when they were paired, so the pill showed nothing for the samples. +- **List:** search with an icon, Category, **Sort** (newest, oldest, largest, smallest, description A–Z), the amount filter, a Flags column (Bill, Recurring, Sub) and a numbered pager. On phones the category, account and flags move under the description. +- **Transaction detail drawer:** amount, date, account and original description at the top; Description; Category and Type side by side; flags as chips; notes; Save and Cancel pinned at the bottom. Type now offers **Card payment**, so saving a payment no longer turns it into an expense. +- **Kept:** bulk select and bulk edit, extra categories (under "Also count it under other categories"), the budget/bucket/debt link, Export CSV, transaction rules. +- **Transaction rules:** one row per keyword with its flags and how many transactions match. A Transaction rules button jumps to them. +- **Dropped to match the mockup:** the Type column, sorting by clicking column headers (the Sort menu replaces it), and the "Re-apply rules" button (rules apply when added or removed, and on every import). + +### Income +- **KPIs:** total income, average per month (over the period in months), interest earned, returns and refunds. +- **Income by source** as a stacked bar and list, **monthly income** bars with the unfinished month shaded lighter, **recurring deposits** with frequency, count, last, next expected and confidence (`recurringDepositsDetail()`), and **all deposits** (6, then Show all). +- **Dropped to match the mockup:** the by-category donut. + +### Spending +- **KPIs:** total spent, average per day, top category, highest month (and how far above average). +- **By category:** a ranked list of buttons; picking one fills the **drill-down** panel next to it. "Open in Transactions" opens the list filtered to that category. +- **Daily spending** heatmap for the period (was the last 365 days), shaded by quartile so rent days don't wash out the rest. **Monthly trend** line with the highest month labelled and an unfinished month drawn hollow, plus a note on which category pushed the highest month up. +- **Top merchants** (7) with category and visits. **Category rules** with Add rule and Re-categorize all. +- **Dropped to match the mockup:** the two Chart.js category charts and the transaction count KPI. + +### Bills +- **+ Add bill** opens an inline form: name, amount, due day, repeats, pays from. +- **KPIs:** bills tracked, cost per month (and its share of average monthly income), due in the next 7 days, subscriptions per month and per year. +- **Spotted recurring charges:** each with its rhythm ("Monthly, around the 18th"), number of charges, account, amount and a confidence bar. **Confirm as bill**, **Dismiss**, and **Undo** after dismissing. +- **Month calendar** with each bill on its due days; Hide / Show calendar. +- **Your bills:** repeats, next due, **pays from**, **last paid** (found in your transactions), status (Overdue, Due today, This week, Upcoming, Paid, Just added) and an edit button. The edit drawer has every field, plus Paid and Delete (click twice). +- **Next due moves on by itself:** a repeat that a payment already covers counts as paid (`billNextDue()`). +- **Fixed with the new edit button:** saving an edited bill used to add a copy. +- **Dropped to match the mockup:** the "Bills, Utilities & Subscriptions (All Time)" transaction table, the old KPI cards, and the Paid checkbox and × in each row (both are in the edit drawer now). + +### Transfers +- **KPIs:** transfers (paired / one-sided), between your accounts, sent outside FinLens (named by the keyword that matched, e.g. "Zelle · 6 payments"), saved to savings (and about how much a month). +- **Where money moved:** a From box per account with an arrow to each destination: amount, count and rhythm ("Monthly transfer, around the 3rd", "Autopay, around the 6th"), and a dashed box for money that left FinLens. +- **List:** From and To filters (including Outside FinLens), Paired / Keyword match, 10 rows then Show all. A row still opens the transfer drawer. +- **Transfer keywords:** removable chips and Add keyword (Enter works). Every change re-runs transfer detection; the separate Re-apply button and its alert are gone. +- **Dropped to match the mockup:** Most Frequent Path and Avg per Transfer, the description column and sortable headers. + +### Technical +- **`aggregation.js`:** new `balanceAt()`, `dataSpan()`, `monthlyFlow()`, `isCardPayment()`, `transferPairs()`, `recurringDepositsDetail()`, and bill helpers (`BILL_FREQS`, `billNextDue()`, `billLastPaid()`, `billDatesBetween()` …). `detectRecurring()` and `detectRecurringDeposits()` now use `recurringKey()` / `depositKey()`; their output is unchanged, and so is the AI summary (compared before and after on the samples). +- **`ui.js`:** `openDrawer(html, { title, footer })` with a scrim, a pinned footer and focus that returns to the opener; older forms that start with an `

` keep working. `svgLineChart()`, `sparkSvg()`, `dailyHeatmapHtml()`, `fmtSigned()`, `fmtShort()`, `acctName()`. `renderHeatmap()`, `renderUpcomingCal()`, `renderTransferFlow()` and `drawSpark()` are removed. `confirmRecurring(r)` takes the detected charge; `undoDismissRecurring()` is new. +- **Bills carry three optional fields:** `account` (pays from), `subscription` and `recurringKey` (the charge it was confirmed from). They live inside `State.bills`, so they're saved to `finlens-state.json`, IndexedDB and exports with it, and cleared with it. No new top-level State keys. +- **Data & Reset → Clear bills** also clears which spotted charges you confirmed or dismissed (`recurringConfirmed`), so they show up again. Start over clears both, as before. +- **Tokens:** `--track`, `--accent-dim`, `--card-soft`, `--card-border`. `[hidden]` always hides. + +### Docs +- **README** — the six screens described as they are now; Transactions pills; what Export CSV exports. +- **CLAUDE.md** — §4.1 Bill shape; §6 tokens and Finances components; §7 inline SVG charts; §8 and §9 new and removed helpers; §11 keyword changes re-run detection, card payments; §12 page actions and the Transactions pills; §20 Clear bills. + +--- + ## [1.13.0] — 2026-11-01 ### App shell — Clarity redesign, part 1 (shell and visual system) diff --git a/CLAUDE.md b/CLAUDE.md index 1180208..21b75a4 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.13.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.14.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. @@ -153,8 +153,8 @@ const State = { budgets: [], // Budget[] — persisted buckets: [], // SavingsBucket[] — persisted debts: [], // Debt[] — persisted - bills: [], // Bill[] — persisted - recurringConfirmed: {}, // { [key]: 'confirmed' | 'dismissed' } + bills: [], // Bill[] — persisted (shape below) + recurringConfirmed: {}, // { [recurringKey]: 'confirmed' | 'dismissed' } — Bills → Spotted recurring charges; Undo deletes the key txOverrides: {}, // { [txId]: TxOverride } — user edits on transactions manualBalances: {}, // { [accountId]: number, [accountId+'_limit']: number, [accountId+'_initial']: number } categoryRules: [], // { contains: string, category: string }[] @@ -177,6 +177,25 @@ const State = { }; ``` +**Bill** (an entry of `State.bills`, v1.14.0): + +```js +{ + merchant: string, // the name shown + amount: number, + category: string, + frequency: 'Monthly' | 'Bi-weekly' | 'Weekly' | 'Quarterly' | 'Annual' | 'One-time', // BILL_FREQS + dueDate: 'YYYY-MM-DD', // the stored due date; billNextDue() moves it on past repeats already paid + paid: boolean, + source: 'auto' | 'manual', + account?: string, // "Pays from" — an accountId, '' when not set + subscription?: boolean, // unset on older bills: billIsSubscription() guesses from category/name + recurringKey?: string, // recurringKey() of the charge it was confirmed from; finds its payments +} +``` + +The optional fields live inside `bills`, so they're saved, loaded, exported and cleared with it. "Last paid" and "Next due" are computed from the transactions (`billLastPaid()`, `billNextDue()`), never stored. + ### 4.2 The Transaction Model Transactions are created by `mkTx()` in `core.js` and never mutated directly — edits go through `State.txOverrides[tx.id]` and are persisted via `lsSet('txOverrides', ...)`. @@ -305,15 +324,15 @@ The visual system is **Clarity** (v1.13.0): indigo accent, Inter type, white car ```css /* surfaces */ --bg, --surface, --surface-2, --muted (chips, tracks), --divider (rows in cards), - --border, --border-strong (inputs, ghost buttons), --scrim + --border, --border-strong (inputs, ghost buttons), --scrim, --track (a meter on --surface-2) /* text */ --text, --text-body, --text-2, --text-3 (lightest allowed), --inverse, --on-solid (text on --accent-solid / --danger fills) /* accent */ --accent (marks, borders), --accent-solid (button fill), --accent-text (links, active nav), - --accent-hover, --accent-strong-text, --accent-soft, --accent-border + --accent-hover, --accent-strong-text, --accent-soft, --accent-border, --accent-dim (an unfinished period's bar) /* status */ --good, --good-text, --good-strong-text, --good-dot, --good-soft, --good-border --warn, --warn-text, --warn-strong-text, --warn-soft, --warn-soft-2, --warn-border --danger, --danger-text, --danger-strong-text, --danger-soft, --danger-border -/* hues */ --teal-2, --sky, --sky-text, --violet, --violet-text, --pink, --card +/* hues */ --teal-2, --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 /* shape */ --shadow (none), --popover-shadow, --radius (16px), --radius-sm (10px) @@ -321,7 +340,7 @@ The visual system is **Clarity** (v1.13.0): indigo accent, Inter type, white car — aliases kept so pre-v1.13.0 inline styles keep working; new code uses the names above ``` -**Never hard-code colors** — always use a CSS variable. Charts and inline SVG can't read variables, so they call `chartColor('--token', alpha?)` when they draw (§7, §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 without a redraw. Use `--on-solid` for text on any solid fill, never `#fff`, so a dark theme can swap it later. @@ -347,7 +366,29 @@ Use `--on-solid` for text on any solid fill, never `#fff`, so a dark theme can s .empty — dashed placeholder when no data .grid-4 .grid-3 .grid-2 — responsive grid layouts .num — tabular numbers (Inter); .mono — DM Mono for code-like text +.sr-only — visually hidden text for screen readers +[hidden] — always display:none (beats a class that sets display) +``` + +**Finances screens (v1.14.0)** — Overview, Transactions and its pill screens are built from these: + ``` +.page-actions — row under the shell's title: .note on the left, .acts (buttons) on the right +.fpills/.fpill — Transactions filter pills; the current one has aria-current="page" +.kpis/.kpi — KPI tiles (.k-label, .k-val, .k-sub); 4 → 2 columns below 900px +.panel — section card (24px 28px padding, h2 15px); .panel-head (title + .aside), .panel.flush (no padding) +.cols-3 + .span-2 — 3-column row with a wide panel; one column below 1000px +.hue-* — sets --c for a series: accent, good, warn, card, teal, pink, sky, violet, neutral, dim +.sw .legend .stack .bars/.bars-x — swatches, legends, stacked bar, box bar charts +.rows/.r — list rows in a panel; .date-block (MON / day) +.tbl.flush — table without side padding; .table-scroll (overflow-x box, positioned); .mw-520…860 min-widths +.fit-sm .hide-sm .w-date .w-amt .w-num — below 600px: fixed layout, hidden columns, set widths +.tag .flag .pill.accent .code-tag — category tag, flag chip, accent pill, rule keyword +.field .field-row .form-row .check-chip .flag-set — form fields (label wraps its control) +.dform .sum-box .drawer-note — drawer bodies; .drawer-head/.drawer-body/.drawer-foot are the drawer itself +``` + +Prefer these over inline styles. Keep touch targets ≥ 44px where feasible (`@media (pointer:coarse)` raises pills and remove buttons). --- @@ -361,6 +402,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. `CHART_PALETTE` is for multi-series charts with no meaning per color. +7. **The Finances screens don't use Chart.js (v1.14.0).** 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 @@ -419,7 +461,17 @@ currentBalances() // { [accountId]: number } — best available current periodEndBalance(accountId) // Balance at end of the active date range detectRecurring() // Recurring charge detection across all transactions detectRecurringDeposits() // Recurring income detection +recurringKey(desc), depositKey(desc) // the grouping keys the two detectors use accountDateRange(accountId) // { min: Date, max: Date } — earliest and latest transaction dates for an account +// v1.14.0 (the Finances screens) — new helpers; the ones above give the same output as before +balanceAt(accountId, date) // balance at the end of a day (manual balance minus later rows, or start + rows so far) +dataSpan(txs) // { first, last, days, months } — months = days ÷ 30.44, as the AI summary states +monthlyFlow(txs) // [{ key, date, income, expense, net, txs }] per month, sumIncome/sumExpense rules +isCardPayment(t) // a payment toward a credit card (its "Payment" row, or the card leg of a paired transfer) +transferPairs(txs) // [{ date, from, to, amount, description, outId, inId, paired }]; null from/to = outside FinLens +recurringDepositsDetail(txs) // detectRecurringDeposits() + count, account, next expected, confidence, steady +BILL_FREQS, billFreq(b), billOccurrence(b, k), billDatesBetween(b, from, to) +billPayments(b), billLastPaid(b), billNextDue(b) // a bill's payments and its next due date, from the transactions // Utilities hash(str) // Deterministic 'tx' + base36 hash for transaction IDs @@ -451,9 +503,9 @@ registerView(id, title, renderFn) // Register a view (called at module load ti showView(id) // Navigate to a view — re-renders from scratch renderActive() // Re-render current view (call after state mutations) -// Drawer (single shared drawer #txDrawer) -openDrawer(htmlString) // Open right-side drawer with HTML content -closeDrawer() // Close drawer +// 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 +closeDrawer() // Close it; focus returns to whatever opened it // Theme — light only for now (dark taken out of v1.13.0) applyTheme() // Point Chart.js defaults (labels, grid, font) at the theme tokens @@ -464,6 +516,8 @@ chartColor('--token', alpha?) // Same, as rgba() when alpha is given — // App bar (index.html .appbar) 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 closeAppBarPopups(focusBtn?) // Close whatever is open (Escape returns focus to its button) updateRangeUI(), updateAcctUI() // Sync the date / accounts popovers, their dots and tooltips @@ -477,16 +531,20 @@ mergeChartOpts(extra) // Merge extra options into CHART_DEFAULTS // Rendering utilities emptyCard(message) // Returns HTML string for empty-state card -renderHeatmap(holder, txs) // Render spending heatmap into a DOM element -renderUpcomingCal(holder) // Render bills mini-calendar -renderTransferFlow(holder, paths) // Render account flow SVG +fmtSigned(n, zero?) / fmtShort(v) // "+$2,450.00" / "−$65.00" (real minus sign); axis labels "$12.5k" +acctName(id), ordinal(n) // account display name (custom label first; null → "Outside FinLens"); "3rd" +svgLineChart(pts, opts) // inline-SVG line chart: pts [{ v, tip }]; opts { w, h, hue, xLabels, valueAt, hollowLast, ariaLabel } +sparkSvg(values, hue, label) // stretchy sparkline +dailyHeatmapHtml(txs, start, end) // weeks × days heatmap, six shades by quartile +// (renderHeatmap, renderUpcomingCal, renderTransferFlow and drawSpark were removed in v1.14.0) // CRUD helpers for Bills, Budgets, Buckets, Debts (all in ui.js) -showBillForm(existing?), saveBill() +showBillForm(i?), saveBill(i?) // edit bill i in the drawer, or add one (i < 0); addBill(bill) adds and marks "Just added" +billIsSubscription(b), deleteBill(i), toggleBillPaid(i) editBudget(i), saveBudget(i), deleteBudget(i), seedBudgets() editBucket(i), saveBucket(i), deleteBucket(i) editDebt(i), saveDebt(i), deleteDebt(i), simulatePayoff(debts, extra) -confirmRecurring(...), dismissRecurring(key) +confirmRecurring(r), dismissRecurring(key), undoDismissRecurring(key) // r: a detectRecurring() entry addCatRule(), delCatRule(i), recategorizeAll() exportAllData(), importJsonFile(ev) clearAllData() // = DataCleanup.startOver('archive') — full reset + reload (§20) @@ -571,7 +629,9 @@ The account id comes last on purpose: `migrate.js` relies on it to rename accoun **Both legs of a transfer are kept.** There is no deduplication. The `Transfers` view pairs them visually. -**Transfer keywords** are now editable in the Transfers tab (bottom section) instead of Settings. The `reapplyTransferKeywords()` helper reruns `detectTransfers()` after a keyword change. +**Transfer keywords** are edited on the Transfers screen. Adding or removing one re-runs detection right away (`addTransferKeyword()` / `removeTransferKeyword()` → `reapplyTransferKeywords()`, which puts unedited transfers back to income/expense and calls `detectTransfers()`). There's no separate Re-apply button any more (v1.14.0). + +**Pairs for display:** `transferPairs(txs)` (aggregation.js) pairs the two legs for the Transfers screen and the Overview's card footnotes. A leg with no partner has `to` (or `from`) = null: money that left (or came from) outside FinLens. --- @@ -579,6 +639,8 @@ The account id comes last on purpose: `migrate.js` relies on it to rename accoun `type='payment'` is set in `normalizeRow()` when `rawType` equals `"Payment"` (case-insensitive). This occurs on credit card uploads where a payment toward the card balance is recorded as a positive-amount transaction with `Type = "Payment"`. Payment transactions are **excluded from income sums** (`sumIncome()` filters them out) to avoid double-counting. They are distinct from `'credit'` (which represents purchase refunds/credits) and `'transfer'` (which represents inter-account moves). +A card payment that `detectTransfers()` pairs with the bank's autopay becomes `type='transfer'` (category `Transfer in`). `isCardPayment(t)` counts both kinds; the Transactions **Payments** pill and its KPIs use it (v1.14.0). + --- ## 12. Coding Standards @@ -632,6 +694,7 @@ One row at the top of every page (`
` in `index.html`); th FinLens · Overview · Transactions · Plan ▾ · Trends · AI Analysis [Synced] [📅] [🏦] [⚙] └─ menu: Budget · Buckets · Debt · Investments · Forecast 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 and Anthropic API Key; all clearing/reset lives in Data & Reset) @@ -641,8 +704,12 @@ Gear → Settings, with tabs: General · Import · Accounts · Credit Cards · C - **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. 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 (income/spending/bills/payments/transfers are filter pills, not separate views) +- `views-main.js` — overview, transactions (All / Payments), income, spending, bills, transfers - `views-plan.js` — budgets, buckets, debt, trends - `views-invest.js` — investments (`_renderForecastInvest` is a helper, not a registered view) - `views-forecast.js` — forecast (tabbed: calls `_renderForecastSavings` / `_renderForecastInvest`) @@ -661,7 +728,7 @@ View registrations by file: ### Filters vs sub-tabs -- Use **filter pills** when it is the same underlying data viewed through different lenses (e.g. Transactions filtered by Income / Spending / Bills). +- Use **filter pills** when it is the same underlying data viewed through different lenses (e.g. Transactions: All / Payments filter the list; Income / Spending / Bills / Transfers are screens of their own behind the same pill row). - Use **sub-tabs** when the content is meaningfully different — different inputs, charts, or logic (e.g. Forecast Savings vs Forecast Investments). ### Adding a new view @@ -817,7 +884,7 @@ Multiple credit card files can be loaded simultaneously. Each gets a unique `acc --- -*Last updated: v1.13.0 — 2026-11-01 (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.5: no section changes: Import Logs race fix; v1.10.4: §8, §13 single `~` is literal; §21 excerpts escape `~`; v1.10.3: §13 refusals; §21 declined runs; 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.14.0 — 2026-11-02 (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.5: no section changes: Import Logs race fix; v1.10.4: §8, §13 single `~` is literal; §21 excerpts escape `~`; v1.10.3: §13 refusals; §21 declined runs; 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)* --- @@ -866,7 +933,7 @@ CSV files on disk are **never** modified. | Clear transactions & accounts | Empties memory + `transactions`/`accounts` stores; with a folder connected, sets `csvAutoImportPaused` | Plans, edits, account labels/balances, settings | | Clear import log | Empties `import_log` | Everything else | | Clear transaction edits | `txOverrides` + `tx_overrides` store; rebuilds loaded transactions with `reconstituteTx(raw, {})` | — | -| Clear budgets / bills / buckets / debts / AI history | `State[key] = []` + `lsSet` | — | +| Clear budgets / bills / buckets / debts / AI history | `State[key] = []` + `lsSet`. Bills also resets `recurringConfirmed` (confirmed/dismissed spotted charges, `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 | | 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) | diff --git a/README.md b/README.md index 4b02c4d..5c25836 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.13.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.14.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -52,7 +52,7 @@ FinLens auto-detects which file is which based on filename and column headers. C **3. Explore** -Use the top bar to move between views: Overview, Transactions, **Plan** (a menu with Budget, Buckets, Debt, Investments and Forecast), Trends and AI Analysis. On a phone or a narrow window they're in the **☰** menu. The calendar icon sets the date range for most views, and the bank icon picks which accounts to include. The **Synced** badge shows whether your changes are being saved to your folder. +Use the top bar to move between views: Overview, Transactions, **Plan** (a menu with Budget, Buckets, Debt, Investments and Forecast), Trends and AI Analysis. Transactions has filter pills for Income, Spending, Bills, Payments and Transfers. On a phone or a narrow window they're in the **☰** menu. The calendar icon sets the date range for most views, and the bank icon picks which accounts to include. The **Synced** badge shows whether your changes are being saved to your folder. --- @@ -103,22 +103,22 @@ FinLens stores all your data — budgets, bills, transaction edits, settings, AI ## Features In Depth ### Overview -Net worth snapshot, per-account balance cards with sparklines, cash flow chart, upcoming bills list, and top credit card transactions for the selected period. +Net worth with a trend chart (1M, 3M or all of your history) and the change since the end of last month. The latest month's money in, money out, net and savings rate, next to your 6-month average. A card per account with a balance sparkline (or, for a credit card, how much of the limit you're using). Six months of cash flow with the net for each month, bills due in the next three weeks, and the largest card purchases of the latest month. Double-click an account name to rename it. ### Transactions -Full transaction table with search, category filter, type filter (Income / Expense / Transfer), sortable columns, and pagination (50 per page). Click any row to open an edit drawer — update description, categories, type, notes, and flags (Bill, Recurring, Subscription). Transaction Rules let you auto-flag transactions by keyword (e.g. "Netflix → Subscription"). +Filter pills across the top: **All**, **Income**, **Spending**, **Bills**, **Payments** and **Transfers**. All and Payments filter the list; the other four open their own screens. The list has search, a category filter, sorting, an amount filter, bulk edits and 50 rows per page. Click a transaction to edit its description, categories, type, notes and flags (Bill, Recurring, Subscription). Edits are kept separately from the imported row, so re-importing never overwrites them. **Transaction rules** flag matching transactions automatically (e.g. "NETFLIX → Subscription"). **Payments** lists the payments made to your credit cards. ### Income -Total income, average monthly, interest earned, and returns/refunds KPI cards. Income by source donut chart, monthly bar chart, recurring deposit detection table, and full deposits list. +Total income, average per month, interest earned and refunds. Income by source as a stacked bar, monthly income (an unfinished month is shaded lighter), recurring deposits with their rhythm, next expected date and confidence, and every deposit. ### Bills -Auto-detected recurring charges with confidence scores and frequency classification. One click to confirm a charge as a bill and add it to your calendar. Manual bill management with due-date tracking, overdue indicators, and a collapsible monthly calendar. +**Spotted recurring charges**: FinLens finds charges that repeat and shows its confidence. Confirm the real bills, or dismiss the rest (Undo brings one back). Add bills by hand with **+ Add bill**. Each bill has how often it repeats, its next due date, the account it pays from and when it was last paid (found in your transactions). Also a month calendar you can hide, and what your bills and subscriptions cost per month. ### Spending -Total spent, average daily, top category, and transaction count. Vertical bar chart and horizontal category ranking (click any bar to drill into transactions), monthly trend line, daily heatmap (last 365 days), and top merchants table. Custom categorization rules (keyword → category). +Total spent, average per day, top category and highest month. Categories ranked by spend: pick one to see its transactions. A daily spending heatmap, the monthly trend, top merchants, and **category rules** (keyword → category). ### Transfers -Auto-paired transfer legs across accounts. Account flow diagram. FROM/TO filter dropdowns. Clickable rows to edit transfer description and notes. +Both legs of a transfer are paired automatically. A diagram shows where money moved between your accounts, and what left FinLens (e.g. Zelle payments). Filter the list by From and To account. **Transfer keywords** decide which unpaired transactions count as transfers; changing them re-runs detection right away. ### Budgeting Monthly budget vs. actual with color-coded progress bars. Over-budget and warning banners. Monthly history chart. Seed from a suggested starter budget or add custom categories. @@ -238,7 +238,7 @@ FinLens/ **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. -**Category rules** — go to **Spending → Category Rules** to teach FinLens your merchants. Rules apply across all future imports. Your category list is managed under **Database → Categories**. +**Category rules** — go to **Transactions → Spending → Category rules** to teach FinLens your merchants. Rules apply across all future imports. Your category list is managed under **Database → 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. @@ -249,7 +249,7 @@ FinLens/ - **Disconnect the folder.** - **Start over from scratch:** type `RESET` to erase everything and reload. Your backup file is either kept as `finlens-state-backup-DDMMYYYY.json` or deleted, your choice. Your CSV files are never touched. -**Exporting** — the Transactions tab has an **Export CSV** button for the currently filtered view. AI responses can be saved as Markdown from the AI Analysis tab. +**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. --- @@ -259,4 +259,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.13.0 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.14.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index 06d3c2b..10fcd8f 100644 --- a/index.html +++ b/index.html @@ -34,6 +34,7 @@ --border:#e5e8ec; --border-strong:#d9dee5; /* inputs, ghost buttons */ --scrim:rgba(15,23,42,.35); + --track:#e2e8f0; /* meter track on --surface-2 */ /* text */ --text:#0f172a; --text-body:#334155; @@ -49,12 +50,14 @@ --accent-strong-text:#3730a3; --accent-soft:#eef2ff; --accent-border:#c7d2fe; + --accent-dim:#a5b4fc; /* an unfinished period's bar */ /* status */ --good:#15803d; --good-text:#15803d; --good-strong-text:#166534; --good-dot:#16a34a; --good-soft:#f0fdf4; --good-border:#bbf7d0; --warn:#d97706; --warn-text:#b45309; --warn-strong-text:#92400e; --warn-soft:#fef3c7; --warn-soft-2:#fffbeb; --warn-border:#fde68a; --danger:#dc2626; --danger-text:#b91c1c; --danger-strong-text:#991b1b; --danger-soft:#fef2f2; --danger-border:#fecaca; /* extra hues */ --teal-2:#0d9488; --sky:#0284c7; --sky-text:#0369a1; --violet:#7c3aed; --violet-text:#6d28d9; --pink:#be185d; --card:#c2410c; + --card-soft:#fff7ed; --card-border:#fed7aa; /* credit card tints */ /* charts (read by chartColor() in ui.js — Chart.js can't read CSS variables itself) */ --chart-in:var(--accent); --chart-out:var(--warn); @@ -77,6 +80,7 @@ --blue:var(--sky); --purple:var(--violet); } *{box-sizing:border-box} +[hidden]{display:none !important} html,body{margin:0;padding:0;min-height:100%;} body{ font-family:'Inter',system-ui,-apple-system,Segoe UI,Roboto,sans-serif; @@ -253,38 +257,41 @@ .tabs button[aria-selected="true"]{color:var(--accent-text);font-weight:600;box-shadow:inset 0 -2px 0 var(--accent-text)} .seg{display:inline-flex;gap:4px;background:var(--muted);padding:4px;border-radius:10px} .seg button{min-height:34px;padding:0 14px;border:0;border-radius:7px;background:transparent;color:var(--text-2);font-weight:600;font-size:13px} -.seg button[aria-checked="true"]{background:var(--surface);color:var(--text);box-shadow:0 1px 2px rgba(15,23,42,.12)} - -/* mini calendar */ -.cal{display:grid;grid-template-columns:repeat(7,1fr);gap:4px;font-size:11px} -.cal .dh{color:var(--text-3);text-align:center;padding:4px 0;font-weight:600} -.cal .day{aspect-ratio:1;background:var(--surface-2);border:1px solid var(--divider);border-radius:8px;display:flex;flex-direction:column;align-items:center;justify-content:flex-start;padding:3px;font-size:11px;position:relative} -.cal .day .num{font-weight:600} -.cal .day .marks{position:absolute;bottom:3px;display:flex;gap:2px} -.cal .day.today{outline:2px solid var(--accent);background:var(--accent-soft)} -.cal .day.empty{background:transparent;border-color:transparent} - -/* collapsible calendar */ -.cal-toggle{display:flex;justify-content:space-between;align-items:center;cursor:pointer;user-select:none;} -.cal-toggle .arr{color:var(--text-3);font-size:12px;transition:transform .2s} -.cal-toggle.open .arr{transform:rotate(180deg)} -.cal-body{overflow:hidden;max-height:0;transition:max-height .3s ease;margin-top:0} -.cal-body.open{max-height:400px;margin-top:10px} - -/* heatmap */ -.heat{display:grid;gap:3px} -.heat .cell{aspect-ratio:1;border-radius:3px;background:var(--muted)} -.heat .cell.l1{background:var(--heat-1)} -.heat .cell.l2{background:var(--heat-2)} -.heat .cell.l3{background:var(--heat-3)} -.heat .cell.l4{background:var(--heat-4)} -.heat .cell.l5{background:var(--heat-5)} - -/* drawer */ -.drawer{position:fixed;right:0;top:0;height:100vh;width:420px;max-width:100%;background:var(--surface);border-left:1px solid var(--border);box-shadow:var(--popover-shadow);transform:translateX(100%);transition:transform .25s;z-index:50;padding:20px 24px;overflow-y:auto} -.drawer.open{transform:translateX(0)} -.drawer h3{margin:0 0 14px;font-size:17px;font-weight:700} -.drawer .close{position:absolute;top:14px;right:14px;width:40px;height:40px;border-radius:10px;background:var(--surface);border:1px solid var(--border);color:var(--text-2);font-size:20px} +.seg button[aria-checked="true"],.seg button[aria-pressed="true"]{background:var(--surface);color:var(--text);box-shadow:0 1px 2px rgba(15,23,42,.12)} + +/* drawer — one shared side panel: title row, scrolling body, optional pinned footer (ui.js openDrawer) */ +.drawer{position:fixed;right:0;top:0;bottom:0;width:440px;max-width:100%;background:var(--surface);border-left:1px solid var(--border);box-shadow:var(--popover-shadow);transform:translateX(100%);visibility:hidden;transition:transform .25s,visibility 0s linear .25s;z-index:50;display:flex;flex-direction:column} +.drawer.open{transform:translateX(0);visibility:visible;transition:transform .25s} +.drawer-head{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:14px 20px 14px 24px;border-bottom:1px solid var(--divider)} +.drawer-head h2{margin:0;font-size:17px;font-weight:700} +.drawer .close{width:40px;height:40px;flex-shrink:0;border-radius:10px;background:var(--surface);border:1px solid var(--border);color:var(--text-body);font-size:20px;line-height:1} +.drawer .close:hover{background:var(--surface-2)} +.drawer-body{flex:1;overflow-y:auto;padding:24px} +.drawer-foot{display:flex;align-items:center;gap:10px;padding:16px 24px;border-top:1px solid var(--divider)} +.drawer-foot[hidden]{display:none} +.drawer-scrim{position:fixed;inset:0;z-index:49;background:var(--scrim);border:0;padding:0} +.drawer-scrim[hidden]{display:none} +@media (prefers-reduced-motion:reduce){.drawer,.drawer.open{transition:none}} +.dform{display:flex;flex-direction:column;gap:18px} +.field{display:flex;flex-direction:column;gap:6px;font-size:13px;font-weight:600;color:var(--text-body);min-width:0} +.field .input,.field .select{font-weight:400;min-height:44px} +.field .textarea{font-weight:400} +.field-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} +.flag-set{border:0;padding:0;margin:0;display:flex;flex-wrap:wrap;gap:8px;min-width:0} +.flag-set legend{font-size:13px;font-weight:600;color:var(--text-body);padding:0;margin-bottom:8px} +.check-chip{display:inline-flex;align-items:center;gap:8px;min-height:40px;padding:0 14px;border:1px solid var(--border-strong);border-radius:10px;font-size:14px;color:var(--text);cursor:pointer} +.check-chip input{width:16px;height:16px;margin:0;accent-color:var(--accent)} +.check-chip:has(input:checked){border-color:var(--accent-border);background:var(--accent-soft)} +.drawer-note{margin:0;font-size:12px;color:var(--text-3);line-height:1.5} +.sum-box{padding:18px;background:var(--surface-2);border-radius:12px;display:flex;flex-direction:column;gap:4px} +.sum-box .amt{font-size:28px;font-weight:700;letter-spacing:-.02em} +.sum-box .meta{font-size:13px;color:var(--text-2)} +.sum-box .orig{font-size:12px;color:var(--text-3);margin-top:6px;overflow-wrap:anywhere} +.sum-box .orig code{font:12px 'DM Mono',ui-monospace,monospace} +details.more-cats summary{cursor:pointer;font-size:13px;font-weight:600;color:var(--accent-text);min-height:32px;display:flex;align-items:center} +details.more-cats .opts{display:flex;flex-wrap:wrap;gap:6px 14px;margin-top:6px} +.grow{flex:1} +.btn.danger-text{color:var(--danger-text)} /* insight — a tinted callout */ .insight{background:var(--accent-soft);border:1px solid var(--accent-border);border-radius:12px;padding:14px 18px;font-size:14px;color:var(--text);} @@ -350,9 +357,314 @@ /* 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} -/* KPI editable label — subtle cursor hint */ -h3.kpi-label{cursor:text} -h3.kpi-label:hover{opacity:.85} +/* =============== FINANCES SCREENS (v1.14.0): Overview, Transactions and its pill screens =============== */ +.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0} +/* the row under the page title: a short note on the left, the screen's actions on the right */ +.page-actions{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px 16px} +.page-actions .note{margin:0;font-size:14px;color:var(--text-2)} +.page-actions .acts{display:flex;flex-wrap:wrap;gap:10px;margin-left:auto} +.btn.lg{min-height:44px} +.btn svg{flex-shrink:0} +.btn.text{background:transparent;color:var(--accent-text);border-color:transparent;padding:0 12px} +.btn.text:hover{background:var(--accent-soft);color:var(--accent-text);filter:none} +/* Transactions filter pills (All · Income · Spending · Bills · Payments · Transfers) */ +.fpills{display:flex;flex-wrap:wrap;gap:8px} +.fpill{display:inline-flex;align-items:center;min-height:38px;padding:0 16px;border:1px solid var(--border-strong);background:var(--surface);color:var(--text-body);border-radius:999px;font-size:14px;font-weight:500;text-decoration:none;cursor:pointer} +.fpill:hover{background:var(--surface-2);color:var(--text)} +.fpill[aria-current="page"]{background:var(--inverse);border-color:var(--inverse);color:var(--on-solid);font-weight:600} +/* KPI tiles */ +.kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px} +.kpi{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:18px 20px;display:flex;flex-direction:column;gap:6px;min-width:0} +.kpi .k-label{font-size:13px;font-weight:500;color:var(--text-3)} +.kpi .k-val{font-size:24px;font-weight:700;letter-spacing:-.02em;line-height:1.25;overflow-wrap:anywhere} +.kpi .k-val small{font-size:14px;font-weight:500;color:var(--text-3);letter-spacing:0} +.kpi .k-sub{font-size:12px;color:var(--text-3)} +.c-good{color:var(--good-text)} .c-card{color:var(--card)} +/* panels: the cards the screens are built from */ +.panel{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:24px 28px;display:flex;flex-direction:column;gap:14px;min-width:0} +.panel h2{margin:0;font-size:15px;font-weight:600} +.panel .sub{margin:4px 0 0;font-size:13px;color:var(--text-3)} +.panel-head{display:flex;justify-content:space-between;align-items:baseline;flex-wrap:wrap;gap:8px 12px} +.panel-head .aside{font-size:12px;color:var(--text-3)} +.panel.flush{padding:0;gap:0} +.more-link{font-size:13px;font-weight:600;text-decoration:none;align-self:flex-start} +.panel .more-link.end{margin-top:auto} +.section-head{display:flex;justify-content:space-between;align-items:baseline;gap:12px} +.section-head h2{margin:0;font-size:18px;font-weight:700;letter-spacing:-.01em} +.eyebrow{font-size:12px;font-weight:600;color:var(--text-3);text-transform:uppercase;letter-spacing:.06em} +.empty-note{margin:0;padding:24px 0;text-align:center;font-size:14px;color:var(--text-2)} +.cols-3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px} +.cols-3>.span-2{grid-column:span 2} +/* series colors: a hue class sets --c for bars, swatches, lines and meters */ +.hue-accent{--c:var(--accent)} .hue-good{--c:var(--good)} .hue-warn{--c:var(--warn)} .hue-card{--c:var(--card)} +.hue-teal{--c:var(--teal-2)} .hue-pink{--c:var(--pink)} .hue-sky{--c:var(--sky)} .hue-violet{--c:var(--violet)} +.hue-neutral{--c:var(--chart-neutral)} .hue-dim{--c:var(--accent-dim)} +.sw{width:10px;height:10px;border-radius:3px;background:var(--c);display:inline-block;flex-shrink:0} +.legend{display:flex;flex-wrap:wrap;gap:16px;font-size:12px;color:var(--text-2)} +.legend span{display:inline-flex;align-items:center;gap:6px} +.progress[class*="hue-"]>div{background:var(--c)} +.progress.on-2{background:var(--track)} +/* inline SVG charts (ui.js svgLineChart / sparkSvg) */ +.linechart{display:block;height:auto;overflow:visible} +.lc-grid{stroke:var(--chart-grid)} .lc-axis{stroke:var(--border)} +.lc-label{fill:var(--text-3);font-size:11px} +.lc-value{fill:var(--text);font-size:11px;font-weight:600} +.lc-line{fill:none;stroke:var(--c);stroke-width:3;stroke-linejoin:round;stroke-linecap:round} +.lc-pt{fill:var(--c)} .lc-pt.hollow{fill:var(--surface);stroke:var(--c);stroke-width:2} +.spark{display:block} +.spark polyline{fill:none;stroke:var(--c);stroke-width:2;stroke-linejoin:round} +/* bar charts built from boxes: cash flow, monthly income */ +.bars{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:20px;height:200px;align-items:end;border-bottom:1px solid var(--border)} +.bars .grp{display:flex;gap:5px;align-items:flex-end;height:100%} +.bars .bar{flex:1;min-height:1px;border-radius:5px 5px 0 0;background:var(--c)} +.bars .col{display:flex;flex-direction:column;justify-content:flex-end;align-items:center;gap:6px;height:100%;min-width:0} +.bars .col .v{font-size:12px;font-weight:600;white-space:nowrap} +.bars .col .bar{flex:none;width:100%;border-radius:6px 6px 0 0} +.bars.tall{height:220px} +.bars.fill{flex:1 1 200px;min-height:200px;height:auto;grid-template-rows:minmax(0,1fr)} +.bars-x{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:20px;text-align:center;font-size:12px;color:var(--text-3)} +.bars-x .v{font-size:13px;font-weight:600;color:var(--text);margin-top:2px;white-space:nowrap} +.bars-x .v .short{display:none} +.stack{display:flex;height:14px;border-radius:999px;overflow:hidden;background:var(--muted)} +.stack>span{display:block;height:100%;background:var(--c)} +/* list rows inside panels */ +.rows{display:flex;flex-direction:column;font-size:14px} +.rows>.r{display:flex;align-items:center;gap:12px;padding:10px 0;border-bottom:1px solid var(--divider);min-width:0} +.rows>.r:last-child{border-bottom:0} +.rows .t{flex:1;min-width:0;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.rows .d{color:var(--text-2);flex-shrink:0} +.rows .amt{font-weight:600;white-space:nowrap} +.date-block{width:40px;text-align:center;flex-shrink:0} +.date-block .mo{font-size:11px;font-weight:600;color:var(--text-3);text-transform:uppercase} +.date-block .dd{font-size:17px;font-weight:700;line-height:1.2} +.pill.accent{background:var(--accent-soft);color:var(--accent-strong-text)} +.flag{font-size:11px;font-weight:600;background:var(--accent-soft);color:var(--accent-strong-text);padding:2px 7px;border-radius:999px;white-space:nowrap} +.tag{display:inline-block;font-size:12px;background:var(--muted);color:var(--text-body);padding:3px 8px;border-radius:6px;white-space:nowrap} +.flags{display:flex;flex-wrap:wrap;gap:4px} +/* tables in panels */ +.table-scroll{overflow-x:auto;position:relative} /* positioned, so .sr-only text inside is clipped too */ +.mw-520{min-width:520px} .mw-560{min-width:560px} .mw-760{min-width:760px} .mw-820{min-width:820px} .mw-860{min-width:860px} +.tbl.flush th:first-child,.tbl.flush td:first-child{padding-left:0} +.tbl.flush th:last-child,.tbl.flush td:last-child{padding-right:0} +.tbl.flush tbody tr:last-child td{border-bottom:0} +.tbl.flush tr:hover td{background:transparent} +.tbl th.r,.tbl td.r{text-align:right} +.tbl td.strong{font-weight:600} +.tbl td.dim{color:var(--text-2)} +.tbl td .s2{font-size:12px;color:var(--text-3)} +.tbl td.nowrap{white-space:nowrap} +.link-btn{border:0;background:none;padding:0;font:inherit;font-weight:600;color:var(--text);text-align:left;cursor:pointer;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block} +.link-btn:hover{color:var(--accent-text)} +.icon-x{width:36px;height:36px;flex-shrink:0;border:0;background:transparent;border-radius:8px;color:var(--text-3);font-size:18px;line-height:1;display:inline-grid;place-items:center} +.icon-x:hover{background:var(--surface-2);color:var(--danger-text)} +.icon-x svg{stroke:currentColor} +.form-row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end} +.form-row .field{font-weight:500} +.form-row .btn{min-height:44px} +.code-tag{font:600 13px 'DM Mono',ui-monospace,monospace;background:var(--muted);color:var(--text);padding:3px 8px;border-radius:6px;overflow-wrap:anywhere} +.rule-row{display:flex;align-items:center;gap:10px 12px;padding:10px 0;border-bottom:1px solid var(--divider);flex-wrap:wrap;font-size:14px} +.rule-row:last-child{border-bottom:0} +.rule-row .k{color:var(--text-2)} +.rule-row .m{font-size:12px;color:var(--text-3)} +/* Overview */ +.panel h2.k-quiet{font-size:14px;font-weight:500;color:var(--text-3)} +.hero h2.k-quiet{margin-bottom:8px} +.hero-head{align-items:flex-start} +.acct-section{display:flex;flex-direction:column;gap:14px} +.hero-val{font-size:40px;font-weight:700;letter-spacing:-.03em;line-height:1} +.hero-val .cents{font-size:22px;color:var(--text-3)} +.delta-pill{display:inline-flex;align-items:center;gap:6px;margin-top:10px;font-size:13px;font-weight:600;padding:4px 10px;border-radius:999px;color:var(--text-body);background:var(--muted)} +.delta-pill.up{color:var(--good-text);background:var(--good-soft)} +.delta-pill.down{color:var(--danger-text);background:var(--danger-soft)} +.kv{display:flex;flex-direction:column;gap:14px;font-size:14px} +.kv>div{display:flex;justify-content:space-between;gap:12px} +.kv .k{color:var(--text-2)} .kv .v{font-weight:600} +.kv .total{padding-top:14px;border-top:1px solid var(--divider)} +.kv .total .k{color:var(--text);font-weight:600} .kv .total .v{font-weight:700} +.rate-box{display:flex;flex-direction:column;gap:8px;padding:16px;background:var(--surface-2);border-radius:12px} +.rate-box .top{display:flex;justify-content:space-between;font-size:13px;font-weight:500} +.rate-box .top b{font-weight:700} +.rate-box .s{font-size:12px;color:var(--text-3)} +.acct-cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px} +.acct-card{display:flex;flex-direction:column;gap:12px;min-width:0} +.acct-top{display:flex;align-items:center;gap:12px} +.icon-tile{width:36px;height:36px;border-radius:10px;display:grid;place-items:center;flex-shrink:0;background:var(--accent-soft);color:var(--accent)} +.icon-tile.t-good{background:var(--good-soft);color:var(--good)} +.icon-tile.t-card{background:var(--card-soft);color:var(--card)} +.acct-name{display:block;font-weight:600;font-size:15px;cursor:text;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:4px} +.acct-kind{font-size:12px;color:var(--text-3)} +.acct-bal{font-size:26px;font-weight:700;letter-spacing:-.02em} +.acct-bal small{font-size:14px;font-weight:500;color:var(--text-3);letter-spacing:0} +.acct-foot{font-size:12px;color:var(--text-3)} +.acct-foot a,.util a{text-decoration:none;font-weight:600} +.util{display:flex;flex-direction:column;gap:6px;padding:6px 0 4px} +.util .meta{display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--text-3)} +/* Transactions list */ +.toolbar{display:flex;flex-wrap:wrap;gap:12px;padding:18px 24px;border-bottom:1px solid var(--divider);align-items:center} +.search{flex:1 1 280px;display:flex;align-items:center;gap:8px;min-height:42px;padding:0 12px;border:1px solid var(--border-strong);border-radius:10px;background:var(--surface)} +.search:focus-within{outline:2px solid var(--accent-border);border-color:var(--accent)} +.search svg{stroke:var(--text-3);flex-shrink:0} +.search input{flex:1;min-width:0;min-height:40px;border:0;outline:0;background:transparent;color:var(--text);font-size:14px} +.inline-field{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500;color:var(--text-2)} +.inline-field .select,.inline-field .input{width:auto;min-height:42px} +.inline-field .input{width:96px} +.inline-field .select{max-width:100%} +.bulk-bar{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:12px 24px;background:var(--accent-soft);border-bottom:1px solid var(--accent-border)} +.bulk-bar .select{width:auto;min-height:36px} +.bulk-bar strong{font-size:13px} +.tx-table td{padding-top:8px;padding-bottom:8px;height:52px} +.tx-table td.chk,.tx-table th.chk{width:44px;padding-left:24px;padding-right:0} +.tx-table td.chk input,.tx-table th.chk input{width:18px;height:18px;margin:0;accent-color:var(--accent)} +.tx-table td:last-child,.tx-table th:last-child{padding-right:24px} +.tx-table .note-line{font-size:12px;color:var(--text-3);font-weight:400;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.tx-table tr.click{cursor:pointer} +.list-foot{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;padding:14px 24px;font-size:13px;color:var(--text-2)} +.pager{display:flex;flex-wrap:wrap;gap:6px} +.pager button{min-width:40px;height:40px;padding:0 8px;border:1px solid var(--border);background:var(--surface);border-radius:10px;color:var(--text-body);font-size:14px;font-weight:500} +.pager button[aria-current="page"]{border-color:transparent;background:var(--accent-soft);color:var(--accent-text);font-weight:600} +.pager button:disabled{opacity:.45;cursor:default} +.pager .gap{align-self:center;color:var(--text-3);padding:0 2px} +/* Income */ +.src-list{display:flex;flex-direction:column;gap:14px;font-size:14px} +.src-list>div{display:flex;align-items:center;gap:10px} +.src-list .who{flex:1;min-width:0} +.src-list .who b{display:block;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.src-list .who span{font-size:12px;color:var(--text-3)} +/* Spending */ +.catlist{display:flex;flex-direction:column;gap:4px} +.catbtn{display:grid;grid-template-columns:150px minmax(0,1fr) 96px 48px;gap:14px;align-items:center;min-height:44px;padding:8px 10px;border:1px solid transparent;background:var(--surface);border-radius:10px;text-align:left;font-size:14px;color:var(--text)} +.catbtn:hover{background:var(--surface-2)} +.catbtn[aria-pressed="true"]{background:var(--accent-soft);border-color:var(--accent-border)} +.catbtn .n{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.catbtn .track{display:block;height:10px;background:var(--muted);border-radius:999px} +.catbtn[aria-pressed="true"] .track{background:var(--surface)} +.catbtn .track>span{display:block;height:100%;background:var(--accent-solid);border-radius:999px} +.catbtn .a{text-align:right;font-weight:600} +.catbtn .p{text-align:right;font-size:12px;color:var(--text-3)} +.panel h2.drill-title{margin-top:4px;font-size:20px;font-weight:700;overflow-wrap:anywhere} +.heatmap{display:flex;gap:10px;overflow-x:auto;padding-bottom:4px} +.hm-days{display:flex;flex-direction:column;gap:3px;padding-top:20px;font-size:11px;color:var(--text-3)} +.hm-days span{height:15px;line-height:15px} +.hm-main{display:flex;flex-direction:column;gap:6px} +.hm-months{display:grid;column-gap:3px;height:14px;font-size:11px;color:var(--text-3);white-space:nowrap} +.hm-grid{display:flex;gap:3px} +.hm-week{display:flex;flex-direction:column;gap:3px} +.hm-cell{display:block;width:15px;height:15px;border-radius:3px;background:var(--muted)} +.hm-cell.none{background:transparent} +.hm-cell.l1{background:var(--heat-1)} .hm-cell.l2{background:var(--heat-2)} .hm-cell.l3{background:var(--heat-3)} .hm-cell.l4{background:var(--heat-4)} .hm-cell.l5{background:var(--heat-5)} +.hm-legend{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-3)} +.hm-legend .hm-cell{width:13px;height:13px} +.hm-legend .hm-cell.l0{box-shadow:inset 0 0 0 1px var(--track)} +.trend-note{margin:0;font-size:13px;color:var(--text-2);line-height:1.5} +/* Bills */ +.bill-form{border-color:var(--accent-border)} +.bill-form .bf-grid{display:grid;grid-template-columns:2fr repeat(3,minmax(0,1fr)) 1.3fr;gap:12px} +.bill-form .bf-acts{display:flex;gap:10px;justify-content:flex-end} +.sug{display:flex;flex-wrap:wrap;align-items:center;gap:12px 16px;padding:14px 0;border-bottom:1px solid var(--divider)} +.sug:last-child{border-bottom:0} +.sug .who{flex:1 1 260px;min-width:0} +.sug .who .n{font-weight:600;font-size:14px;overflow-wrap:anywhere} +.sug .who .m{font-size:12px;color:var(--text-3);margin-top:2px} +.sug .amt{width:110px;font-weight:600;font-size:14px} +.sug .conf{width:150px;display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--text-2)} +.confbar{display:block;height:6px;background:var(--muted);border-radius:999px} +.confbar>span{display:block;height:100%;border-radius:999px;background:var(--c)} +.sug .acts{display:flex;align-items:center;justify-content:flex-end;gap:8px;min-width:236px;font-size:14px;color:var(--text-2)} +.done-chip{min-height:40px;display:inline-flex;align-items:center;gap:6px;padding:0 14px;border-radius:10px;background:var(--good-soft);color:var(--good-strong-text);font-size:14px;font-weight:600} +.bcal{display:flex;flex-direction:column;gap:6px;min-width:720px} +.bcal-h,.bcal-g{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:6px} +.bcal-h span{padding:0 8px;font-size:12px;font-weight:600;color:var(--text-3);text-transform:uppercase;letter-spacing:.06em} +.bcal-d{min-height:74px;border-radius:10px;padding:8px;background:var(--surface-2);border:1px solid var(--chart-grid);display:flex;flex-direction:column;gap:4px;min-width:0} +.bcal-d.blank{background:transparent;border-color:transparent} +.bcal-d.today{background:var(--accent-soft);border-color:var(--accent)} +.bcal-d .n{font-size:13px;font-weight:500;color:var(--text-body)} +.bcal-d.today .n{font-weight:700;color:var(--accent-strong-text)} +.bcal-d .b{font-size:11px;font-weight:600;color:var(--accent-strong-text);background:var(--accent-soft);padding:2px 6px;border-radius:5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.bcal-d.today .b{background:var(--surface)} +.icon-btn.sm{width:40px;height:40px;border-color:transparent;background:transparent} +.icon-btn.sm:hover{background:var(--surface-2)} +/* Transfers */ +.flow-wrap{display:flex;flex-direction:column;gap:20px} +.flow{display:grid;grid-template-columns:220px minmax(0,1fr) 240px;row-gap:16px;min-width:760px} +.flow-from{align-self:center;border:2px solid var(--accent);border-radius:14px;padding:18px 20px;background:var(--accent-soft);display:flex;flex-direction:column;gap:4px;min-width:0} +.flow-from.k-out{border:2px dashed var(--chart-neutral);background:var(--surface-2)} +.flow-from .eyebrow{color:var(--accent-strong-text)} +.flow-from.k-out .eyebrow{color:var(--text-3)} +.flow-from .n{font-size:17px;font-weight:700;overflow-wrap:anywhere} +.flow-from .m,.flow-to .m{font-size:13px;color:var(--text-2)} +.flow-arrow{display:flex;flex-direction:column;justify-content:center;gap:6px;padding:0 14px;min-height:92px} +.flow-arrow .l{font-size:13px;font-weight:600;text-align:center} +.flow-arrow .l span{color:var(--text-3);font-weight:500} +.flow-arrow .line{display:flex;align-items:center} +.flow-arrow .line>i{flex:1;height:3px;background:var(--c);border-radius:2px} +.flow-arrow .line>b{width:0;height:0;border-top:7px solid transparent;border-bottom:7px solid transparent;border-left:11px solid var(--c)} +.flow-arrow.dashed .line>i{height:0;background:none;border-top:3px dashed var(--c);border-radius:0} +.flow-to{border:1px solid var(--accent-border);background:var(--accent-soft);border-radius:14px;padding:14px 18px;display:flex;flex-direction:column;justify-content:center;gap:2px;min-height:92px;min-width:0} +.flow-to .n{font-size:15px;font-weight:700;overflow-wrap:anywhere} +.flow-to.k-good{border-color:var(--good-border);background:var(--good-soft)} +.flow-to.k-card{border-color:var(--card-border);background:var(--card-soft)} +.flow-to.k-out{border:1px dashed var(--chart-neutral);background:var(--surface-2)} +.kw-list{display:flex;flex-wrap:wrap;gap:8px} +.kw{display:inline-flex;align-items:center;gap:2px;height:34px;padding:0 4px 0 12px;border-radius:999px;background:var(--muted);font-size:13px;font-weight:500;color:var(--text-body)} +.kw button{width:28px;height:28px;border:0;background:transparent;border-radius:50%;color:var(--text-3);font-size:16px;line-height:1} +.kw button:hover{background:var(--surface);color:var(--danger-text)} +/* responsive */ +@media (max-width:1100px){.acct-cards{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media (max-width:1000px){.cols-3{grid-template-columns:minmax(0,1fr)}.cols-3>.span-2{grid-column:auto}} +@media (max-width:900px){ + .kpis{grid-template-columns:repeat(2,minmax(0,1fr))} + .bill-form .bf-grid{grid-template-columns:repeat(2,minmax(0,1fr))} + .bill-form .bf-grid .wide{grid-column:1/-1} +} +@media (max-width:720px){ + .acct-cards{grid-template-columns:minmax(0,1fr)} + .panel{padding:18px} + .toolbar,.list-foot,.bulk-bar{padding-left:16px;padding-right:16px} + .tx-table td.chk,.tx-table th.chk{padding-left:16px} + .tx-table td:last-child,.tx-table th:last-child{padding-right:16px} + .bars,.bars-x{gap:8px} + .bars .grp{gap:3px} + .hero-val{font-size:34px} + .sug .amt,.sug .conf{width:auto} + .sug .conf{flex:1 1 120px} + .sug .acts{min-width:0;justify-content:flex-start} + .flow{grid-template-columns:minmax(0,1fr);min-width:0;row-gap:6px} + .flow-from{grid-row:auto !important;margin-bottom:8px} + .flow-arrow{min-height:0;padding:2px 0} + .flow-arrow .l{text-align:left} + .flow-to{min-height:0;margin-bottom:10px} +} +@media (max-width:480px){ + .bars-x .v .full{display:none} + .bars-x .v .short{display:inline} +} +.tx-table .show-sm{display:none} +@media (max-width:600px){ + .hide-sm{display:none} + .tbl.fit-sm{min-width:0;table-layout:fixed;width:100%} + .fit-sm .w-date{width:64px} .fit-sm .w-amt{width:104px} .fit-sm .w-num{width:56px} + .tx-table.fit-sm td:nth-child(3){max-width:none !important} + .tx-table .show-sm{display:block} +} +@media (max-width:560px){ + .catbtn{grid-template-columns:minmax(0,1fr) auto;row-gap:6px} + .catbtn .track{grid-column:1/-1;grid-row:2} + .catbtn .p{display:none} +} +@media (max-width:480px){ + .kpis{gap:10px} + .kpi{padding:14px 16px} + .kpi .k-val{font-size:20px} + .field-row{grid-template-columns:minmax(0,1fr)} + .page-actions .acts{margin-left:0} +} +/* 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} +} @@ -458,14 +770,18 @@
-
v1.13.0 · FinLens
- - -
- -

Transaction Detail

-
-
+
v1.14.0 · FinLens
+ + + + diff --git a/js/aggregation.js b/js/aggregation.js index 8972dde..c39d6b6 100644 --- a/js/aggregation.js +++ b/js/aggregation.js @@ -84,12 +84,17 @@ function periodEndBalance(accountId) { /* ---------- RECURRING DETECTION ---------- */ const SUBS_KEYWORDS = ['NETFLIX','SPOTIFY','HULU','DISNEY+','APPLE.COM','ICLOUD','GOOGLE STORAGE','PRIME VIDEO','HBO','PARAMOUNT','PEACOCK','YOUTUBE','ADOBE','DROPBOX','MICROSOFT 365','LINKEDIN','NYTIMES','WSJ','AUDIBLE','PATREON','SUBSTACK','CHATGPT','ANTHROPIC','OPENAI','MIDJOURNEY','CANVA','NORDVPN','EXPRESSVPN','GITHUB']; +// Groups charges from the same merchant: letters and spaces only, upper case, 30 chars. +// detectRecurring() keys on it; bills confirmed from a detected charge store it (bill.recurringKey). +function recurringKey(desc) { + return (desc||'').toUpperCase().replace(/[^A-Z ]/g,'').replace(/\s+/g,' ').trim().slice(0,30); +} + function detectRecurring() { const txs=State.transactions.filter(t=>t.amount<0&&t.type!=='transfer'&&t.category!=='Transfer'); const groups={}; for (const t of txs) { - const key=t._originalDesc||t.description; - const k=key.toUpperCase().replace(/[^A-Z ]/g,'').replace(/\s+/g,' ').trim().slice(0,30); + const k=recurringKey(t._originalDesc||t.description); if (!k) continue; if (!groups[k]) groups[k]={items:[]}; groups[k].items.push(t); @@ -124,10 +129,15 @@ function detectRecurring() { return out.sort((a,b)=>b.confidence-a.confidence||b.avg-a.avg); } +// Groups deposits from the same source: digits removed, 30 chars. +function depositKey(desc) { + return (desc||'').replace(/\d/g,'').trim().slice(0,30); +} + function detectRecurringDeposits(txs) { const groups={}; for (const t of txs) { - const key=t.description.replace(/\d/g,'').trim().slice(0,30); + const key=depositKey(t.description); if (!groups[key]) groups[key]=[]; groups[key].push(t); } @@ -158,3 +168,146 @@ function accountDateRange(accountId) { const dates = txs.map(t => t.date).sort((a, b) => a - b); return { min: dates[0], max: dates[dates.length - 1] }; } + +/* ---------- BALANCE AT A DATE (v1.14.0) ---------- */ +// An account's balance at the end of `date`. With a manual (current) balance: that balance +// minus everything after `date`. Otherwise: starting balance plus everything up to `date`. +// Used for the Overview net-worth chart and account sparklines. +function balanceAt(accountId, date) { + const txs=State.transactions.filter(t=>t.account===accountId); + if (State.manualBalances[accountId]!=null) { + return Number(State.manualBalances[accountId])-txs.filter(t=>t.date>date).reduce((s,t)=>s+t.amount,0); + } + const initial=State.manualBalances[accountId+'_initial']!=null?Number(State.manualBalances[accountId+'_initial']):0; + return initial+txs.filter(t=>t.date<=date).reduce((s,t)=>s+t.amount,0); +} + +/* ---------- SPANS AND MONTHS (v1.14.0) ---------- */ +// First and last transaction dates, the days between them (inclusive) and that in months +// (days ÷ 30.44, the same count the AI summary states). null when there are none. +function dataSpan(txs) { + if (!txs.length) return null; + let min=Infinity, max=-Infinity; + for (const t of txs) { const v=t.date.getTime(); if (vmax) max=v; } + const first=new Date(min), last=new Date(max); + const days=Math.round((last-first)/86400000)+1; + return { first, last, days, months:days/30.44 }; +} +// Money in and out per calendar month, with the same rules as sumIncome() / sumExpense() +// (byMonth() counts card payments as income; this doesn't). Oldest first. +function monthlyFlow(txs) { + const m={}; + for (const t of txs) { const k=monthKey(t.date); (m[k]=m[k]||[]).push(t); } + return Object.keys(m).sort().map(k=>{ + const a=m[k], income=sumIncome(a), expense=sumExpense(a); + return { key:k, date:new Date(+k.slice(0,4), +k.slice(5,7)-1, 1), income, expense, net:income-expense, txs:a }; + }); +} + +/* ---------- TRANSFERS AND CARD PAYMENTS (v1.14.0) ---------- */ +// A payment toward a credit card: its own "Payment" row, or the card side of a transfer +// that detectTransfers() paired with the bank's autopay. +function isCardPayment(t) { + const a=State.accounts[t.account]; + return t.amount>0 && (t.type==='payment' || (t.type==='transfer' && !!a && a.kind==='credit_card')); +} +// Pairs each outgoing transfer leg with its incoming leg in another account (equal amount +// within $1, at most 2 days apart). Legs with no partner stay one-sided: `to` (or `from`) +// is null, meaning money left (or came from) outside FinLens. Newest first. +// → [{ date, from, to, amount, description, outId, inId, paired }] +function transferPairs(txs) { + const all=txs.filter(t=>t.type==='transfer'||['Transfer','Transfer in','Transfer out'].includes(t.category)); + const outgoing=all.filter(t=>t.amount<0||t.categories?.includes('Transfer out')); + const incoming=all.filter(t=>t.amount>0||t.categories?.includes('Transfer in')); + const used=new Set(), pairs=[]; + for (const out of outgoing) { + if (used.has(out.id)) continue; + const match=incoming.find(inn=>!used.has(inn.id)&&inn.account!==out.account&& + Math.abs(Math.abs(out.amount)-Math.abs(inn.amount))<1&&Math.abs((out.date-inn.date)/86400000)<=2); + used.add(out.id); + if (match) { + used.add(match.id); + pairs.push({ date:out.date, from:out.account, to:match.account, amount:Math.abs(out.amount), description:out.description, outId:out.id, inId:match.id, paired:true }); + } else { + pairs.push({ date:out.date, from:out.account, to:null, amount:Math.abs(out.amount), description:out.description, outId:out.id, inId:null, paired:false }); + } + } + for (const inn of incoming) { + if (used.has(inn.id)) continue; + pairs.push({ date:inn.date, from:null, to:inn.account, amount:Math.abs(inn.amount), description:inn.description, outId:null, inId:inn.id, paired:false }); + } + return pairs.sort((a,b)=>b.date-a.date); +} + +/* ---------- RECURRING DEPOSITS, IN DETAIL (v1.14.0) ---------- */ +// detectRecurringDeposits() plus what the Income screen shows: how many deposits, the +// account they land in, the next expected date and a confidence (High: a regular rhythm +// seen 4+ times; Medium: a regular rhythm seen 2–3 times; Low: no regular rhythm). +function recurringDepositsDetail(txs) { + const groups={}; + for (const t of txs) { const k=depositKey(t.description); (groups[k]=groups[k]||[]).push(t); } + return detectRecurringDeposits(txs).map(r=>{ + const arr=groups[r.source]||[]; + let next=null; + if (r.freq==='Monthly') { next=new Date(r.last); next.setMonth(next.getMonth()+1); } + else if (r.freq==='Bi-weekly') { next=new Date(r.last); next.setDate(next.getDate()+14); } + else if (r.freq==='Weekly') { next=new Date(r.last); next.setDate(next.getDate()+7); } + const maxDev=arr.length?Math.max(...arr.map(t=>Math.abs(t.amount-r.avg)/r.avg)):0; + const accts={}; arr.forEach(t=>{ accts[t.account]=(accts[t.account]||0)+1; }); + const account=(Object.entries(accts).sort((a,b)=>b[1]-a[1])[0]||[null])[0]; + const confidence=r.freq==='Irregular'?'Low':arr.length>=4?'High':'Medium'; + return { ...r, count:arr.length, next, account, confidence, steady:maxDev<=0.005 }; + }); +} + +/* ---------- BILLS (v1.14.0) ---------- */ +// Bill frequencies as stored (bill.frequency) → label, monthly cost factor, and step. +const BILL_FREQS={ + 'Monthly': { label:'Monthly', perMonth:1, months:1 }, + 'Bi-weekly':{ label:'Every 2 weeks', perMonth:26/12, days:14 }, + 'Weekly': { label:'Weekly', perMonth:52/12, days:7 }, + 'Quarterly':{ label:'Quarterly', perMonth:1/3, months:3 }, + 'Annual': { label:'Yearly', perMonth:1/12, months:12 }, + 'One-time': { label:'One-time', perMonth:0 }, +}; +function billFreq(b) { return BILL_FREQS[b.frequency]||BILL_FREQS.Monthly; } +// The k-th repeat of a bill's stored due date (k may be negative). Months keep the day +// of the month, clamped to short months, so a bill due on the 31st never drifts. +function billOccurrence(b, k) { + const a=parseDate(b.dueDate,'YYYY-MM-DD')||new Date(); + const f=billFreq(b); + if (f.days) return new Date(a.getFullYear(), a.getMonth(), a.getDate()+k*f.days); + if (!f.months) return a; + const y=a.getFullYear(), m=a.getMonth()+k*f.months; + const last=new Date(y, m+1, 0).getDate(); + return new Date(y, m, Math.min(a.getDate(), last)); +} +// Transactions that pay a bill: the merchant key it was confirmed from, or else its name +// inside the description. Newest first. +function billPayments(b) { + const name=(b.merchant||'').trim().toUpperCase(); + if (!b.recurringKey && !name) return []; + return State.transactions.filter(t=>t.amount<0 && (b.recurringKey + ? recurringKey(t._originalDesc||t.description)===b.recurringKey + : (t._originalDesc||t.description||'').toUpperCase().includes(name))).sort((x,y)=>y.date-x.date); +} +function billLastPaid(b) { const p=billPayments(b); return p.length?p[0].date:null; } +// The next due date: the stored date, moved on one repeat for every repeat a payment +// already covers (a payment up to 7 days early counts). One-time bills don't move. +function billNextDue(b) { + const f=billFreq(b); + let k=0, d=billOccurrence(b,0); + if (!f.days && !f.months) return d; + const lp=billLastPaid(b); + while (lp && lp.getTime()>=d.getTime()-7*86400000 && k<520) { k++; d=billOccurrence(b,k); } + return d; +} +// Every due date of a bill between two dates (inclusive), e.g. for a month calendar. +function billDatesBetween(b, from, to) { + const f=billFreq(b), out=[]; + if (!f.days && !f.months) { const d=billOccurrence(b,0); return d>=from&&d<=to?[d]:[]; } + let k=0; + while (billOccurrence(b,k)>from && k>-520) k--; + for (let d=billOccurrence(b,k); d<=to && k<520; d=billOccurrence(b,++k)) if (d>=from) out.push(d); + return out; +} diff --git a/js/ui.js b/js/ui.js index 456cdfc..22c7143 100644 --- a/js/ui.js +++ b/js/ui.js @@ -7,16 +7,25 @@ const VIEWS = {}; function registerView(id, title, render) { VIEWS[id]={title,render}; } +// Transactions and the four screens its filter pills open (Income, Spending, Bills, +// Transfers). The app bar keeps Transactions underlined on all five (v1.14.0). +const TX_VIEWS = ['transactions','income','spending','bills','transfers']; + function showView(id) { if (!VIEWS[id]) id='overview'; // Moving to another screen closes any open menu. Re-rendering the same screen (a filter // change from the Accounts popover) leaves it open, so several boxes can be toggled. if (id!==State.currentView) closeAppBarPopups(); - // App bar + menus: mark the current page. The Plan button stands for its five screens. + // App bar + menus: mark the current page. The Plan button stands for its five screens, + // and the Transactions link for its pill screens (aria-current="true" there, not "page"). $$('.mainnav [data-view], .menu [data-view], .mobile-menu [data-view], .appbar .gear').forEach(a=>{ - const on=a.dataset.view===id; - a.classList.toggle('active',on); - if (on) a.setAttribute('aria-current','page'); else a.removeAttribute('aria-current'); + const v=a.dataset.view; + const exact=v===id; + const parent=!exact && v==='transactions' && TX_VIEWS.includes(id) && !!a.closest('.mainnav, .mobile-menu'); + a.classList.toggle('active',exact||parent); + if (exact) a.setAttribute('aria-current','page'); + else if (parent) a.setAttribute('aria-current','true'); + else a.removeAttribute('aria-current'); }); 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'); @@ -35,11 +44,40 @@ function showView(id) { function renderActive() { showView(State.currentView||'overview'); } /* ---------- DRAWER ---------- */ -function openDrawer(html) { - $('#drawerBody').innerHTML=html; - $('#txDrawer').classList.add('open'); +// One shared side panel (#txDrawer in index.html) with a title row, a scrolling body and +// an optional footer pinned at the bottom: +// openDrawer(bodyHtml, { title, footer }) +// Older callers (Budget, Bucket, Debt forms) put their own

first in the body: it +// becomes the title. The scrim, × and Escape close it, and focus goes back to the +// element that opened it. +let _drawerReturnFocus=null; +function openDrawer(html, opts={}) { + const dr=$('#txDrawer'), body=$('#drawerBody'); + if (!dr||!body) return; + body.innerHTML=html; + let title=opts.title; + const h=body.firstElementChild; + if (!title && h && h.tagName==='H3') { title=h.textContent; h.remove(); } + const tt=$('#drawerTitle'); if (tt) tt.textContent=title||'Details'; + const foot=$('#drawerFoot'); + if (foot) { foot.innerHTML=opts.footer||''; foot.hidden=!opts.footer; } + if (!dr.classList.contains('open')) _drawerReturnFocus=document.activeElement; + dr.classList.add('open'); + dr.setAttribute('aria-hidden','false'); + const s=$('#drawerScrim'); if (s) s.hidden=false; + body.scrollTop=0; + const close=dr.querySelector('.drawer-head .close'); + if (close) setTimeout(()=>{ if (dr.classList.contains('open')) close.focus({preventScroll:true}); },0); +} +function closeDrawer() { + const dr=$('#txDrawer'); if (!dr) return; + const wasOpen=dr.classList.contains('open'); + dr.classList.remove('open'); + dr.setAttribute('aria-hidden','true'); + const s=$('#drawerScrim'); if (s) s.hidden=true; + if (wasOpen && _drawerReturnFocus && _drawerReturnFocus.isConnected) _drawerReturnFocus.focus({preventScroll:true}); + _drawerReturnFocus=null; } -function closeDrawer() { $('#txDrawer').classList.remove('open'); } /* ---------- THEME ---------- */ // Light only for now (v1.13.0). The dark theme and its Settings choice were taken out and @@ -154,125 +192,155 @@ function mergeChartOpts(extra) { return Object.assign({}, CHART_DEFAULTS, extra); } -/* ---------- SPARKLINE ---------- */ -function drawSpark(id, accountId, opts={}) { - const ctx=document.getElementById(id); - if (!ctx) return; - const txs=State.transactions.filter(t=>t.account===accountId).sort((a,b)=>a.date-b.date); - if (!txs.length) return; - const balances=currentBalances(); - let bal=balances[accountId]||0; - const series=[]; - for (let i=txs.length-1;i>=0;i--){ series.unshift(bal); bal-=txs[i].amount; } - series.unshift(bal); - const last30=series.slice(-30); - const lineColor=opts.color||chartColor('--chart-in'); - const fillColor=opts.bg||chartColor('--chart-in',.15); - new Chart(ctx,{ - type:'line', - data:{labels:last30.map((_,i)=>i),datasets:[{data:last30,borderColor:lineColor,backgroundColor:fillColor,fill:true,tension:.4,pointRadius:0,borderWidth:2}]}, - options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{x:{display:false},y:{display:false}}} - }); +/* ---------- SMALL FORMATTERS (v1.14.0) ---------- */ +// Signed money with a real minus sign: "+$2,450.00", "−$65.00". `zero` decides the sign of 0. +function fmtSigned(n, zero='+') { + if (n===null||n===undefined||isNaN(n)) return '—'; + const sign=n>0.004?'+':n<-0.004?'−':zero; + return sign+fmt(Math.abs(n)).replace('-',''); +} +// Axis labels: $0, $950, $2k, $12.5k, −$3k. +function fmtShort(v) { + const a=Math.abs(v), s=v<0?'−':''; + if (a>=1000) return s+'$'+(+(a/1000).toFixed(a%1000?1:0))+'k'; + return s+'$'+Math.round(a); +} +const ordinal=(n)=>n+(n%10===1&&n!==11?'st':n%10===2&&n!==12?'nd':n%10===3&&n!==13?'rd':'th'); +// Display name of an account (custom label first). +function acctName(id) { + if (!id) return 'Outside FinLens'; + return State.accountLabels?.[id]||State.accounts[id]?.name||id; } -/* ---------- HEATMAP ---------- */ -function renderHeatmap(holder, txs) { - const map={}; - txs.forEach(t=>{ const k=dayjs(t.date).format('YYYY-MM-DD'); map[k]=(map[k]||0)+Math.abs(t.amount); }); - const today=new Date(); - const start=new Date(today); start.setDate(start.getDate()-365); - while (start.getDay()!==0) start.setDate(start.getDate()-1); - const days=[]; - for (let d=new Date(start);d<=today;d.setDate(d.getDate()+1)) { - const k=dayjs(d).format('YYYY-MM-DD'); - days.push({date:new Date(d),amount:map[k]||0}); +/* ---------- INLINE SVG CHARTS (v1.14.0) ---------- */ +// The Overview, Spending and account cards draw small line charts as inline SVG. Their +// colors come from CSS classes in index.html (.lc-*, .spark, .hue-*), which read the +// theme tokens directly, without chartColor(). +function niceStep(x) { + if (!(x>0)) return 1; + const p=Math.pow(10,Math.floor(Math.log10(x))), f=x/p; + return (f<=1?1:f<=2?2:f<=2.5?2.5:f<=5?5:10)*p; +} +// pts: [{ v, tip }] evenly spaced left to right. +// opts: { w, h, hue, xLabels:[{ i, text }], valueAt (index to label with its value), +// hollowLast (an unfinished last point), dots (default true when ≤ 40 points) } +function svgLineChart(pts, opts={}) { + const w=opts.w||760, h=opts.h||180, L=40, R=12, T=18, B=28; + if (!pts.length) return ''; + const vals=pts.map(p=>p.v); + let lo=Math.min(0,...vals), hi=Math.max(0,...vals); + const step=niceStep((hi-lo)/2||1); + hi=Math.ceil(hi/step-1e-9)*step; lo=Math.floor(lo/step+1e-9)*step; + if (hi<=lo) hi=lo+step; + const pw=w-L-R, ph=h-T-B; + const X=i=>L+(pts.length<2?pw/2:i*pw/(pts.length-1)); + const Y=v=>T+(hi-v)/(hi-lo)*ph; + const out=[``]; + for (let v=lo; v<=hi+1e-9; v+=step) { + const y=Y(v).toFixed(1); + out.push(``); + out.push(`${fmtShort(v)}`); } - const max=Math.max(...days.map(d=>d.amount),1); - const cols=Math.ceil(days.length/7); - const html=[`
`]; - for (let col=0;col
'); continue; } - const r=d.amount/max; - let cls='cell'; - if (d.amount>0){ - if (r<0.2) cls+=' l1'; else if(r<0.4) cls+=' l2'; else if(r<0.6) cls+=' l3'; else if(r<0.8) cls+=' l4'; else cls+=' l5'; - } - html.push(`
`); - } - } - html.push(''); - holder.innerHTML=html.join(''); -} - -/* ---------- TRANSFER FLOW SVG ---------- */ -function renderTransferFlow(holder, paths) { - const accts=Object.values(State.accounts); - if (!accts.length){ holder.innerHTML='No accounts loaded.'; return; } - const w=520, h=Math.max(180,accts.length*60+40); - const neutral=chartColor('--chart-neutral'); - const colors={bank_checking:chartColor('--chart-in'),bank_savings:chartColor('--chart-save'),credit_card:chartColor('--chart-card'),unknown:neutral}; - const yFor=i=>30+i*60; - let svg=``; - svg+=``; - accts.forEach((a,i)=>{ - const c=colors[a.kind]||neutral; - svg+=``; - svg+=`${escapeHtml(a.name)}`; - svg+=``; - svg+=`${escapeHtml(a.name)}`; + out.push(``); + const dots=opts.dots??pts.length<=40; + pts.forEach((p,i)=>{ + const last=i===pts.length-1; + if (!dots && !last && i!==opts.valueAt) return; + const cls=last&&opts.hollowLast?'lc-pt hollow':'lc-pt'; + const r=last&&!opts.hollowLast||i===opts.valueAt?5:3.5; + out.push(`${escapeHtml(p.tip||fmt(p.v))}`); }); - for (const k in paths) { - const [from,to]=k.split('→'); - const fi=accts.findIndex(a=>a.id===from); - const ti=accts.findIndex(a=>a.id===to); - if (fi<0||ti<0) continue; - const count=paths[k]; - const stroke=Math.max(1.5,Math.min(8,count*1.5)); - svg+=``; - svg+=`×${count}`; + if (opts.valueAt!=null && pts[opts.valueAt]) { + const i=opts.valueAt; + out.push(`${fmt0(pts[i].v)}`); } - svg+=''; - holder.innerHTML=svg; + // x labels: drop any that would overlap the one before (the last label always stays) + const box=(l)=>{ + const wd=l.text.length*6.2, x=X(l.i); + const anchor=l.i===0&&pts.length>1?'start':l.i===pts.length-1&&pts.length>1?'end':'middle'; + return { l, anchor, a:anchor==='start'?x:anchor==='end'?x-wd:x-wd/2, b:anchor==='start'?x+wd:anchor==='end'?x:x+wd/2 }; + }; + const kept=[]; + (opts.xLabels||[]).map(box).forEach(bx=>{ + while (kept.length && bx.a1) kept.pop(); else return; + } + kept.push(bx); + }); + kept.forEach(bx=>out.push(`${escapeHtml(bx.l.text)}`)); + out.push(''); + return out.join(''); +} +// A sparkline that stretches to its box. hue: accent | good | card | warn +function sparkSvg(vals, hue, label) { + if (vals.length<2) return ''; + const lo=Math.min(...vals), hi=Math.max(...vals), span=hi-lo||1; + const pts=vals.map((v,i)=>`${(i*220/(vals.length-1)).toFixed(1)},${(40-(v-lo)/span*36).toFixed(1)}`).join(' '); + return ``; } -/* ---------- UPCOMING CALENDAR ---------- */ -function renderUpcomingCal(holder) { - const today=new Date(); - const start=startOfMonth(today); - const end=endOfMonth(today); - const days=end.getDate(); - const lead=start.getDay(); - const html=['
']; - ['S','M','T','W','T','F','S'].forEach(d=>html.push(`
${d}
`)); - for (let i=0;i
'); - for (let d=1;d<=days;d++) { - const bills=(State.bills||[]).filter(b=>{ - const bd=new Date(b.dueDate); return bd.getDate()===d&&bd.getMonth()===today.getMonth(); - }); - const isToday=d===today.getDate(); - const marks=bills.map(b=>{ - const dd=Math.ceil((new Date(b.dueDate)-today)/(1000*60*60*24)); - let cls='dot'; - if (b.paid) cls='dot gray'; - else if (dd<0) cls='dot red'; - else if (dd<=7) cls='dot amber'; - return ``; - }).join(''); - html.push(`
${d}
${marks}
`); +/* ---------- DAILY SPENDING HEATMAP (v1.14.0) ---------- */ +// One column per week (Sunday first), from `start` to `end`. Days are shaded in six +// steps by where they fall among the days that had spending (quartiles, then the top 5%), +// so a few large days (rent) don't wash everything else out. Days outside the period are blank. +function dailyHeatmapHtml(txs, start, end) { + const map={}; + txs.forEach(t=>{ const k=dayjs(t.date).format('YYYY-MM-DD'); map[k]=(map[k]||0)+Math.abs(t.amount); }); + const vals=Object.values(map).filter(v=>v>0).sort((a,b)=>a-b); + const q=p=>vals.length?vals[Math.min(vals.length-1,Math.floor(p*(vals.length-1)))]:0; + const th=[q(.25),q(.5),q(.75),q(.95)]; + const level=v=>v<=0?0:v<=th[0]?1:v<=th[1]?2:v<=th[2]?3:v<=th[3]?4:5; + const s=new Date(start.getFullYear(),start.getMonth(),start.getDate()); + const e=new Date(end.getFullYear(),end.getMonth(),end.getDate()); + const first=new Date(s); first.setDate(first.getDate()-first.getDay()); + const weeks=[], months=[]; + for (let d=new Date(first), w=0; d<=e; w++) { + const col=[]; + for (let i=0;i<7;i++,d.setDate(d.getDate()+1)) { + if (d.getDate()===1 || (w===0&&i===0)) { + const lbl=dayjs(de) { col.push(''); continue; } + const k=dayjs(d).format('YYYY-MM-DD'), v=map[k]||0; + col.push(``); + } + weeks.push(`${col.join('')}`); } - html.push(''); - holder.innerHTML=html.join(''); + // drop a month label that would sit on top of the previous one + const labels=months.filter((m,i)=>i===0||m.col-months[i-1].col>=3); + return `
+ +
+ + +
+
`; } /* ---------- BILL HELPERS ---------- */ -function confirmRecurring(key, merchant, amount, freq, nextDue, category) { - State.recurringConfirmed[key]='confirmed'; - lsSet('recurring',State.recurringConfirmed); - State.bills.push({merchant,amount,frequency:freq,dueDate:nextDue,category,paid:false,source:'auto'}); +// State.bills entries: { merchant, amount, category, frequency, dueDate:'YYYY-MM-DD', paid, +// source:'auto'|'manual', account?, subscription?, recurringKey? } (CLAUDE.md §4.1) +// Bills added in this session show "Just added" in the bills table. +const _justAddedBills=new Set(); +function billIsSubscription(b) { + if (b.subscription!=null) return !!b.subscription; + const m=(b.merchant||'').toUpperCase(); + return b.category==='Subscriptions' || SUBS_KEYWORDS.some(k=>m.includes(k)); +} +function addBill(bill) { + State.bills.push(bill); + _justAddedBills.add(bill); lsSet('bills',State.bills); +} +// Confirm a charge detectRecurring() spotted: it becomes a bill that pays from the same +// account, due on its next expected date. +function confirmRecurring(r) { + State.recurringConfirmed[r.key]='confirmed'; + lsSet('recurring',State.recurringConfirmed); + addBill({ merchant:r.merchant, amount:Math.round(r.avg*100)/100, frequency:r.freq, + dueDate:dayjs(r.nextDue).format('YYYY-MM-DD'), category:r.category, paid:false, source:'auto', + account:r.account||'', subscription:!!r.isSubscription, recurringKey:r.key }); renderActive(); } function dismissRecurring(key) { @@ -280,39 +348,68 @@ function dismissRecurring(key) { lsSet('recurring',State.recurringConfirmed); renderActive(); } +function undoDismissRecurring(key) { + delete State.recurringConfirmed[key]; + lsSet('recurring',State.recurringConfirmed); + renderActive(); +} function toggleBillPaid(i){ State.bills[i].paid=!State.bills[i].paid; lsSet('bills',State.bills); renderActive(); } -function deleteBill(i){ if(!confirm('Delete this bill?')) return; State.bills.splice(i,1); lsSet('bills',State.bills); renderActive(); } +// No confirm() here: the edit drawer's Delete button asks for a second click instead. +function deleteBill(i){ State.bills.splice(i,1); lsSet('bills',State.bills); renderActive(); } -function showBillForm(existing) { - const b=existing||{merchant:'',amount:0,frequency:'Monthly',dueDate:dayjs().format('YYYY-MM-DD'),category:'Bills & Utilities',paid:false}; - openDrawer(` -

${existing?'Edit':'Add'} Bill

- - - - - - - - -
- - `); +function _billAccountOptions(sel) { + return ``+orderedAccounts().map(a=>``).join(''); +} +function _billFreqOptions(sel) { + return Object.entries(BILL_FREQS).map(([v,f])=>``).join(''); +} +// Edit a bill (i ≥ 0) or add one (i < 0) in the drawer. +function showBillForm(i=-1) { + const b=i>=0?State.bills[i]:{merchant:'',amount:'',frequency:'Monthly',dueDate:dayjs().format('YYYY-MM-DD'),category:'Bills & Utilities',paid:false,account:''}; + const cats=[...new Set([...State.categories, b.category].filter(Boolean))]; + openDrawer(`
+ +
+ + +
+
+ + +
+ +
Flags + + +
+ ${i>=0&&b.recurringKey?`

Confirmed from a recurring charge FinLens spotted. Its last payment and next due date come from your transactions.

`:''}
`, + { title:i>=0?'Edit bill':'Add bill', + footer:`${i>=0?'':''}` }); + $('#bSave').onclick=()=>saveBill(i); + const del=$('#bDelete'); + if (del) del.onclick=()=>{ + if (del.dataset.armed!=='1') { del.dataset.armed='1'; del.textContent='Click again to delete'; return; } + closeDrawer(); deleteBill(i); + }; } -function saveBill() { - const bill={ - merchant:$('#bMerchant').value.trim(), +function saveBill(i=-1) { + const merchant=$('#bMerchant').value.trim(); + if (!merchant){ alert('Give the bill a name.'); return; } + const prev=i>=0?State.bills[i]:{source:'manual'}; + const bill={ ...prev, + merchant, amount:parseFloat($('#bAmount').value)||0, category:$('#bCategory').value, frequency:$('#bFreq').value, - dueDate:$('#bDue').value, + dueDate:$('#bDue').value||dayjs().format('YYYY-MM-DD'), + account:$('#bAccount').value, + subscription:$('#bSub').checked, paid:$('#bPaid').checked, - source:'manual' }; - if (!bill.merchant){ alert('Merchant required.'); return; } - State.bills.push(bill); - lsSet('bills',State.bills); - closeDrawer(); renderActive(); + closeDrawer(); + if (i>=0) { State.bills[i]=bill; if (_justAddedBills.has(prev)) _justAddedBills.add(bill); lsSet('bills',State.bills); } + else addBill(bill); + renderActive(); } /* ---------- CATEGORY HELPERS ---------- */ diff --git a/js/views-cleanup.js b/js/views-cleanup.js index f5d2a26..73166f6 100644 --- a/js/views-cleanup.js +++ b/js/views-cleanup.js @@ -23,6 +23,10 @@ const DataCleanup = { ['debts', 'Debts'], ['aiHistory', 'AI history'], ], + // Cleared together with a plan item: [State key, lsSet key, empty value, note] + PLAN_ALSO: { + bills: [['recurringConfirmed', 'recurring', {}, 'Also forgets which spotted recurring charges you confirmed or dismissed.']], + }, /* ---------- actions ---------- */ @@ -64,6 +68,7 @@ const DataCleanup = { if (!item) return; State[key] = []; lsSet(key, []); + (this.PLAN_ALSO[key] || []).forEach(([sk, lk, empty]) => { State[sk] = empty; lsSet(lk, empty); }); await this._finish(`${item[1]} cleared.`); }, @@ -216,7 +221,8 @@ registerView('data-cleanup', 'Data & Reset', (root) => {
${DataCleanup.PLAN_ITEMS.map(([key, label]) => { const len = (State[key] || []).length; - return row(label, key === 'aiHistory' ? plural(len, 'entry', 'entries') : n(len), '', btn('clearPlan', 'Clear', key)); + const also = (DataCleanup.PLAN_ALSO[key] || []).map(a => a[3]).join(' '); + return row(label, key === 'aiHistory' ? plural(len, 'entry', 'entries') : n(len), also, btn('clearPlan', 'Clear', key)); }).join('')}
`; root.appendChild(plans); diff --git a/js/views-main.js b/js/views-main.js index 958474b..276ed04 100644 --- a/js/views-main.js +++ b/js/views-main.js @@ -1,22 +1,114 @@ /* ================================================================ FINLENS — views-main.js - Overview, Transactions, Income, Bills, Spending, Transfers + The Finances screens (Clarity, v1.14.0): Overview, Transactions (All and + Payments), and the screens its filter pills open: Income, Spending, Bills, + Transfers. All four are registered views; the app bar keeps Transactions + underlined on them (TX_VIEWS in ui.js). ================================================================ */ +/* =================== SHARED PIECES =================== */ +const _svg=(paths,size=16)=>``; +const ICON={ + reload: _svg(''), + sparkle: _svg(''), + download:_svg(''), + search: _svg(''), + pencil: _svg(''), + bank: _svg('',18), + piggy: _svg('',18), + card: _svg('',18), +}; +const DAY=86400000; +const fmtSigned0=(n)=>(n>=0.5?'+':n<=-0.5?'−':'')+fmt0(Math.abs(n)).replace('-',''); +const plural=(n,one,many)=>`${n.toLocaleString()} ${n===1?one:(many||one+'s')}`; +const pctStr=(x,d=0)=>(x*100).toFixed(d)+'%'; +const cap=(s)=>s?s[0].toUpperCase()+s.slice(1):s; + +// The row under the page title: a note on the left, the screen's actions on the right. +// `note` and `acts` are HTML (callers escape what they put in). +function pageActions(root, note, acts) { + const d=document.createElement('div'); + d.className='page-actions'; + d.innerHTML=`${note?`

${note}

`:''}${acts?`
${acts}
`:''}`; + root.appendChild(d); + return d; +} + +// Transactions filter pills. All and Payments filter the Transactions list (txPillFilter); +// Income, Spending, Bills and Transfers open their own registered views. +const TX_PILLS=[['all','All','transactions'],['income','Income','income'],['spending','Spending','spending'], + ['bills','Bills','bills'],['payments','Payments','transactions'],['transfers','Transfers','transfers']]; +function renderTxPills(root, current) { + const nav=document.createElement('nav'); + nav.className='fpills'; + nav.setAttribute('aria-label','Transaction filters'); + nav.innerHTML=TX_PILLS.map(([k,l,v])=>`
${l}`).join(''); + nav.addEventListener('click',e=>{ + const a=e.target.closest('[data-pill]'); + if (!a) return; + e.preventDefault(); + const k=a.dataset.pill; + txPillFilter=k; txPage=1; selectedTxIds.clear(); + showView(TX_PILLS.find(p=>p[0]===k)[2]); + const now=$(`#content .fpill[data-pill="${k}"]`); + if (now) now.focus({preventScroll:true}); + }); + root.appendChild(nav); +} + +// KPI tiles: [{ label, value (HTML), sub, cls }] +function kpiTiles(items) { + return `
${items.map(k=>`
${k.label}${k.value}${k.sub!=null?`${k.sub}`:''}
`).join('')}
`; +} +// The active range for a sentence: "this month", "all time", or "Dec 1, 2026 – Dec 31, 2026". +function rangeText() { const r=describeRange(); return State.range.mode==='custom'?r:r.toLowerCase(); } +function emptyPanel(msg) { return `

${msg}

`; } +function appendHtml(root, html) { root.insertAdjacentHTML('beforeend', html); } + +// In-view links: . Optional data-tab (a Settings +// tab), data-pill (the Transactions filter) and data-cat (its category filter). +function wireLinks(root) { + root.addEventListener('click',e=>{ + const a=e.target.closest('[data-goto]'); + if (!a||!root.contains(a)) return; + e.preventDefault(); + if (a.dataset.tab) settingsTab=a.dataset.tab; + if (a.dataset.pill) txPillFilter=a.dataset.pill; + if (a.dataset.cat!=null) { txCatFilter=a.dataset.cat; txSearch=''; txPage=1; } + showView(a.dataset.goto); + window.scrollTo(0,0); + }); +} +// Rows whose [data-open] element opens the transaction drawer. +function wireTxOpeners(root) { + root.addEventListener('click',e=>{ + const b=e.target.closest('[data-open]'); + if (b&&root.contains(b)) showTxDrawer(b.dataset.open); + }); +} +const isCashAcct=a=>a.kind==='bank_checking'||a.kind==='bank_savings'; +const isCardAcct=a=>a.kind==='credit_card'; +// Card balances count as debt whichever sign they were entered with (as before v1.14.0). +const debtOf=b=>b==null||isNaN(b)?0:Math.abs(b); +const KIND_LABEL={bank_checking:'Checking',bank_savings:'Savings',credit_card:'Credit card',unknown:'Account'}; +const FREQ_LABEL={'Bi-weekly':'Every 2 weeks',Monthly:'Monthly',Weekly:'Weekly',Quarterly:'Every 3 months',Annual:'Yearly',Irregular:'Irregular'}; +const medianDay=(dates)=>{ const d=dates.map(x=>x.getDate()).sort((a,b)=>a-b); return d.length?d[Math.floor((d.length-1)/2)]:null; }; +// "Monthly, around the 16th" from a list of dates. +function rhythmOf(dates) { + if (dates.length<2) return ''; + const s=[...dates].sort((a,b)=>a-b); + const gaps=s.slice(1).map((d,i)=>(d-s[i])/DAY); + const g=gaps.reduce((a,b)=>a+b,0)/gaps.length; + if (g>=27&&g<=33) return `Monthly, around the ${ordinal(medianDay(s))}`; + if (g>=12&&g<=16) return 'Every 2 weeks'; + if (g>=6&&g<=8) return 'Weekly'; + return ''; +} + /* =================== OVERVIEW =================== */ -registerView('overview','Overview',(root)=>{ - const txs=filteredTx(); - // Use period-aware balances so the cards reflect the selected date range - const balances={}; - orderedAccounts().forEach(a=>{ balances[a.id]=periodEndBalance(a.id); }); - const cash=orderedAccounts().filter(a=>a.kind==='bank_checking'||a.kind==='bank_savings').reduce((s,a)=>s+(balances[a.id]||0),0); - const debt=orderedAccounts().filter(a=>a.kind==='credit_card').reduce((s,a)=>{ const b=balances[a.id]; if(b==null) return s; return s+(b<0?Math.abs(b):b); },0); - const net=cash-debt; - const income=sumIncome(txs); - const expense=sumExpense(txs); - const cashflow=income-expense; - const savingsRate=income>0?(income-expense)/income:0; +let nwPeriod='all'; // net worth chart: '1m' | '3m' | 'all' +registerView('overview','Overview',(root)=>{ if (!State.transactions.length) { root.innerHTML=`

Welcome to FinLens 👋

@@ -29,1045 +121,1216 @@ registerView('overview','Overview',(root)=>{

`; return; } + wireLinks(root); + wireTxOpeners(root); + pageActions(root, escapeHtml(dayjs().format('dddd, MMMM D')), + ` +
${ICON.sparkle}Ask AI about this`); + $('#ovReload').onclick=()=>reloadDataFiles(); + + const accts=orderedAccounts(); + const txs=filteredTx(); + const endBal={}; accts.forEach(a=>{ endBal[a.id]=periodEndBalance(a.id); }); + const netWith=(balOf)=>accts.reduce((s,a)=>isCashAcct(a)?s+(balOf(a.id)||0):isCardAcct(a)?s-debtOf(balOf(a.id)):s,0); + const net=netWith(id=>endBal[id]); + // The balance history ends at the range end or the last transaction, whichever is first. + const span=dataSpan(State.transactions); + const rEnd=State.range.end; + const seriesEnd=span?new Date(Math.min(rEnd?rEnd.getTime():Infinity, new Date(span.last).setHours(23,59,59))):null; + const hasHistory=!!(span&&seriesEnd>=span.first); + const netAt=(d)=>netWith(id=>balanceAt(id,d)); + + /* ---- Net worth + latest month ---- */ + const row1=document.createElement('div'); row1.className='cols-3'; + const money=fmt(net), dot=money.lastIndexOf('.'); + let deltaHtml=''; + if (hasHistory) { + const prevEnd=new Date(seriesEnd.getFullYear(), seriesEnd.getMonth(), 0, 23,59,59); + if (prevEnd>=span.first) { + const ch=netAt(seriesEnd)-netAt(prevEnd); + deltaHtml=`
${ch>=0?'Up':'Down'} ${fmt(Math.abs(ch))} since ${dayjs(prevEnd).format('MMM D')}
`; + } + } + const flow=monthlyFlow(txs); + const latest=flow[flow.length-1]; + let latestHtml; + if (latest) { + const last=dataSpan(latest.txs).last; + const full=last.getDate()===endOfMonth(last).getDate(); + const rate=latest.income>0?latest.net/latest.income:null; + const recent=flow.slice(-6).filter(m=>m.income>0); + const avg=recent.length?recent.reduce((s,m)=>s+m.net/m.income,0)/recent.length:null; + latestHtml=` +
+

Latest month · ${dayjs(latest.date).format('MMMM')}

+

${full?'Full month':`Data runs through ${dayjs(last).format('MMM D')}`}

+
+
+
Money in${fmtSigned(latest.income)}
+
Money out${fmtSigned(-latest.expense,'−')}
+
Net${fmtSigned(latest.net)}
+
+ ${rate==null?'':`
+
Savings rate${pctStr(rate)}
+ + ${recent.length>1&&avg!=null?`${recent.length}-month average ${pctStr(avg)}`:''} +
`} + See trends →`; + } else { + latestHtml=`

Latest month

No transactions in ${escapeHtml(rangeText())}.

`; + } + row1.innerHTML=` +
+
+
+

Net worth

+
${money.slice(0,dot)}${money.slice(dot)}
+ ${deltaHtml} +
+ ${hasHistory?`
+ ${[['1m','1M'],['3m','3M'],['all','All']].map(([k,l])=>``).join('')} +
`:''} +
+
${hasHistory?'':'

No balance history before this period.

'}
+
+
${latestHtml}
`; + root.appendChild(row1); - // Metric cards - const metrics=document.createElement('div'); metrics.className='grid grid-4'; - metrics.innerHTML=` -

Total Cash

${fmt(cash)}
Bank Checking + Savings
-

Total Debt

${fmt(debt)}
Credit card balances
-

Net Worth

${fmt(net)}
Cash − Debt
-

Cash Flow

${fmt(cashflow)}
Savings rate ${pct(savingsRate)}
`; - root.appendChild(metrics); - - // Account cards — rendered in user-defined order - const accts=document.createElement('div'); accts.className='grid grid-3'; - orderedAccounts().forEach(a=>{ - const bal=balances[a.id]; - const limit=State.manualBalances[a.id+'_limit']; - const util=(a.kind==='credit_card'&&limit)?(Math.abs(bal||0)/limit):null; - const periodNet=filteredTx().filter(t=>t.account===a.id).reduce((s,t)=>s+t.amount,0); - const netLabel=periodNet===0?'':`· Net ${periodNet>=0?'+':''}${fmt(periodNet)}`; - const netSummary=periodNet===0?'No activity this period':`Net ${periodNet>=0?'+':''}${fmt(periodNet)}`; - const sparkId='sp_'+a.id; - const isCC=a.kind==='credit_card'; - const c=document.createElement('div'); c.className='card'; - c.innerHTML=` -

${escapeHtml(State.accountLabels?.[a.id]||a.name)}

-
${isCC?fmt(Math.abs(bal||0)):fmt(bal)}
- ${isCC - ?`
Limit ${fmt(limit||0)} · Util. ${util==null?'—':pct(util)} ${netLabel}
` - :`
${netSummary}
`} -
`; - accts.appendChild(c); - setTimeout(()=>drawSpark(sparkId,a.id,isCC?{color:chartColor('--chart-card'),bg:chartColor('--chart-card',.15)}:{}),0); + const drawNetWorth=()=>{ + const holder=$('#nwChart'); if (!holder||!hasHistory) return; + const first=new Date(span.first); + const dates=[]; + if (nwPeriod==='all') { + dates.push(new Date(first.getFullYear(),first.getMonth(),first.getDate(),23,59,59)); + for (let m=new Date(first.getFullYear(),first.getMonth()+1,0,23,59,59); mdates[0]) dates.push(m); + if (seriesEnd>dates[dates.length-1]) dates.push(seriesEnd); + } else { + const days=nwPeriod==='1m'?30:91, step=nwPeriod==='1m'?1:7; + const start=new Date(Math.max(first.getTime(), seriesEnd.getTime()-days*DAY)); + for (let d=new Date(start); ddates[dates.length-1]) dates.push(seriesEnd); + } + const pts=dates.map(d=>({ v:netAt(d), tip:`${dayjs(d).format('MMM D, YYYY')}: ${fmt(netAt(d))}` })); + const labels=[]; + if (nwPeriod==='all') { + dates.forEach((d,i)=>{ + if (i===0||i===dates.length-1) labels.push({i,text:dayjs(d).format('MMM D')}); + else labels.push({i,text:dayjs(d).format('MMM')}); + }); + } else { + const every=Math.max(1,Math.ceil(dates.length/6)); + dates.forEach((d,i)=>{ if (i===0||i===dates.length-1||(i%every===0&&dates.length-1-i>=every/2)) labels.push({i,text:dayjs(d).format('MMM D')}); }); + } + const a=pts[0].v, b=pts[pts.length-1].v; + const w=Math.max(300,Math.min(900,Math.round(holder.clientWidth||760))); + holder.innerHTML=svgLineChart(pts,{ w, h:190, hue:'accent', xLabels:labels, + ariaLabel:`Net worth ${b>=a?'rose':'fell'} from ${fmt0(a)} on ${dayjs(dates[0]).format('MMMM D')} to ${fmt0(b)} on ${dayjs(dates[dates.length-1]).format('MMMM D')}` }); + }; + drawNetWorth(); + $$('[data-nw]',row1).forEach(btn=>btn.onclick=()=>{ + nwPeriod=btn.dataset.nw; + $$('[data-nw]',row1).forEach(b=>b.setAttribute('aria-pressed',String(b===btn))); + drawNetWorth(); }); - root.appendChild(accts); - - // Cash flow chart + upcoming bills (next 5 table) - const upcomingBills=(State.bills||[]).filter(b=>!b.paid).sort((a,b)=>new Date(a.dueDate)-new Date(b.dueDate)).slice(0,5); - const today=new Date(); today.setHours(0,0,0,0); - const billListHtml=upcomingBills.length?` - - - ${upcomingBills.map(b=>{ - const dd=new Date(b.dueDate); dd.setHours(0,0,0,0); - const days=Math.round((dd-today)/86400000); - let badgeStyle; - if (days<0) badgeStyle='color:var(--red);font-weight:600'; - else if (days<=7) badgeStyle='color:var(--amber);font-weight:600'; - else badgeStyle='color:var(--text-2)'; - const dateStr=days<0?`Overdue ${Math.abs(days)}d`: - days===0?`Today`: - `${dayjs(b.dueDate).format('MMM D')}`; - return ` - - - - `; - }).join('')} -
DateBillAmount
${dateStr}${escapeHtml(b.merchant)}
${b.frequency||'Monthly'}
${fmt(b.amount)}
` - :`

No upcoming bills. Add bills in the Bills tab.

`; - const row1=document.createElement('div'); row1.className='grid grid-2'; - row1.innerHTML=` -
-

Cash Flow

-
-
-
-

Upcoming Bills

-
${billListHtml}
-
`; - root.appendChild(row1); + /* ---- Accounts ---- */ + const acctSec=document.createElement('section'); + acctSec.className='acct-section'; + acctSec.setAttribute('aria-labelledby','ovAcctH'); + const pairsAll=transferPairs(State.transactions); + acctSec.innerHTML=` +
${accts.map(a=>accountCardHtml(a,endBal[a.id],seriesEnd,pairsAll)).join('')}
`; + root.appendChild(acctSec); + wireAccountRename(acctSec); + + /* ---- Cash flow + upcoming bills ---- */ + const row2=document.createElement('div'); row2.className='cols-3'; + const months=flow.slice(-6); + let cfHtml; + if (months.length) { + const max=Math.max(1,...months.map(m=>Math.max(m.income,m.expense))); + const peakIn=months.reduce((p,m)=>m.income>p.income?m:p,months[0]); + const peakOut=months.reduce((p,m)=>m.expense>p.expense?m:p,months[0]); + const mName=(m)=>dayjs(m.date).format('MMMM'); + cfHtml=` + +
${months.map(m=>`
${dayjs(m.date).format('MMM')}
${fmtSigned0(m.net)}
`).join('')}
`; + } else cfHtml=`

No transactions in ${escapeHtml(rangeText())}.

`; + row2.innerHTML=` +
+

Cash flow

+
Money inMoney out
+ ${cfHtml} +
+
${upcomingBillsHtml()}
`; + root.appendChild(row2); - // Credit Cards - Most Expensive Transactions - const ccAccts=orderedAccounts().filter(a=>a.kind==='credit_card'); - const ccAcctIds=ccAccts.map(a=>a.id); - const ccExpenses=txs.filter(t=>ccAcctIds.includes(t.account)&&t.amount<0&&t.type!=='transfer').sort((a,b)=>a.amount-b.amount).slice(0,5); - if (ccAccts.length) { - const topCardTxCard=document.createElement('div'); topCardTxCard.className='card'; - topCardTxCard.innerHTML=`

Credit Cards — Most Expensive Transactions

- ${ccExpenses.length?` - - ${ccExpenses.map(t=>` - - - - - - `).join('')} -
DateDescriptionAccountCategoryAmount
${dayjs(t.date).format('MMM D')}${escapeHtml(t.description)}${State.accounts[t.account]?.name||t.account}${t.category}${fmt(t.amount)}
`:`

No credit card transactions in selected period.

`}`; - root.appendChild(topCardTxCard); + /* ---- Largest card purchases ---- */ + const cards=accts.filter(isCardAcct); + if (cards.length) { + const cardIds=new Set(cards.map(a=>a.id)); + const cardTx=txs.filter(t=>cardIds.has(t.account)&&t.amount<0&&t.type!=='transfer'); + const lastMonth=cardTx.length?monthKey(dataSpan(cardTx).last):null; + const inMonth=cardTx.filter(t=>monthKey(t.date)===lastMonth).sort((a,b)=>a.amount-b.amount).slice(0,5); + const which=new Set(inMonth.map(t=>t.account)); + const sub=lastMonth?`${escapeHtml(which.size===1?acctName([...which][0]):cards.length===1?acctName(cards[0].id):'All cards')} · ${dayjs(lastMonth+'-01').format('MMMM')}`:''; + const sec=document.createElement('section'); + sec.className='panel'; + sec.setAttribute('aria-labelledby','ovTopH'); + sec.innerHTML=`

Largest card purchases

${sub?`

${sub}

`:''}
+ All transactions →
+ ${inMonth.length?`
+ + ${inMonth.map(t=>` + + + + `).join('')}
MerchantDateCategoryAmount
${dayjs(t.date).format('MMM D')}${escapeHtml(t.category)}${fmtSigned(t.amount)}
` + :`

No card purchases in ${escapeHtml(rangeText())}.

`}`; + root.appendChild(sec); } +}); - // Recent Transactions — top 5 across bank checking + savings combined - const bankAccts=orderedAccounts().filter(a=>a.kind==='bank_checking'||a.kind==='bank_savings'); - if (bankAccts.length) { - const bankIds=new Set(bankAccts.map(a=>a.id)); - const recentBank=filteredTx().filter(t=>bankIds.has(t.account)).slice(0,5); - const recentCard=document.createElement('div'); recentCard.className='card'; - recentCard.innerHTML=`

Recent Transactions

- ${recentBank.length?` - - ${recentBank.map(t=>` - - - - - `).join('')} -
DateDescriptionAccountAmount
${dayjs(t.date).format('MMM D')}${escapeHtml(t.description)}${escapeHtml(State.accountLabels?.[t.account]||State.accounts[t.account]?.name||t.account)}${fmt(t.amount)}
`:`

No transactions in selected period.

`}`; - root.appendChild(recentCard); +// 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) { + const own=State.transactions.filter(t=>t.account===a.id); + const name=acctName(a.id); + const manual=State.manualBalances[a.id]!=null; + const kind=a.kind; + const tile=kind==='bank_savings'?['t-good',ICON.piggy]:kind==='credit_card'?['t-card',ICON.card]:['',ICON.bank]; + let sub=`${KIND_LABEL[kind]||'Account'} · ${plural(own.length,'transaction')}`; + let middle='', foot=''; + const sparkVals=()=>{ + if (!own.length||!seriesEnd) return []; + const first=dataSpan(own).first.getTime(), end=seriesEnd.getTime(); + if (end<=first) return []; + const n=24, out=[]; + for (let i=0;iy.date-x.date); + const lastPair=pays.length?pairsAll.find(p=>p.inId===pays[0].id):null; + const autopay=!!(lastPair&&lastPair.outId&&/auto\s?pay/i.test(State.transactions.find(t=>t.id===lastPair.outId)?.description||'')); + const payNote=autopay?'Autopay on':pays.length?`Last paid ${dayjs(pays[0].date).format('MMM D')}`:'No payments yet'; + const balHtml=`${fmt(owed)} owed`; + middle=limit + ?`
+
${pctStr(owed/limit)} of ${fmt0(limit)} limit${payNote}
` + :`
No credit limit set · Add one${payNote}
`; + foot=manual?'Balance entered in Settings → Accounts':'Computed from imported transactions'; + return accountCardShell(a,name,sub,tile,balHtml,middle,foot); } - - // Quick stats - const top=byCategory(txs,'expense')[0]; - const merchantMap={}; - txs.filter(t=>t.amount<0&&t.type!=='transfer').forEach(t=>{ const k=t.description.slice(0,40); merchantMap[k]=(merchantMap[k]||0)+1; }); - const topMerchant=Object.entries(merchantMap).sort((a,b)=>b[1]-a[1])[0]; - const incomeSrc=byCategory(txs,'income')[0]; - const stats=document.createElement('div'); stats.className='grid grid-3'; - stats.innerHTML=` -

Top Spending Category

${top?top.category:'—'}
${top?fmt(top.amount):''}
-

Most Frequent Merchant

${topMerchant?topMerchant[0]:'—'}
${topMerchant?topMerchant[1]+' transactions':''}
-

Top Income Source

${incomeSrc?fmt(incomeSrc.amount):'—'}
${incomeSrc?incomeSrc.category:''}
`; - root.appendChild(stats); - - // Wire up editable KPI card labels (double-click to rename) - setTimeout(()=>{ - $$('h3.kpi-label').forEach(h3=>{ - h3.style.cursor='text'; - h3.addEventListener('dblclick',()=>{ - const id=h3.dataset.acctId; - const cur=h3.textContent.trim(); - const inp=document.createElement('input'); - inp.className='input'; inp.value=cur; - inp.style.cssText='font-size:13px;font-weight:500;padding:3px 6px;height:28px;width:100%;margin:0'; - h3.replaceWith(inp); inp.focus(); inp.select(); - const save=()=>{ - const newName=inp.value.trim()||cur; - if (!State.accountLabels) State.accountLabels={}; - State.accountLabels[id]=newName; - if (State.accounts[id]) State.accounts[id].name=newName; - lsSet('accountLabels',State.accountLabels); - buildAccountFilter(); - renderActive(); - }; - inp.addEventListener('blur',save); - inp.addEventListener('keydown',e=>{ - if (e.key==='Enter'){e.preventDefault();save();} - if (e.key==='Escape'){inp.replaceWith(h3);} - }); - }); - }); - },0); - - // Draw charts - setTimeout(()=>{ - const ctx=$('#cfChart'); - if (ctx) { - new Chart(ctx,{ - type:'bar', - data:{labels:['Income','Spending','Transfers'],datasets:[{data:[income,expense,sumTransfers(txs)],backgroundColor:[chartColor('--chart-in'),chartColor('--chart-out'),chartColor('--chart-neutral')],borderRadius:6}]}, - options:{responsive:true,maintainAspectRatio:false,indexAxis:'y',plugins:{legend:{display:false}},scales:{x:{ticks:{callback:v=>'$'+v.toLocaleString()}}}} + const vals=sparkVals(); + const hue=kind==='bank_savings'?'good':'accent'; + middle=vals.length>1?sparkSvg(vals,hue,`${name} balance trend, ${vals[vals.length-1]>=vals[0]?'rising':'falling'}`):''; + if (kind==='bank_savings') { + const interest=own.filter(t=>t.amount>0&&/interest/i.test(t._originalDesc||t.description)&&(!seriesEnd||t.date<=seriesEnd)).reduce((s,t)=>s+t.amount,0); + if (interest>0) sub=`Savings · interest ${fmt(interest)} to date`; + const buckets=State.buckets||[]; + if (buckets.length) { + const assigned=buckets.reduce((s,b)=>s+(Number(b.current)||0),0); + foot=`${assigned>=(bal||0)-0.005?'Fully assigned':`${fmt0(assigned)} assigned`} to ${plural(buckets.length,'bucket')} · View`; + } else foot=`No savings buckets yet · Create one`; + } else { + foot=manual?'Balance entered in Settings → Accounts' + :State.manualBalances[a.id+'_initial']!=null?'Starting balance plus imported transactions' + :`Sum of imported transactions · Set balance`; + } + return accountCardShell(a,name,sub,tile,fmt(bal),middle,foot); +} +function accountCardShell(a,name,sub,tile,balHtml,middle,foot) { + return `
+
+ ${tile[1]} +
+ ${escapeHtml(name)} +
${sub}
+
+
+
${balHtml}
+ ${middle} + ${foot} +
`; +} +// Double-click an account name (or focus it and press Enter) to rename it. The name is +// saved in State.accountLabels and used everywhere. +function wireAccountRename(scope) { + $$('.acct-name',scope).forEach(el=>{ + const start=()=>{ + const id=el.dataset.acctId, cur=el.textContent.trim(); + const inp=document.createElement('input'); + inp.className='input'; inp.value=cur; + inp.setAttribute('aria-label','Account name'); + inp.style.cssText='font-size:15px;font-weight:600;min-height:32px;padding:3px 8px'; + el.replaceWith(inp); inp.focus(); inp.select(); + let done=false; + const save=()=>{ + if (done) return; done=true; + const newName=inp.value.trim()||cur; + if (!State.accountLabels) State.accountLabels={}; + State.accountLabels[id]=newName; + if (State.accounts[id]) State.accounts[id].name=newName; + lsSet('accountLabels',State.accountLabels); + buildAccountFilter(); + renderActive(); + }; + inp.addEventListener('blur',save); + inp.addEventListener('keydown',e=>{ + if (e.key==='Enter'){ e.preventDefault(); save(); } + if (e.key==='Escape'){ done=true; e.stopPropagation(); inp.replaceWith(el); el.focus(); } }); - } - },0); -}); + }; + el.addEventListener('dblclick',start); + el.addEventListener('keydown',e=>{ if (e.key==='Enter'||e.key==='F2'){ e.preventDefault(); start(); } }); + }); +} +// Overview: bills due in the next three weeks (and any overdue). With no bills yet, the +// recurring charges FinLens spotted that are due in that window, marked as not confirmed. +function upcomingBillsHtml() { + const t0=today(), horizon=new Date(t0.getTime()+21*DAY); + const bills=State.bills||[]; + let items, spotted=false; + if (bills.length) { + items=bills.map(b=>({ name:b.merchant, amount:b.amount, due:billNextDue(b), paid:b.paid })).filter(x=>!x.paid&&x.due<=horizon); + } else { + spotted=true; + items=detectRecurring().filter(r=>!State.recurringConfirmed[r.key]&&r.nextDue>=t0&&r.nextDue<=horizon) + .map(r=>({ name:r.merchant, amount:r.avg, due:r.nextDue })); + } + items.sort((a,b)=>a.due-b.due); + const rows=items.slice(0,6).map(x=>{ + const days=Math.round((new Date(x.due.getFullYear(),x.due.getMonth(),x.due.getDate())-t0)/DAY); + const pill=days<0?`Overdue ${-days}d`:days===0?'Due today':''; + return `
${dayjs(x.due).format('MMM')}
${x.due.getDate()}
+
${escapeHtml(x.name)}${pill?`
${pill}
`:''}
${fmt(x.amount)}
`; + }).join(''); + return `

Upcoming bills

Next 3 weeks
+ ${rows?`
${rows}
`:`

Nothing due in the next 3 weeks.

`} + ${spotted&&rows?`

Spotted in your transactions, not confirmed as bills yet.

`:''} + ${spotted?'Review in Bills →':'All bills →'}`; +} -/* =================== TRANSACTIONS =================== */ +/* =================== TRANSACTIONS (All · Payments) =================== */ let txSort={key:'date',dir:'desc'}; let txPage=1; let txSearch=''; let txCatFilter='all'; -let txPillFilter='all'; // all | income | spending | bills | payments | transfers +let txPillFilter='all'; // the current pill: all | income | spending | bills | payments | transfers let txAmtMode=''; let txAmtVal=null; let txAmtVal2=null; let selectedTxIds=new Set(); +const TX_PAGE_SIZE=50; +const TX_SORTS=[['date-desc','Newest first'],['date-asc','Oldest first'],['amount-desc','Largest amount'],['amount-asc','Smallest amount'],['description-asc','Description A–Z']]; +const FLAG_LABEL={bill:'Bill',recurring:'Recurring',subscription:'Subscription'}; registerView('transactions','Transactions',(root)=>{ - const txs=filteredTx(); - const TRANSFER_CATS=['Transfer in','Transfer out']; - const cats=['all','(Uncategorized)',...new Set(txs.flatMap(t=>t.categories||[t.category]).filter(c=>c&&!TRANSFER_CATS.includes(c)&&c!=='Other'))]; - - // Filter pills - const pillBar=document.createElement('div'); - pillBar.style.cssText='display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px'; - const PILLS=[['all','All'],['income','Income'],['spending','Spending'],['bills','Bills'],['payments','Payments'],['transfers','Transfers']]; - pillBar.innerHTML=PILLS.map(([k,l])=>``).join(''); - root.appendChild(pillBar); - pillBar.querySelectorAll('[data-pill]').forEach(btn=>btn.onclick=()=>{txPillFilter=btn.dataset.pill;txPage=1;renderActive();}); + // Income, Spending, Bills and Transfers are their own screens; this one lists All or Payments. + if (!['all','payments'].includes(txPillFilter)) txPillFilter='all'; + const pay=txPillFilter==='payments'; + const all=filteredTx(); + const base=pay?all.filter(isCardPayment):all; + wireLinks(root); + const files=Object.values(State.accounts).filter(a=>a.sourceFile&&a.sourceFile!=='manual').length; + pageActions(root, files?plural(files,'CSV file'):'', + `Transaction rules + `); + renderTxPills(root, txPillFilter); + + if (pay) { + const total=base.reduce((s,t)=>s+t.amount,0); + const bals=currentBalances(); + const owed=orderedAccounts().filter(isCardAcct).reduce((s,a)=>s+debtOf(bals[a.id]),0); + appendHtml(root,kpiTiles([ + {label:'Card payments',value:base.length.toLocaleString()}, + {label:'Total paid',value:fmt(total)}, + {label:'Average payment',value:base.length?fmt(total/base.length):'—'}, + {label:'Card balance now',value:fmt(owed),cls:'c-card'}, + ])); + } else { + const inc=sumIncome(base), out=sumExpense(base); + appendHtml(root,kpiTiles([ + {label:'Transactions',value:base.length.toLocaleString()}, + {label:'Money in',value:fmtSigned(inc),cls:'c-good'}, + {label:'Money out',value:fmtSigned(-out,'−')}, + {label:'Net',value:fmtSigned(inc-out)}, + ])); + } - const ctrl=document.createElement('div'); ctrl.className='card'; - ctrl.innerHTML=` -
-
- -
- - ${txSearch?``:''} -
-
-
- - -
-
- -
- - - – - -
+ const TRANSFER_CATS=['Transfer in','Transfer out']; + const cats=[...new Set(base.flatMap(t=>t.categories||[t.category]).filter(c=>c&&!TRANSFER_CATS.includes(c)&&c!=='Other'))].sort(); + if (txCatFilter!=='all'&&txCatFilter!=='(Uncategorized)'&&!cats.includes(txCatFilter)) cats.push(txCatFilter); + const sortVal=`${txSort.key}-${txSort.dir}`; + const list=document.createElement('section'); + list.className='panel flush'; + list.setAttribute('aria-label',pay?'Card payments':'Transaction list'); + list.innerHTML=` +
+ + + +
+ + + + and +
- -
`; - root.appendChild(ctrl); - - const tableCard=document.createElement('div'); tableCard.className='card'; - tableCard.innerHTML=` - -
-
`; - root.appendChild(tableCard); +
+
`; + root.appendChild(list); + + const matches=(t)=>{ + if (txSearch){ + const q=txSearch.toLowerCase(); + const cs=(t.categories||[t.category]).join(' '); + if (!(t.description+' '+cs+' '+(t.notes||'')).toLowerCase().includes(q)) return false; + } + if (txCatFilter==='(Uncategorized)') { + const tc=(t.categories||[t.category]); + if (!(!tc.length||tc.every(c=>!c||c==='Other'))) return false; + } else if (txCatFilter!=='all'&&!(t.categories||[t.category]).includes(txCatFilter)) return false; + if (txAmtMode) { + const abs=Math.abs(t.amount); + if (txAmtMode==='eq' && txAmtVal!==null && Math.abs(abs-txAmtVal)>0.01) return false; + if (txAmtMode==='lt' && txAmtVal!==null && abs>=txAmtVal) return false; + if (txAmtMode==='gt' && txAmtVal!==null && abs<=txAmtVal) return false; + if (txAmtMode==='range') { + if (txAmtVal!==null && abstxAmtVal2) return false; + } + } + return true; + }; + + const updateBulk=(rowsLen,pages)=>{ + const bar=$('#bulkBar'); if (bar) bar.hidden=!selectedTxIds.size; + const bc=$('#bulkCount'); if (bc) bc.textContent=`${selectedTxIds.size} selected`; + }; + const countText=(rows,slice)=>{ + const sel=selectedTxIds.size?` · ${selectedTxIds.size} selected`:''; + if (pay) return `Showing ${slice.length} of ${plural(rows.length,'card payment')}${sel}`; + const filtered=rows.length!==base.length?` (${base.length.toLocaleString()} before filters)`:''; + return `Showing ${slice.length} of ${rows.length.toLocaleString()}${filtered} · ${TX_PAGE_SIZE} per page${sel}`; + }; const renderTable=()=>{ - let rows=txs.filter(t=>{ - if (txSearch){ - const q=txSearch.toLowerCase(); - const cats=(t.categories||[t.category]).join(' '); - if (!(t.description+cats+(t.notes||'')).toLowerCase().includes(q)) return false; - } - if (txCatFilter==='(Uncategorized)') { - const tCats=(t.categories||[t.category]); - if (!(!tCats.length||tCats.every(c=>!c||c==='Other'))) return false; - } else if (txCatFilter!=='all'&&!(t.categories||[t.category]).includes(txCatFilter)) return false; - // Pill filter - if (txPillFilter==='income' && !(t.amount>0&&t.type!=='transfer'&&t.type!=='payment')) return false; - if (txPillFilter==='spending' && !(t.amount<0&&t.type!=='transfer')) return false; - if (txPillFilter==='bills' && !t.isBill) return false; - if (txPillFilter==='payments' && t.type!=='payment') return false; - if (txPillFilter==='transfers' && t.type!=='transfer') return false; - if (txAmtMode) { - const abs=Math.abs(t.amount); - if (txAmtMode==='eq' && txAmtVal!==null && Math.abs(abs-txAmtVal)>0.01) return false; - if (txAmtMode==='lt' && txAmtVal!==null && abs>=txAmtVal) return false; - if (txAmtMode==='gt' && txAmtVal!==null && abs<=txAmtVal) return false; - if (txAmtMode==='range') { - if (txAmtVal!==null && abstxAmtVal2) return false; - } - } - return true; - }); + const rows=base.filter(matches); rows.sort((a,b)=>{ let av=a[txSort.key], bv=b[txSort.key]; - if (txSort.key==='amount'){av=Math.abs(a.amount);bv=Math.abs(b.amount);} + if (txSort.key==='amount'){ av=Math.abs(a.amount); bv=Math.abs(b.amount); } + if (txSort.key==='description'){ av=(a.description||'').toLowerCase(); bv=(b.description||'').toLowerCase(); } if (avbv) return txSort.dir==='asc'?1:-1; return 0; }); - const pageSize=50; - const pages=Math.max(1,Math.ceil(rows.length/pageSize)); + const pages=Math.max(1,Math.ceil(rows.length/TX_PAGE_SIZE)); if (txPage>pages) txPage=pages; - const slice=rows.slice((txPage-1)*pageSize,txPage*pageSize); - const arr=(k)=>txSort.key===k?(txSort.dir==='asc'?'▲':'▼'):''; - const accountName=(id)=>State.accountLabels?.[id]||State.accounts[id]?.name||id; - const allPageIds=slice.map(t=>t.id); - const allPageChecked=allPageIds.length&&allPageIds.every(id=>selectedTxIds.has(id)); - + const slice=rows.slice((txPage-1)*TX_PAGE_SIZE,txPage*TX_PAGE_SIZE); + const pageIds=slice.map(t=>t.id); + const allChecked=pageIds.length&&pageIds.every(id=>selectedTxIds.has(id)); + const empty=txSearch?`No transactions match “${escapeHtml(txSearch)}”.` + :pay?`No card payments in ${escapeHtml(rangeText())}.` + :base.length?'No transactions match these filters.':`No transactions in ${escapeHtml(rangeText())}.`; $('#txTable').innerHTML=` - - Date ${arr('date')} - Account - Description ${arr('description')} - Category - Amount ${arr('amount')} - Type + + DateDescriptionCategory + AccountFlagsAmount - - ${slice.map(t=>{ - const cats=(t.categories||[t.category]); - let typeLabel, typeClass; - if (t.type==='transfer') { - const isOut=cats.includes('Transfer out'), isIn=cats.includes('Transfer in'); - typeLabel=isOut?'Transfer out':isIn?'Transfer in':'Transfer'; - typeClass=isOut?'chip xfer-out':isIn?'chip xfer-in':'chip'; - } else if (t.type==='credit'||t.amount>0) { - typeLabel='Income'; typeClass='chip income'; - } else { - typeLabel='Expense'; typeClass='chip debit'; - } - const typeChip=`${typeLabel}`; - const displayCats=cats.filter(c=>c!=='Transfer in'&&c!=='Transfer out'); - const subBadge=t.isSubscription?'sub':''; - return ` - - ${dayjs(t.date).format('MMM D')} - ${escapeHtml(accountName(t.account))} - ${escapeHtml(t.description)}${subBadge}${t.notes?`
${escapeHtml(t.notes)}
`:''} -
${displayCats.map(c=>`${escapeHtml(c)}`).join('')}
- ${t.type==='transfer'?''+fmt(t.amount)+'':(t.amount>=0?'+'+fmt(t.amount).replace('-','')+'':''+fmt(t.amount)+'')} - ${typeChip} - `; - }).join('')} - `; - $('#txCount').textContent=`${rows.length} transactions · page ${txPage} of ${pages}${selectedTxIds.size?` · ${selectedTxIds.size} selected`:''}`; - $('#txPager').innerHTML=` - - `; - - // Bulk bar visibility - const bulkBar=$('#bulkBar'); - if (bulkBar) { - bulkBar.style.display=selectedTxIds.size?'flex':'none'; - const bc=$('#bulkCount'); if (bc) bc.textContent=`${selectedTxIds.size} selected`; - } - - // Wire sortable headers - $$('#txTable th.sortable').forEach(th=>th.onclick=()=>{ - const k=th.dataset.k; - if (txSort.key===k) txSort.dir=txSort.dir==='asc'?'desc':'asc'; - else { txSort.key=k; txSort.dir='desc'; } - renderActive(); + ${slice.length?slice.map(t=>{ + const cs=(t.categories&&t.categories.length?t.categories:[t.category]); + const flags=[t.isBill&&'Bill',t.isRecurring&&'Recurring',t.isSubscription&&'Sub'].filter(Boolean); + return ` + + ${dayjs(t.date).format('MMM D')} + ${t.notes?`
${escapeHtml(t.notes)}
`:''}
${escapeHtml(cs.join(', '))} · ${escapeHtml(acctName(t.account))}${flags.length?' · '+flags.join(', '):''}
+
${cs.map(c=>`${escapeHtml(c)}`).join('')}
+ ${escapeHtml(acctName(t.account))} +
${flags.map(f=>`${f}`).join('')}
+ ${fmtSigned(t.amount)} + `; + }).join(''):`

${empty}

`}`; + $('#txCount').textContent=countText(rows,slice); + // Pager: ‹ 1 … 4 5 6 … 12 › + const nums=[]; + for (let p=1;p<=pages;p++) if (p===1||p===pages||Math.abs(p-txPage)<=1) nums.push(p); else if (nums[nums.length-1]!=='…') nums.push('…'); + $('#txPager').innerHTML=pages>1?` + ${nums.map(p=>p==='…'?'':``).join('')} + `:''; + $$('#txPager [data-page]').forEach(b=>b.onclick=()=>{ + txPage=Math.min(pages,Math.max(1,+b.dataset.page)); renderTable(); + const cur=$('#txPager [aria-current="page"]'); if (cur) cur.focus({preventScroll:true}); + list.scrollIntoView({block:'start'}); }); - // Row click → drawer (not on checkbox cell) - $$('#txTable tr.click').forEach(tr=>tr.onclick=()=>showTxDrawer(tr.dataset.id)); - // Individual checkboxes - $$('.tx-chk').forEach(cb=>{ + updateBulk(); + $$('#txTable tr.click').forEach(tr=>tr.onclick=e=>{ if (!e.target.closest('.chk')&&!e.target.closest('[data-open]')) showTxDrawer(tr.dataset.id); }); + $$('#txTable [data-open]').forEach(b=>b.onclick=()=>showTxDrawer(b.dataset.open)); + $$('#txTable .tx-chk').forEach(cb=>{ cb.onchange=()=>{ cb.checked?selectedTxIds.add(cb.dataset.id):selectedTxIds.delete(cb.dataset.id); - const bc=$('#bulkCount'); if (bc) bc.textContent=`${selectedTxIds.size} selected`; - const bar=$('#bulkBar'); if (bar) bar.style.display=selectedTxIds.size?'flex':'none'; - const cnt=$('#txCount'); if (cnt) cnt.textContent=`${rows.length} transactions · page ${txPage} of ${pages}${selectedTxIds.size?` · ${selectedTxIds.size} selected`:''}`; - // Update select-all state - const sa=$('#txSelectAll'); if (sa) sa.checked=allPageIds.every(id=>selectedTxIds.has(id)); + updateBulk(); + $('#txCount').textContent=countText(rows,slice); + const sa=$('#txSelectAll'); if (sa) sa.checked=pageIds.every(id=>selectedTxIds.has(id)); }; }); - // Select-all checkbox const sa=$('#txSelectAll'); - if (sa) sa.onchange=()=>{ - allPageIds.forEach(id=>sa.checked?selectedTxIds.add(id):selectedTxIds.delete(id)); - renderTable(); - }; + if (sa) sa.onchange=()=>{ pageIds.forEach(id=>sa.checked?selectedTxIds.add(id):selectedTxIds.delete(id)); renderTable(); const s2=$('#txSelectAll'); if (s2) s2.focus(); }; }; - $('#txSearch').oninput=debounce((e)=>{txSearch=e.target.value;renderTable();},200); - const txClearBtn=$('#txSearchClear'); - if (txClearBtn) txClearBtn.onclick=()=>{txSearch='';txPage=1;renderActive();}; - $('#txCat').onchange=(e)=>{txCatFilter=e.target.value;txPage=1;renderTable();}; - - // Amount filter handlers + $('#txSearch').oninput=debounce((e)=>{ txSearch=e.target.value; txPage=1; renderTable(); },200); + $('#txCat').onchange=(e)=>{ txCatFilter=e.target.value; txPage=1; renderTable(); }; + $('#txSortSel').onchange=(e)=>{ const [k,d]=e.target.value.split('-'); txSort={key:k,dir:d}; txPage=1; renderTable(); }; $('#txAmtMode').onchange=(e)=>{ txAmtMode=e.target.value; txAmtVal=null; txAmtVal2=null; txPage=1; const v=$('#txAmtVal'), sep=$('#txAmtSep'), v2=$('#txAmtVal2'); - if (v){ v.value=''; v.style.display=txAmtMode?'inline-block':'none'; } - if (sep) sep.style.display=txAmtMode==='range'?'inline':'none'; - if (v2){ v2.value=''; v2.style.display=txAmtMode==='range'?'inline-block':'none'; } + v.value=''; v.hidden=!txAmtMode; sep.hidden=txAmtMode!=='range'; v2.value=''; v2.hidden=txAmtMode!=='range'; renderTable(); }; - if ($('#txAmtVal')) $('#txAmtVal').oninput=debounce((e)=>{ txAmtVal=e.target.value?parseFloat(e.target.value):null; txPage=1; renderTable(); },300); - if ($('#txAmtVal2')) $('#txAmtVal2').oninput=debounce((e)=>{ txAmtVal2=e.target.value?parseFloat(e.target.value):null; txPage=1; renderTable(); },300); + $('#txAmtVal').oninput=debounce((e)=>{ txAmtVal=e.target.value?parseFloat(e.target.value):null; txPage=1; renderTable(); },300); + $('#txAmtVal2').oninput=debounce((e)=>{ txAmtVal2=e.target.value?parseFloat(e.target.value):null; txPage=1; renderTable(); },300); - // Bulk action handlers - $('#bulkApplyCat').onclick=()=>{ - const cat=$('#bulkCatSel').value; if (!cat) return; + // Bulk edits: stored as overrides, like single edits in the drawer + const bulk=(fn)=>{ let changed=0; selectedTxIds.forEach(id=>{ const t=State.transactions.find(x=>x.id===id); if (!t) return; const ov=State.txOverrides[id]||{}; - ov.categories=[cat]; State.txOverrides[id]=ov; t.categories=[cat]; changed++; + fn(t,ov); State.txOverrides[id]=ov; changed++; }); - if (changed) { lsSet('txOverrides',State.txOverrides); selectedTxIds.clear(); renderActive(); } + if (changed){ lsSet('txOverrides',State.txOverrides); selectedTxIds.clear(); renderActive(); } }; + $('#bulkApplyCat').onclick=()=>{ const cat=$('#bulkCatSel').value; if (cat) bulk((t,ov)=>{ ov.categories=[cat]; t.categories=[cat]; }); }; $('#bulkApplyType').onclick=()=>{ const type=$('#bulkTypeSel').value; if (!type) return; - let changed=0; - selectedTxIds.forEach(id=>{ - const t=State.transactions.find(x=>x.id===id); if (!t) return; - const ov=State.txOverrides[id]||{}; + bulk((t,ov)=>{ ov.type=type; if (type==='transfer') { const existing=ov.categories||t.categories||[]; - const hasDir=existing.includes('Transfer in')||existing.includes('Transfer out'); - if (!hasDir){ ov.categories=[t.amount<0?'Transfer out':'Transfer in']; t.categories=ov.categories; } + if (!existing.includes('Transfer in')&&!existing.includes('Transfer out')) { ov.categories=[t.amount<0?'Transfer out':'Transfer in']; t.categories=ov.categories; } } - State.txOverrides[id]=ov; t.type=type; changed++; + t.type=type; }); - if (changed){ lsSet('txOverrides',State.txOverrides); selectedTxIds.clear(); renderActive(); } }; - $('#bulkMarkBill').onclick=()=>{ - selectedTxIds.forEach(id=>{ - const t=State.transactions.find(x=>x.id===id); if (!t) return; - const ov=State.txOverrides[id]||{}; ov.isBill=true; State.txOverrides[id]=ov; t.isBill=true; - }); - lsSet('txOverrides',State.txOverrides); selectedTxIds.clear(); renderActive(); - }; - $('#bulkMarkSub').onclick=()=>{ - selectedTxIds.forEach(id=>{ - const t=State.transactions.find(x=>x.id===id); if (!t) return; - const ov=State.txOverrides[id]||{}; ov.isSubscription=true; State.txOverrides[id]=ov; t.isSubscription=true; - }); - lsSet('txOverrides',State.txOverrides); selectedTxIds.clear(); renderActive(); - }; - $('#bulkClear').onclick=()=>{ selectedTxIds.clear(); renderActive(); }; + $('#bulkMarkBill').onclick=()=>bulk((t,ov)=>{ ov.isBill=true; t.isBill=true; }); + $('#bulkMarkSub').onclick=()=>bulk((t,ov)=>{ ov.isSubscription=true; t.isSubscription=true; }); + $('#bulkClear').onclick=()=>{ selectedTxIds.clear(); renderTable(); }; $('#txExport').onclick=()=>{ const r=filteredTx(); - const csv=Papa.unparse(r.map(t=>({Date:dayjs(t.date).format('YYYY-MM-DD'),Account:State.accounts[t.account]?.name||t.account,Description:t.description,Categories:(t.categories||[t.category]).join(';'),Amount:t.amount,Type:t.type,Subscription:t.isSubscription?'Yes':'',Balance:t.balance,Notes:t.notes||''}))); + const csv=Papa.unparse(r.map(t=>({Date:dayjs(t.date).format('YYYY-MM-DD'),Account:acctName(t.account),Description:t.description,Categories:(t.categories||[t.category]).join(';'),Amount:t.amount,Type:t.type,Subscription:t.isSubscription?'Yes':'',Balance:t.balance,Notes:t.notes||''}))); downloadFile('transactions.csv',csv,'text/csv'); }; renderTable(); - /* ---- Transaction Rules card ---- */ - const txRulesCard=document.createElement('div'); txRulesCard.className='card'; - txRulesCard.innerHTML=` -

Transaction Rules

-

Automatically flag transactions as Bill, Subscription, or Recurring when their description contains a keyword.

-
-
-
- -
- -
-
-

Active Rules

-
${(State.txRules||[]).map((r,i)=>` -
- ${escapeHtml(r.contains)} → ${r.flag} - -
`).join('')||'No rules yet.'}
-
- `; - root.appendChild(txRulesCard); - - $('#txRuleAdd').onclick=()=>{ - const contains=$('#txRuleContains').value.trim(); + /* ---- Transaction rules ---- */ + const rules=State.txRules||[]; + const groups=[]; + rules.forEach(r=>{ + const k=(r.contains||'').toLowerCase(); + let g=groups.find(x=>x.k===k); + if (!g) groups.push(g={k,contains:r.contains,flags:[]}); + if (!g.flags.includes(r.flag)) g.flags.push(r.flag); + }); + const matchCount=(c)=>{ const u=c.toUpperCase(); return State.transactions.filter(t=>(t._originalDesc||t.description||'').toUpperCase().includes(u)).length; }; + const rulesSec=document.createElement('section'); + rulesSec.className='panel'; + rulesSec.id='txRules'; + rulesSec.setAttribute('aria-labelledby','txRulesH'); + rulesSec.innerHTML=` +

Transaction rules

Flag matching transactions automatically, now and on every future import.

+ ${groups.length?`
${groups.map((g,i)=>`
Contains${escapeHtml(g.contains)}${g.flags.map(f=>`${FLAG_LABEL[f]||escapeHtml(f)}`).join('')}${plural(matchCount(g.contains),'match','matches')}
`).join('')}
` + :'

No rules yet. Add one below, e.g. NETFLIX → Subscription.

'} +
+ + + +
`; + root.appendChild(rulesSec); + $('#txRulesJump').onclick=(e)=>{ e.preventDefault(); rulesSec.scrollIntoView({behavior:'smooth',block:'start'}); $('#txRulesH').focus({preventScroll:true}); }; + const addRule=()=>{ + const inp=$('#txRuleContains'); + const contains=inp.value.trim(); const flag=$('#txRuleFlag').value; - if (!contains){ alert('Enter a keyword to match.'); return; } - if ((State.txRules||[]).some(r=>r.contains.toLowerCase()===contains.toLowerCase()&&r.flag===flag)){ - alert('That rule already exists.'); return; - } + if (!contains){ inp.setAttribute('aria-invalid','true'); inp.focus(); return; } if (!State.txRules) State.txRules=[]; - State.txRules.push({contains,flag}); + if (!State.txRules.some(r=>r.contains.toLowerCase()===contains.toLowerCase()&&r.flag===flag)) { + State.txRules.push({contains,flag}); + lsSet('txRules',State.txRules); + applyTxRulesToAll(); + } + renderActive(); + const again=$('#txRuleContains'); if (again) again.focus({preventScroll:true}); + }; + $('#txRuleAdd').onclick=addRule; + $('#txRuleContains').onkeydown=(e)=>{ if (e.key==='Enter'){ e.preventDefault(); addRule(); } }; + $$('[data-rule-del]',rulesSec).forEach(btn=>btn.onclick=()=>{ + const g=groups[+btn.dataset.ruleDel]; + State.txRules=(State.txRules||[]).filter(r=>(r.contains||'').toLowerCase()!==g.k); lsSet('txRules',State.txRules); applyTxRulesToAll(); renderActive(); - }; - $('#txRuleReapply').onclick=()=>{ applyTxRulesToAll(); renderActive(); }; - $$('[data-tx-rule-del]',txRulesCard).forEach(btn=>{ - btn.onclick=()=>{ - const i=parseInt(btn.dataset.txRuleDel); - State.txRules.splice(i,1); - lsSet('txRules',State.txRules); - applyTxRulesToAll(); - renderActive(); - }; }); }); +/* ---- Transaction detail drawer ---- */ function showTxDrawer(id) { const t=State.transactions.find(x=>x.id===id); if (!t) return; - const cats=State.categories; - const currentCats=t.categories||[t.category]; - const catsChecked=cats.map(c=>` - `).join(''); - - openDrawer(` -
${dayjs(t.date).format('dddd, MMM D, YYYY')}
-
${fmt(t.amount)}
-
- - - -
${State.accounts[t.account]?.name||t.account}
- -
${catsChecked}
- - - - -
- - - + const ov=State.txOverrides[t.id]||{}; + const cur=t.categories&&t.categories.length?t.categories:[t.category]; + const opts=[...new Set([...State.categories,...cur])]; + const extra=cur.slice(1); + const lnk=ov.link; + const canLink=State.budgets.length||State.buckets.length||State.debts.length||lnk; + const linkItems=(type)=>type==='budget'?State.budgets:type==='bucket'?State.buckets:type==='debt'?State.debts:[]; + const linkOpts=(type,sel)=>linkItems(type).map((item,i)=>``).join(''); + openDrawer(`
+
+ ${fmtSigned(t.amount)} + ${dayjs(t.date).format('dddd, MMM D, YYYY')} · ${escapeHtml(acctName(t.account))} + Original: ${escapeHtml(t._originalDesc||t.description)}
-
- -
- - + +
+ +
-
- - - `); - // Wire link type → show/populate target dropdown - $('#dLinkType').onchange=()=>{ - const type=$('#dLinkType').value; +
+ Also count it under other categories${extra.length?` (${extra.length})`:''} +
${opts.map(c=>``).join('')}
+
+
Flags + + + +
+ + ${canLink?`
Link to a budget, bucket or debt +
+ + +
`:''} +

Edits are stored separately from the imported row, so re-importing the CSV never overwrites them.

+
`,{ title:'Transaction detail', + footer:`` }); + const lt=$('#dLinkType'); + if (lt) lt.onchange=()=>{ const tgt=$('#dLinkTarget'); - if (!type){ tgt.style.display='none'; tgt.innerHTML=''; return; } - const items=type==='budget'?State.budgets:type==='bucket'?State.buckets:State.debts; - tgt.innerHTML=items.map((item,i)=>``).join(''); - tgt.style.display='block'; + tgt.innerHTML=lt.value?linkOpts(lt.value,0):''; + tgt.hidden=!lt.value; }; - $('#dSave').onclick=()=>{ - const ov=State.txOverrides[t.id]||{}; - const selectedCats=[...$$(`.dCatCheck:checked`)].map(cb=>cb.value); - ov.description=$('#dDesc').value.trim()||t._originalDesc; - ov.categories=selectedCats.length?selectedCats:[t.category]; - ov.type=$('#dType').value; - // Auto-assign transfer direction category so the Transfers tab picks it up - if (ov.type==='transfer') { - const hasDir=ov.categories.includes('Transfer in')||ov.categories.includes('Transfer out'); - if (!hasDir) ov.categories=[t.amount<0?'Transfer out':'Transfer in']; - } - ov.notes=$('#dNotes').value; - ov.isBill=$('#dBill').checked; - ov.isRecurring=$('#dRec').checked; - ov.isSubscription=$('#dSub').checked; - // Save link - const linkType=$('#dLinkType').value; - if (linkType) { ov.link={ type:linkType, idx:parseInt($('#dLinkTarget').value)||0 }; } - else { delete ov.link; } - State.txOverrides[t.id]=ov; + const o=State.txOverrides[t.id]||{}; + const primary=$('#dCat').value; + const more=$$('.dCatCheck:checked').map(cb=>cb.value).filter(c=>c!==primary); + o.description=$('#dDesc').value.trim()||t._originalDesc; + o.categories=[primary,...more]; + o.type=$('#dType').value; + // A transfer needs its direction as a category so the Transfers screen picks it up + if (o.type==='transfer'&&!o.categories.includes('Transfer in')&&!o.categories.includes('Transfer out')) o.categories=[t.amount<0?'Transfer out':'Transfer in']; + o.notes=$('#dNotes').value; + o.isBill=$('#dBill').checked; + o.isRecurring=$('#dRec').checked; + o.isSubscription=$('#dSub').checked; + const linkType=lt?lt.value:''; + if (linkType) o.link={ type:linkType, idx:parseInt($('#dLinkTarget').value)||0 }; + else delete o.link; + State.txOverrides[t.id]=o; lsSet('txOverrides',State.txOverrides); - // Apply overrides to transaction object - t.description=ov.description; - t.categories=ov.categories; - t.type=ov.type; - t.notes=ov.notes; - t.isBill=ov.isBill; - t.isRecurring=ov.isRecurring; - t.isSubscription=ov.isSubscription; + t.description=o.description; t.categories=o.categories; t.type=o.type; t.notes=o.notes; + t.isBill=o.isBill; t.isRecurring=o.isRecurring; t.isSubscription=o.isSubscription; closeDrawer(); renderActive(); }; } /* =================== INCOME =================== */ -registerView('income','Income & Deposits',(root)=>{ - const allPos=filteredTx().filter(t=>t.amount>0&&t.type!=='transfer'&&!['Transfer','Transfer in','Transfer out'].includes(t.category)); - const txs=allPos.filter(t=>t.category!=='Returns'); - const returnsTxs=allPos.filter(t=>t.category==='Returns'); - const interestTxs=allPos.filter(t=>/interest/i.test(t.description)||t.category==='Interest'); - if (!allPos.length){ root.innerHTML=emptyCard('No income found in selected period.'); return; } - const total=txs.reduce((s,t)=>s+t.amount,0); - const interest=interestTxs.reduce((s,t)=>s+t.amount,0); - const returns=returnsTxs.reduce((s,t)=>s+t.amount,0); - const months=byMonth(filteredTx()); - const avgMonthly=months.length?months.reduce((s,m)=>s+m.income,0)/months.length:0; - - const range=State.range; - let yoy=null; - if (range.start&&range.end) { - const days=(range.end-range.start)/86400000; - const prevEnd=new Date(range.start); prevEnd.setDate(prevEnd.getDate()-1); - const prevStart=new Date(prevEnd); prevStart.setDate(prevStart.getDate()-days); - const prevIncome=State.transactions.filter(t=>t.amount>0&&t.type!=='transfer'&&t.date>=prevStart&&t.date<=prevEnd).reduce((s,t)=>s+t.amount,0); - yoy=prevIncome>0?(total-prevIncome)/prevIncome:null; - } - - const m=document.createElement('div'); m.className='grid grid-4'; - m.innerHTML=` -

Total Income

${fmt(total)}
${describeRange()}
-

Avg Monthly

${fmt(avgMonthly)}
Across ${months.length} months
-

Interest Earned

${fmt(interest)}
${interestTxs.length} payment${interestTxs.length!==1?'s':''}
-

Returns / Refunds

${fmt(returns)}
${returnsTxs.length} transaction${returnsTxs.length!==1?'s':''}
`; - root.appendChild(m); - - // By Source chart — fixed smaller size - const charts=document.createElement('div'); charts.className='grid grid-2'; - charts.innerHTML=` -
-

By Source

-
-
-
-

Monthly Income

-
-
`; - root.appendChild(charts); - - const rec=detectRecurringDeposits(txs); - if (rec.length) { - const recCard=document.createElement('div'); recCard.className='card'; - recCard.innerHTML=`

Recurring Deposits

- - ${rec.map(r=>``).join('')}
SourceAvg AmountFrequencyLast seen
${escapeHtml(r.source)}${fmt(r.avg)}${r.freq}${dayjs(r.last).format('MMM D, YYYY')}
`; - root.appendChild(recCard); - } - - const tbl=document.createElement('div'); tbl.className='card'; - tbl.innerHTML=`

Deposits

- - ${txs.slice(0,200).map(t=>``).join('')}
DateSourceAccountAmount
${dayjs(t.date).format('MMM D')}${escapeHtml(t.description)}${State.accounts[t.account]?.name||t.account}+${fmt(t.amount).replace('-','')}
`; - root.appendChild(tbl); - - setTimeout(()=>{ - const srcCats=byCategory(txs,'income'); - new Chart($('#incDonut'),{ - type:'doughnut', - data:{labels:srcCats.map(c=>c.category),datasets:[{data:srcCats.map(c=>c.amount),backgroundColor:CHART_PALETTE}]}, - options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'right',labels:{boxWidth:10,font:{size:11}}}}} - }); - new Chart($('#incBar'),{ - type:'bar', - data:{labels:months.map(m=>m.month),datasets:[{label:'Income',data:months.map(m=>m.income),backgroundColor:chartColor('--chart-in'),borderRadius:5}]}, - options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{y:{ticks:{callback:v=>'$'+v.toLocaleString()}}}} - }); - },0); -}); - -/* =================== BILLS =================== */ -registerView('bills','Bills',(root)=>{ - const recurring=detectRecurring(); - const bills=State.bills||[]; - - // Summary - const monthlySubs=recurring.filter(r=>r.isSubscription&&r.freq==='Monthly').reduce((s,r)=>s+r.avg,0) - +recurring.filter(r=>r.isSubscription&&r.freq==='Annual').reduce((s,r)=>s+r.avg/12,0) - +recurring.filter(r=>r.isSubscription&&r.freq==='Bi-weekly').reduce((s,r)=>s+r.avg*2.17,0); - const monthlyBills=recurring.filter(r=>!r.isSubscription&&r.freq==='Monthly').reduce((s,r)=>s+r.avg,0); - const upcoming=bills.filter(b=>!b.paid).sort((a,b)=>new Date(a.dueDate)-new Date(b.dueDate)); - const overdue=upcoming.filter(b=>new Date(b.dueDate)

Manual Bills

${bills.length}
${overdue} overdue
-

Auto-Detected Recurring

${recurring.length}
From transactions
-

Est. Monthly Bills

${fmt(monthlyBills)}
Utilities + recurring
-

Est. Monthly Subs

${fmt(monthlySubs)}
Subscriptions only
`; - root.appendChild(m); - - // Bills, Utilities & Subscriptions from ALL transactions (not date-filtered) - // Broad keyword match against description — no word-boundary tricks that miss common names - const BILL_KW=/electric|water|gas(?:\s|&|$)|internet|comcast|xfinity|verizon|t-mobile|at&t|at &t|spectrum|cox\b|rent\b|mortgage|hoa\b|insurance|phone|utility|utilities|spotify|netflix|hulu|disney|apple\.com|icloud|prime\s|chatgpt|openai|adobe|dropbox|microsoft|github|youtube|sirius|cable|wireless|telecom|sewage|trash|garbage|subscription|membership|billing|dues\b|gym\b|planet fitness|audible|patreon|substack/i; - // Match against category field too — card exports have bank-assigned categories like "Phone & Communications" - const BILL_CAT_KW=/bill|utilit|cable|internet|phone|telecom|subscri|rent|mortgage|insur|electric|gas\b|water|housing|membership/i; - const billTxs=State.transactions.filter(t=> - t.amount<0 && t.type!=='transfer' && - ( - (t.categories||[t.category]).some(c=>BILL_CAT_KW.test(c)) - || t.isBill || t.isSubscription || BILL_KW.test(t.description) - ) - ).sort((a,b)=>b.date-a.date); - - const btCard=document.createElement('div'); btCard.className='card'; - btCard.innerHTML=`

Bills, Utilities & Subscriptions (All Time)

- ${billTxs.length?` - - ${billTxs.slice(0,200).map(t=>` - - - - - - `).join('')} -
DateDescriptionAccountCategoryAmount
${dayjs(t.date).format('MMM D, YYYY')}${escapeHtml(t.description)}${t.isBill?'bill':''}${t.isSubscription?'sub':''}${State.accounts[t.account]?.name||t.account}${(t.categories||[t.category]).join(', ')}${fmt(t.amount)}
`:`
ℹ️ No bills, utilities, or subscriptions found. Load more CSV history or manually flag transactions as bills.
`}`; - root.appendChild(btCard); - - // Auto-detected recurring - const recCard=document.createElement('div'); recCard.className='card'; - recCard.innerHTML=`

Auto-Detected Recurring Charges

-

Confirm to add to bills calendar. Subscriptions are marked automatically.

- - ${recurring.length?recurring.map(r=>{ - const status=State.recurringConfirmed[r.key]||'pending'; - return ` - - - - - - - - `; - }).join(''):''}
MerchantCategoryAvgFrequencyNext DueConfidence
${escapeHtml(r.merchant)}${r.isSubscription?' sub':''}${r.category}${fmt(r.avg)}${r.freq}${dayjs(r.nextDue).format('MMM D')}${Math.round(r.confidence*100)}%${status==='confirmed'?'Confirmed':status==='dismissed'?'Dismissed':` `}
No recurring charges detected — load more history.
`; - root.appendChild(recCard); - - // Manual bills - const billsCard=document.createElement('div'); billsCard.className='card'; - billsCard.innerHTML=`

Manual Bills

- -
MerchantCategoryAmountFrequencyNext DueStatus
`; - root.appendChild(billsCard); - - const renderBills=()=>{ - const today=new Date(); - $('#billsTbody').innerHTML=bills.length?bills.map((b,i)=>{ - const dd=new Date(b.dueDate); - const days=Math.ceil((dd-today)/86400000); - let sh; - if (b.paid) sh='Paid'; - else if (days<0) sh=`Overdue ${Math.abs(days)}d`; - else if (days<=7) sh=`Due in ${days}d`; - else sh=`In ${days}d`; - return ` - ${escapeHtml(b.merchant)} - ${b.category||'—'} - ${fmt(b.amount)} - ${b.frequency||'Monthly'} - ${dayjs(b.dueDate).format('MMM D, YYYY')} - ${sh} - - `; - }).join(''):'No bills yet. Confirm an auto-detected charge above or add one manually.'; - }; - renderBills(); - $('#addBillBtn').onclick=()=>showBillForm(); - - // Collapsible bills calendar - const calCard=document.createElement('div'); calCard.className='card'; - calCard.innerHTML=` -
-

- Bills Calendar - - overdue - due ≤7d - upcoming - paid - -

- ▼ -
-
`; - root.appendChild(calCard); - setTimeout(()=>{ - const calBody=$('#billsCalBody'), calToggle=$('#billsCalToggle'); - if (calBody) renderUpcomingCal(calBody); - if (calToggle) calToggle.addEventListener('click',()=>{ calToggle.classList.toggle('open'); calBody.classList.toggle('open'); }); - },0); +let incomeShowAll=false; +const SOURCE_HUES=['accent','warn','teal','pink','sky']; + +registerView('income','Income',(root)=>{ + txPillFilter='income'; + wireLinks(root); + wireTxOpeners(root); + pageActions(root,'Transfers and card payments excluded',''); + renderTxPills(root,'income'); + const all=filteredTx(); + const inc=all.filter(t=>t.amount>0&&t.type!=='transfer'&&t.type!=='payment'&&t.category!=='Transfer').sort((a,b)=>b.date-a.date); + if (!inc.length){ appendHtml(root,emptyPanel(`No income in ${escapeHtml(rangeText())}.`)); return; } + const total=sumIncome(all); + const span=dataSpan(all); + const interest=inc.filter(t=>/interest/i.test(t.description)||t.category==='Interest'); + const refunds=inc.filter(t=>/refund|return/i.test(t._originalDesc||t.description)||['Returns','Refunds','Refund'].includes(t.category)||State.accounts[t.account]?.kind==='credit_card'); + const sumOf=a=>a.reduce((s,t)=>s+t.amount,0); + const intAccts=[...new Set(interest.map(t=>acctName(t.account)))]; + appendHtml(root,kpiTiles([ + {label:'Total income',value:fmt(total),cls:'c-good',sub:plural(inc.length,'deposit')}, + {label:'Average per month',value:fmt(total/Math.max(1,span.months)),sub:span.days>=45?`Over ${span.months.toFixed(1)} months`:`Over ${plural(span.days,'day')}`}, + {label:'Interest earned',value:fmt(sumOf(interest)),sub:interest.length?`${escapeHtml(intAccts.join(', '))} · ${plural(interest.length,'payment')}`:'None in this period'}, + {label:'Returns & refunds',value:fmt(sumOf(refunds)),sub:refunds.length?`${plural(refunds.length,'refund')} · ${refunds.length===1?'':'latest '}${dayjs(refunds[0].date).format('MMM D')}`:'None in this period'}, + ])); + + /* ---- by source + monthly ---- */ + const bySrc={}; + inc.forEach(t=>{ const k=depositKey(t.description)||t.description; (bySrc[k]=bySrc[k]||{name:k,amount:0,count:0}); bySrc[k].amount+=t.amount; bySrc[k].count++; }); + let srcs=Object.values(bySrc).sort((a,b)=>b.amount-a.amount); + if (srcs.length>5) { const rest=srcs.slice(4); srcs=[...srcs.slice(0,4),{name:'Everything else',amount:rest.reduce((s,x)=>s+x.amount,0),count:rest.reduce((s,x)=>s+x.count,0),other:true}]; } + const srcTotal=srcs.reduce((s,x)=>s+x.amount,0)||1; + const hueOf=(x,i)=>x.other?'neutral':SOURCE_HUES[i]; + const share=x=>(x.amount/srcTotal*100); + const months=monthlyFlow(all).slice(-12); + const maxIn=Math.max(1,...months.map(m=>m.income)); + const lastAll=dataSpan(State.transactions).last; + const partial=(m)=>{ const end=endOfMonth(m.date); return monthKey(m.date)===monthKey(lastAll)&&lastAll.getDate()m.income>p.income?m:p,months[0]); + const topCount=top?top.txs.filter(t=>t.amount>0&&t.type!=='transfer'&&t.type!=='payment'&&t.category!=='Transfer').length:0; + const row=document.createElement('div'); row.className='cols-3'; + row.innerHTML=` +
+

Income by source

+ +
${srcs.map((x,i)=>`
${escapeHtml(x.name)}${share(x).toFixed(1)}% · ${plural(x.count,'deposit')}${fmt(x.amount)}
`).join('')}
+
+
+

Monthly income

${months.length>1&&top?`Highest: ${dayjs(top.date).format('MMMM')}, ${plural(topCount,'deposit')}`:''}
+ +
${months.map(m=>`${dayjs(m.date).format('MMM')}${partial(m)?` · to the ${ordinal(lastAll.getDate())}`:''}`).join('')}
+
`; + root.appendChild(row); + + /* ---- recurring deposits ---- */ + const rec=recurringDepositsDetail(inc); + const confPill={High:'good',Medium:'warn',Low:''}; + appendHtml(root,`
+

Recurring deposits

Detected from deposits with a steady amount and rhythm

+ ${rec.length?`
+ + ${rec.map(r=>` + + + + + + `).join('')}
SourceFrequencyDepositsLastNext expectedConfidenceTypical amount
${escapeHtml(r.source)}
${r.account?`
${escapeHtml(acctName(r.account))}
`:''}
${FREQ_LABEL[r.freq]||r.freq}${r.count}${dayjs(r.last).format('MMM D')}${r.next?dayjs(r.next).format('MMM D'):'—'}${r.confidence}${r.steady?'':'~'}${fmt(r.avg)}
` + :'

No deposits with a regular rhythm in this period.

'} +
`); + + /* ---- all deposits ---- */ + const shown=incomeShowAll?inc:inc.slice(0,6); + const depSec=document.createElement('section'); + depSec.className='panel'; + depSec.setAttribute('aria-labelledby','inDepH'); + depSec.innerHTML=`

All deposits

Newest first · ${plural(inc.length,'deposit')}
+
+ + ${shown.map(t=>` + + + `).join('')}
Deposits, newest first
DateDescriptionAccountAmount
${dayjs(t.date).format('MMM D')}${escapeHtml(acctName(t.account))}${fmtSigned(t.amount)}
+ ${inc.length>6?``:''}`; + root.appendChild(depSec); + const sa=$('#inShowAll',depSec); + if (sa) sa.onclick=()=>{ incomeShowAll=!incomeShowAll; renderActive(); const b=$('#inShowAll'); if (b) b.focus({preventScroll:true}); }; }); /* =================== SPENDING =================== */ let spendingDrillCategory=null; -registerView('spending','Spending & Expenses',(root)=>{ - const txs=filteredTx().filter(t=>t.amount<0&&t.type!=='transfer'&&t.category!=='Transfer'); - if (!txs.length){ root.innerHTML=emptyCard('No expenses found in selected period.'); return; } - const total=txs.reduce((s,t)=>s+Math.abs(t.amount),0); - // Filter "Other" and blank categories from chart data — they're noise, not signal - const cats=byCategory(filteredTx(),'expense').filter(c=>c.category&&c.category!=='Other'); - const months=byMonth(filteredTx()); - const avgDaily=total/Math.max(1,(State.range.start&&State.range.end?(State.range.end-State.range.start)/86400000:30)); - - const m=document.createElement('div'); m.className='grid grid-4'; - m.innerHTML=` -

Total Spent

${fmt(total)}
${describeRange()}
-

Avg Daily

${fmt(avgDaily)}
In selected range
-

Top Category

${cats[0]?cats[0].category:'—'}
${cats[0]?fmt(cats[0].amount):''}
-

Transactions

${txs.length}
expense entries
`; - root.appendChild(m); - const row1=document.createElement('div'); row1.className='grid grid-2'; - row1.innerHTML=` -

By Category

-

Category Ranking

`; - root.appendChild(row1); +registerView('spending','Spending',(root)=>{ + txPillFilter='spending'; + wireLinks(root); + wireTxOpeners(root); + pageActions(root,'Transfers and card payments excluded',''); + renderTxPills(root,'spending'); + const all=filteredTx(); + const txs=all.filter(t=>t.amount<0&&t.type!=='transfer'&&t.category!=='Transfer').sort((a,b)=>b.date-a.date); + if (!txs.length){ appendHtml(root,emptyPanel(`No spending in ${escapeHtml(rangeText())}.`)); renderCategoryRules(root); return; } + const total=sumExpense(all); + const span=dataSpan(all); + const cats=byCategory(all,'expense'); + const months=monthlyFlow(all).filter(m=>m.expense>0); + const avgMonth=months.reduce((s,m)=>s+m.expense,0)/Math.max(1,months.length); + const hi=months.reduce((p,m)=>m.expense>p.expense?m:p,months[0]); + const above=avgMonth?(hi.expense/avgMonth-1):0; + appendHtml(root,kpiTiles([ + {label:'Total spent',value:fmt(total),sub:plural(txs.length,'transaction')}, + {label:'Average per day',value:fmt(total/span.days),sub:`Over ${plural(span.days,'day')}`}, + {label:'Top category',value:escapeHtml(cats[0].category),sub:`${fmt(cats[0].amount)} · ${pctStr(cats[0].amount/total)} of spending`}, + {label:'Highest month',value:dayjs(hi.date).format('MMMM'),sub:months.length>1?`${fmt0(hi.expense)} · ${pctStr(Math.abs(above))} ${above>=0?'above':'below'} average`:`${fmt0(hi.expense)} · the only month`}, + ])); + + /* ---- by category + drill-down ---- */ + if (!cats.some(c=>c.category===spendingDrillCategory)) spendingDrillCategory=cats[0].category; + const max=cats[0].amount||1; + const row=document.createElement('div'); row.className='cols-3'; + row.innerHTML=` +
+

By category

Select a category to see its transactions
+
${cats.map((c,i)=>``).join('')}
+
+
`; + root.appendChild(row); + const drawDrill=()=>{ + const c=cats.find(x=>x.category===spendingDrillCategory); + const list=txs.filter(t=>(t.categories||[t.category]).includes(c.category)); + $('#spDrill').innerHTML=` +
Drill-down

${escapeHtml(c.category)}

${fmt(c.amount)} · ${plural(list.length,'transaction')}

+
${list.slice(0,8).map(t=>`
${dayjs(t.date).format('MMM D')}${fmtSigned(t.amount)}
`).join('')}
+ ${list.length>8?`

${list.length-8} more in Transactions

`:''} + Open in Transactions →`; + }; + drawDrill(); + $$('[data-cat-i]',row).forEach(b=>b.onclick=()=>{ + spendingDrillCategory=cats[+b.dataset.catI].category; + $$('[data-cat-i]',row).forEach(x=>x.setAttribute('aria-pressed',String(x===b))); + drawDrill(); + // one column: the drill-down sits below the list, so bring it into view + if (getComputedStyle(row).gridTemplateColumns.split(' ').length===1) $('#spDrill').scrollIntoView({behavior:'smooth',block:'start'}); + }); - const row2=document.createElement('div'); row2.className='grid grid-2'; + /* ---- daily heatmap + monthly trend ---- */ + const r=State.range; + let hmStart=new Date(Math.max(span.first.getTime(), r.start?r.start.getTime():-Infinity)); + const hmEnd=new Date(Math.min(span.last.getTime(), r.end?r.end.getTime():Infinity)); + if (hmEnd-hmStart>370*DAY) hmStart=new Date(hmEnd.getTime()-370*DAY); + const lastAll=dataSpan(State.transactions).last; + const lastM=months[months.length-1]; + const lastPartial=lastM&&monthKey(lastM.date)===monthKey(lastAll)&&lastAll.getDate()1) { + const catAvg={}; + months.forEach(m=>byCategory(m.txs,'expense').forEach(c=>{ catAvg[c.category]=(catAvg[c.category]||0)+c.amount/months.length; })); + const ex=byCategory(hi.txs,'expense').map(c=>({c:c.category,d:c.amount-(catAvg[c.category]||0)})).sort((a,b)=>b.d-a.d)[0]; + if (ex&&ex.d>0) why=` ${dayjs(hi.date).format('MMMM')} ran high on ${escapeHtml(ex.c)}.`; + } + const row2=document.createElement('div'); row2.className='cols-3'; row2.innerHTML=` -

Monthly Spending Trend

-

Daily Spending Heatmap (last 365d)

`; +
+

Daily spending

Darker days cost more
+ ${dailyHeatmapHtml(txs,hmStart,hmEnd)} + +
+
+

Monthly trend

+
+

${lastPartial?`${dayjs(lastM.date).format('MMMM')} is partial (through the ${ordinal(lastAll.getDate())}).`:''}${why}

+
`; root.appendChild(row2); + const tr=$('#spTrend'); + if (months.length>1) { + const hiIdx=months.indexOf(hi); + const w=Math.max(280,Math.min(420,Math.round(tr.clientWidth||360))); + tr.innerHTML=svgLineChart(months.map(m=>({v:m.expense,tip:`${dayjs(m.date).format('MMMM YYYY')}: ${fmt(m.expense)}`})), + { w, h:200, hue:'warn', valueAt:hiIdx, hollowLast:lastPartial, xLabels:months.map((m,i)=>({i,text:dayjs(m.date).format('MMM')})), + ariaLabel:`Monthly spending: ${months.map((m,i)=>`${dayjs(m.date).format('MMMM')} ${fmt0(m.expense)}${i===months.length-1&&lastPartial?' so far':''}`).join(', ')}` }); + } else tr.innerHTML=`

One month of data so far.

`; + + /* ---- top merchants + category rules ---- */ + const merch={}; + txs.forEach(t=>{ + const k=(t.description||'').replace(/\d+/g,'').replace(/\s+/g,' ').trim().slice(0,40)||t.description; + const m=merch[k]=merch[k]||{name:k,amount:0,count:0,cats:{}}; + m.amount+=Math.abs(t.amount); m.count++; m.cats[t.category]=(m.cats[t.category]||0)+1; + }); + const topM=Object.values(merch).sort((a,b)=>b.amount-a.amount).slice(0,7); + const row3=document.createElement('div'); row3.className='cols-3'; + row3.innerHTML=` +
+

Top merchants

+
+ + ${topM.map(m=>``).join('')} +
MerchantCategoryVisitsTotal
${escapeHtml(m.name)}${escapeHtml(Object.entries(m.cats).sort((a,b)=>b[1]-a[1])[0][0])}${m.count}${fmt(m.amount)}
+
`; + root.appendChild(row3); + renderCategoryRules(row3); +}); + +// Category rules: "description contains X → category Y". Applied on import, or to +// everything with Re-categorize all (ui.js addCatRule / delCatRule / recategorizeAll). +function renderCategoryRules(parent) { + const rules=State.categoryRules||[]; + const sec=document.createElement('section'); + sec.className='panel'; + sec.setAttribute('aria-labelledby','spRuleH'); + sec.innerHTML=` +

Category rules

Teach FinLens your merchants. Rules apply to every import.

+ ${rules.length?`
${rules.map((r,i)=>`
${escapeHtml(r.contains)}→ ${escapeHtml(r.category)}
`).join('')}
` + :'

No rules yet.

'} + + +
`; + parent.appendChild(sec); + $('#ruleAdd').onclick=()=>{ const i=$('#ruleContains'); if (!i.value.trim()){ i.setAttribute('aria-invalid','true'); i.focus(); return; } addCatRule(); }; + $('#ruleContains').onkeydown=(e)=>{ if (e.key==='Enter'){ e.preventDefault(); $('#ruleAdd').click(); } }; + $('#ruleReapply').onclick=()=>recategorizeAll(); + $$('[data-catrule-del]',sec).forEach(b=>b.onclick=()=>delCatRule(+b.dataset.catruleDel)); +} + +/* =================== BILLS =================== */ +let billsCalOpen=true; +let billFormOpen=false; - const merchantMap={}; - txs.forEach(t=>{ const k=(t.description||'').replace(/\d+/g,'').trim().slice(0,40)||t.description; if (!merchantMap[k]) merchantMap[k]={amount:0,count:0}; merchantMap[k].amount+=Math.abs(t.amount); merchantMap[k].count++; }); - const top=Object.entries(merchantMap).map(([k,v])=>({merchant:k,...v,avg:v.amount/v.count})).sort((a,b)=>b.amount-a.amount).slice(0,15); - const merchCard=document.createElement('div'); merchCard.className='card'; - merchCard.innerHTML=`

Top Merchants

- - ${top.map(t=>``).join('')}
MerchantTotalFrequencyAvg
${escapeHtml(t.merchant)}${fmt(t.amount)}${t.count}×${fmt(t.avg)}
`; - root.appendChild(merchCard); +registerView('bills','Bills & subscriptions',(root)=>{ + txPillFilter='bills'; + wireLinks(root); + pageActions(root,'Recurring charges, due dates and what FinLens has spotted', + ``); + renderTxPills(root,'bills'); + $('#billAddBtn').onclick=()=>{ billFormOpen=!billFormOpen; renderActive(); const f=billFormOpen?$('#nbName'):$('#billAddBtn'); if (f) f.focus(); }; - if (spendingDrillCategory) { - const drill=txs.filter(t=>(t.categories||[t.category]).includes(spendingDrillCategory)).sort((a,b)=>b.date-a.date); - const dCard=document.createElement('div'); dCard.className='card'; - dCard.innerHTML=`

- ${escapeHtml(spendingDrillCategory)} — Transactions - -

-

Click any row to edit.

- - ${drill.slice(0,200).map(t=>` - - - - - `).join('')}
DateMerchantAccountAmount
${dayjs(t.date).format('MMM D, YYYY')}${escapeHtml(t.description)}${State.accounts[t.account]?.name||t.account}${fmt(t.amount)}
`; - root.appendChild(dCard); - // Wire up row clicks to the standard transaction edit drawer - $$('tr.click', dCard).forEach(tr=>tr.onclick=()=>showTxDrawer(tr.dataset.id)); + const bills=State.bills||[]; + const t0=today(); + const daysTo=(d)=>Math.round((new Date(d.getFullYear(),d.getMonth(),d.getDate())-t0)/DAY); + + /* ---- new bill form ---- */ + if (billFormOpen) { + appendHtml(root,`
+

New bill

+
+ + + + + +
+
+
`); + $('#nbCancel').onclick=()=>{ billFormOpen=false; renderActive(); const b=$('#billAddBtn'); if (b) b.focus(); }; + $('#nbSave').onclick=()=>{ + const name=$('#nbName').value.trim(); + if (!name){ $('#nbName').setAttribute('aria-invalid','true'); $('#nbName').focus(); return; } + const day=Math.min(31,Math.max(1,parseInt($('#nbDay').value,10)||1)); + // first due date: that day this month if it hasn't passed, otherwise next month + const clamp=(y,m)=>new Date(y,m,Math.min(day,new Date(y,m+1,0).getDate())); + let due=clamp(t0.getFullYear(),t0.getMonth()); + if (dueCategory Rules

-

When a description contains "X", assign category "Y".

-
-
-
- -
-
-

Active Rules

-
${(State.categoryRules||[]).map((r,i)=>`
- ${escapeHtml(r.contains)} → ${r.category} -
`).join('')||'No custom rules.'}
-
- `; - root.appendChild(mgmtCard); + /* ---- KPIs ---- */ + const subs=bills.filter(billIsSubscription); + const perMonth=bills.reduce((s,b)=>s+(Number(b.amount)||0)*billFreq(b).perMonth,0); + const subsMonth=subs.reduce((s,b)=>s+(Number(b.amount)||0)*billFreq(b).perMonth,0); + const allSpan=dataSpan(State.transactions); + const pay=allSpan?sumIncome(State.transactions)/Math.max(1,allSpan.months):0; + const withDue=bills.map((b,i)=>({b,i,due:billNextDue(b)})); + const week=withDue.filter(x=>!x.b.paid&&daysTo(x.due)>=0&&daysTo(x.due)<=7); + const overdue=withDue.filter(x=>!x.b.paid&&daysTo(x.due)<0); + const dueToday=week.filter(x=>daysTo(x.due)===0); + const weekNote=[plural(week.length,'bill')]; + if (dueToday.length) weekNote.push(`${escapeHtml(dueToday[0].b.merchant)} ${dueToday.length>1?`and ${dueToday.length-1} more are`:'is'} due today`); + if (overdue.length) weekNote.push(`${overdue.length} overdue`); + appendHtml(root,kpiTiles([ + {label:'Bills tracked',value:String(bills.length),sub:subs.length?`${subs.length} ${subs.length===1?'is a subscription':'are subscriptions'}`:'No subscriptions'}, + {label:'Per month',value:fmt(perMonth),sub:pay>0&&perMonth>0?`${pctStr(perMonth/pay)} of take-home pay`:'All bills, as a monthly cost'}, + {label:'Due in the next 7 days',value:fmt(week.reduce((s,x)=>s+(Number(x.b.amount)||0),0)),sub:weekNote.join(' · ')}, + {label:'Subscriptions',value:`${fmt(subsMonth)}/mo`,sub:`${fmt(subsMonth*12)} a year`}, + ])); + + /* ---- spotted recurring charges ---- */ + const recurring=detectRecurring(); + const billKeys=new Set(bills.map(b=>b.recurringKey||recurringKey(b.merchant))); + const charges=State.transactions.filter(t=>t.amount<0&&t.type!=='transfer'&&t.category!=='Transfer'); + const sugHtml=recurring.map((r,i)=>{ + const items=charges.filter(t=>recurringKey(t._originalDesc||t.description)===r.key); + const steady=items.every(t=>Math.abs(Math.abs(t.amount)-r.avg)<0.005); + const pattern=r.freq==='Monthly'?`Monthly, around the ${ordinal(medianDay(items.map(t=>t.date))||r.lastSeen.getDate())}`:FREQ_LABEL[r.freq]||r.freq; + const conf=Math.round(r.confidence*100); + const state=billKeys.has(r.key)?'confirmed':State.recurringConfirmed[r.key]==='dismissed'?'dismissed':'pending'; + const acts=state==='confirmed'?'✓ Added to bills' + :state==='dismissed'?`Dismissed` + :``; + return `
+
${escapeHtml(r.merchant)}
${pattern} · ${r.count} charges · ${escapeHtml(acctName(r.account))}
+
${steady?'':'avg '}${fmt(r.avg)}
+
${conf}% confidence
+
${acts}
`; + }).join(''); + const sugSec=document.createElement('section'); + sugSec.className='panel'; + sugSec.setAttribute('aria-labelledby','blSugH'); + sugSec.innerHTML=`

Spotted recurring charges

FinLens found these repeating. Confirm the real bills so they get due dates and reminders.

+ ${sugHtml?`
${sugHtml}
`:'

Nothing repeating found yet. Import a few months of history.

'}`; + root.appendChild(sugSec); + const refocus=(key,sel)=>{ const row=$(`#content .sug[data-sug-key="${CSS.escape(key)}"]`); const el=row&&(row.querySelector(sel)||row.querySelector('button,.done-chip')); if (el){ if (!el.matches('button')) el.tabIndex=-1; el.focus({preventScroll:true}); } }; + $$('[data-confirm]',sugSec).forEach(b=>b.onclick=()=>{ const r=recurring[+b.dataset.confirm]; confirmRecurring(r); refocus(r.key,'.done-chip'); }); + $$('[data-dismiss]',sugSec).forEach(b=>b.onclick=()=>{ const r=recurring[+b.dataset.dismiss]; dismissRecurring(r.key); refocus(r.key,'[data-undo]'); }); + $$('[data-undo]',sugSec).forEach(b=>b.onclick=()=>{ const r=recurring[+b.dataset.undo]; undoDismissRecurring(r.key); refocus(r.key,'[data-confirm]'); }); + + /* ---- month calendar ---- */ + const now=new Date(), y=now.getFullYear(), m=now.getMonth(); + const mStart=new Date(y,m,1), mEnd=new Date(y,m+1,0,23,59,59); + const byDay={}; + bills.forEach(b=>billDatesBetween(b,mStart,mEnd).forEach(d=>{ (byDay[d.getDate()]=byDay[d.getDate()]||[]).push(b.merchant); })); + const lead=mStart.getDay(), days=mEnd.getDate(); + const cells=[]; + for (let i=0;i