From bedbbc53a2cab50c7d7bf9693cefd809cd6b80ef Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 05:56:28 +0000 Subject: [PATCH] Clarity redesign, part 3: Plan screens (v1.15.0) Budget, Savings buckets, Debt tracker, Investing ideas and Forecast rebuilt to match the Clarity mockups. Every number is computed from State; none come from the mockups. - Budget: month switcher with "Data through", per-category alerts, KPIs, table with inline amount edit and a drawer for name/categories/delete, 6-month budget-vs-actual bars. "Use starter budget" now builds budgets from your spending and only adds categories no budget covers. - Buckets: inline New bucket form with a monthly preview, KPIs, savings pace (same number as Transfers), cards with icon/color, months left and monthly need; edit drawer with icon and color choices and linked transactions. - Debt: KPIs, debts table, debts can take balance and limit from a credit card in the CSVs (debt.account), payoff plan with an extra-payment slider and avalanche / snowball / minimums-only cards, summary, balance bars, payoff order, first 6 months. New payoffPlan() rolls freed minimums forward; simulatePayoff() kept unchanged. - Investments: My mix (stacked bar, split, link to Forecast), 9 funds with My % inputs, 6 stocks to read about, "not financial advice" note. - Forecast: real tabs; Savings with APY and tax and saved scenarios (old scenarios still list); Investments with presets and today's dollars. Monthly rate is (1 + yearly)^(1/12) - 1 (was yearly / 12). - New stored data: State.debtPlan (localStorage, IndexedDB, state file, export/import; Clear debts resets it; Start over erases it). Bucket icon/hue, debt account and the new scenario shape live in their records. Data & Reset gains Forecast scenarios and Investment mix rows. - Shell hides the date-range label on Plan screens. AI summary reports a linked debt's card balance; unchanged otherwise (diffed on the samples). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Z8iBXzUjiQbYziDZ8CZft --- CHANGELOG.md | 67 +++++ CLAUDE.md | 89 ++++-- README.md | 42 ++- index.html | 205 +++++++++++++- js/aggregation.js | 132 +++++++++ js/core.js | 4 +- js/db.js | 3 +- js/ui.js | 308 ++++++++++++++++----- js/views-ai.js | 2 +- js/views-cleanup.js | 35 ++- js/views-db.js | 2 +- js/views-forecast.js | 319 ++++++++-------------- js/views-invest.js | 470 +++++++++++--------------------- js/views-plan.js | 624 +++++++++++++++++++++++++------------------ js/views-settings.js | 2 +- 15 files changed, 1399 insertions(+), 905 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92d93ab..29d6177 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,73 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.15.0] — 2026-11-02 + +### Plan screens — Clarity redesign, part 3 +Budget, Buckets, Debt, Investments and Forecast (the screens under **Plan**) now match the Clarity mockups. Every number is computed from your data and your plans; none come from the mockups. + +- **Shared:** each screen opens with a note and its buttons in the `.page-actions` row. KPI tiles, panels, callouts, meters and bar charts reuse the Finances classes or new Clarity classes in `index.html`; the charts are plain boxes colored by theme tokens, each with a text description for screen readers. Forms open in the side drawer with Save, Cancel and Delete (click twice) pinned at the bottom. No `confirm()` or `alert()` dialogs are left on these screens. +- **The date range label is hidden on the five Plan screens.** None of them use it; Budget has its own month. +- **Titles:** Budget, Savings buckets, Debt tracker, Investing ideas, Forecast. +- **Phones:** grids fold to one column, and wide tables move their secondary columns under the first one below 600px. Nothing scrolls sideways at 390px. + +### Budget +- **Month switcher** (‹ October 2026 ›) with how far the data runs ("Data through Oct 20"). It opens on the latest month with transactions. +- **Alerts:** one per category over its budget (red) or at 90–99% (amber). +- **KPIs:** budgeted, spent (share of budget), left to spend (days to go, or "October has ended"), over budget (and how many are close). +- **Budget by category:** progress, spent, budget, left. The pencil edits the amount in the row (Enter or ✓ saves, Escape cancels). The name opens the drawer for the name, the categories (chips) and Delete. +- **Budget vs. actual, month by month:** 6 months of spending in budgeted categories against the total budget (dashed line). Months over budget are red; an unfinished month is lighter and labelled "so far". +- **Use starter budget** now builds one from your spending: a budget per category, the average of up to 3 recent complete months, rounded up to $10 (`starterBudgetList()`). It only adds categories no budget covers yet, so it never replaces yours. Without transactions it adds the old suggested set. +- **Dropped to match the mockup:** the three old KPI cards, the single over/near-limit banner, per-budget colors and the color picker, and the stacked Chart.js history by budget. + +### Savings buckets +- **+ New bucket** opens an inline form: name, target, saved so far, months to goal, with "That's $X a month" as you type. +- **KPIs:** saved in buckets, total of targets (share reached), needed each month to hit every date, unassigned savings (savings balance minus the buckets). +- **Savings pace:** "You've moved about $488 a month into savings since May. These goals need $X a month…", using the same number as Transfers → Saved to savings (`savingsPace()`). +- **Bucket cards:** icon, name, "By Jun 2027 · 7 months left", saved of target, a progress bar, % saved, amount to go, and what it needs a month (`bucketPlan()`: what's left ÷ calendar months to the date). +- **Edit drawer:** name, target, saved, target date, an icon (9) and a color (8), the transactions linked to the bucket, Delete. +- **Dropped to match the mockup:** the old KPI cards, the "Your Buckets" header card, the bucket detail drawer (its linked transactions are now in the edit drawer), emoji icons, the hex color picker and the days-left countdown. + +### Debt tracker +- **KPIs:** total debt, minimum payments (share of take-home pay), average APR weighted by balance, card utilization. +- **Your debts:** balance, APR (20% and up in red), minimum, credit limit with a usage bar, edit. A debt can take its balance from a **credit card in your CSVs** ("Credit card · from your CSV"): the drawer's **Balance from** picks the card, its balance updates with each import, and its credit limit is the card account's limit (the same one the Overview uses). With no debts, the screen offers to add each card from your CSVs. +- **Payoff plan:** an **Extra each month** slider ($0–$1,500, $25 steps) and three plans: **Avalanche** (highest APR first), **Snowball** (smallest balance first) and **Minimums only**, each with its debt-free month, interest paid and how long it takes. "Least interest" marks the cheaper of avalanche and snowball. A summary compares the chosen extra with paying only the minimums. The chosen plan shows its total balance by month, the payoff order with dates, and the first 6 months (paid, interest, remaining). +- **The plan and the extra amount are saved** (`State.debtPlan`); before, they reset on every page load. +- **New payoff math** (`payoffPlan()` in `aggregation.js`): interest is added monthly at APR ÷ 12, every minimum is paid, then the extra and the minimums of debts already paid off go to one debt at a time, re-ordered each month. Minimums only moves nothing on. It stops at 50 years and says so. The old `simulatePayoff()` (extra to the first debt only, no rollover) is kept unchanged but no longer used. +- **Dropped to match the mockup:** the Type and Due columns (both are in the drawer), the avalanche/snowball toggle, the extra-payment number box, the Months to Debt-Free / Total Interest / Focus Order cards and the 24-month table. + +### Investing ideas +- **My mix:** the share assigned ("100% assigned" or "85% of 100%"), a stacked bar, each fund's %, the stocks / bonds / real estate split, and **Project this mix in Forecast →** (opens Forecast → Investments). +- **Index funds and ETFs:** 9 funds (VOO and AVUV added) with what they hold, risk (Lower / Medium / Higher), the balanced preset's % and **My %**. Typing updates the mix at once; the value is saved when you leave the field. +- **Individual stocks to read about:** 6 reference cards (AAPL, MSFT, BRK.B, JNJ, PG, COST), with no % inputs. A stock % saved before still counts in the mix. +- **Clear my %** and **Use the balanced preset** (40/20/20/10/5/5, as before). +- **The "not financial advice" note stays,** reworded as in the mockup. +- **Dropped to match the mockup:** the surplus, emergency-fund and investable-cash cards, the personalized starter allocation, the recommended portfolio table and both doughnut charts, the rationale / category / suggested columns, the blue-chip stock table with % inputs (GOOGL, AMZN and NVDA are gone from the list), the portfolio summary table and the Ask Claude card. + +### Forecast +- **Savings / Investments** are real tabs (`role="tab"`, arrow keys move between them). +- **Savings:** checking, savings and debt start from your accounts and debts; saved each month starts from your savings pace; interest (APY) and tax on interest; 1–30 years. It shows projected savings, what's left after today's debt and interest earned, with yearly bars of what you put in and interest after tax. **Reset** goes back to your balances. +- **Saved scenarios** (up to 10): save, load (click the name) and delete (×). Scenarios saved by the old simulator still list, as their monthly net with no interest. +- **Investments:** starting amount, added each month, 1–40 years, Conservative 5% / Moderate 8% / Aggressive 11% / Custom, today's dollars on or off, inflation. Projected value, value in today's dollars and what you put in; bars and a year-by-year table. +- **Compounding is now exact for a yearly rate:** the monthly rate is (1 + yearly)^(1/12) − 1, so 8% a year gives 8% a year. Before, the investment forecast used yearly ÷ 12, which compounds to 8.30%. Savings use the same rule for the APY after tax. +- **Dropped to match the mockup:** the old savings simulator (separate checking / savings / debt lines, income, expense, transfer, extra debt payment and debt APR inputs, a 3–36 month horizon, one-off events, Run Simulation, the month-by-month table), the Load scenario menu and the name prompt, and the investment forecast's line chart, summary sentence and gains column. + +### Technical +- **`aggregation.js`:** `budgetSpent()`, `starterBudgetList()`, `bucketPlan()`, `savingsPace()`, `debtLinked()`, `debtIsCard()`, `debtBalance()`, `debtLimit()`, `payoffPlan()`, `monthlyRateFromYearly()`, `growthByYear()`. +- **`ui.js`:** new budget, bucket and debt drawers (`editBudget/editBucket/editDebt`, `_armTwoClick()` for Delete), `setBudgetLimit()`, `starterBudgetsToAdd()`, `addBucket()`, bucket icons and hues, `debtCardChoices()`, `setPayoffStrategy()` / `setPayoffExtra()`. `deleteBudget/Bucket/Debt()` no longer ask with `confirm()`. `SUGGESTED_BUDGETS` lost its hex colors. +- **New stored data:** + - `State.debtPlan` `{ strategy, extra }`: localStorage, IndexedDB `app_state` (`DB.loadAll()`), `finlens-state.json`, JSON export and import. **Clear debts** resets it; Start over erases it. + - Inside existing records: bucket `icon` (a key) and `hue`; debt `account`; scenarios `{ name, kind:'savings', inputs }`. +- **Data & Reset:** new **Forecast scenarios** and **Investment mix** rows; **Clear debts** also resets the payoff plan. +- **AI summary:** a debt linked to a card reports the card's current balance (`debtBalance()`). For other debts the summary is unchanged (compared before and after on the samples, with and without debts). +- **Tokens:** `--teal-text` (light and dark). + +### Docs +- **README** — the five Plan screens as they are now. +- **CLAUDE.md** — §3 file roles; §4.1 `debtPlan`, Budget / Bucket / Debt / Scenario shapes; §6 Plan components and `--teal-text`; §7 Plan charts; §8 new helpers; §9 plan form helpers; §12 titles, Forecast tabs, range label; §13 debt balances in the summary; §20 new Data & Reset rows. + +--- + ## [1.14.0] — 2026-11-02 ### Finances screens — Clarity redesign, part 2 diff --git a/CLAUDE.md b/CLAUDE.md index de8aec1..bca5400 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.14.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.15.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). **What it does:** Imports CSV exports from a bank (checking + savings) and credit cards, parses and normalizes them into a unified transaction model, and renders a multi-tab financial dashboard with budgeting, debt tracking, savings forecasting, investment planning, and Claude-powered AI analysis. @@ -115,9 +115,9 @@ FinLens/ ├── migrate.js ← Rewrites data saved by older versions: account codes (§22) ├── ui.js ← View registry, drawer, theme, chart helpers, CRUD helpers ├── views-main.js ← Overview, Transactions, Income, Bills, Spending, Transfers - ├── views-plan.js ← Budgeting, Savings Buckets, Debt Tracker, Trends - ├── views-invest.js ← Investing Ideas tab - ├── views-forecast.js ← Forecast Savings + Forecast Investments tabs + ├── views-plan.js ← Budget, Savings buckets, Debt tracker (Plan, v1.15.0); Trends + ├── views-invest.js ← Investing ideas + the Forecast → Investments tab (_renderForecastInvest) + ├── views-forecast.js ← Forecast: Savings and Investments tabs, saved scenarios ├── views-ai.js ← AI Analysis tab (Claude integration) ├── views-data.js ← Import, Accounts, Credit Cards, Categories (Settings tabs) + Import Logs ├── views-settings.js ← Settings shell (tab bar) + General tab (display, Anthropic API key) @@ -161,8 +161,9 @@ const State = { categories: [], // string[] — user-editable category list apiKey: '', // Anthropic API key aiHistory: [], // { timestamp, question, response }[] - scenarios: [], // Forecast scenario saves - investAlloc: {}, // { [ticker]: userPct } + scenarios: [], // Scenario[] — Forecast → Savings, up to 10 (shape below) + investAlloc: {}, // { [ticker]: userPct } — Investing ideas "My %" (0 / missing = not in the mix) + debtPlan: { strategy, extra }, // Debt payoff plan: 'avalanche' | 'snowball' | 'minimum', extra $ a month (v1.15.0) range: { mode, start, end }, // Active date range selectedAccounts: 'all', // 'all' | string[] theme: 'light', // 'light' | 'dark' | 'system' (follow the OS) — Settings → General @@ -196,6 +197,26 @@ const State = { 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. +**Plan records (v1.15.0).** New fields live inside the existing arrays; only `debtPlan` is a new top-level key. + +```js +// Budget (State.budgets) +{ name, limit: number /* a month */, categories: string[], color?: '#hex' /* before v1.15.0; kept, not shown */ } +// Bucket (State.buckets) +{ name, goal, current, targetDate: 'YYYY-MM-DD' | '', + icon?: 'shield'|'plane'|'laptop'|'wrench'|'home'|'gift'|'heart'|'book'|'star', // BUCKET_ICONS + hue?: 'accent'|'pink'|'sky'|'card'|'good'|'violet'|'teal'|'warn' } // BUCKET_HUES + // older buckets have an emoji icon and a hex color: they show an icon guessed from the name and a hue by position +// Debt (State.debts) +{ name, type: 'Credit Card'|'Personal Loan'|'Student Loan'|'Auto Loan'|'Mortgage'|'Other', + balance, apr /* % */, minPayment, limit, dueDay, + account?: string } // a credit card account: balance and limit then come from it (debtBalance(), debtLimit()); + // `balance` keeps the value at the last save; the limit is State.manualBalances[account+'_limit'] +// Scenario (State.scenarios) +{ name, kind: 'savings', inputs: { checking, savings, debt, monthly, rate /* APY % */, tax /* % */, years } } + // scenarios from before v1.15.0 have the old simulator's inputs; scenarioInputs() converts them for display +``` + ### 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', ...)`. @@ -332,7 +353,7 @@ The visual system is **Clarity** (v1.13.0): indigo accent, Inter type, white car /* 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, --card-soft, --card-border +/* hues */ --teal-2, --teal-text (v1.15.0), --sky, --sky-text, --violet, --violet-text, --pink, --card, --card-soft, --card-border /* charts */ --chart-in, --chart-out, --chart-save, --chart-debt, --chart-card, --chart-neutral, --chart-grid /* heatmap */ --heat-1 … --heat-5 /* shape */ --shadow (none), --popover-shadow, --radius (16px), --radius-sm (10px) @@ -388,6 +409,23 @@ Dark mode is applied by setting `data-theme="dark"` on `` (`applyTheme()`, .dform .sum-box .drawer-note — drawer bodies; .drawer-head/.drawer-body/.drawer-foot are the drawer itself ``` +**Plan screens (v1.15.0)** — Budget, Buckets, Debt, Investments and Forecast add: + +``` +.callout(.bad/.warn/.good/.plain) — tinted box with an icon: budget alerts, the savings-pace note, the payoff summary, the advice note +.slider (.sm) — a range input with its value label (.top b) and end labels (.ends) +.month-nav — Budget's ‹ month › switcher; .icon-btn:disabled +.meter .progress.lg/.xs .hue-danger — progress bars (role="progressbar", aria-valuenow, aria-valuetext) +.bud-tbl .bud-hist(.ref) .bud-x — budget table and the budget-vs-actual bars with the dashed budget line +.bucket-grid .bucket .tile .bk-grid .form-panel .form-foot — bucket cards and the inline New bucket form +.choice-set .choice — icon / color radio tiles in a drawer; .form-err — a drawer form's error +.debt-tbl .lim-cell .plan-head .plan-cards .plan-card[aria-pressed] .mini-bars .order-list .num-badge +.stack.lg .mix-list .split3 .fund-tbl .alloc-input .pct-field .ref-cards .ref-card — Investing ideas +.seg.tabs-seg [role=tab][aria-selected] .fc-form .fc-out .big-stats .ybars(.yb .c .g / .ov .n .r, .nominal) .preset-set .preset[aria-pressed] .toggle-row .scroll-y .tbl.sticky .scen +.sm-line .compact-sm — phones: a line under a table's first cell replaces its hidden columns; tighter cells +.strong .c-bad .c-warn .c-dim .c-teal .axis-ends .sw.dash .mw-640 .mw-720 +``` + Prefer these over inline styles. Keep touch targets ≥ 44px where feasible (`@media (pointer:coarse)` raises pills and remove buttons). --- @@ -402,7 +440,7 @@ These rules exist because Chart.js will cause infinite layout loops if violated. 4. **Always** destroy a chart before recreating it on the same canvas — or use a unique canvas ID per render. `ui.js` enforces this: `Chart` is a guard subclass that destroys any chart already on the canvas, and any chart whose canvas has left the page, before drawing. Keep it. Without it, two renders in a row throw "Canvas is already in use" and every render leaks its charts. 5. **Never** let a chart container have `height: auto` — always an explicit pixel height. 6. **Colors come from the theme:** `chartColor('--chart-in')`, `chartColor('--chart-out', .12)` and so on, read when the chart is created, never hex literals. `setTheme()` re-renders, so charts recolor when the theme changes. `CHART_PALETTE` is for multi-series charts with no meaning per color. -7. **The Finances 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. +7. **The Finances and Plan screens don't use Chart.js (v1.14.0, v1.15.0).** The Plan screens' budget, debt and forecast bars are plain boxes (`.bud-hist`, `.mini-bars`, `.ybars`). Their line charts, sparklines, bars and heatmap are inline SVG or plain boxes (`svgLineChart()`, `sparkSvg()`, `dailyHeatmapHtml()` in `ui.js`; `.bars` in CSS). Give each one `role="img"` and an `aria-label` that says what it shows. `svgLineChart()` takes the width it should draw at: measure the holder (`clientWidth`, the view is already in the page when it renders) so its 11px labels stay 11px. ```js // Correct pattern @@ -472,6 +510,16 @@ transferPairs(txs) // [{ date, from, to, amount, description, outId, inI 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 +// v1.15.0 (the Plan screens) +budgetSpent(b, from, to) // charges (not transfers) in any of a budget's categories, each counted in full +starterBudgetList() // a budget per category: average of up to 3 recent complete months, rounded up to $10 +bucketPlan(b) // { goal, saved, left, due, months (calendar months, ≥ 1 while ahead; 0 once passed), monthly } +savingsPace() // { total, perMonth, since }: paired transfers into savings − out of them (= Transfers "Saved to savings") +debtLinked(d), debtIsCard(d), debtBalance(d), debtLimit(d) // a debt linked to a card account reads its balance/limit from it +payoffPlan(debts, extra, strategy) // 'avalanche' | 'snowball' | 'minimum' → { months, interest, paidOff, order, left, rows } + // interest = balance × APR/12 monthly; minimums, then extra + freed minimums to one debt at a time; 600-month cap +monthlyRateFromYearly(pct) // (1 + pct)^(1/12) − 1: twelve months compound to exactly the yearly rate +growthByYear(start, monthly, yearlyPct, years) // [{ year, balance, putIn }], deposits at the end of each month // Utilities hash(str) // Deterministic 'tx' + base36 hash for transaction IDs @@ -543,9 +591,14 @@ dailyHeatmapHtml(txs, start, end) // weeks × days heatmap, six shades by qua // CRUD helpers for Bills, Budgets, Buckets, Debts (all in ui.js) 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) +// Plan forms (v1.15.0) open in the drawer: fields, an inline error (#planFormErr), Delete (two clicks, _armTwoClick) +editBudget(i), saveBudget(i), setBudgetLimit(i, v), deleteBudget(i) // i < 0 adds; setBudgetLimit = the row's inline edit +seedBudgets(), starterBudgetsToAdd() // "Use starter budget": adds only categories no budget covers; SUGGESTED_BUDGETS without spending +editBucket(i), saveBucket(i), addBucket(b), deleteBucket(i) // BUCKET_ICONS, BUCKET_HUES, bucketIconKey(), bucketHue(), guessBucketIcon(), bucketIconSvg() +editDebt(i, account?), saveDebt(i), deleteDebt(i), debtCardChoices(current) // account: start a new debt linked to a card +setPayoffStrategy(s), setPayoffExtra(v) // save State.debtPlan +simulatePayoff(debts, extra) // older payoff model, kept unchanged and unused (extra to the first debt only, no rollover) +// deleteBudget/Bucket/Debt no longer confirm(): the drawer's Delete asks for a second click confirmRecurring(r), dismissRecurring(key), undoDismissRecurring(key) // r: a detectRecurring() entry addCatRule(), delCatRule(i), recategorizeAll() exportAllData(), importJsonFile(ev) @@ -706,15 +759,15 @@ 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). +- **Page title:** the shell renders it (`#pageTitle` from the registered title, `#rangeLabel` the range). Views never render their own H1. On the five Plan screens (`PLAN_VIEWS`) `showView()` hides `#rangeLabel`: none of them use the date range (v1.15.0). A screen's buttons and one-line note go in a `.page-actions` row at the top (`pageActions()` in views-main.js). **Transactions pills (v1.14.0).** `renderTxPills(root, current)` draws the row on all five screens. **All** and **Payments** set `txPillFilter` and show the `transactions` view, which lists one or the other. **Income**, **Spending**, **Bills** and **Transfers** set `txPillFilter` and open the registered views `income`, `spending`, `bills`, `transfers` (titles "Income", "Spending", "Bills & subscriptions", "Transfers"). The Transactions view treats any other `txPillFilter` as All, so the app bar link always lands on the list. `TX_VIEWS` (ui.js) keeps Transactions underlined on all five. View registrations by file: - `views-main.js` — overview, transactions (All / Payments), income, spending, bills, transfers -- `views-plan.js` — budgets, buckets, debt, trends -- `views-invest.js` — investments (`_renderForecastInvest` is a helper, not a registered view) -- `views-forecast.js` — forecast (tabbed: calls `_renderForecastSavings` / `_renderForecastInvest`) +- `views-plan.js` — budgets, buckets, debt (titles "Budget", "Savings buckets", "Debt tracker"), trends +- `views-invest.js` — investments ("Investing ideas"; `_renderForecastInvest` is a helper, not a registered view) +- `views-forecast.js` — forecast: a `role="tablist"` with Savings / Investments (`forecastTab`, arrow keys move between them), one `role="tabpanel"` filled by `_renderForecastSavings` / `_renderForecastInvest` - `views-ai.js` — ai - `views-data.js` — import, accounts, credit-cards, categories - `views-settings.js` — settings (internal use only, not in nav) @@ -751,7 +804,7 @@ Views build a fresh DOM on every `showView()` call. This is intentional. Do not - Uses the model in `AI_MODEL` (currently `claude-sonnet-5-5`) via direct browser fetch to `https://api.anthropic.com/v1/messages`. `claude-sonnet-4-20250514` was retired 2026-06-15 — check Anthropic's model deprecations page before changing models. - Requires `anthropic-dangerous-direct-browser-access: true` header (CORS bypass). - API key is stored in `State.apiKey` (localStorage + IndexedDB `app_state` only — **never** in `finlens-state.json`, see §4.5). It is entered in **Settings → General → Anthropic API Key**; the settings card never renders the stored value back into the DOM. **Never log or expose it.** -- `buildFinancialSummary()` assembles a plain-text snapshot of current State. **It always states its dates (v1.10.2):** +- `buildFinancialSummary()` assembles a plain-text snapshot of current State. Debts report `debtBalance(d)`: a debt linked to a card account gives the card's current balance (v1.15.0); others give `d.balance` as before. **It always states its dates (v1.10.2):** - **The period line** gives the span of the transactions it covers (`summarySpan()`), e.g. "Period: All time (transactions from May 1, 2026 to Oct 20, 2026: 173 days, about 5.7 months)". - **A partial month** in the monthly trend is marked (`partialMonthNote()`), e.g. "2026-10 (through Oct 20)". @@ -885,7 +938,7 @@ Multiple credit card files can be loaded simultaneously. Each gets a unique `acc --- -*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.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.15.0 — 2026-11-02 (Plan screens rebuilt: §3 file roles; §4.1 `debtPlan` and the Budget / Bucket / Debt / Scenario shapes; §6 `--teal-text` and Plan components; §7 rule 7 covers the Plan charts; §8 plan helpers (`payoffPlan()`, `growthByYear()` …); §9 plan form helpers, `simulatePayoff()` kept unused; §12 Plan titles, Forecast tabs, range label hidden on Plan screens; §13 debt balances in the summary; §20 Clear forecast scenarios / investment mix, Clear debts resets `debtPlan`; v1.14.0: Finances screens rebuilt: §4.1 Bill shape and `recurringConfirmed`; §6 new tokens and Finances components; §7 rule 7 inline SVG charts; §8 new aggregation helpers; §9 drawer, `TX_VIEWS`, SVG/heatmap/format helpers, bill helpers, removed renderers; §11 keywords re-run detection, `transferPairs()`, card payments; §12 page actions and Transactions pills; §20 Clear bills also clears spotted-charge choices; v1.13.0: Clarity redesign — §6 tokens and components; §9 theme, chart colors and app bar helpers; §12 app bar navigation replaces the sidebar and the emoji rule; §17 footer; §20 Data & Reset; v1.12.0: bank-neutral account codes, names, samples and docs; §22 `migrate.js` added; §3, §4, §5, §10, §18, §21 updated; v1.10.2: §13 summary states its dates; §21 per-month derivations; v1.10.1: §13 `AI_MAX_TOKENS`, thinking and cut-off answers; v1.10.0: §21 AI Eval added; §13 `callClaude()` raw mode; v1.9.6: §14 folder access lasts until the last tab closes, not one page load; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §20 Data & Reset added; v1.8.1: §10 re-upload dedup rewritten for the occurrence-suffix fix; v1.8.0: AI Analysis restored with API-key and output hardening; `renderMarkdown()` added; `samples/` added; §1–3, §13, §14, §17 corrected to match the code)* --- @@ -934,7 +987,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`. Bills also resets `recurringConfirmed` (confirmed/dismissed spotted charges, `PLAN_ALSO`) | — | +| Clear budgets / bills / buckets / debts / forecast scenarios / investment mix / AI history | `State[key] = []` (`{}` for `investAlloc`; the empty value is `PLAN_ITEMS[i][2]`) + `lsSet`. Bills also resets `recurringConfirmed` (confirmed/dismissed spotted charges); Debts also resets `debtPlan` (`PLAN_ALSO`) | — | | Rebuild from folder | Clears transactions, accounts, import log, then `reloadFromDirHandle()` | Plans, edits, settings | | Disconnect folder | `forgetDataFolder()` — stops CSV auto-reload and state-file writes | Files on disk | | 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 93891d3..0319a74 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.14.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.15.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -17,11 +17,12 @@ Load your CSV files once, and FinLens gives you: - **Spending** breakdowns by category with drill-down tables and a heatmap - **Income** analysis with recurring deposit detection - **Bills & Subscriptions** tracking with an auto-detection engine -- **Budgeting** with progress bars and month-over-month history -- **Savings Buckets** with goal tracking and target dates -- **Debt Tracker** with avalanche vs. snowball payoff simulation +- **Budget** by category, month by month, with a starter budget built from your spending +- **Savings buckets** with targets, dates and what each needs a month +- **Debt tracker** with avalanche, snowball and minimums-only payoff plans +- **Investing ideas**: sketch a portfolio mix from reference lists (not financial advice) - **Trends** across months, categories, and accounts -- **Forecast** simulators for savings and investment growth +- **Forecast** for savings and investment growth, with saved scenarios - **AI Analysis** powered by Claude (Anthropic API key required) --- @@ -120,26 +121,23 @@ Total spent, average per day, top category and highest month. Categories ranked ### Transfers 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. +### Budget +Pick a month with ‹ and ›. Each category shows a progress bar, what you spent, its budget and what's left; the pencil changes the amount right in the row, and the name opens the full edit (name, categories, delete). Alerts flag categories over budget or at 90% and up. A chart compares 6 months of spending with the total budget. **Use starter budget** fills in a budget per category from what you usually spend (the average of up to 3 recent complete months, rounded up to $10) and never replaces one you have. -### Savings Buckets -Goal-based savings tracker with emoji icons, target dates, progress bars, and monthly contribution estimates. +### Savings buckets +Split your savings into goals. Each bucket has a target, what's saved, a date, an icon and a color, and shows what it needs a month to get there. The screen adds up what's saved, the targets, what every goal needs a month and what's not assigned yet, and compares it with how much you've actually been moving into savings. -### Debt Tracker -Debt list with balance, APR, minimum payment, and credit limit. Avalanche vs. snowball payoff simulation with a month-by-month breakdown and total interest comparison. +### Debt tracker +Enter your debts, or take a credit card's balance and limit straight from your CSVs. Total debt, minimums (and their share of take-home pay), average APR and card utilization. The **payoff plan** compares avalanche (highest rate first), snowball (smallest balance first) and paying only the minimums for any extra amount a month: when you'd be debt-free, the interest you'd pay, the payoff order and the first 6 months. Interest is added monthly at APR ÷ 12; a paid-off debt's minimum moves on to the next one. ### Trends Monthly income/expense/savings bar chart, rolling savings rate line, top category ranking over time, and account balance trends. -### Investing Ideas -Curated ETF and individual stock reference lists with suggested allocations. User-editable "My %" inputs (saved across sessions). Portfolio donut chart and a recommended strong-portfolio preset (VTI/VXUS/BND/SCHD/VNQ/VTIP). +### Investing ideas +Reference lists for learning, not financial advice. Type your own % next to nine index funds and ETFs (or use the balanced 40/20/20/10/5/5 preset) and see your mix, and its stock / bond / real estate split, update as you type. Six well-known stocks are listed to read about. Your mix is saved with your other plans. -### Forecast Savings -Project your savings over 1–30 years with configurable starting balances (Checking, Savings, Debt), monthly contribution, expected return, and tax drag. Save and compare up to 10 scenarios. - -### Forecast Investments -Compound growth projection with starting amount, monthly contributions, time horizon, return presets (Conservative 5% / Moderate 8% / Aggressive 11% / Custom), and inflation adjustment. Year-by-year nominal vs. real value table. +### Forecast +**Savings:** start from your checking, savings and debt, add what you save each month, and pick an interest rate (APY) and the tax on it, for 1–30 years. Save up to 10 scenarios and load them back. **Investments:** a starting amount, monthly additions, 1–40 years and a yearly return (5%, 8%, 11% or your own), shown in future and in today's dollars, year by year. Growth compounds monthly so that a yearly rate compounds to exactly that rate. ### AI Analysis Ask Claude anything about your finances. Eight preset quick-analysis prompts or a free-form custom question. Claude receives a structured summary of your current financial state (balances, income, spending by category, debts, subscriptions) as context. Requires your own [Anthropic API key](https://console.anthropic.com). History is saved locally (up to 50 entries) and exportable as Markdown. @@ -218,9 +216,9 @@ FinLens/ ├── migrate.js ← Rewrites data saved by older versions (account codes, v1.12.0) ├── ui.js ← View engine, drawer, chart helpers, CRUD ├── views-main.js ← Overview, Transactions, Income, Bills, Spending, Transfers - ├── views-plan.js ← Budgeting, Savings Buckets, Debt Tracker, Trends - ├── views-invest.js ← Investing Ideas - ├── views-forecast.js ← Forecast Savings + Forecast Investments + ├── views-plan.js ← Budget, Savings buckets, Debt tracker, Trends + ├── views-invest.js ← Investing ideas + the Forecast → Investments tab + ├── views-forecast.js ← Forecast (Savings and Investments tabs) ├── views-ai.js ← AI Analysis (Claude integration) ├── views-data.js ← Database section: Import, Accounts, Categories, Import Logs ├── views-settings.js ← Settings shell + General tab (theme, API key) @@ -261,4 +259,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.14.0 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.15.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index 43ac706..aa6db0b 100644 --- a/index.html +++ b/index.html @@ -57,6 +57,7 @@ --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; + --teal-text:#0f766e; /* teal text (Forecast interest): 5.0:1 or more on every surface */ --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); @@ -108,6 +109,7 @@ --warn:#f59e0b; --warn-text:#fbbf24; --warn-strong-text:#fcd34d; --warn-soft:#3a2a0c; --warn-soft-2:#2a1f0a; --warn-border:#5c4410; --danger:#f87171; --danger-text:#fca5a5; --danger-strong-text:#fecaca; --danger-soft:#2d1414; --danger-border:#5c2020; --teal-2:#2dd4bf; --sky:#38bdf8; --sky-text:#7dd3fc; --violet:#a78bfa; --violet-text:#c4b5fd; --pink:#f472b6; --card:#fb923c; + --teal-text:#2dd4bf; --card-soft:#2b1a0c; --card-border:#5a3313; --chart-neutral:#5b6678; --chart-grid:#1d2535; @@ -693,6 +695,207 @@ .field-row{grid-template-columns:minmax(0,1fr)} .page-actions .acts{margin-left:0} } +/* =============== PLAN SCREENS (v1.15.0): Budget, Buckets, Debt, Investments, Forecast =============== */ +.hue-danger{--c:var(--danger)} +.strong{font-weight:600} +/* a second line under a table's first cell, shown on phones in place of hidden columns */ +.sm-line{display:none;flex-wrap:wrap;align-items:center;gap:4px 8px;margin-top:4px;font-size:12px;font-weight:400;color:var(--text-3)} +.sm-line .progress{flex:1 1 60px} +.c-bad{color:var(--danger-text)} .c-warn{color:var(--warn-text)} .c-dim{color:var(--text-2)} .c-teal{color:var(--teal-text)} +.panel h3{margin:0;font-size:14px;font-weight:600} +.panel.tight{padding:12px 28px 16px;gap:0} +.panel-head.center{align-items:center} +.panel-head .n-of{font-weight:500;color:var(--text-3)} +.icon-btn:disabled{opacity:.45;cursor:default;background:var(--surface);color:var(--text-2)} +.icon-btn.sm.on{background:var(--accent-soft);color:var(--accent)} +.progress.lg{height:10px} +.progress.xs{height:6px;width:80px;flex-shrink:0} +.input[readonly]{background:var(--surface-2);color:var(--text-2)} +.form-err{margin:0;font-size:13px;font-weight:600;color:var(--danger-text)} +.form-panel{border-color:var(--accent-border)} +.form-foot{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px} +.form-foot .preview{font-size:14px;color:var(--text-2)} +.form-foot .preview strong{color:var(--text)} +.form-foot .acts{display:flex;gap:10px;margin-left:auto} +.axis-ends{display:flex;justify-content:space-between;gap:12px;font-size:12px;color:var(--text-3)} +.sw.dash{width:16px;height:0;border-radius:0;background:none;border-top:2px dashed var(--inverse)} +/* callouts: a tinted box with an icon (alerts, notes, plan summaries) */ +.callout{display:flex;align-items:flex-start;gap:12px;margin:0;padding:14px 18px;border-radius:12px;font-size:14px;line-height:1.5;background:var(--accent-soft);border:1px solid var(--accent-border);color:var(--accent-strong-text)} +.callout svg{flex-shrink:0;margin-top:2px} +.callout.bad{background:var(--danger-soft);border-color:var(--danger-border);color:var(--danger-strong-text)} +.callout.warn{background:var(--warn-soft-2);border-color:var(--warn-border);color:var(--warn-strong-text)} +.callout.good{background:var(--good-soft);border-color:var(--good-border);color:var(--good-strong-text)} +.callout.plain{background:var(--surface-2);border-color:var(--border);color:var(--text-2);font-size:13px} +.alerts{display:flex;flex-direction:column;gap:12px} +/* range sliders with a value label */ +.slider{display:flex;flex-direction:column;gap:8px;font-size:13px;font-weight:600;color:var(--text-body);min-width:min(320px,100%)} +.slider .top{display:flex;justify-content:space-between;align-items:baseline;gap:8px} +.slider .top b{font-size:18px;font-weight:700;color:var(--accent-text)} +.slider.sm{min-width:0} +.slider.sm .top b{font-size:13px;font-weight:600} +.slider input[type=range]{width:100%;height:24px;margin:0;accent-color:var(--accent)} +.slider .ends{display:flex;justify-content:space-between;font-size:12px;font-weight:500;color:var(--text-3)} +/* Budget */ +.month-nav{display:flex;align-items:center;flex-wrap:wrap;gap:6px} +.month-nav .m{font-size:15px;font-weight:600;padding:0 8px;min-width:128px;text-align:center} +.month-nav .note{font-size:13px;color:var(--text-2);margin-left:6px} +.bud-tbl td{height:58px} +.bud-tbl th:nth-child(1){width:180px} .bud-tbl th:nth-child(3){width:120px} .bud-tbl th:nth-child(4){width:150px} .bud-tbl th:nth-child(5){width:110px} .bud-tbl th:nth-child(6){width:48px} +.bud-tbl .link-btn{font-weight:600} +.meter{display:flex;align-items:center;gap:10px} +.meter .progress{flex:1} +.meter .p{width:44px;flex-shrink:0;text-align:right;font-size:13px;font-weight:600} +.inline-num{display:inline-flex;align-items:center;gap:4px} +.inline-num .input{width:96px;min-height:38px;padding:0 8px;text-align:right;border-color:var(--accent)} +.bud-hist{position:relative;height:200px;border-bottom:1px solid var(--border)} +.bud-hist .ref{position:absolute;left:0;right:0;border-top:2px dashed var(--inverse)} +.bud-hist .bars{position:absolute;inset:0;height:auto;border-bottom:0;padding:0 16px;gap:32px} +.bud-x{padding:0 16px;gap:32px} +.bud-x .v{font-weight:600} +.bud-x .v.c-bad{color:var(--danger-text)} +.bud-tbl .link-btn{white-space:normal;overflow-wrap:anywhere} +/* Savings buckets */ +.bk-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px} +.bk-grid .span-2{grid-column:span 2} +.bucket-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px} +.bucket{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:22px 24px;display:flex;flex-direction:column;gap:14px;min-width:0} +.bucket-top{display:flex;align-items:center;gap:12px} +.bucket-top .who{flex:1;min-width:0} +.bucket h2{margin:0;font-size:16px;font-weight:700;overflow-wrap:anywhere} +.bucket .when{font-size:12px;color:var(--text-3)} +.tile{width:42px;height:42px;border-radius:12px;display:grid;place-items:center;flex-shrink:0;background:color-mix(in srgb,var(--c) 14%,var(--surface));color:var(--c)} +.bucket .amt{display:flex;align-items:baseline;flex-wrap:wrap;gap:6px} +.bucket .amt b{font-size:26px;font-weight:700;letter-spacing:-.02em} +.bucket .amt span{font-size:14px;color:var(--text-3)} +.bucket .prog{display:flex;flex-direction:column;gap:6px} +.bucket .meta{display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--text-2)} +.bucket .need{margin-top:auto;padding:12px 14px;background:var(--surface-2);border-radius:10px;font-size:13px;color:var(--text-body)} +.choice-set{border:0;padding:0;margin:0;display:flex;flex-wrap:wrap;gap:8px;min-width:0} +.choice-set legend{font-size:13px;font-weight:600;color:var(--text-body);padding:0;margin-bottom:8px} +.choice{position:relative;width:44px;height:44px;display:grid;place-items:center;border:1px solid var(--border-strong);border-radius:10px;background:var(--surface);color:var(--text-2);cursor:pointer} +.choice input{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer} +.choice:has(input:checked){border-color:var(--accent);background:var(--accent-soft);color:var(--accent-strong-text);box-shadow:inset 0 0 0 1px var(--accent)} +.choice:has(input:focus-visible){outline:2px solid var(--accent);outline-offset:2px} +.choice .sw{width:18px;height:18px;border-radius:50%} +.linked{display:flex;flex-direction:column;gap:6px} +.linked h3{margin:0;font-size:13px;font-weight:600;color:var(--text-body)} +.linked h3 span{font-weight:500;color:var(--text-3)} +.linked .rows{font-size:13px} +/* Debt */ +.mw-640{min-width:640px} .mw-720{min-width:720px} +.debt-tbl td{padding-top:14px;padding-bottom:14px} +.debt-tbl .s2{font-size:12px;color:var(--text-3)} +.lim-cell{display:flex;align-items:center;gap:8px} +.plan-head{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:flex-end;gap:16px} +.plan-out{display:flex;flex-direction:column;gap:20px} +.plan-cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px} +.plan-card{text-align:left;border:2px solid var(--border);background:var(--surface);border-radius:14px;padding:18px 20px;display:flex;flex-direction:column;gap:10px;font-size:14px;color:var(--text);min-width:0} +.plan-card:hover{border-color:var(--accent-border)} +.plan-card[aria-pressed="true"]{border-color:var(--accent);background:var(--accent-soft)} +.plan-card .top{display:flex;justify-content:space-between;align-items:center;gap:8px;width:100%} +.plan-card .n{font-size:15px;font-weight:700} +.plan-card .d{font-size:13px;color:var(--text-2)} +.plan-card .stats{display:flex;flex-wrap:wrap;gap:20px} +.plan-card .stats .l{display:block;font-size:12px;color:var(--text-3)} +.plan-card .stats b{font-size:18px;font-weight:700} +.plan-card .dur{font-size:12px;color:var(--text-2)} +.plan-detail h3,.plan-out>div>h3{margin-bottom:10px} +.mini-bars{display:flex;align-items:flex-end;gap:3px;height:160px;border-bottom:1px solid var(--border)} +.mini-bars>span{flex:1;min-width:2px;background:var(--c);border-radius:3px 3px 0 0} +.order-list{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:8px} +.order-list li{display:flex;align-items:center;gap:12px;padding:12px 14px;border:1px solid var(--border);border-radius:12px;font-size:14px;min-width:0} +.order-list .t{flex:1;min-width:0;font-weight:600;overflow-wrap:anywhere} +.order-list .d{color:var(--text-2);white-space:nowrap} +.num-badge{width:26px;height:26px;border-radius:50%;flex-shrink:0;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent-strong-text);font-size:13px;font-weight:700} +/* Investments */ +.stack.lg{height:20px} +.mix-list{display:flex;flex-direction:column;gap:10px;font-size:14px} +.mix-list>div{display:flex;align-items:center;gap:10px} +.mix-list .t{flex:1;font-weight:600} +.mix-list .v{color:var(--text-2)} +.split3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;padding-top:14px;border-top:1px solid var(--divider);text-align:center} +.split3 b{display:block;font-size:18px;font-weight:700} +.split3 span{font-size:12px;color:var(--text-3)} +.fund-tbl td{height:56px} +.fund-tbl th:nth-child(1){width:70px} .fund-tbl th:nth-child(3){width:110px} .fund-tbl th:nth-child(4){width:90px} .fund-tbl th:nth-child(5){width:100px} +.fund-tbl .s2{display:block} +.pct-field{display:inline-flex;align-items:center;gap:4px;color:var(--text-3)} +.alloc-input{width:64px;height:40px;padding:0 8px;border:1px solid var(--border-strong);border-radius:9px;background:var(--surface);color:var(--text);font:600 14px 'Inter',system-ui,sans-serif;text-align:right} +.alloc-input:focus{outline:2px solid var(--accent-border);border-color:var(--accent)} +.ref-cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px} +.ref-card{display:flex;align-items:center;gap:12px;padding:14px 16px;border:1px solid var(--border);border-radius:12px;min-width:0} +.ref-card .tk{width:56px;flex-shrink:0;font-weight:700} +.ref-card .nm{display:block;font-size:14px;font-weight:500} +.ref-card .sec{font-size:12px;color:var(--text-3)} +/* Forecast */ +.seg.tabs-seg{align-self:flex-start;padding:4px;border-radius:12px} +.seg.tabs-seg button{min-height:40px;padding:0 20px;border-radius:9px;font-size:14px} +.seg button[aria-selected="true"]{background:var(--surface);color:var(--text);box-shadow:0 1px 2px rgba(15,23,42,.12)} +.fc-form{display:flex;flex-direction:column;gap:14px} +.fc-form .field .input{min-height:42px} +.fc-out{display:flex;flex-direction:column;gap:20px;min-width:0} +.big-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px} +.big-stats .l{display:block;font-size:13px;font-weight:500;color:var(--text-3)} +.big-stats .v{display:block;font-size:30px;font-weight:700;letter-spacing:-.02em;line-height:1.25;overflow-wrap:anywhere} +.ybars{display:flex;align-items:flex-end;gap:4px;height:220px;border-bottom:1px solid var(--border)} +.ybars .yb{flex:1;min-width:4px;height:100%;display:flex;flex-direction:column;justify-content:flex-end;position:relative} +.ybars .yb i{display:block} +.ybars .c{background:var(--accent-solid)} +.ybars .g{background:var(--teal-2);border-radius:3px 3px 0 0} +.ybars .yb.ov i{position:absolute;left:0;right:0;bottom:0;border-radius:3px 3px 0 0} +.ybars .ov .n{background:var(--accent-border)} +.ybars .ov .r{background:var(--teal-2)} +.ybars.nominal .ov .n{background:var(--accent-solid)} +.preset-set{border:0;padding:0;margin:0;display:flex;flex-direction:column;gap:8px;min-width:0} +.preset-set legend{font-size:13px;font-weight:600;color:var(--text-body);padding:0;margin-bottom:8px} +.preset-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} +.preset{min-height:52px;border:1px solid var(--border-strong);background:var(--surface);border-radius:10px;color:var(--text);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px;font-size:13px} +.preset:hover{background:var(--surface-2)} +.preset[aria-pressed="true"]{background:var(--accent-soft);border-color:var(--accent)} +.preset b{font-weight:600} +.preset span{font-size:12px;color:var(--text-2)} +.toggle-row{display:flex;align-items:center;justify-content:space-between;gap:10px;min-height:44px;font-size:13px;font-weight:600;color:var(--text-body);cursor:pointer} +.toggle-row input{width:20px;height:20px;margin:0;accent-color:var(--accent)} +.scroll-y{max-height:300px;overflow-y:auto} +.tbl.sticky thead th{position:sticky;top:0;background:var(--surface);z-index:1} +.scen .t{flex:1 1 200px} +.scen .link-btn{font-weight:600} +.scen .amt{width:120px;text-align:right;font-weight:700} +@media (max-width:1100px){.bucket-grid,.ref-cards{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media (max-width:900px){ + .plan-cards{grid-template-columns:minmax(0,1fr)} + .bk-grid{grid-template-columns:repeat(2,minmax(0,1fr))} + .bk-grid .span-2{grid-column:1/-1} +} +@media (max-width:720px){ + .panel.tight{padding:8px 18px 12px} + .bucket-grid,.ref-cards{grid-template-columns:minmax(0,1fr)} + .bucket{padding:18px} + .bud-hist .bars,.bud-x{padding:0 4px;gap:8px} + .month-nav .note{flex-basis:100%;margin-left:0} +} +@media (max-width:600px){ + .sm-line{display:flex} + .bud-tbl.fit-sm th:nth-child(1){width:auto} .bud-tbl.fit-sm th:nth-child(4){width:92px} .bud-tbl.fit-sm th:nth-child(5){width:80px} .bud-tbl.fit-sm th:nth-child(6){width:52px} + .bud-tbl .sm-line .progress{flex-basis:100%} + .bud-tbl td{height:auto;padding-top:12px;padding-bottom:12px} + .inline-num .input{width:64px} + .debt-tbl.fit-sm th:nth-child(2){width:108px} .debt-tbl.fit-sm th:nth-child(6){width:52px} + .fund-tbl.fit-sm th:nth-child(1){width:64px} .fund-tbl.fit-sm th:nth-child(5){width:96px} + .fund-tbl td{height:auto;padding-top:12px;padding-bottom:12px} + .tbl.compact-sm{min-width:0;font-size:13px} + .tbl.compact-sm th,.tbl.compact-sm td{padding-left:4px;padding-right:4px} + .big-stats{grid-template-columns:minmax(0,1fr);gap:10px} + .big-stats .v{font-size:26px} + .scen{flex-wrap:wrap} + .scen .t{flex-basis:100%} + .scen .amt{width:auto;margin-left:auto} +} +@media (max-width:480px){ + .bk-grid{grid-template-columns:minmax(0,1fr)} + .seg.tabs-seg{align-self:stretch} + .seg.tabs-seg button{flex:1} +} /* bigger touch targets on touch screens */ @media (pointer:coarse){ .fpill,.seg button{min-height:44px} @@ -805,7 +1008,7 @@
-
v1.14.0 · FinLens
+
v1.15.0 · FinLens
diff --git a/js/aggregation.js b/js/aggregation.js index c39d6b6..80e55aa 100644 --- a/js/aggregation.js +++ b/js/aggregation.js @@ -311,3 +311,135 @@ function billDatesBetween(b, from, to) { for (let d=billOccurrence(b,k); d<=to && k<520; d=billOccurrence(b,++k)) if (d>=from) out.push(d); return out; } + +/* ---------- BUDGETS (v1.15.0) ---------- */ +// What a budget spent between two dates: charges (amount < 0, not transfers) that carry any +// of its categories, each counted in full. Same rule as the Budget screen before v1.15.0. +function budgetSpent(b, from, to, txs=State.transactions) { + const cats=new Set(b.categories||[]); + let s=0; + for (const t of txs) { + if (t.amount>=0||t.type==='transfer'||t.dateto) continue; + const tc=Array.isArray(t.categories)&&t.categories.length?t.categories:[t.category]; + if (tc.some(c=>cats.has(c))) s+=Math.abs(t.amount); + } + return s; +} +// Starter budgets from your own spending: one per category you spend on, its limit the +// average of up to 3 recent complete calendar months, rounded up to the next $10. Only +// months the data covers from the 1st to the last day count; with none, every month does. +// → [{ name, limit, categories:[name] }] biggest first, or [] without any spending +function starterBudgetList(txs=State.transactions) { + const span=dataSpan(txs); + if (!span) return []; + const isCharge=t=>t.amount<0&&t.type!=='transfer'&&!['Transfer','Transfer in','Transfer out'].includes(t.category); + const keys=[...new Set(txs.filter(isCharge).map(t=>monthKey(t.date)))].sort().reverse(); + const first=new Date(span.first.getFullYear(),span.first.getMonth(),span.first.getDate()); + const complete=keys.filter(k=>{ const s=new Date(+k.slice(0,4),+k.slice(5)-1,1), e=new Date(s.getFullYear(),s.getMonth()+1,0); return s>=first&&e<=span.last; }); + const use=(complete.length?complete:keys).slice(0,3); + if (!use.length) return []; + const totals={}; + for (const t of txs) { + if (!isCharge(t)||!use.includes(monthKey(t.date))) continue; + (Array.isArray(t.categories)&&t.categories.length?t.categories:[t.category]).forEach(c=>{ totals[c]=(totals[c]||0)+Math.abs(t.amount); }); + } + return Object.entries(totals).map(([c,v])=>({ name:c, limit:Math.ceil(v/use.length/10)*10, categories:[c], avg:v/use.length })) + .filter(b=>b.avg>=5).sort((a,b)=>b.avg-a.avg).map(({name,limit,categories})=>({name,limit,categories})); +} + +/* ---------- SAVINGS BUCKETS (v1.15.0) ---------- */ +// What a bucket still needs and how much a month. Months to the target date are calendar +// months (November → June is 7), at least 1 while the date is still ahead. +// → { goal, saved, left, due (Date|null), months (null: no date; 0: the date has passed), +// monthly (left ÷ months; null without a date, all of `left` once the date passed) } +function bucketPlan(b, now=today()) { + const goal=Math.max(0,Number(b.goal)||0), saved=Math.max(0,Number(b.current)||0); + const left=Math.max(0,goal-saved); + const due=b.targetDate?parseDate(b.targetDate,'YYYY-MM-DD'):null; + if (!due) return { goal, saved, left, due:null, months:null, monthly:null }; + if (dueid?State.accounts[id]?.kind:null; + const paired=transferPairs(txs).filter(p=>p.paired); + const sum=a=>a.reduce((s,p)=>s+p.amount,0); + const total=sum(paired.filter(p=>kind(p.to)==='bank_savings'))-sum(paired.filter(p=>kind(p.from)==='bank_savings'&&kind(p.to)!=='bank_savings')); + return { total, perMonth:total/Math.max(1,span.months), since:span.first }; +} + +/* ---------- DEBTS (v1.15.0) ---------- */ +// A debt can take its balance from a credit card account in your CSVs (debt.account). Its +// limit then comes from that account's credit limit (Settings → Credit Cards). Without a +// linked account, or once it's gone, the debt's own fields count. +function debtLinked(d) { return !!(d&&d.account&&State.accounts[d.account]); } +function debtIsCard(d) { return debtLinked(d)?State.accounts[d.account].kind==='credit_card':d.type==='Credit Card'; } +function debtBalance(d) { + if (debtLinked(d)) { const b=currentBalances()[d.account]; return b==null||isNaN(b)?0:Math.abs(b); } + return Number(d.balance)||0; +} +function debtLimit(d) { + if (debtLinked(d)) { const l=State.manualBalances[d.account+'_limit']; return l!=null?Number(l)||0:0; } + return Number(d.limit)||0; +} +// Debt payoff, month by month. Every month: add interest (balance × APR ÷ 12) to each debt, +// pay each minimum (or what's left of the debt), then put `extra` — plus the minimums of +// debts already paid off — toward one debt at a time: +// 'avalanche' highest APR first (ties: smaller balance first) +// 'snowball' smallest balance first (ties: higher APR first) +// 'minimum' no extra, and a paid-off debt's minimum is not moved on +// The order is re-checked every month. Stops after 600 months (50 years). +// debts: [{ name, balance, apr (percent), minPayment }] +// → { months, interest, paidOff, order:[{ name, month }], left:[name], rows:[{ month, paid, interest, remaining }] } +// simulatePayoff() in ui.js (older, kept as it was) moves only `extra`, never freed minimums. +const PAYOFF_MAX_MONTHS=600; +function payoffPlan(debts, extra, strategy) { + const ds=debts.map(d=>({ name:d.name, bal:Math.max(0,Number(d.balance)||0), apr:Math.max(0,Number(d.apr)||0), min:Math.max(0,Number(d.minPayment)||0) })); + ds.forEach(d=>{ d.done=d.bal<=0.005; if (d.done) d.bal=0; }); + const ex=strategy==='minimum'?0:Math.max(0,Number(extra)||0); + const budget=ds.reduce((s,d)=>s+d.min,0)+ex; + const order=[], rows=[]; + let month=0, interest=0; + while (ds.some(d=>!d.done) && month!d.done&&d.bal>0.005) + .sort(strategy==='snowball'?(a,b)=>a.bal-b.bal||b.apr-a.apr:(a,b)=>b.apr-a.apr||a.bal-b.bal); + for (const d of act) { if (avail<=0.005) break; const p=Math.min(avail,d.bal); d.bal-=p; avail-=p; paid+=p; } + } + for (const d of ds) if (!d.done && d.bal<=0.005) { d.done=true; d.bal=0; order.push({ name:d.name, month }); } + interest+=mi; + rows.push({ month, paid, interest:mi, remaining:ds.reduce((s,d)=>s+d.bal,0) }); + } + return { months:month, interest, paidOff:ds.every(d=>d.done), order, left:ds.filter(d=>!d.done).map(d=>d.name), rows }; +} + +/* ---------- GROWTH (v1.15.0): Forecast ---------- */ +// The monthly rate that compounds to a yearly rate: (1 + yearly)^(1/12) − 1. So 8% a year +// is 0.6434% a month, and 12 months of it give exactly 8%. +function monthlyRateFromYearly(pct) { + return Math.pow(1+Math.max(-99,Number(pct)||0)/100, 1/12)-1; +} +// Year by year: `start` today, `monthly` added at the end of each month, the balance growing +// at `yearlyPct` a year, compounded monthly. → [{ year, balance, putIn }] +function growthByYear(start, monthly, yearlyPct, years) { + const r=monthlyRateFromYearly(yearlyPct), out=[]; + let bal=Number(start)||0, put=bal; + const add=Number(monthly)||0; + for (let y=1; y<=years; y++) { + for (let m=0; m<12; m++) { bal=bal*(1+r)+add; put+=add; } + out.push({ year:y, balance:bal, putIn:put }); + } + return out; +} diff --git a/js/core.js b/js/core.js index 7a7d242..dafa4b6 100644 --- a/js/core.js +++ b/js/core.js @@ -197,6 +197,7 @@ async function saveStateToFile(state) { aiHistory: state.aiHistory, scenarios: state.scenarios, investAlloc: state.investAlloc, + debtPlan: state.debtPlan, theme: state.theme, fileAssignments: state.fileAssignments, accountOrder: state.accountOrder, @@ -360,8 +361,9 @@ const State = { ], apiKey: lsGet('apiKey', ''), aiHistory: lsGet('aiHistory', []), - scenarios: lsGet('scenarios', []), + scenarios: lsGet('scenarios', []), // Forecast → Savings scenarios (CLAUDE.md §4.1) investAlloc: lsGet('investAlloc', {}), // ticker -> user % + debtPlan: lsGet('debtPlan', { strategy:'avalanche', extra:0 }), // Debt payoff plan: 'avalanche'|'snowball'|'minimum', extra $/mo range: { mode:'month', start:null, end:null }, selectedAccounts: 'all', theme: lsGet('theme', 'light'), diff --git a/js/db.js b/js/db.js index f5c7b15..7e46aa6 100644 --- a/js/db.js +++ b/js/db.js @@ -115,7 +115,7 @@ const DB = { _migrateSync(appStateStore) { const LS_KEYS = [ 'budgets','buckets','debts','bills','recurring','txOverrides','manualBalances', - 'catRules','categories','apiKey','aiHistory','scenarios','investAlloc', + 'catRules','categories','apiKey','aiHistory','scenarios','investAlloc','debtPlan', 'fileAssignments','lastFolderName','theme','accountOrder','accountLabels', 'txRules','transferKeywords','customSchemas', ]; @@ -322,6 +322,7 @@ const DB = { ['aiHistory', 'aiHistory', []], ['scenarios', 'scenarios', []], ['investAlloc', 'investAlloc', {}], + ['debtPlan', 'debtPlan', null], ['fileAssignments', 'fileAssignments', {}], ['lastFolderName', 'lastFolderName', ''], ['theme', 'theme', 'light'], diff --git a/js/ui.js b/js/ui.js index 5475c20..1e06ae2 100644 --- a/js/ui.js +++ b/js/ui.js @@ -30,6 +30,8 @@ function showView(id) { const pb=$('#planBtn'); if (pb) pb.classList.toggle('active',PLAN_VIEWS.includes(id)); const gear=$('.appbar .gear'); if (gear) gear.classList.toggle('on',id==='settings'); const pt=$('#pageTitle'); if (pt) pt.textContent=VIEWS[id].title; + // The Plan screens don't use the date range (Budget has its own month), so its label hides there. + const rl=$('#rangeLabel'); if (rl) rl.hidden=PLAN_VIEWS.includes(id); if (typeof updateSyncBadge==='function') updateSyncBadge(); const c=$('#content'); if (!c) return; c.innerHTML=''; @@ -450,106 +452,263 @@ function recategorizeAll() { renderActive(); } +/* ---------- PLAN FORMS: shared bits (v1.15.0) ---------- */ +// A drawer's Delete button: the first click arms it, the second runs `fn` (no confirm()). +function _armTwoClick(btn, fn) { + if (!btn) return; + btn.onclick=()=>{ + if (btn.dataset.armed!=='1') { btn.dataset.armed='1'; btn.textContent='Click again to delete'; return; } + closeDrawer(); fn(); + }; +} +// Show a form error in the drawer and mark the field. +function _formError(msg, el) { + const err=$('#planFormErr'); + if (err) { err.textContent=msg; err.hidden=false; } + if (el) { el.setAttribute('aria-invalid','true'); el.focus(); } +} +const _drawerFooter=(isEdit, saveId, saveLabel, delId)=> + `${isEdit?``:''}`; + /* ---------- BUDGET HELPERS ---------- */ +// State.budgets entries: { name, limit, categories:[…] }. Budgets saved before v1.15.0 may +// also carry a hex `color`; it's kept but no longer shown (rows are colored by status). +// The suggested set is the starter budget when there's no spending to build one from. const SUGGESTED_BUDGETS=[ - {name:'Food & Dining',limit:600,categories:['Food & Dining','Groceries'],color:'#EF4444'}, - {name:'Housing',limit:1500,categories:['Housing'],color:'#8B5CF6'}, - {name:'Transport',limit:300,categories:['Transport'],color:'#3B82F6'}, - {name:'Entertainment',limit:150,categories:['Entertainment'],color:'#F472B6'}, - {name:'Health',limit:150,categories:['Health'],color:'#34D399'}, - {name:'Shopping',limit:250,categories:['Shopping'],color:'#F59E0B'}, - {name:'Bills & Utilities',limit:300,categories:['Bills & Utilities'],color:'#7DD3FC'}, - {name:'Subscriptions',limit:80,categories:['Subscriptions'],color:'#A78BFA'}, + {name:'Food & Dining',limit:600,categories:['Food & Dining','Groceries']}, + {name:'Housing',limit:1500,categories:['Housing']}, + {name:'Transport',limit:300,categories:['Transport']}, + {name:'Entertainment',limit:150,categories:['Entertainment']}, + {name:'Health',limit:150,categories:['Health']}, + {name:'Shopping',limit:250,categories:['Shopping']}, + {name:'Bills & Utilities',limit:300,categories:['Bills & Utilities']}, + {name:'Subscriptions',limit:80,categories:['Subscriptions']}, ]; -function seedBudgets(){ State.budgets=JSON.parse(JSON.stringify(SUGGESTED_BUDGETS)); lsSet('budgets',State.budgets); renderActive(); } +// "Use starter budget": one row per category you spend on (starterBudgetList() in +// aggregation.js), or the suggested set without any spending. Only categories no budget +// covers yet are added, so it never replaces or changes a budget you already have. +function starterBudgetsToAdd() { + const have=new Set((State.budgets||[]).flatMap(b=>b.categories||[])); + let src=starterBudgetList(); + if (!src.length) src=JSON.parse(JSON.stringify(SUGGESTED_BUDGETS)); + return src.filter(b=>!b.categories.some(c=>have.has(c))); +} +function seedBudgets() { + const add=starterBudgetsToAdd(); + if (add.length) { State.budgets.push(...add); lsSet('budgets',State.budgets); } + renderActive(); + return add.length; +} function addBudget(){ editBudget(-1); } +// Categories a budget can count: those you spend on (biggest first), then the rest of your +// category list, then any the budget already has. +function budgetCategoryChoices(b) { + const spent=byCategory(State.transactions,'expense').map(c=>c.category); + const listed=(State.categories||[]).filter(c=>!['Income','Transfer'].includes(c)); + return [...new Set([...spent, ...listed, ...(b.categories||[])])]; +} +// Edit budget i in the drawer, or add one (i < 0). function editBudget(i) { - const b=i>=0?State.budgets[i]:{name:'',limit:0,categories:[],color:'#6366f1'}; - openDrawer(` -

${i>=0?'Edit':'Add'} Budget

- - - - -
Available: ${State.categories.join(', ')}
- - -
- - `); + const b=i>=0?State.budgets[i]:{name:'',limit:'',categories:[]}; + const cats=budgetCategoryChoices(b); + openDrawer(`
+ + +
Counts spending in + ${cats.map(c=>``).join('')} +
+

Every charge in these categories counts in full. Pick one category for a budget per category.

+
`, + { title:i>=0?'Edit budget':'Add budget category', footer:_drawerFooter(i>=0,'bnSave','Save budget','bnDelete') }); + // The name follows the first category picked while it's still empty. + $$('#bnCats input').forEach(cb=>cb.addEventListener('change',()=>{ const n=$('#bnName'); if (cb.checked&&!n.value.trim()) n.value=cb.value; })); + $('#bnSave').onclick=()=>saveBudget(i); + _armTwoClick($('#bnDelete'),()=>deleteBudget(i)); } function saveBudget(i) { - const obj={ - name:$('#bnName').value.trim(), - limit:parseFloat($('#bnLimit').value)||0, - categories:$('#bnCats').value.split(',').map(s=>s.trim()).filter(Boolean), - color:$('#bnColor').value - }; - if (!obj.name||!obj.categories.length){ alert('Name and at least one category required.'); return; } + const name=$('#bnName').value.trim(); + const categories=$$('#bnCats input:checked').map(c=>c.value); + if (!name) return _formError('Give the budget a name.', $('#bnName')); + if (!categories.length) return _formError('Pick at least one category.', $('#bnCats input')); + const prev=i>=0?State.budgets[i]:{}; + const obj={ ...prev, name, limit:Math.max(0,parseFloat($('#bnLimit').value)||0), categories }; if (i>=0) State.budgets[i]=obj; else State.budgets.push(obj); lsSet('budgets',State.budgets); closeDrawer(); renderActive(); } -function deleteBudget(i){ if(!confirm('Delete this budget?')) return; State.budgets.splice(i,1); lsSet('budgets',State.budgets); renderActive(); } +// The Budget screen's inline edit: just the monthly amount. +function setBudgetLimit(i, v) { + const b=State.budgets[i]; if (!b) return; + b.limit=Math.max(0,parseFloat(v)||0); + lsSet('budgets',State.budgets); +} +// No confirm() here: the edit drawer's Delete button asks for a second click. +function deleteBudget(i){ State.budgets.splice(i,1); lsSet('budgets',State.budgets); renderActive(); } /* ---------- SAVINGS BUCKET HELPERS ---------- */ +// State.buckets entries: { name, goal, current, targetDate:'YYYY-MM-DD'|'', icon, hue }. +// icon: a BUCKET_ICONS key, hue: one of BUCKET_HUES (v1.15.0). Buckets saved before have an +// emoji icon and a hex color: until edited they show an icon guessed from the name and a +// hue by position (the old values stay in the record). +const BUCKET_ICONS={ + shield:'M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z', + plane:'M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z', + laptop:'M4 5h16v11H4zM2 20h20', + wrench:'M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z', + home:'M3 11l9-7 9 7M5 10v10h14V10M10 20v-6h4v6', + gift:'M4 11h16v10H4zM2 7h20v4H2zM12 7v14M12 7c-1.5-3-5-3-5-1s3 1 5 1c2 0 5 1 5-1s-3.5-2-5 1', + heart:'M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10z', + book:'M4 4h6a2 2 0 0 1 2 2v14a2 2 0 0 0-2-2H4zM20 4h-6a2 2 0 0 0-2 2v14a2 2 0 0 1 2-2h6z', + star:'M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z', +}; +const BUCKET_ICON_NAMES={shield:'Shield',plane:'Plane',laptop:'Laptop',wrench:'Wrench',home:'House',gift:'Gift',heart:'Heart',book:'Book',star:'Star'}; +const BUCKET_HUES=['accent','pink','sky','card','good','violet','teal','warn']; +const BUCKET_HUE_NAMES={accent:'Indigo',pink:'Pink',sky:'Blue',card:'Orange',good:'Green',violet:'Violet',teal:'Teal',warn:'Amber'}; +function guessBucketIcon(name) { + const n=(name||'').toLowerCase(); + if (/emergenc|rainy|safety|cushion/.test(n)) return 'shield'; + if (/trip|travel|vacation|holiday|flight/.test(n)) return 'plane'; + if (/laptop|computer|phone|tech|tablet/.test(n)) return 'laptop'; + if (/car|auto|repair|mainten/.test(n)) return 'wrench'; + if (/home|house|down payment|apartment|moving/.test(n)) return 'home'; + if (/gift|christmas|birthday|present/.test(n)) return 'gift'; + if (/wedding|health|medical|baby|dental/.test(n)) return 'heart'; + if (/school|tuition|college|course|book|education/.test(n)) return 'book'; + return 'star'; +} +function bucketIconKey(b) { return BUCKET_ICONS[b.icon]?b.icon:guessBucketIcon(b.name); } +function bucketHue(b, i) { return BUCKET_HUES.includes(b.hue)?b.hue:BUCKET_HUES[i%BUCKET_HUES.length]; } +function bucketIconSvg(key, size=20) { + return ``; +} +function addBucket(b) { State.buckets.push(b); lsSet('buckets',State.buckets); } +// Edit bucket i in the drawer, or add one (i < 0). function editBucket(i) { - const b=i>=0?State.buckets[i]:{name:'',goal:0,current:0,targetDate:'',color:'#6366f1',icon:'💰'}; - openDrawer(` -

${i>=0?'Edit':'Add'} Bucket

- -
-
-
-
- -
-
-
+ const b=i>=0?State.buckets[i]:{name:'',goal:'',current:0,targetDate:''}; + const icon=i>=0?bucketIconKey(b):'star', hue=i>=0?bucketHue(b,i):BUCKET_HUES[State.buckets.length%BUCKET_HUES.length]; + const linked=i<0?[]:State.transactions.filter(t=>{ const l=State.txOverrides[t.id]?.link; return l&&l.type==='bucket'&&l.idx===i; }).sort((x,y)=>y.date-x.date); + openDrawer(`
+ +
+ +
-
- - `); + +
Icon + ${Object.keys(BUCKET_ICONS).map(k=>``).join('')} +
+
Color + ${BUCKET_HUES.map(h=>``).join('')} +
+ ${i>=0?`

Linked transactions · ${linked.length}

+ ${linked.length?`
${linked.slice(0,20).map(t=>`
${dayjs(t.date).format('MMM D')}${escapeHtml(t.description)}${fmtSigned(t.amount)}
`).join('')}
` + :`

None yet. Open a transaction and use Link to → Bucket.

`}
`:''} +
`, + { title:i>=0?'Edit bucket':'New bucket', footer:_drawerFooter(i>=0,'bkSave','Save bucket','bkDelete') }); + $('#bkSave').onclick=()=>saveBucket(i); + _armTwoClick($('#bkDelete'),()=>deleteBucket(i)); } function saveBucket(i) { - const obj={name:$('#bkName').value.trim(),goal:parseFloat($('#bkGoal').value)||0,current:parseFloat($('#bkCur').value)||0,targetDate:$('#bkDate').value,color:$('#bkColor').value,icon:$('#bkIcon').value||'💰'}; - if (!obj.name){ alert('Name required.'); return; } + const name=$('#bkName').value.trim(); + if (!name) return _formError('Give the bucket a name.', $('#bkName')); + const prev=i>=0?State.buckets[i]:{}; + const obj={ ...prev, name, + goal:Math.max(0,parseFloat($('#bkGoal').value)||0), + current:Math.max(0,parseFloat($('#bkCur').value)||0), + targetDate:$('#bkDate').value||'', + icon:($('input[name="bkIcon"]:checked')||{}).value||guessBucketIcon(name), + hue:($('input[name="bkHue"]:checked')||{}).value||BUCKET_HUES[0] }; if (i>=0) State.buckets[i]=obj; else State.buckets.push(obj); lsSet('buckets',State.buckets); closeDrawer(); renderActive(); } -function deleteBucket(i){ if(!confirm('Delete this bucket?')) return; State.buckets.splice(i,1); lsSet('buckets',State.buckets); renderActive(); } +// No confirm() here: the edit drawer's Delete button asks for a second click. +function deleteBucket(i){ State.buckets.splice(i,1); lsSet('buckets',State.buckets); renderActive(); } /* ---------- DEBT HELPERS ---------- */ -function editDebt(i) { - const d=i>=0?State.debts[i]:{name:'',type:'Credit Card',balance:0,apr:0,minPayment:0,limit:0,dueDay:1}; - openDrawer(` -

${i>=0?'Edit':'Add'} Debt

- - - -
-
-
+// State.debts entries: { name, type, balance, apr, minPayment, limit, dueDay, account? }. +// account (v1.15.0): a credit card account from your CSVs. The balance and credit limit +// then come from that account (debtBalance(), debtLimit() in aggregation.js); `balance` +// keeps the value it had when last saved, used if the account is gone. +const DEBT_TYPES=['Credit Card','Personal Loan','Student Loan','Auto Loan','Mortgage','Other']; +const DEBT_TYPE_LABEL={'Credit Card':'Credit card','Personal Loan':'Personal loan','Student Loan':'Student loan','Auto Loan':'Auto loan','Mortgage':'Mortgage','Other':'Other'}; +// Card accounts a debt can take its balance from: those no other debt uses yet. +function debtCardChoices(current) { + const used=new Set((State.debts||[]).map(d=>d.account).filter(Boolean)); + return orderedAccounts().filter(a=>a.kind==='credit_card'&&(a.id===current||!used.has(a.id))); +} +// Edit debt i in the drawer, or add one (i < 0); `account` links a new one to a card. +function editDebt(i, account) { + const d=i>=0?State.debts[i]:{name:account?acctName(account):'',type:'Credit Card',balance:'',apr:'',minPayment:'',limit:'',dueDay:'',account:account||''}; + const acct=debtLinked(d)?d.account:''; + const cards=debtCardChoices(acct); + const limit=acct?(State.manualBalances[acct+'_limit']??''):(d.limit||''); + const num=v=>v===''||v==null?'':escapeHtml(String(Number(v)||0)); + openDrawer(`
+ ${cards.length?``:''} + +
+ +
-
-
-
+

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

+
+ +
- -
- - `); +
+ + +
+
`, + { title:i>=0?'Edit debt':'Add debt', footer:_drawerFooter(i>=0,'dtSave','Save debt','dtDelete') }); + const sel=$('#dtAcct'); + if (sel) sel.onchange=()=>{ + const id=sel.value, bal=$('#dtBal'), name=$('#dtName'); + bal.readOnly=!!id; + if (id) bal.setAttribute('aria-describedby','dtBalNote'); else bal.removeAttribute('aria-describedby'); + $('#dtBalNote').hidden=!id; + if (id) { + bal.value=debtBalance({account:id}).toFixed(2); + $('#dtType').value='Credit Card'; + if (!name.value.trim()||cards.some(a=>acctName(a.id)===name.value)) name.value=acctName(id); + const l=State.manualBalances[id+'_limit']; $('#dtLim').value=l==null||l===''?'':l; + } + }; + $('#dtSave').onclick=()=>saveDebt(i); + _armTwoClick($('#dtDelete'),()=>deleteDebt(i)); } function saveDebt(i) { - const obj={name:$('#dtName').value.trim(),type:$('#dtType').value,balance:parseFloat($('#dtBal').value)||0,apr:parseFloat($('#dtApr').value)||0,minPayment:parseFloat($('#dtMin').value)||0,limit:parseFloat($('#dtLim').value)||0,dueDay:parseInt($('#dtDue').value)||1}; - if (!obj.name){ alert('Name required.'); return; } + const name=$('#dtName').value.trim(); + if (!name) return _formError('Give the debt a name.', $('#dtName')); + const account=$('#dtAcct')?$('#dtAcct').value:''; + const prev=i>=0?State.debts[i]:{}; + const limRaw=$('#dtLim').value.trim(); + const obj={ ...prev, name, type:$('#dtType').value, + apr:Math.max(0,parseFloat($('#dtApr').value)||0), + minPayment:Math.max(0,parseFloat($('#dtMin').value)||0), + dueDay:Math.min(31,Math.max(1,parseInt($('#dtDue').value,10)||1)) }; + if (account) { + obj.account=account; + obj.balance=Math.round(debtBalance({account})*100)/100; + // A linked card's limit is the account's credit limit, shared with the Overview and Settings. + State.manualBalances[account+'_limit']=limRaw===''?'':Math.max(0,parseFloat(limRaw)||0); + lsSet('manualBalances',State.manualBalances); + } else { + delete obj.account; + obj.balance=Math.max(0,parseFloat($('#dtBal').value)||0); + obj.limit=Math.max(0,parseFloat(limRaw)||0); + } if (i>=0) State.debts[i]=obj; else State.debts.push(obj); lsSet('debts',State.debts); closeDrawer(); renderActive(); } -function deleteDebt(i){ if(!confirm('Delete this debt?')) return; State.debts.splice(i,1); lsSet('debts',State.debts); renderActive(); } +// No confirm() here: the edit drawer's Delete button asks for a second click. +function deleteDebt(i){ State.debts.splice(i,1); lsSet('debts',State.debts); renderActive(); } +// Older payoff simulation (before v1.15.0), kept unchanged for compatibility: pays every +// minimum, then `extra` goes to the first debt in the given order that still has a +// balance. A paid-off debt's minimum is not moved on. The Debt screen uses payoffPlan(). function simulatePayoff(debtsIn, extra) { const debts=debtsIn.map(d=>({name:d.name,balance:d.balance||0,apr:(d.apr||0)/100/12,minPayment:d.minPayment||0})); let month=0, totalInterest=0; @@ -565,7 +724,15 @@ function simulatePayoff(debtsIn, extra) { } return {months:month,totalInterest,rows}; } -function setPayoffStrategy(s){ State.payoffStrategy=s; renderActive(); } +// The Debt screen's payoff plan (State.debtPlan, saved): strategy and extra per month. +function setPayoffStrategy(s) { + State.debtPlan={ ...(State.debtPlan||{}), strategy:['avalanche','snowball','minimum'].includes(s)?s:'avalanche' }; + lsSet('debtPlan',State.debtPlan); +} +function setPayoffExtra(v) { + State.debtPlan={ ...(State.debtPlan||{}), extra:Math.max(0,Math.round(parseFloat(v)||0)) }; + lsSet('debtPlan',State.debtPlan); +} /* ---------- EXPORT / IMPORT ---------- */ function exportAllData() { @@ -576,6 +743,7 @@ function exportAllData() { categoryRules:State.categoryRules, categories:State.categories, aiHistory:State.aiHistory, scenarios:State.scenarios, recurringConfirmed:State.recurringConfirmed, investAlloc:State.investAlloc, + debtPlan:State.debtPlan, }; downloadFile(`finlens-export-${dayjs().format('YYYYMMDD')}.json`, JSON.stringify(data,null,2),'application/json'); } @@ -587,7 +755,7 @@ function importJsonFile(ev) { const d=JSON.parse(e.target.result); // Exports from before v1.12.0 use the old account codes (migrate.js) IdMigration.migrateState(d); - ['budgets','buckets','debts','bills','txOverrides','manualBalances','categoryRules','categories','aiHistory','scenarios','recurringConfirmed','investAlloc'].forEach(k=>{ + ['budgets','buckets','debts','bills','txOverrides','manualBalances','categoryRules','categories','aiHistory','scenarios','recurringConfirmed','investAlloc','debtPlan'].forEach(k=>{ if (d[k]!==undefined){ State[k]=d[k]; lsSet(k,d[k]); } }); if (IdMigration.adoptOverrides(State.transactions).size) lsSet('txOverrides',State.txOverrides); diff --git a/js/views-ai.js b/js/views-ai.js index 6d360aa..04e3a5f 100644 --- a/js/views-ai.js +++ b/js/views-ai.js @@ -66,7 +66,7 @@ function buildFinancialSummary() { incomeCats.forEach(c=>lines.push(` - ${c.category}: ${fmt(c.amount)}`)); lines.push(''); lines.push('Recent monthly trend:'); recent3.forEach(m=>lines.push(` - ${m.month}${partialMonthNote(m.month, State.transactions)}: income ${fmt(m.income)}, expense ${fmt(m.expense)}, net ${fmt(m.income-m.expense)}`)); - if (State.debts&&State.debts.length){ lines.push(''); lines.push('Debts:'); State.debts.forEach(d=>lines.push(` - ${d.name}: balance ${fmt(d.balance)}, APR ${(d.apr||0).toFixed(2)}%, min pmt ${fmt(d.minPayment||0)}`)); } + if (State.debts&&State.debts.length){ lines.push(''); lines.push('Debts:'); State.debts.forEach(d=>lines.push(` - ${d.name}: balance ${fmt(debtBalance(d))}, APR ${(d.apr||0).toFixed(2)}%, min pmt ${fmt(d.minPayment||0)}`)); } if (recurring.length){ lines.push(''); lines.push('Subscriptions:'); recurring.forEach(r=>lines.push(` - ${r.merchant}: ${fmt(r.avg)} ${r.freq}`)); } return lines.join('\n'); } diff --git a/js/views-cleanup.js b/js/views-cleanup.js index 73166f6..59bd61e 100644 --- a/js/views-cleanup.js +++ b/js/views-cleanup.js @@ -15,17 +15,26 @@ const DataCleanup = { lastMessage: null, // { kind: 'good'|'warn'|'bad', text } shown once at the top of the tab - // Plans and history the user created: [State key (= lsSet key), label] + // Plans and history the user created: [State key (= lsSet key), label, empty value (default [])] PLAN_ITEMS: [ - ['budgets', 'Budgets'], - ['bills', 'Bills'], - ['buckets', 'Savings buckets'], - ['debts', 'Debts'], - ['aiHistory', 'AI history'], + ['budgets', 'Budgets'], + ['bills', 'Bills'], + ['buckets', 'Savings buckets'], + ['debts', 'Debts'], + ['scenarios', 'Forecast scenarios'], + ['investAlloc', 'Investment mix', {}], + ['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.']], + debts: [['debtPlan', 'debtPlan', { strategy: 'avalanche', extra: 0 }, 'Also resets the payoff plan (strategy and extra payment).']], + }, + // How many entries a plan item holds (the investment mix: tickers with a share above 0) + _planCount(key) { + const v = State[key]; + if (Array.isArray(v)) return v.length; + return Object.values(v || {}).filter(x => Number(x) > 0).length; }, /* ---------- actions ---------- */ @@ -66,9 +75,10 @@ const DataCleanup = { async clearPlan(key) { const item = this.PLAN_ITEMS.find(i => i[0] === key); if (!item) return; - State[key] = []; - lsSet(key, []); - (this.PLAN_ALSO[key] || []).forEach(([sk, lk, empty]) => { State[sk] = empty; lsSet(lk, empty); }); + const fresh = (v) => JSON.parse(JSON.stringify(v)); + State[key] = fresh(item[2] !== undefined ? item[2] : []); + lsSet(key, State[key]); + (this.PLAN_ALSO[key] || []).forEach(([sk, lk, empty]) => { State[sk] = fresh(empty); lsSet(lk, State[sk]); }); await this._finish(`${item[1]} cleared.`); }, @@ -220,9 +230,10 @@ registerView('data-cleanup', 'Data & Reset', (root) => {

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

${DataCleanup.PLAN_ITEMS.map(([key, label]) => { - const len = (State[key] || []).length; + const len = DataCleanup._planCount(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)); + const count = key === 'aiHistory' ? plural(len, 'entry', 'entries') : key === 'investAlloc' ? plural(len, 'fund', 'funds') : n(len); + return row(label, count, also, btn('clearPlan', 'Clear', key)); }).join('')}
`; root.appendChild(plans); @@ -246,7 +257,7 @@ registerView('data-cleanup', 'Data & Reset', (root) => { reset.style.borderColor = 'var(--red)'; reset.innerHTML = `

Start over from scratch

-

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

+

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

${folder ? `
Backup file in “${escapeHtml(folder)}”
diff --git a/js/views-db.js b/js/views-db.js index 536828b..6ec69ac 100644 --- a/js/views-db.js +++ b/js/views-db.js @@ -121,7 +121,7 @@ registerView('db-schema', 'DB Schema', (root) => { { name: 'key', type: 'string', key: 'PK', note: 'lsSet() key' }, { name: 'value', type: 'any', key: '', note: 'JSON-serializable' }, ], - note: 'budgets · bills · debts · buckets · categories · apiKey · aiHistory · scenarios · investAlloc · manualBalances · txOverrides · accountOrder · accountLabels · categoryRules · txRules · transferKeywords · customSchemas · fileAssignments · theme', + note: 'budgets · bills · debts · buckets · categories · apiKey · aiHistory · scenarios · investAlloc · debtPlan · manualBalances · txOverrides · accountOrder · accountLabels · categoryRules · txRules · transferKeywords · customSchemas · fileAssignments · theme', }, ]; diff --git a/js/views-forecast.js b/js/views-forecast.js index 778ca38..549986d 100644 --- a/js/views-forecast.js +++ b/js/views-forecast.js @@ -1,224 +1,133 @@ /* ================================================================ FINLENS — views-forecast.js - Forecast Savings (renamed from Forecast Simulator) + Forecast (Clarity, v1.15.0): sub-tabs Savings and Investments. + The Investments tab is drawn by _renderForecastInvest() in views-invest.js. + Projections use growthByYear() in aggregation.js. ================================================================ */ +let forecastTab='savings'; // 'savings' | 'investments' +// Savings inputs live in memory: they start from your accounts on every page load. Saved +// scenarios (State.scenarios) keep a copy of them. let forecastInputs=null; -let forecastTab='savings'; // 'savings' | 'investments' +const SCENARIO_MAX=10; function getForecastDefaults() { - const balances=currentBalances(); - const months=byMonth(State.transactions); - const recent3=months.slice(-3); - const avgIncome=recent3.length?recent3.reduce((s,m)=>s+m.income,0)/recent3.length:3000; - const avgExpense=recent3.length?recent3.reduce((s,m)=>s+m.expense,0)/recent3.length:2000; - const checking=Object.values(State.accounts).find(a=>a.kind==='bank_checking'); - const savings=Object.values(State.accounts).find(a=>a.kind==='bank_savings'); - const debt=Object.values(State.accounts).filter(a=>a.kind==='credit_card').reduce((s,a)=>s+Math.abs(balances[a.id]||0),0); - return { - checkingStart: checking?(balances[checking.id]||0):1000, - savingsStart: savings?(balances[savings.id]||0):0, - debtStart: debt, - monthlyIncome: avgIncome, - monthlyExpense: avgExpense, - transferToSavings: 0, - debtPaymentExtra: 0, - debtAPR: 22, - horizon: 12, - events: [], - }; + const bal=currentBalances(), accts=orderedAccounts(); + const sumKind=(k)=>accts.filter(a=>a.kind===k).reduce((s,a)=>s+(Number(bal[a.id])||0),0); + // Today's debt: every debt on the Debt screen, plus card balances no debt there stands for. + const linked=new Set((State.debts||[]).filter(debtLinked).map(d=>d.account)); + const cards=accts.filter(a=>a.kind==='credit_card'&&!linked.has(a.id)).reduce((s,a)=>s+Math.abs(Number(bal[a.id])||0),0); + const debt=cards+(State.debts||[]).reduce((s,d)=>s+debtBalance(d),0); + const pace=savingsPace(); + return { checking:Math.round(sumKind('bank_checking')), savings:Math.round(sumKind('bank_savings')), debt:Math.round(debt), + monthly:pace&&pace.perMonth>0?Math.round(pace.perMonth/10)*10:0, rate:4, tax:22, years:10 }; } - -function _renderForecastSavings(root){ - if (!forecastInputs) forecastInputs=getForecastDefaults(); - const f=forecastInputs; - - const inputCard=document.createElement('div'); inputCard.className='card'; - inputCard.innerHTML=` -

- Inputs - -

-
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-

One-Off Events

-
- -
-
- - - -
`; - root.appendChild(inputCard); - - renderForecastEvents(); - - const outCard=document.createElement('div'); outCard.className='card'; outCard.id='fcOut'; - outCard.innerHTML=` -

Projection

-
-
`; - root.appendChild(outCard); - - // Wire inputs - ['fcChecking','fcSavings','fcDebt','fcInc','fcExp','fcTransfer','fcDebtExtra','fcApr'].forEach(id=>{ - const el=$('#'+id); - if (el) el.oninput=()=>{ - f.checkingStart=parseFloat($('#fcChecking').value)||0; - f.savingsStart=parseFloat($('#fcSavings').value)||0; - f.debtStart=parseFloat($('#fcDebt').value)||0; - f.monthlyIncome=parseFloat($('#fcInc').value)||0; - f.monthlyExpense=parseFloat($('#fcExp').value)||0; - f.transferToSavings=parseFloat($('#fcTransfer').value)||0; - f.debtPaymentExtra=parseFloat($('#fcDebtExtra').value)||0; - f.debtAPR=parseFloat($('#fcApr').value)||0; - runForecast(); - }; - }); - $('#fcHor').oninput=()=>{ f.horizon=parseInt($('#fcHor').value); $('#fcHorVal').textContent=f.horizon; runForecast(); }; - setTimeout(runForecast,0); +// After-tax yearly rate: the APY less the tax on its interest. +const savingsAfterTax=(f)=>(Number(f.rate)||0)*(1-(Number(f.tax)||0)/100); +function savingsProjection(f) { + return growthByYear((Number(f.checking)||0)+(Number(f.savings)||0), f.monthly, savingsAfterTax(f), f.years); +} +// A saved scenario's inputs. Scenarios saved before v1.15.0 held the old simulator's +// inputs (income, expenses, a transfer to savings, debt payments, a horizon in months): +// they become their monthly net (income − expenses − extra debt payment), no interest, +// and the horizon in whole years. +function scenarioInputs(s) { + const i=s.inputs||{}; + if (i.checking!=null||s.kind==='savings') return { checking:+i.checking||0, savings:+i.savings||0, debt:+i.debt||0, monthly:+i.monthly||0, rate:+i.rate||0, tax:+i.tax||0, years:Math.min(30,Math.max(1,+i.years||1)) }; + return { checking:+i.checkingStart||0, savings:+i.savingsStart||0, debt:+i.debtStart||0, + monthly:(+i.monthlyIncome||0)-(+i.monthlyExpense||0)-(+i.debtPaymentExtra||0), rate:0, tax:0, + years:Math.min(30,Math.max(1,Math.round((+i.horizon||12)/12))), old:true }; } registerView('forecast','Forecast',(root)=>{ - // Sub-tab bar: Savings · Investments - const tabBar=document.createElement('div'); - tabBar.style.cssText='display:flex;gap:6px;margin-bottom:12px'; - tabBar.innerHTML=` - - `; - root.appendChild(tabBar); - tabBar.querySelectorAll('[data-tab]').forEach(btn=>btn.onclick=()=>{forecastTab=btn.dataset.tab;renderActive();}); - - if (forecastTab==='savings') _renderForecastSavings(root); - else _renderForecastInvest(root); + pageActions(root,'Projections from the numbers you choose. Returns are assumptions, not promises.',''); + const tabs=[['savings','Savings','fcTabSav'],['investments','Investments','fcTabInv']]; + appendHtml(root,`
${tabs.map(([k,l,id])=> + ``).join('')}
`); + const pick=(k)=>{ forecastTab=k; renderActive(); const t=$(`[role="tab"][data-tab="${k}"]`); if (t) t.focus(); }; + $$('[role="tab"]',root).forEach((b,i,all)=>{ + b.onclick=()=>pick(b.dataset.tab); + b.onkeydown=(e)=>{ + const n=e.key==='ArrowRight'?i+1:e.key==='ArrowLeft'?i-1:e.key==='Home'?0:e.key==='End'?all.length-1:null; + if (n==null) return; + e.preventDefault(); pick(all[(n+all.length)%all.length].dataset.tab); + }; + }); + const panel=document.createElement('div'); + panel.id='fcPanel'; panel.setAttribute('role','tabpanel'); + panel.setAttribute('aria-labelledby',forecastTab==='savings'?'fcTabSav':'fcTabInv'); + root.appendChild(panel); + if (forecastTab==='investments') _renderForecastInvest(panel); + else _renderForecastSavings(panel); }); -function renderForecastEvents() { +function _renderForecastSavings(panel) { + if (!forecastInputs) forecastInputs=getForecastDefaults(); const f=forecastInputs; - const el=$('#fcEvents'); if (!el) return; - el.innerHTML=(f.events||[]).map((e,i)=>` -
- - - - -
`).join(''); + const inp=(k,label,step)=>``; + panel.insertAdjacentHTML('beforeend',`
+
+

Your numbers

+

Starting balances come from your accounts. Change any of them.

+
+ ${inp('checking','Checking ($)',1)}${inp('savings','Savings ($)',1)}${inp('debt','Debt to subtract ($)',1)}${inp('monthly','Saved each month ($)',50)} +
${inp('rate','Interest (APY %)',0.1)}${inp('tax','Tax on interest (%)',1)}
+ +
+
+
+
+
+
`); + const draw=()=>{ $('#fcOut').innerHTML=savingsForecastHtml(f); }; + draw(); drawScenarios(); + $$('[data-fc]',panel).forEach(el=>el.addEventListener('input',()=>{ + const k=el.dataset.fc, v=parseFloat(el.value); + f[k]=k==='years'?Math.min(30,Math.max(1,Math.round(v)||1)):(isFinite(v)?v:0); + if (k==='years') $('#fcYearsVal').textContent=f.years; + draw(); + })); + $('#fcReset').onclick=()=>{ forecastInputs=getForecastDefaults(); renderActive(); const b=$('#fcReset'); if (b) b.focus(); }; } -function addForecastEvent() { forecastInputs.events.push({label:'',month:1,amount:0}); renderActive(); } - -function runForecast() { - const chartEl=$('#fcChart'); - if (!chartEl) return; - const f=forecastInputs; - const months=[]; - let chk=f.checkingStart, sav=f.savingsStart, debt=f.debtStart; - const apr=f.debtAPR/100/12; - for (let mo=0;mo0) debt+=debt*apr; - chk+=f.monthlyIncome-f.monthlyExpense; - chk-=f.transferToSavings; sav+=f.transferToSavings; - const debtPay=Math.min(debt,f.debtPaymentExtra+(f.monthlyIncome>0?Math.min(50,debt*0.02):0)); - chk-=debtPay; debt=Math.max(0,debt-debtPay); - (f.events||[]).filter(e=>e.month===mo+1).forEach(e=>{ chk+=e.amount; }); - months.push({ - month:mo+1, - label:dayjs(new Date(new Date().getFullYear(),new Date().getMonth()+mo+1,1)).format('MMM YY'), - checking:chk, savings:sav, debt - }); - } - - if (window._fcChart) window._fcChart.destroy(); - window._fcChart=new Chart(chartEl,{ - type:'line', - data:{ - labels:months.map(m=>m.label), - datasets:[ - {label:'Checking',data:months.map(m=>m.checking),borderColor:chartColor('--chart-in'),backgroundColor:chartColor('--chart-in',.1),fill:true,tension:.25,borderWidth:2,pointRadius:2}, - {label:'Savings',data:months.map(m=>m.savings),borderColor:chartColor('--chart-save'),backgroundColor:chartColor('--chart-save',.1),fill:true,tension:.25,borderWidth:2,pointRadius:2}, - {label:'Debt',data:months.map(m=>-m.debt),borderColor:chartColor('--chart-debt'),backgroundColor:chartColor('--chart-debt',.1),fill:true,tension:.25,borderWidth:2,pointRadius:2}, - ] - }, - options:{ - responsive:true, - maintainAspectRatio:false, - plugins:{legend:{position:'bottom',labels:{boxWidth:10,font:{size:11}}}}, - scales:{ - y:{ - ticks:{callback:v=>{ const a=Math.abs(v); return (v<0?'-':'')+( a>=1000?'$'+(a/1000).toFixed(0)+'K':'$'+a ); }}, - } - } - } - }); - - const tableDiv=$('#fcTable'); - if (tableDiv) { - tableDiv.innerHTML=` -

Month-by-Month

- - ${months.map(m=>{ - const net=m.checking+m.savings-m.debt; - return ` - - - - - - `; - }).join('')}
MonthCheckingSavingsDebtNet
${m.label}${fmt(m.checking)}${fmt(m.savings)}${fmt(m.debt)}${fmt(net)}
`; - } +function savingsForecastHtml(f) { + const rows=savingsProjection(f), last=rows[rows.length-1]; + const max=Math.max(1,...rows.map(r=>Math.max(r.balance,r.putIn))); + const at=savingsAfterTax(f); + return `

In ${plural(f.years,'year')}

+
Projected savings${fmtMinus0(last.balance)}
+
After today's debt${fmtMinus0(last.balance-(Number(f.debt)||0))}
+
Interest earned${fmtMinus0(last.balance-last.putIn)}
+
What you put inInterest after tax
+ +
Year 1Year ${f.years}
+

Interest compounds monthly from the APY after tax (${pctNum(Number(f.rate)||0)}% less ${pctNum(Number(f.tax)||0)}% tax is ${at.toFixed(2)}% a year). What you save each month is added at the end of the month.

`; } -function saveScenario() { - const name=prompt('Name this scenario:'); - if (!name) return; - State.scenarios=State.scenarios||[]; - State.scenarios.push({name,inputs:JSON.parse(JSON.stringify(forecastInputs))}); - lsSet('scenarios',State.scenarios); - renderActive(); -} -function loadScenario(idx) { - if (!idx) return; - forecastInputs=JSON.parse(JSON.stringify(State.scenarios[idx].inputs)); - renderActive(); +function drawScenarios() { + const box=$('#fcScen'); if (!box) return; + const list=State.scenarios||[]; + box.innerHTML=`

Saved scenarios · ${list.length} of ${SCENARIO_MAX}

+
+ ${list.length?`
${list.map((s,i)=>{ + const x=scenarioInputs(s), rows=savingsProjection(x), fin=rows[rows.length-1].balance; + const detail=`${fmt0(x.monthly)}/mo · ${x.years} yrs · ${(Number(x.rate)||0).toFixed(1)}%${x.old?' · from an earlier version':''}`; + const n=escapeHtml(s.name||`Scenario ${i+1}`); + return `
+ ${detail}${fmtMinus0(fin)} +
`; }).join('')}
` + :'

No saved scenarios yet. Save this one to compare it with others later.

'}`; + $('#fcSave').onclick=()=>{ + const list=State.scenarios=State.scenarios||[]; + if (list.length>=SCENARIO_MAX) return; + const names=new Set(list.map(s=>s.name)); + let n=list.length+1; while (names.has(`Scenario ${n}`)) n++; + list.push({ name:`Scenario ${n}`, kind:'savings', inputs:{ ...forecastInputs } }); + lsSet('scenarios',list); + drawScenarios(); const b=$('#fcSave'); if (b&&!b.disabled) b.focus(); else { const ls=$$('[data-sc-load]'); if (ls.length) ls[ls.length-1].focus(); } + }; + $$('[data-sc-load]',box).forEach(b=>b.onclick=()=>{ const x=scenarioInputs(State.scenarios[+b.dataset.scLoad]); delete x.old; forecastInputs=x; renderActive(); const f=$('[data-fc="checking"]'); if (f) f.focus(); }); + $$('[data-sc-del]',box).forEach(b=>b.onclick=()=>{ State.scenarios.splice(+b.dataset.scDel,1); lsSet('scenarios',State.scenarios); drawScenarios(); const s=$('#fcSave'); if (s) s.focus(); }); } diff --git a/js/views-invest.js b/js/views-invest.js index f297f74..f85fef5 100644 --- a/js/views-invest.js +++ b/js/views-invest.js @@ -1,340 +1,176 @@ /* ================================================================ FINLENS — views-invest.js - Investing Ideas + Forecast Investments (new tab) + Investing ideas (Clarity, v1.15.0): a portfolio mix you sketch from + reference lists, saved in State.investAlloc. Also the Forecast → + Investments tab (_renderForecastInvest), drawn by views-forecast.js. + Reference lists for learning, not financial advice. ================================================================ */ /* =================== INVESTING IDEAS =================== */ -const ETF_LIST = [ - {ticker:'VTI', name:'Vanguard Total Stock Market', cat:'US Equities', risk:'Medium', sugPct:35, rationale:'Broad exposure to the entire US stock market in one fund.'}, - {ticker:'VXUS', name:'Vanguard Total International', cat:'Intl Equities',risk:'Medium', sugPct:15, rationale:'Global diversification outside the US.'}, - {ticker:'BND', name:'Vanguard Total Bond Market', cat:'US Bonds', risk:'Low', sugPct:20, rationale:'Income and stability — counter-balance to stocks.'}, - {ticker:'VNQ', name:'Vanguard Real Estate', cat:'REITs', risk:'Medium', sugPct:5, rationale:'Real estate exposure without owning property.'}, - {ticker:'QQQ', name:'Invesco Nasdaq-100', cat:'Tech-heavy', risk:'High', sugPct:10, rationale:'Concentrated bet on large US tech.'}, - {ticker:'SCHD', name:'Schwab US Dividend Equity', cat:'Dividend', risk:'Medium', sugPct:10, rationale:'High-quality dividend payers — passive income tilt.'}, - {ticker:'VTIP', name:'Vanguard Short-Term TIPS', cat:'Inflation', risk:'Low', sugPct:5, rationale:'Inflation protection for bond portion.'}, +// type: s = stocks, b = bonds, r = real estate. preset: the balanced preset's share (%). +const INVEST_FUNDS=[ + {ticker:'VTI', name:'US total stock market', cls:'US stocks', type:'s', risk:'Higher', preset:40, hue:'accent'}, + {ticker:'VXUS', name:'Stocks outside the US', cls:'International stocks', type:'s', risk:'Higher', preset:20, hue:'teal'}, + {ticker:'BND', name:'US investment-grade bonds', cls:'Bonds', type:'b', risk:'Lower', preset:20, hue:'warn'}, + {ticker:'SCHD', name:'US dividend-paying companies', cls:'US stocks', type:'s', risk:'Medium', preset:10, hue:'pink'}, + {ticker:'VNQ', name:'US real estate (REITs)', cls:'Real estate', type:'r', risk:'Higher', preset:5, hue:'sky'}, + {ticker:'VTIP', name:'Short-term inflation-protected bonds', cls:'Bonds', type:'b', risk:'Lower', preset:5, hue:'good'}, + {ticker:'VOO', name:'S&P 500 companies', cls:'US stocks', type:'s', risk:'Higher', preset:0, hue:'violet'}, + {ticker:'QQQ', name:'Nasdaq-100 companies', cls:'US stocks', type:'s', risk:'Higher', preset:0, hue:'card'}, + {ticker:'AVUV', name:'US small-cap value companies', cls:'US stocks', type:'s', risk:'Higher', preset:0, hue:'neutral'}, ]; -const STOCK_LIST = [ - {ticker:'AAPL', name:'Apple', cat:'Mega-cap tech', risk:'Medium', sugPct:10, rationale:'Massive cash generation and ecosystem moat.'}, - {ticker:'MSFT', name:'Microsoft', cat:'Mega-cap tech', risk:'Medium', sugPct:10, rationale:'Cloud + enterprise software durable growth.'}, - {ticker:'GOOGL', name:'Alphabet', cat:'Mega-cap tech', risk:'Medium', sugPct:8, rationale:'Search dominance plus AI/cloud optionality.'}, - {ticker:'AMZN', name:'Amazon', cat:'Consumer + Cloud', risk:'Medium', sugPct:8, rationale:'Retail scale + AWS profit engine.'}, - {ticker:'BRK.B', name:'Berkshire Hathaway', cat:'Conglomerate', risk:'Low-Med', sugPct:10, rationale:'Diversified holdings, value-oriented, Buffett-managed.'}, - {ticker:'JNJ', name:'Johnson & Johnson', cat:'Healthcare', risk:'Low', sugPct:8, rationale:'Defensive dividend-payer with healthcare moat.'}, - {ticker:'PG', name:'Procter & Gamble', cat:'Consumer Staples', risk:'Low', sugPct:8, rationale:'Recession-resistant brand portfolio.'}, - {ticker:'NVDA', name:'NVIDIA', cat:'AI / Semiconductors',risk:'High', sugPct:10, rationale:'Dominant position in AI chips and data center compute.'}, +const INVEST_STOCKS=[ + {ticker:'AAPL', name:'Apple', sector:'Technology'}, + {ticker:'MSFT', name:'Microsoft', sector:'Technology'}, + {ticker:'BRK.B', name:'Berkshire Hathaway', sector:'Financials'}, + {ticker:'JNJ', name:'Johnson & Johnson', sector:'Health care'}, + {ticker:'PG', name:'Procter & Gamble', sector:'Consumer staples'}, + {ticker:'COST', name:'Costco', sector:'Consumer staples'}, ]; +const RISK_PILL={Lower:'good',Medium:'warn',Higher:'bad'}; +const pctNum=(n)=>String(Math.round(n*10)/10); + +// The mix from State.investAlloc: the funds above, then any other ticker with a share +// (stocks given a % before v1.15.0, when that list had inputs too), counted as stocks. +function investMix() { + const a=State.investAlloc||{}; + const val=(t)=>Math.max(0,Number(a[t])||0); + const known=new Set(INVEST_FUNDS.map(f=>f.ticker)); + const rows=INVEST_FUNDS.filter(f=>val(f.ticker)>0).map(f=>({ ticker:f.ticker, pct:val(f.ticker), hue:f.hue, type:f.type })) + .concat(Object.keys(a).filter(t=>!known.has(t)&&val(t)>0).map(t=>({ ticker:t, pct:val(t), hue:'neutral', type:'s' }))); + const total=rows.reduce((s,r)=>s+r.pct,0); + const sum=(k)=>rows.filter(r=>r.type===k).reduce((s,r)=>s+r.pct,0); + return { rows, total, stocks:sum('s'), bonds:sum('b'), reits:sum('r') }; +} +function investMixHtml() { + const m=investMix(), ok=Math.abs(m.total-100)<0.001; + const aria=m.rows.length?m.rows.map(r=>`${r.ticker} ${pctNum(r.pct)}%`).join(', '):'Nothing assigned yet'; + return `

My mix

${ok?'100% assigned':`${pctNum(m.total)}% of 100%`}
+ + ${m.rows.length?`
${m.rows.map(r=>`
${escapeHtml(r.ticker)}${pctNum(r.pct)}%
`).join('')}
` + :'

Nothing assigned yet. Type a % next to a fund, or use the balanced preset.

'} +
${pctNum(m.stocks)}%Stocks
${pctNum(m.bonds)}%Bonds
${pctNum(m.reits)}%Real estate
+
Project this mix in Forecast →`; +} -// Strong recommended portfolio -const RECOMMENDED_PORTFOLIO = [ - {ticker:'VTI', pct:40, reason:'Core US equity engine — captures entire market growth'}, - {ticker:'VXUS', pct:20, reason:'International diversification reduces single-market risk'}, - {ticker:'BND', pct:20, reason:'Bond cushion reduces volatility, generates income'}, - {ticker:'SCHD', pct:10, reason:'Dividend reinvestment compounds returns over time'}, - {ticker:'VNQ', pct:5, reason:'Real estate exposure acts as inflation hedge'}, - {ticker:'VTIP', pct:5, reason:'Short-term TIPS protect against unexpected inflation'}, -]; - -registerView('investments','Investments',(root)=>{ - const disc=document.createElement('div'); - disc.className='insight warn'; - disc.innerHTML=`⚠️ Educational only — not financial advice. Consult a financial advisor before investing. All investments carry risk.`; - root.appendChild(disc); - - // Investable surplus - const months=byMonth(State.transactions); - const recent3=months.slice(-3); - const avgIncome=recent3.length?recent3.reduce((s,m)=>s+m.income,0)/recent3.length:0; - const avgExpense=recent3.length?recent3.reduce((s,m)=>s+m.expense,0)/recent3.length:0; - const debtPmts=(State.debts||[]).reduce((s,d)=>s+(d.minPayment||0),0); - const surplus=Math.max(0,avgIncome-avgExpense-debtPmts); - const balances=currentBalances(); - const totalCash=Object.values(State.accounts).filter(a=>a.kind==='bank_checking'||a.kind==='bank_savings').reduce((s,a)=>s+(balances[a.id]||0),0); - const monthsSaved=avgExpense>0?totalCash/avgExpense:0; - const emergencyTarget=avgExpense*3; - - const m=document.createElement('div'); m.className='grid grid-3'; - m.innerHTML=` -

Avg Monthly Surplus

${fmt(surplus)}
Income − Spend − Min debt pmts
-

Emergency Fund

${monthsSaved.toFixed(1)} mo
Target: 3 months = ${fmt(emergencyTarget)}
-

Investable Cash

${fmt(Math.max(0,totalCash-emergencyTarget))}
After emergency buffer
`; - root.appendChild(m); - - // Allocation suggestion - const allocCard=document.createElement('div'); allocCard.className='card'; - let allocRows; - if (surplus<=0) { - allocRows=`

No monthly surplus detected — focus on reducing expenses or increasing income before investing.

`; - } else if (monthsSaved<3) { - allocRows=`
First: build emergency fund to ${fmt(emergencyTarget)} (${fmt(Math.max(0,emergencyTarget-totalCash))} more needed).
-

Suggested split of ${fmt(surplus)}/mo while building emergency fund:

- - -
BucketAllocationWhy
Bank Savings / HYSA${fmt(surplus*0.7)}Emergency fund priority
401(k) up to employer match${fmt(surplus*0.3)}Free money — never leave match on the table
`; - } else { - const a401k=Math.min(surplus*0.4,1000); - const aETF=(surplus-a401k)*0.7; - const aSavings=(surplus-a401k)*0.3; - allocRows=`

Suggested monthly split of ${fmt(surplus)} surplus:

- - - - - -
BucketAllocationWhy
401(k) / IRA${fmt(a401k)}Tax-advantaged. Capture employer match first.
Diversified ETF basket${fmt(aETF)}VTI + VXUS + BND for broad market exposure.
High-yield savings buffer${fmt(aSavings)}Liquid buffer above 3-month emergency fund.
`; - } - allocCard.innerHTML=`

Personalized Starter Allocation

${allocRows}
`; - root.appendChild(allocCard); - - // Recommended strong portfolio - const recCard=document.createElement('div'); recCard.className='card'; - recCard.style.background='linear-gradient(135deg,var(--surface),var(--surface-2))'; - recCard.innerHTML=`

⭐ Recommended Strong Portfolio

-

A time-tested passive portfolio optimized for long-term growth with balanced risk. Based on evidence-based investing principles.

- - - ${RECOMMENDED_PORTFOLIO.map(r=>` - - - - `).join('')} -
Ticker%Reason
${r.ticker}${r.pct}%${r.reason}
-
-

This 60/40-inspired portfolio targets ~7–8% annualized long-term returns with lower volatility than pure equity portfolios.

`; - root.appendChild(recCard); - - // ETF table with allocation inputs - const etfCard=document.createElement('div'); etfCard.className='card'; - etfCard.innerHTML=`

ETFs to Consider

-

Set your own % allocation in the "My %" column. Your custom portfolio is calculated below.

- - - ${ETF_LIST.map(e=>` - - - - - - - - `).join('')} -
TickerNameCategoryRiskSuggested %My %Rationale
${e.ticker}${e.name}${e.cat}${e.risk}${e.sugPct}%${e.rationale}
`; - root.appendChild(etfCard); - - // Stock table with allocation inputs - const stkCard=document.createElement('div'); stkCard.className='card'; - stkCard.innerHTML=`

Blue-Chip Stocks (Examples)

- - - ${STOCK_LIST.map(s=>` - - - - - - - - `).join('')} -
TickerNameCategoryRiskSuggested %My %Rationale
${s.ticker}${s.name}${s.cat}${s.risk}${s.sugPct}%${s.rationale}
`; - root.appendChild(stkCard); - - // My portfolio summary - const allItems=[...ETF_LIST,...STOCK_LIST]; - const myAlloc=allItems.filter(x=>State.investAlloc[x.ticker]>0).map(x=>({...x,myPct:Number(State.investAlloc[x.ticker])})); - const totalMyPct=myAlloc.reduce((s,x)=>s+x.myPct,0); - if (myAlloc.length) { - const myCard=document.createElement('div'); myCard.className='card'; - myCard.innerHTML=`

My Portfolio Summary

- ${totalMyPct!==100?`
Allocations total ${totalMyPct}% — ${totalMyPct<100?'add '+(100-totalMyPct)+'% more':'reduce by '+(totalMyPct-100)+'%'} to reach 100%.
`:''} - - - ${myAlloc.map(x=>``).join('')} -
TickerNameMy %
${x.ticker}${x.name}${x.myPct}%
-
`; - root.appendChild(myCard); - setTimeout(()=>{ - const ctx=$('#myPortChart'); - if (ctx) { - new Chart(ctx,{type:'doughnut',data:{labels:myAlloc.map(x=>x.ticker),datasets:[{data:myAlloc.map(x=>x.myPct),backgroundColor:CHART_PALETTE}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'right',labels:{boxWidth:10,font:{size:11}}}}}}); - } - },0); - } - - // AI CTA - const cta=document.createElement('div'); cta.className='card'; cta.style.background='var(--accent-soft)'; cta.style.borderColor='var(--accent-border)'; - cta.innerHTML=`
Want personalized investing analysis?
Ask Claude to analyze your full financial picture and tailor a plan.
`; - root.appendChild(cta); - - setTimeout(()=>{ - const ctx=$('#recPortChart'); - if (ctx) { - new Chart(ctx,{type:'doughnut',data:{labels:RECOMMENDED_PORTFOLIO.map(r=>r.ticker),datasets:[{data:RECOMMENDED_PORTFOLIO.map(r=>r.pct),backgroundColor:CHART_PALETTE}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'right',labels:{boxWidth:10,font:{size:11}}}}}}); - } - },0); +registerView('investments','Investing ideas',(root)=>{ + pageActions(root,'Sketch a portfolio mix and save it with your other plans', + ``); + appendHtml(root,`

These are reference lists for learning, not financial advice. FinLens doesn't connect to a brokerage or place trades. Check current fund details with the provider before you invest.

`); + const a=State.investAlloc||{}; + appendHtml(root,`
+
${investMixHtml()}
+
+

Index funds and ETFs

Type your own percentages. They're saved with your plans.

+
+ + ${INVEST_FUNDS.map(f=>` + + + + + + `).join('')}
TickerWhat it holdsRiskPresetMy %
${f.ticker}${f.name}${f.cls} +
${f.risk} riskPreset ${f.preset?f.preset+'%':'—'}
${f.risk}${f.preset?f.preset+'%':'—'}
+
`); + appendHtml(root,`
+

Individual stocks to read about

Large, widely held companies across sectors. A starting point for research, not picks.

+
${INVEST_STOCKS.map(s=>`
${s.ticker}${escapeHtml(s.name)}${s.sector}
`).join('')}
+
`); + + const mix=$('#ivMix'); + const toForecast=(e)=>{ const l=e.target.closest('[data-to-forecast]'); if (!l) return; e.preventDefault(); forecastTab='investments'; showView('forecast'); window.scrollTo(0,0); }; + mix.addEventListener('click',toForecast); + $$('.alloc-input',root).forEach(inp=>{ + inp.addEventListener('input',()=>{ setInvestAlloc(inp.dataset.ticker,inp.value,false); mix.innerHTML=investMixHtml(); }); + inp.addEventListener('change',()=>{ setInvestAlloc(inp.dataset.ticker,inp.value,true); }); + }); + $('#ivClear').onclick=()=>{ State.investAlloc={}; lsSet('investAlloc',State.investAlloc); renderActive(); $('#ivClear').focus(); }; + $('#ivPreset').onclick=()=>{ + State.investAlloc=Object.fromEntries(INVEST_FUNDS.filter(f=>f.preset>0).map(f=>[f.ticker,f.preset])); + lsSet('investAlloc',State.investAlloc); renderActive(); $('#ivPreset').focus(); + }; }); -function saveInvestAlloc(input) { - const ticker=input.dataset.ticker; - const val=parseFloat(input.value)||0; - State.investAlloc[ticker]=val; - lsSet('investAlloc',State.investAlloc); +// A fund's share: 0–100, saved when `save` (on change; typing only updates the mix). +function setInvestAlloc(ticker, raw, save) { + const v=Math.min(100,Math.max(0,parseFloat(raw)||0)); + State.investAlloc=State.investAlloc||{}; + if (v>0) State.investAlloc[ticker]=v; else delete State.investAlloc[ticker]; + if (save) lsSet('investAlloc',State.investAlloc); } +// Kept for callers before v1.15.0: save the value of a "My %" input. +function saveInvestAlloc(input) { setInvestAlloc(input.dataset.ticker,input.value,true); } -/* =================== FORECAST INVESTMENTS (NEW) =================== */ +/* =================== FORECAST → INVESTMENTS (views-forecast.js draws the tabs) =================== */ +// Inputs live in memory: they start from these defaults on every page load. let investForecastInputs=null; +const RETURN_PRESETS={conservative:5,moderate:8,aggressive:11}; +const RETURN_PRESET_LIST=[['conservative','Conservative'],['moderate','Moderate'],['aggressive','Aggressive'],['custom','Custom']]; function getInvestForecastDefaults() { - const months=byMonth(State.transactions); - const recent3=months.slice(-3); + const recent3=byMonth(State.transactions).slice(-3); const avgSurplus=recent3.length?Math.max(0,recent3.reduce((s,m)=>s+(m.income-m.expense),0)/recent3.length):500; - return { - startingAmount: 1000, - monthlyContrib: Math.round(avgSurplus*0.5), - annualReturn: 8, - horizon: 20, - returnPreset: 'moderate', // conservative/moderate/aggressive/custom - inflation: 2.5, - allocPreset: 'recommended', // recommended / custom - }; + return { start:1000, monthly:Math.round(avgSurplus*0.5), years:20, preset:'moderate', custom:7, inflOn:true, infl:2.5 }; } +const investRate=(f)=>f.preset==='custom'?(Number(f.custom)||0):RETURN_PRESETS[f.preset]??8; -function _renderForecastInvest(root){ +function _renderForecastInvest(panel) { if (!investForecastInputs) investForecastInputs=getInvestForecastDefaults(); const f=investForecastInputs; - - const inputCard=document.createElement('div'); inputCard.className='card'; - inputCard.innerHTML=` -

- Investment Forecast Inputs - -

-
-
- - -
-
- - -
-
- - + panel.insertAdjacentHTML('beforeend',`
+
+

Your numbers

+
+ + + +
Yearly return +
${RETURN_PRESET_LIST.map(([k,n])=>``).join('')}
+ ${f.preset==='custom'?``:''} +
+ +
-
-
- -
- - - - -
- ${f.returnPreset==='custom'?`
`:''} -
-
- - -
`; - root.appendChild(inputCard); - - const chartCard=document.createElement('div'); chartCard.className='card'; - chartCard.innerHTML=` -

Portfolio Growth Projection

-
`; - root.appendChild(chartCard); - - const summaryCard=document.createElement('div'); summaryCard.id='ifSummary'; summaryCard.className='card'; - summaryCard.innerHTML=`

Summary

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

Year-by-Year Breakdown

`; - root.appendChild(tableCard); - - setTimeout(runInvestForecast,0); -} - -const RETURN_PRESETS={conservative:5,moderate:8,aggressive:11}; - -function setReturnPreset(preset) { - investForecastInputs.returnPreset=preset; - if (preset!=='custom') investForecastInputs.annualReturn=RETURN_PRESETS[preset]; - renderActive(); -} - -function runInvestForecast() { - const chart=$('#ifChart'); - if (!chart) return; - const f=investForecastInputs; - const rate=f.annualReturn/100/12; - const inflRate=f.inflation/100/12; - const totalMonths=f.horizon*12; - - const nominal=[], real=[], contributions=[], years=[]; - let val=f.startingAmount, contribTotal=f.startingAmount; - - for (let m=1;m<=totalMonths;m++) { - val=val*(1+rate)+f.monthlyContrib; - contribTotal+=f.monthlyContrib; - if (m%12===0) { - const yr=m/12; - const realVal=val/Math.pow(1+f.inflation/100,yr); - years.push(yr); - nominal.push(Math.round(val)); - real.push(Math.round(realVal)); - contributions.push(Math.round(contribTotal)); - } - } - - if (window._ifChart) window._ifChart.destroy(); - window._ifChart=new Chart(chart,{ - type:'line', - data:{ - labels:years.map(y=>`Year ${y}`), - datasets:[ - {label:'Portfolio Value',data:nominal,borderColor:chartColor('--chart-in'),backgroundColor:chartColor('--chart-in',.1),fill:true,tension:.3,borderWidth:2,pointRadius:2}, - {label:'Real Value (inflation-adj)',data:real,borderColor:chartColor('--chart-save'),backgroundColor:chartColor('--chart-save',.05),fill:false,tension:.3,borderWidth:2,borderDash:[5,5],pointRadius:0}, - {label:'Total Contributed',data:contributions,borderColor:chartColor('--chart-neutral'),backgroundColor:chartColor('--chart-neutral',.08),fill:true,tension:.3,borderWidth:1.5,pointRadius:0}, - ] - }, - options:{ - responsive:true,maintainAspectRatio:false, - plugins:{legend:{position:'bottom',labels:{boxWidth:10,font:{size:11}}}}, - scales:{y:{ticks:{callback:v=>{ if(v>=1e6) return '$'+(v/1e6).toFixed(1)+'M'; if(v>=1e3) return '$'+(v/1e3).toFixed(0)+'K'; return '$'+v; }}}} - } + +
+
+
+
`); + const draw=()=>{ const o=investForecastHtml(f); $('#ifOut').innerHTML=o.out; $('#ifTbl').innerHTML=o.table; }; + draw(); + $$('[data-if]',panel).forEach(inp=>inp.addEventListener('input',()=>{ + const k=inp.dataset.if, v=parseFloat(inp.value); + f[k]=k==='years'?Math.min(40,Math.max(1,Math.round(v)||1)):(isFinite(v)?v:0); + if (k==='years') $('#ifYearsVal').textContent=f.years; + draw(); + })); + $('#ifInflOn').addEventListener('change',e=>{ f.inflOn=e.target.checked; draw(); }); + $$('[data-preset]',panel).forEach(b=>b.onclick=()=>{ + f.preset=b.dataset.preset; renderActive(); + const n=$(`[data-preset="${f.preset}"]`); if (n) n.focus(); }); +} - const finalNominal=nominal[nominal.length-1]||0; - const finalReal=real[real.length-1]||0; - const totalContrib=contributions[contributions.length-1]||0; - const gains=finalNominal-totalContrib; - const gainsMultiplier=totalContrib>0?(finalNominal/totalContrib).toFixed(2):0; - - const summaryBody=$('#ifSummaryBody'); - if (summaryBody) { - summaryBody.innerHTML=` -
-

Final Value (Nominal)

${fmt(finalNominal)}
-

Final Value (Real)

${fmt(finalReal)}
Inflation-adjusted
-

Total Contributed

${fmt(totalContrib)}
-

Investment Gains

${fmt(gains)}
${gainsMultiplier}× money multiplier
-
-
- Contributing ${fmt(f.monthlyContrib)}/month at ${f.annualReturn}% annual return for ${f.horizon} years turns ${fmt(f.startingAmount+totalContrib)} in contributions into ${fmt(finalNominal)} — a ${fmt(gains)} gain. -
`; - } - - const tableDiv=$('#ifTable'); - if (tableDiv) { - const rows=years.map((yr,i)=>{ - const gain=nominal[i]-contributions[i]; - return ` - Year ${yr} - ${fmt(contributions[i])} - ${fmt(nominal[i])} - ${fmt(real[i])} - ${fmt(gain)} - `; - }); - tableDiv.innerHTML=`${rows.join('')}
PeriodTotal ContributedPortfolio ValueReal ValueGains
`; - } +// Year by year at the chosen yearly return (growthByYear() in aggregation.js). Today's +// dollars divide each year's value by (1 + inflation) for every year that has passed. +function investForecastHtml(f) { + const rate=investRate(f), infl=(Number(f.infl)||0)/100; + const rows=growthByYear(f.start,f.monthly,rate,f.years).map(r=>({ ...r, real:r.balance/Math.pow(1+infl,r.year) })); + const last=rows[rows.length-1]; + const max=Math.max(1,...rows.map(r=>Math.max(r.balance,r.real))); + const h=(v)=>(Math.max(0,v)/max*100).toFixed(1); + const rl=pctNum(rate)+'%'; + const out=`

In ${plural(f.years,'year')}, at ${rl} a year

+
Projected value${fmt0(last.balance)}
+
In today's dollars${fmt0(last.real)}
+
You put in${fmt0(last.putIn)}
+
Projected value${f.inflOn?'In today\'s dollars':''}
+ +
Year 1Year ${f.years}
+

Returns are assumptions, not promises. Growth compounds monthly: ${rl} a year is ${(monthlyRateFromYearly(rate)*100).toFixed(3)}% a month. Additions land at the end of each month. Today's dollars take off ${pctNum(infl*100)}% inflation a year.

`; + const table=`

Year by year

+
+ + ${rows.map(r=>``).join('')}
YearPut inValueToday's dollars
${r.year}${fmt0(r.putIn)}${fmt0(r.balance)}${fmt0(r.real)}
`; + return { out, table }; } diff --git a/js/views-plan.js b/js/views-plan.js index a971cc6..461fcc1 100644 --- a/js/views-plan.js +++ b/js/views-plan.js @@ -1,282 +1,396 @@ /* ================================================================ FINLENS — views-plan.js - Budgeting, Savings Buckets, Debt Tracker, Trends & Insights + The Plan screens (Clarity, v1.15.0): Budget, Savings buckets and + Debt tracker. Investing ideas is in views-invest.js, Forecast in + views-forecast.js. Trends (below) is unchanged until its own redesign. + Shared pieces (pageActions, kpiTiles, appendHtml, ICON, plural …) are + in views-main.js; the forms and their helpers are in ui.js. ================================================================ */ -/* =================== BUDGETING =================== */ -registerView('budgets','Budgeting',(root)=>{ - if (!State.budgets||!State.budgets.length) { - const intro=document.createElement('div'); intro.className='card'; - intro.innerHTML=`

Set Up Your Budget

-

Start with a suggested set or add custom categories.

-
- - -
`; - root.appendChild(intro); return; +/* =================== SHARED PLAN PIECES =================== */ +const ICON_ALERT=_svg('',18); +const ICON_CHECK=_svg(''); +const ICON_PREV=_svg(''); +const ICON_NEXT=_svg(''); +// Money with a real minus sign and no plus: "$12.00", "−$40.00". +const fmtMinus=(n)=>n<-0.004?'−'+fmt(-n):fmt(Math.abs(n)); +const fmtMinus0=(n)=>n<=-0.5?'−'+fmt0(-n):fmt0(Math.abs(n)); +// A progress bar (role="progressbar"). pct may pass 100: the bar stops full, the value doesn't. +function meterHtml(pct, hue, label, valuetext, size='') { + const p=Math.max(0,Math.round(pct)); + return `
`; +} +const callout=(cls, html, role='status')=>`
${ICON_ALERT}${html}
`; +// "2 years, 3 months" +function yearsMonths(m) { + const y=Math.floor(m/12), r=m%12; + return [y?plural(y,'year'):'', r?plural(r,'month'):''].filter(Boolean).join(', ')||'0 months'; +} +// Month k of a plan: 1 = next calendar month. +const planMonth=(k)=>dayjs(startOfMonth(new Date())).add(k,'month').format('MMM YYYY'); + +/* =================== BUDGET =================== */ +let budgetMonth=null; // first day of the month shown; null → the latest month with data +let budgetEditing=-1; // the budget whose amount is being edited in its row + +registerView('budgets','Budget',(root)=>{ + const now=new Date(), curMonth=startOfMonth(now); + const span=dataSpan(State.transactions); + if (!budgetMonth) budgetMonth=startOfMonth(span&&span.lastmEnd) dataNote=isCur?'No transactions this month yet':`No transactions in ${mName}`; + else if (span.lastM) dataNote=`Data from ${dayjs(span.first).format('MMM D')}`; + const toAdd=starterBudgetsToAdd(); + appendHtml(root,`
+
+ + ${dayjs(M).format('MMMM YYYY')} + + ${dataNote?`${dataNote}`:''} +
+
+ + +
`); + const step=(d)=>{ + budgetMonth=new Date(M.getFullYear(),M.getMonth()+d,1); budgetEditing=-1; renderActive(); + const b=$(d<0?'#bmPrev':'#bmNext'), o=$(d<0?'#bmNext':'#bmPrev'); + (b&&!b.disabled?b:o).focus(); + }; + $('#bmPrev').onclick=()=>step(-1); + $('#bmNext').onclick=()=>step(1); + $('#bgStarter').onclick=()=>{ seedBudgets(); const b=$('#bgAdd'); if (b) b.focus(); }; + $('#bgAdd').onclick=()=>editBudget(-1); + + if (!budgets.length) { + appendHtml(root,emptyPanel('No budget yet. Use starter budget fills one in from what you spend each month, or add a category yourself.')); + return; } - const monthStart=startOfMonth(new Date()), monthEnd=endOfMonth(new Date()); - const monthTxs=State.transactions.filter(t=>t.date>=monthStart&&t.date<=monthEnd&&t.amount<0&&t.type!=='transfer'); - const spent=(b)=>monthTxs.filter(t=>b.categories.some(c=>(t.categories||[t.category]).includes(c))).reduce((s,t)=>s+Math.abs(t.amount),0); - - const totalLimit=State.budgets.reduce((s,b)=>s+b.limit,0); - const totalSpent=State.budgets.reduce((s,b)=>s+spent(b),0); - const overBudget=State.budgets.filter(b=>spent(b)>b.limit); - const warning=State.budgets.filter(b=>spent(b)/b.limit>=0.80&&spent(b)<=b.limit); - - if (overBudget.length||warning.length) { - const banner=document.createElement('div'); - banner.className='insight '+(overBudget.length?'bad':'warn'); - banner.innerHTML=`${overBudget.length?overBudget.length+' over budget':warning.length+' approaching limit'}: ${(overBudget.length?overBudget:warning).map(b=>b.name).join(', ')}`; - root.appendChild(banner); + /* ---- rows ---- */ + const rows=budgets.map((b,i)=>{ + const lim=Math.max(0,Number(b.limit)||0), sp=budgetSpent(b,M,mEnd); + const ratio=lim>0?sp/lim:0; + const over=sp>lim+0.004, warn=!over&&lim>0&&ratio>=0.9&&spb.sp-a.sp||a.i-b.i); + const totLim=rows.reduce((s,r)=>s+r.lim,0), totSp=rows.reduce((s,r)=>s+r.sp,0); + const overN=rows.filter(r=>r.over).length, warnN=rows.filter(r=>r.warn).length; + const daysLeft=endOfMonth(now).getDate()-now.getDate(); + const daysTxt=daysLeft===0?'the last day of the month':plural(daysLeft,'day')+' to go'; + const pctOf=(r)=>r.lim>0?Math.round(r.ratio*100)+'%':r.sp>0?'—':'0%'; + + /* ---- alerts ---- */ + const alerts=rows.filter(r=>r.over||r.warn).map(r=>{ + const n=escapeHtml(r.b.name); + if (r.over) return callout('bad',`${n} is ${fmt(r.sp-r.lim)} over budget. You ${isCur?'have spent':'spent'} ${fmt(r.sp)} of ${fmt(r.lim)} ${isCur?'this month':'in '+mName}.`); + return callout('warn',`${n} is at ${pctOf(r)}. ${isCur?`Only ${fmt(r.lim-r.sp)} left with ${daysTxt}.`:`${fmt(r.lim-r.sp)} was left in ${mName}.`}`); + }); + if (alerts.length) appendHtml(root,`
${alerts.join('')}
`); + + /* ---- KPIs ---- */ + appendHtml(root,kpiTiles([ + {label:'Budgeted',value:fmt(totLim),sub:plural(rows.length,'category','categories')}, + {label:'Spent',value:fmt(totSp),sub:totLim>0?`${Math.round(totSp/totLim*100)}% of budget`:'No amounts set yet'}, + {label:'Left to spend',value:fmtMinus(totLim-totSp),cls:totLim-totSp<-0.004?'c-bad':'c-good',sub:isCur?cap(daysTxt):`${mName} has ended`}, + {label:'Over budget',value:String(overN),cls:overN?'c-bad':'',sub:`${warnN} close to the limit`}, + ])); + + /* ---- budget by category ---- */ + const rowHtml=rows.map(r=>{ + const n=escapeHtml(r.b.name), ed=budgetEditing===r.i; + const hue=r.over?'danger':r.warn?'warn':'accent'; + const pctCls=r.over?'c-bad':r.warn?'c-warn':'c-dim'; + const pv=r.lim>0?r.ratio*100:(r.sp>0?100:0); + return ` + +
${meterHtml(pv,hue,`${r.b.name} spent`,`${fmt(r.sp)} of ${fmt(r.lim)}`)}${pctOf(r)}${fmt(r.sp)} spent
+
${meterHtml(pv,hue,`${r.b.name} spent`,`${fmt(r.sp)} of ${fmt(r.lim)}`,'lg')}${pctOf(r)}
+ ${fmt(r.sp)} + ${ed?``:`${fmt(r.lim)}`} + ${fmtMinus(r.lim-r.sp)} + + `; + }).join(''); + appendHtml(root,`
+

Budget by category, ${dayjs(M).format('MMMM YYYY')}

+
+ + ${rowHtml}
CategoryProgressSpentBudgetLeftEdit
+
`); + $$('[data-bud-open]',root).forEach(b=>b.onclick=()=>editBudget(+b.dataset.budOpen)); + const limIn=$('#bgLimitIn'); + const finish=(save)=>{ + const i=budgetEditing; + if (save&&limIn) setBudgetLimit(i,limIn.value); + budgetEditing=-1; renderActive(); + const b=$(`[data-bud-edit="${i}"]`); if (b) b.focus(); + }; + $$('[data-bud-edit]',root).forEach(b=>b.onclick=()=>{ + const i=+b.dataset.budEdit; + if (budgetEditing===i) return finish(true); + if (limIn) setBudgetLimit(budgetEditing,limIn.value); + budgetEditing=i; renderActive(); + const inp=$('#bgLimitIn'); if (inp) { inp.focus(); inp.select(); } + }); + if (limIn) { + limIn.addEventListener('change',()=>{ if (budgetEditing===+limIn.dataset.i) setBudgetLimit(budgetEditing,limIn.value); }); + limIn.addEventListener('keydown',e=>{ if (e.key==='Enter'){ e.preventDefault(); finish(true); } else if (e.key==='Escape'){ e.preventDefault(); e.stopPropagation(); finish(false); } }); } - const sum=document.createElement('div'); sum.className='grid grid-3'; - sum.innerHTML=` -

Total Budget

${fmt(totalLimit)}
${State.budgets.length} categories
-

Spent (This Month)

${fmt(totalSpent)}
${pct(totalSpent/Math.max(1,totalLimit),0)} of budget
-

Remaining

${fmt(totalLimit-totalSpent)}
${overBudget.length} over · ${warning.length} warning
`; - root.appendChild(sum); - - const card=document.createElement('div'); card.className='card'; - card.innerHTML=`

Budget vs Actual — ${dayjs(monthStart).format('MMMM YYYY')}

-
${State.budgets.map((b,i)=>{ - const s=spent(b); const r=s/b.limit; - const cls=r>1?'bad':r>=0.8?'warn':''; - const remaining=b.limit-s; - return `
-
-
${b.name} · ${b.categories.join(', ')}
-
${fmt(s)} / ${fmt(b.limit)} (${(r*100).toFixed(0)}%)
-
-
-
${remaining>=0?fmt(remaining)+' remaining':fmt(Math.abs(remaining))+' over'}
-
`; - }).join('')}
`; - root.appendChild(card); - - const historyCard=document.createElement('div'); historyCard.className='card'; - historyCard.innerHTML=`

Monthly History

`; - root.appendChild(historyCard); - - setTimeout(()=>{ - const mos=[]; - for (let i=5;i>=0;i--){ const d=new Date(); d.setMonth(d.getMonth()-i); mos.push({key:monthKey(d),label:dayjs(d).format('MMM'),start:startOfMonth(d),end:endOfMonth(d)}); } - const datasets=State.budgets.map(b=>({ - label:b.name,backgroundColor:b.color||chartColor('--chart-neutral'),borderRadius:4, - data:mos.map(m=>{ const txs=State.transactions.filter(t=>t.date>=m.start&&t.date<=m.end&&t.amount<0&&t.type!=='transfer'&&b.categories.some(c=>(t.categories||[t.category]).includes(c))); return txs.reduce((s,t)=>s+Math.abs(t.amount),0); }) - })); - new Chart($('#budgetHist'),{type:'bar',data:{labels:mos.map(m=>m.label),datasets},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{boxWidth:10,font:{size:11}}}},scales:{x:{stacked:true},y:{stacked:true,ticks:{callback:v=>'$'+v.toLocaleString()}}}}}); - },0); + /* ---- budget vs. actual, month by month ---- */ + const hist=[]; + for (let k=5;k>=0;k--) { + const s=new Date(M.getFullYear(),M.getMonth()-k,1), e=endOfMonth(s); + const has=!!span&&span.first<=e&&span.last>=s; + const sp=has?budgets.reduce((t,b)=>t+budgetSpent(b,s,e),0):null; + const partial=has&&(s.getTime()===curMonth.getTime()||span.lasttotLim+0.004 }); + } + const peak=Math.max(totLim,...hist.map(h=>h.sp||0)); + const scaleMax=peak>0?Math.ceil(peak/niceStep(peak/4))*niceStep(peak/4):1; + const overMonths=hist.filter(h=>h.over); + const hLabel=(h)=>`${dayjs(h.s).format('MMM')}${h.partial?' · so far':''}`; + const aria=`Spending in budgeted categories against a ${fmt0(totLim)} monthly budget, ${dayjs(hist[0].s).format('MMMM')} to ${dayjs(hist[5].s).format('MMMM YYYY')}: ${overMonths.length?overMonths.map(h=>`${dayjs(h.s).format('MMMM')} at ${fmt0(h.sp)}`).join(', ')+' went over':'no month went over'}`; + appendHtml(root,`
+

Budget vs. actual, month by month

+
Within budgetOver budget${fmt(totLim)} budget
+ + +
`); }); /* =================== SAVINGS BUCKETS =================== */ -registerView('buckets','Savings Buckets',(root)=>{ - const balances=currentBalances(); - const totalSavings=Object.values(State.accounts).filter(a=>a.kind==='bank_savings').reduce((s,a)=>s+(balances[a.id]||0),0); - const allocated=(State.buckets||[]).reduce((s,b)=>s+(b.current||0),0); - const unalloc=totalSavings-allocated; - const totalGoal=(State.buckets||[]).reduce((s,b)=>s+(b.goal||0),0); - - const m=document.createElement('div'); m.className='grid grid-4'; - m.innerHTML=` -

Total Savings

${fmt(totalSavings)}
Bank Savings balance
-

Allocated

${fmt(allocated)}
Across ${State.buckets.length} buckets
-

Unallocated

${fmt(unalloc)}
${unalloc<0?'Over-allocated':'Available to assign'}
-

Total Goals

${fmt(totalGoal)}
${pct(allocated/Math.max(1,totalGoal),0)} of total goals
`; - root.appendChild(m); +let bucketFormOpen=false; + +registerView('buckets','Savings buckets',(root)=>{ + const buckets=State.buckets||[]; + const bal=currentBalances(); + const savAccts=orderedAccounts().filter(a=>a.kind==='bank_savings'); + const savTotal=savAccts.reduce((s,a)=>s+(Number(bal[a.id])||0),0); + const savName=savAccts.length===1?acctName(savAccts[0].id):'your savings'; + pageActions(root,`Split ${escapeHtml(savName)} into goals, each with a target and a date`, + ``); + $('#bkNew').onclick=()=>{ bucketFormOpen=!bucketFormOpen; renderActive(); const f=bucketFormOpen?$('#nbkName'):$('#bkNew'); if (f) f.focus(); }; + + const plans=buckets.map((b,i)=>({ b, i, p:bucketPlan(b), hue:bucketHue(b,i), icon:bucketIconKey(b) })); + const totSaved=plans.reduce((s,x)=>s+x.p.saved,0), totGoal=plans.reduce((s,x)=>s+x.p.goal,0); + const totMonthly=plans.reduce((s,x)=>s+(x.p.months>0&&x.p.left>0?x.p.monthly:0),0); + + /* ---- KPIs + pace ---- */ + if (buckets.length) { + appendHtml(root,kpiTiles([ + {label:'Saved in buckets',value:fmt(totSaved),sub:plural(buckets.length,'bucket')}, + {label:'Total of targets',value:fmt(totGoal),sub:totGoal>0?`${Math.round(totSaved/totGoal*100)}% of the way there`:'No targets set'}, + {label:'Needed each month',value:fmt(totMonthly),sub:'To hit every target date'}, + {label:'Unassigned savings',value:savAccts.length?fmtMinus(savTotal-totSaved):'—',cls:savAccts.length&&savTotal-totSaved<-0.004?'c-bad':'', + sub:savAccts.length?`${escapeHtml(savAccts.length===1?savName:plural(savAccts.length,'savings account'))} · ${fmt(savTotal)}`:'No savings account imported'}, + ])); + if (totMonthly>0.005) { + const pace=savingsPace(); + const msg=`These goals need ${fmt(totMonthly)} a month.`; + let html; + if (pace&&pace.perMonth>=0.5) { + const since=dayjs(pace.since).format(pace.since.getFullYear()===new Date().getFullYear()?'MMMM':'MMMM YYYY'); + const moved=`You've moved about ${fmt0(pace.perMonth)} a month into savings since ${since}.`; + html=pace.perMonth+0.5

Your Buckets

`; - root.appendChild(ctrl); + /* ---- new bucket form ---- */ + if (bucketFormOpen) { + appendHtml(root,`
+

New bucket

+
+ + + + +
+
That's a month. +
+
`); + const vals=()=>{ const t=Math.max(0,parseFloat($('#nbkTarget').value)||0), s=Math.max(0,parseFloat($('#nbkSaved').value)||0), m=Math.min(120,Math.max(1,parseInt($('#nbkMonths').value,10)||1)); return {t,s,m}; }; + const preview=()=>{ const v=vals(); $('#nbkPreview').textContent=fmt(Math.max(0,v.t-v.s)/v.m); }; + ['#nbkTarget','#nbkSaved','#nbkMonths'].forEach(s=>$(s).addEventListener('input',preview)); + preview(); + $('#nbkCancel').onclick=()=>{ bucketFormOpen=false; renderActive(); const b=$('#bkNew'); if (b) b.focus(); }; + $('#nbkSave').onclick=()=>{ + const name=$('#nbkName').value.trim(); + if (!name) { $('#nbkName').setAttribute('aria-invalid','true'); $('#nbkName').focus(); return; } + const v=vals(); + addBucket({ name, goal:v.t, current:v.s, targetDate:dayjs(today()).add(v.m,'month').format('YYYY-MM-DD'), + icon:guessBucketIcon(name), hue:BUCKET_HUES[buckets.length%BUCKET_HUES.length] }); + bucketFormOpen=false; renderActive(); + const b=$(`[data-bk-edit="${State.buckets.length-1}"]`)||$('#bkNew'); if (b) b.focus(); + }; + } - if (!State.buckets.length) { - const empty=document.createElement('div'); empty.className='empty'; - empty.innerHTML=`

No buckets yet

Split your savings into named goals like Emergency Fund, Vacation, Car Repair.

`; - root.appendChild(empty); return; + if (!buckets.length) { + if (!bucketFormOpen) appendHtml(root,emptyPanel('No buckets yet. Use + New bucket to split your savings into goals, like an emergency fund or a trip.')); + return; } - const grid=document.createElement('div'); grid.className='grid grid-2'; - State.buckets.forEach((b,i)=>{ - const hasGoal=!!(b.goal&&b.goal>0); - const r=hasGoal?(b.current||0)/b.goal:0; - const daysLeft=b.targetDate?Math.ceil((new Date(b.targetDate)-new Date())/86400000):null; - const card=document.createElement('div'); card.className='card'; card.style.cursor='pointer'; - card.innerHTML=` -
-
${b.icon||'💰'} ${escapeHtml(b.name)}
- ${b.targetDate?`
Target ${dayjs(b.targetDate).format('MMM D, YYYY')} · ${daysLeft!==null?(daysLeft>=0?daysLeft+' days left':'overdue'):''}
`:''}
-
- - -
-
-
${fmt(b.current||0)}${hasGoal?` of ${fmt(b.goal)}`:''}
- ${hasGoal?` -
-
- ${(r*100).toFixed(0)}% complete - ${fmt(Math.max(0,b.goal-(b.current||0)))} to go -
`: - '
No goal set
' - }`; - // Drill-down: click card body (not buttons) opens drawer - card.addEventListener('click', e=>{ - if (e.target.closest('[data-bkt-edit],[data-bkt-del]')) return; - showBucketDrawer(i); - }); - card.querySelector('[data-bkt-edit]').onclick=(e)=>{ e.stopPropagation(); editBucket(i); }; - card.querySelector('[data-bkt-del]').onclick=(e)=>{ e.stopPropagation(); deleteBucket(i); }; - grid.appendChild(card); - }); - root.appendChild(grid); + /* ---- bucket cards ---- */ + appendHtml(root,`
${plans.map(({b,i,p,hue,icon})=>{ + const n=escapeHtml(b.name); + const pct=p.goal>0?Math.min(100,Math.round(p.saved/p.goal*100)):0; + const when=p.due?`By ${dayjs(p.due).format('MMM YYYY')} · ${p.months===0?'date passed':plural(p.months,'month')+' left'}`:'No target date'; + const need=p.goal>0&&p.left<=0.005?'Goal reached' + :!p.due?'Add a target date to see a monthly amount' + :p.months===0?`Date passed · ${fmt(p.left)} still to save` + :`Needs ${fmt(p.monthly)} a month`; + return `
+
${bucketIconSvg(icon)} +

${n}

${when}
+
+
${fmt(p.saved)}${p.goal>0?`of ${fmt(p.goal)}`:''}
+ ${p.goal>0?`
${meterHtml(pct,hue,`${b.name} saved`,`${pct}% saved, ${fmt(p.left)} to go`,'lg')} +
${pct}% saved${fmt(p.left)} to go
`:'
No target set
'} +
${need}
+
`; + }).join('')}
`); + $$('[data-bk-edit]',root).forEach(b=>b.onclick=()=>editBucket(+b.dataset.bkEdit)); }); -/* =================== BUCKET DRAWER =================== */ -function showBucketDrawer(i) { - const b=State.buckets[i]; - if (!b) return; - - const hasGoal=!!(b.goal&&b.goal>0); - const r=hasGoal?(b.current||0)/b.goal:0; - const daysLeft=b.targetDate?Math.ceil((new Date(b.targetDate)-new Date())/86400000):null; - const pctComplete=hasGoal?(r*100).toFixed(0):null; - - // Transactions linked to this bucket via txOverrides - const linked=State.transactions.filter(t=>{ - const lnk=State.txOverrides[t.id]?.link; - return lnk&&lnk.type==='bucket'&&lnk.idx===i; - }).sort((a,b)=>b.date-a.date); - - // Savings account deposits in the date range that could relate (any positive transfer into savings) - const savingsDeposits=State.transactions.filter(t=> - (t.account==='bank_savings'||State.accounts[t.account]?.kind==='bank_savings')&& - t.amount>0&&t.type!=='transfer' - ).slice(0,10); - - openDrawer(` -
- ${b.icon||'💰'} -
-
${escapeHtml(b.name)}
- ${b.targetDate?`
- Target: ${dayjs(b.targetDate).format('MMM D, YYYY')} - ${daysLeft!==null?(daysLeft>=0?` · ${daysLeft} days left`:' · Overdue'):''} -
`:''} -
-
+/* =================== DEBT TRACKER =================== */ +const PAYOFF_PLANS=[['avalanche','Avalanche','Highest interest rate first'],['snowball','Snowball','Smallest balance first'],['minimum','Minimums only','No extra payment, for comparison']]; -
-
-
Current
-
${fmt(b.current||0)}
-
- ${hasGoal?`
-
Goal
-
${fmt(b.goal)}
-
`:''} -
+registerView('debt','Debt tracker',(root)=>{ + const debts=State.debts||[]; + pageActions(root,'Balances you enter, plus a payoff plan you can test',``); + $('#dtAdd').onclick=()=>editDebt(-1); + + if (!debts.length) { + const cards=debtCardChoices(''); + appendHtml(root,`

Your debts

+

No debts yet. Add a loan or a card with + Add debt${cards.length?', or start from a credit card in your CSVs':''}.

+ ${cards.length?`
${cards.map(a=>``).join('')}
`:''} +
`); + $$('[data-dt-card]',root).forEach(b=>b.onclick=()=>editDebt(-1,b.dataset.dtCard)); + return; + } - ${hasGoal?` -
-
- ${pctComplete}% complete - ${fmt(Math.max(0,b.goal-(b.current||0)))} remaining -
`:''} + /* ---- KPIs ---- */ + const rows=debts.map((d,i)=>{ const card=debtIsCard(d); return { d, i, bal:debtBalance(d), apr:Math.max(0,Number(d.apr)||0), min:Math.max(0,Number(d.minPayment)||0), card, lim:card?debtLimit(d):0, linked:debtLinked(d) }; }); + const total=rows.reduce((s,r)=>s+r.bal,0), mins=rows.reduce((s,r)=>s+r.min,0); + const wAPR=total>0?rows.reduce((s,r)=>s+r.bal*r.apr,0)/total:0; + const withLim=rows.filter(r=>r.card&&r.lim>0); + const cBal=withLim.reduce((s,r)=>s+r.bal,0), cLim=withLim.reduce((s,r)=>s+r.lim,0); + const span=dataSpan(State.transactions); + const pay=span?sumIncome(State.transactions)/Math.max(1,span.months):0; + appendHtml(root,kpiTiles([ + {label:'Total debt',value:fmt(total),sub:plural(debts.length,'debt')}, + {label:'Minimum payments',value:`${fmt(mins)}/mo`,sub:pay>0&&mins>0?`${Math.round(mins/pay*100)}% of take-home pay`:'Every minimum, added up'}, + {label:'Average APR',value:`${wAPR.toFixed(2)}%`,sub:'Weighted by balance'}, + {label:'Card utilization',value:cLim>0?`${Math.round(cBal/cLim*100)}%`:'—',sub:cLim>0?`${fmt(cBal)} of ${fmt0(cLim)}`:'No credit limit set'}, + ])); + + /* ---- your debts ---- */ + appendHtml(root,`

Your debts

+
+ + ${rows.map(r=>{ + const n=escapeHtml(r.d.name), u=r.lim>0?r.bal/r.lim*100:0; + return ` + + + + + + + `; }).join('')}
DebtBalanceAPRMinimumCredit limitActions
${n}
${r.linked?'Credit card · from your CSV':'Entered manually'}
+
=20?' class="strong c-bad"':''}>${r.apr.toFixed(2)}% APR${fmt(r.min)} min${r.lim>0?`${Math.round(u)}% of ${fmt0(r.lim)}`:''}
${fmt(r.bal)}${r.apr>=20?`${r.apr.toFixed(2)}%`:r.apr.toFixed(2)+'%'}${fmt(r.min)}${r.lim>0?`
${meterHtml(u,'card',`${r.d.name} credit used`,`${Math.round(u)}% of ${fmt0(r.lim)} used`,'xs')}${fmt0(r.lim)}
`:'—'}
+
`); + $$('[data-dt-edit]',root).forEach(b=>b.onclick=()=>editDebt(+b.dataset.dtEdit)); + + /* ---- payoff plan ---- */ + if (total<=0.005) { appendHtml(root,emptyPanel('Every debt here has a $0 balance, so there is nothing to plan.')); return; } + const plan=State.debtPlan||{}; + let extra=Math.max(0,Number(plan.extra)||0); + const max=Math.max(1500,Math.ceil(extra/25)*25); + appendHtml(root,`
+
+

Payoff plan

Pay every minimum, then put the extra toward one debt at a time

+ +
+
+
`); + const input=rows.map(r=>({ name:r.d.name, balance:r.bal, apr:r.apr, minPayment:r.min })); + const draw=()=>{ + const sel=PAYOFF_PLANS.some(p=>p[0]===(State.debtPlan||{}).strategy)?State.debtPlan.strategy:'avalanche'; + $('#planOut').innerHTML=payoffPlanHtml(input,extra,sel,total); + $$('#planOut [data-plan]').forEach(b=>b.onclick=()=>{ setPayoffStrategy(b.dataset.plan); draw(); const f=$(`#planOut [data-plan="${b.dataset.plan}"]`); if (f) f.focus(); }); + }; + draw(); + const sl=$('#dtExtra'); + sl.addEventListener('input',()=>{ extra=+sl.value; $('#dtExtraVal').textContent=fmt0(extra); sl.setAttribute('aria-valuetext',`${fmt0(extra)} a month`); draw(); }); + sl.addEventListener('change',()=>setPayoffExtra(sl.value)); +}); -
+// The payoff plan's results: the three plan cards, a summary, the selected plan's balance +// bars, payoff order and first 6 months. Uses payoffPlan() (aggregation.js). +function payoffPlanHtml(debts, extra, sel, total) { + const res={ avalanche:payoffPlan(debts,extra,'avalanche'), snowball:payoffPlan(debts,extra,'snowball'), minimum:payoffPlan(debts,0,'minimum') }; + const fin=(r)=>r.paidOff?planMonth(r.months):'Not within 50 years'; + const av=res.avalanche, sn=res.snowball; + const best=av.paidOff&&(!sn.paidOff||av.interest<=sn.interest+0.005)?'avalanche':sn.paidOff?'snowball':null; + const cards=PAYOFF_PLANS.map(([k,name,desc])=>{ const r=res[k]; return ``; }).join(''); + + let summary, tone='good'; + if (!(extra>0)) summary='Move the slider to see how an extra payment changes your payoff date and interest.'; + else if (!best) { tone='warn'; summary=`Even with an extra ${fmt0(extra)} a month, these debts aren't paid off within 50 years. Raise the extra amount or the minimums.`; } + else { + const B=res[best], other=best==='avalanche'?'snowball':'avalanche', O=res[other], Mn=res.minimum; + summary=`An extra ${fmt0(extra)} a month with ${best} makes you debt-free `+(Mn.paidOff + ?(Mn.months>B.months?`${yearsMonths(Mn.months-B.months)} sooner than paying only the minimums`:'as soon as paying only the minimums')+`, and saves ${fmt0(Mn.interest-B.interest)} in interest.` + :`by ${planMonth(B.months)}. Paying only the minimums wouldn't clear them within 50 years.`); + if (O.paidOff) summary+=O.interest-B.interest>=0.5?` ${cap(best)} saves ${fmt0(O.interest-B.interest)} more than ${other}.`:' Avalanche and snowball cost the same here.'; + } -
- Linked Transactions - — ${linked.length} linked -
- ${linked.length?` - - - ${linked.map(t=>` - - - - `).join('')} -
DateDescriptionAmount
${dayjs(t.date).format('MMM D, YYYY')}${escapeHtml(t.description)}${fmt(t.amount)}
` - :`

- No transactions linked yet. Open any transaction, click its row to edit, and use Link to → Bucket → ${escapeHtml(b.name)}. -

`} - -
-
- - - + const r=res[sel], selName=PAYOFF_PLANS.find(p=>p[0]===sel)[1]; + const stepN=Math.max(1,Math.ceil(r.rows.length/30)); + const bars=[]; + for (let i=0;i`); } + const last=r.rows[r.rows.length-1]; + const aria=r.paidOff?`Total debt balance falling from ${fmt0(total)} to zero by ${planMonth(r.months)}`:`Total debt balance: ${fmt0(total)} now, still ${fmt0(last?last.remaining:total)} after 50 years`; + const order=r.order.map((o,i)=>`
  • ${i+1}${escapeHtml(o.name)}${planMonth(o.month)}
  • `) + .concat(r.left.map((n,i)=>`
  • ${r.order.length+i+1}${escapeHtml(n)}Not paid off
  • `)).join(''); + return `
    ${cards}
    + ${callout(tone,summary)} +
    +

    Total balance · ${selName}

    + +
    ${planMonth(1)}${r.paidOff?planMonth(r.months):planMonth(r.months)+' and still owing'}
    +

    Payoff order

      ${order}
    - `); - - $('#bktDrawerEdit').onclick=()=>{ closeDrawer(); editBucket(i); }; - $('#bktDrawerDel').onclick=()=>{ if(confirm(`Delete "${b.name}"?`)){ deleteBucket(i); closeDrawer(); } }; +

    First 6 months

    +
    + ${r.rows.slice(0,6).map((m,i)=>``).join('')}
    MonthPaidInterestRemaining
    ${planMonth(i+1)}${fmt(m.paid)}${fmt(m.interest)}${fmt(m.remaining)}
    +

    Interest is added monthly at APR ÷ 12 and minimums stay as entered. Once a debt is paid off, its minimum goes to the next one (not in Minimums only).

    +
    `; } -/* =================== DEBT TRACKER =================== */ -registerView('debt','Debt Tracker',(root)=>{ - const debts=State.debts||[]; - const totalDebt=debts.reduce((s,d)=>s+(d.balance||0),0); - const totalLimit=debts.filter(d=>d.type==='Credit Card').reduce((s,d)=>s+(d.limit||0),0); - const totalMin=debts.reduce((s,d)=>s+(d.minPayment||0),0); - const wAPR=totalDebt>0?debts.reduce((s,d)=>s+(d.balance||0)*(d.apr||0)/100,0)/totalDebt:0; - const utilization=totalLimit>0?totalDebt/totalLimit:null; - - const m=document.createElement('div'); m.className='grid grid-4'; - m.innerHTML=` -

    Total Debt

    ${fmt(totalDebt)}
    ${debts.length} accounts
    -

    Weighted APR

    ${(wAPR).toFixed(2)}%
    -

    Min Payments / mo

    ${fmt(totalMin)}
    -

    Credit Utilization

    ${utilization==null?'—':(utilization*100).toFixed(0)+'%'}
    `; - root.appendChild(m); - - const ctrl=document.createElement('div'); ctrl.className='card'; - ctrl.innerHTML=`

    Debt Accounts

    - ${debts.length?` - ${debts.map((d,i)=>` - - - - - - - - `).join('')}
    NameTypeBalanceAPRMin PmtDue
    ${escapeHtml(d.name)}${d.type}${fmt(d.balance)}${(d.apr||0).toFixed(2)}%${fmt(d.minPayment||0)}${d.dueDay?'Day '+d.dueDay:'—'}
    `:'

    No debts tracked yet.

    '}`; - root.appendChild(ctrl); - - if (!debts.length) return; - - const stratCard=document.createElement('div'); stratCard.className='card'; - stratCard.innerHTML=`

    Payoff Strategy

    -
    - - -
    -
    -
    `; - root.appendChild(stratCard); - - const strategy=State.payoffStrategy||'avalanche'; - const extra=State.extraPayment||0; - const sortedDebts=[...debts].sort((a,b)=>strategy==='avalanche'?(b.apr||0)-(a.apr||0):(a.balance||0)-(b.balance||0)); - const schedule=simulatePayoff(sortedDebts,extra); - setTimeout(()=>{ - if (!$('#payoffPlan')) return; - $('#payoffPlan').innerHTML=` -
    -

    Months to Debt-Free

    ${schedule.months}
    ${(schedule.months/12).toFixed(1)} years
    -

    Total Interest

    ${fmt(schedule.totalInterest)}
    -

    Focus Order

    ${sortedDebts.map((d,i)=>`
    ${i+1}. ${escapeHtml(d.name)}
    `).join('')}
    -
    -

    Month-by-Month (first 24 mos)

    -
    - ${schedule.rows.slice(0,24).map(r=>``).join('')}
    MonthBalanceInterestPayment
    ${r.month}${fmt(r.balance)}${fmt(r.interest)}${fmt(r.payment)}
    `; - },0); -}); - /* =================== TRENDS & INSIGHTS =================== */ registerView('trends','Trends & Insights',(root)=>{ if (!State.transactions.length){ root.innerHTML=emptyCard('Load data to see trends.'); return; } diff --git a/js/views-settings.js b/js/views-settings.js index 20c4e91..ab713c9 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -54,7 +54,7 @@ function _renderGeneralSettings(root) {
    -
    FinLens v1.14.0 · ${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
    `; +
    FinLens v1.15.0 · ${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
    `; root.appendChild(displayCard); displayCard.querySelectorAll('[data-theme-opt]').forEach(b=>b.addEventListener('click',()=>setTheme(b.dataset.themeOpt)));