diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cc2bb8..9086e63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,76 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.14.0] — 2026-11-02 + +### Finances screens — Clarity redesign, part 2 +Overview, Transactions and the screens behind its filter pills (Income, Spending, Bills, Transfers) now match the Clarity mockups. Every number is computed from your data; none come from the mockups. + +- **Shared:** a note and the screen's buttons sit in one row under the page title (`.page-actions`). KPI tiles, panels, tags and lists use new Clarity classes in `index.html` instead of inline styles. Charts on these screens are inline SVG or plain boxes colored by theme tokens, each with a text description for screen readers. +- **Filter pills:** All · Income · Spending · Bills · Payments · Transfers on all five screens. All and Payments filter the list; the other four open their own screens (`income`, `spending`, `bills`, `transfers`, as before). The app bar keeps **Transactions** underlined on all of them (`TX_VIEWS` in `ui.js`). Screen titles: Income, Spending, Bills & subscriptions, Transfers. +- **Phones:** grids fold to one or two columns, wide tables hide secondary columns below 600px, and the transfer diagram stacks. No screen scrolls sideways at 390px. + +### Overview +- **Net worth** with a trend chart: **1M** (daily), **3M** (weekly) or **All** (month ends). A pill shows the change since the end of last month. +- **Latest month:** money in, money out, net, the savings rate as a bar, and the average rate over up to 6 months. It says how far the data runs ("Data runs through Oct 20"). +- **Account cards:** an icon, the number of transactions, a balance sparkline for bank accounts, and for a card how much of its limit is used ("No credit limit set · Add one" without one) and whether it's on autopay. Footnotes say where the balance comes from, or how much savings is assigned to buckets. +- **Cash flow:** 6 months of money in and out as bars, with the net under each month. +- **Upcoming bills:** bills due in the next 3 weeks, plus any overdue, with a "Due today" pill. With no bills yet, it shows the recurring charges FinLens spotted, marked as not confirmed. +- **Largest card purchases** of the latest month. +- **Kept:** double-click an account name to rename it (Enter on a focused name works too). **Added:** Reload CSVs and Ask AI about this buttons. +- **Dropped to match the mockup:** the four KPI cards (Total Cash, Total Debt, Net Worth, Cash Flow), the income/spending/transfers bar chart, Recent Transactions, and the Top Spending Category, Most Frequent Merchant and Top Income Source cards. + +### Transactions +- **KPIs:** transactions, money in, money out, net. On **Payments**: card payments, total paid, average payment, card balance now. +- **Payments** now lists payments to your credit cards, including the card side of an autopay transfer (`isCardPayment()`). Before, those became transfers when they were paired, so the pill showed nothing for the samples. +- **List:** search with an icon, Category, **Sort** (newest, oldest, largest, smallest, description A–Z), the amount filter, a Flags column (Bill, Recurring, Sub) and a numbered pager. On phones the category, account and flags move under the description. +- **Transaction detail drawer:** amount, date, account and original description at the top; Description; Category and Type side by side; flags as chips; notes; Save and Cancel pinned at the bottom. Type now offers **Card payment**, so saving a payment no longer turns it into an expense. +- **Kept:** bulk select and bulk edit, extra categories (under "Also count it under other categories"), the budget/bucket/debt link, Export CSV, transaction rules. +- **Transaction rules:** one row per keyword with its flags and how many transactions match. A Transaction rules button jumps to them. +- **Dropped to match the mockup:** the Type column, sorting by clicking column headers (the Sort menu replaces it), and the "Re-apply rules" button (rules apply when added or removed, and on every import). + +### Income +- **KPIs:** total income, average per month (over the period in months), interest earned, returns and refunds. +- **Income by source** as a stacked bar and list, **monthly income** bars with the unfinished month shaded lighter, **recurring deposits** with frequency, count, last, next expected and confidence (`recurringDepositsDetail()`), and **all deposits** (6, then Show all). +- **Dropped to match the mockup:** the by-category donut. + +### Spending +- **KPIs:** total spent, average per day, top category, highest month (and how far above average). +- **By category:** a ranked list of buttons; picking one fills the **drill-down** panel next to it. "Open in Transactions" opens the list filtered to that category. +- **Daily spending** heatmap for the period (was the last 365 days), shaded by quartile so rent days don't wash out the rest. **Monthly trend** line with the highest month labelled and an unfinished month drawn hollow, plus a note on which category pushed the highest month up. +- **Top merchants** (7) with category and visits. **Category rules** with Add rule and Re-categorize all. +- **Dropped to match the mockup:** the two Chart.js category charts and the transaction count KPI. + +### Bills +- **+ Add bill** opens an inline form: name, amount, due day, repeats, pays from. +- **KPIs:** bills tracked, cost per month (and its share of average monthly income), due in the next 7 days, subscriptions per month and per year. +- **Spotted recurring charges:** each with its rhythm ("Monthly, around the 18th"), number of charges, account, amount and a confidence bar. **Confirm as bill**, **Dismiss**, and **Undo** after dismissing. +- **Month calendar** with each bill on its due days; Hide / Show calendar. +- **Your bills:** repeats, next due, **pays from**, **last paid** (found in your transactions), status (Overdue, Due today, This week, Upcoming, Paid, Just added) and an edit button. The edit drawer has every field, plus Paid and Delete (click twice). +- **Next due moves on by itself:** a repeat that a payment already covers counts as paid (`billNextDue()`). +- **Fixed with the new edit button:** saving an edited bill used to add a copy. +- **Dropped to match the mockup:** the "Bills, Utilities & Subscriptions (All Time)" transaction table, the old KPI cards, and the Paid checkbox and × in each row (both are in the edit drawer now). + +### Transfers +- **KPIs:** transfers (paired / one-sided), between your accounts, sent outside FinLens (named by the keyword that matched, e.g. "Zelle · 6 payments"), saved to savings (and about how much a month). +- **Where money moved:** a From box per account with an arrow to each destination: amount, count and rhythm ("Monthly transfer, around the 3rd", "Autopay, around the 6th"), and a dashed box for money that left FinLens. +- **List:** From and To filters (including Outside FinLens), Paired / Keyword match, 10 rows then Show all. A row still opens the transfer drawer. +- **Transfer keywords:** removable chips and Add keyword (Enter works). Every change re-runs transfer detection; the separate Re-apply button and its alert are gone. +- **Dropped to match the mockup:** Most Frequent Path and Avg per Transfer, the description column and sortable headers. + +### Technical +- **`aggregation.js`:** new `balanceAt()`, `dataSpan()`, `monthlyFlow()`, `isCardPayment()`, `transferPairs()`, `recurringDepositsDetail()`, and bill helpers (`BILL_FREQS`, `billNextDue()`, `billLastPaid()`, `billDatesBetween()` …). `detectRecurring()` and `detectRecurringDeposits()` now use `recurringKey()` / `depositKey()`; their output is unchanged, and so is the AI summary (compared before and after on the samples). +- **`ui.js`:** `openDrawer(html, { title, footer })` with a scrim, a pinned footer and focus that returns to the opener; older forms that start with an `
Confirmed from a recurring charge FinLens spotted. Its last payment and next due date come from your transactions.
`:''}${note}
`:''}${acts?`${msg}
${full?'Full month':`Data runs through ${dayjs(last).format('MMM D')}`}
+No transactions in ${escapeHtml(rangeText())}.
No balance history before this period.
'}| Date | Bill | Amount |
|---|---|---|
| ${dateStr} | -${escapeHtml(b.merchant)} ${b.frequency||'Monthly'} |
- ${fmt(b.amount)} | -
No upcoming bills. Add bills in the Bills tab.
`; - const row1=document.createElement('div'); row1.className='grid grid-2'; - row1.innerHTML=` -No transactions in ${escapeHtml(rangeText())}.
`; + row2.innerHTML=` +| Date | Description | Account | Category | Amount |
|---|---|---|---|---|
| ${dayjs(t.date).format('MMM D')} | -${escapeHtml(t.description)} | -${State.accounts[t.account]?.name||t.account} | -${t.category} | -${fmt(t.amount)} | -
No credit card transactions in selected period.
`}`; - root.appendChild(topCardTxCard); + /* ---- Largest card purchases ---- */ + const cards=accts.filter(isCardAcct); + if (cards.length) { + const cardIds=new Set(cards.map(a=>a.id)); + const cardTx=txs.filter(t=>cardIds.has(t.account)&&t.amount<0&&t.type!=='transfer'); + const lastMonth=cardTx.length?monthKey(dataSpan(cardTx).last):null; + const inMonth=cardTx.filter(t=>monthKey(t.date)===lastMonth).sort((a,b)=>a.amount-b.amount).slice(0,5); + const which=new Set(inMonth.map(t=>t.account)); + const sub=lastMonth?`${escapeHtml(which.size===1?acctName([...which][0]):cards.length===1?acctName(cards[0].id):'All cards')} · ${dayjs(lastMonth+'-01').format('MMMM')}`:''; + const sec=document.createElement('section'); + sec.className='panel'; + sec.setAttribute('aria-labelledby','ovTopH'); + sec.innerHTML=`${sub}
`:''}| Merchant | Date | Amount |
|---|---|---|
| + | ${dayjs(t.date).format('MMM D')} | + +${fmtSigned(t.amount)} |
No card purchases in ${escapeHtml(rangeText())}.
`}`; + root.appendChild(sec); } +}); - // Recent Transactions — top 5 across bank checking + savings combined - const bankAccts=orderedAccounts().filter(a=>a.kind==='bank_checking'||a.kind==='bank_savings'); - if (bankAccts.length) { - const bankIds=new Set(bankAccts.map(a=>a.id)); - const recentBank=filteredTx().filter(t=>bankIds.has(t.account)).slice(0,5); - const recentCard=document.createElement('div'); recentCard.className='card'; - recentCard.innerHTML=`| Date | Description | Account | Amount |
|---|---|---|---|
| ${dayjs(t.date).format('MMM D')} | -${escapeHtml(t.description)} | -${escapeHtml(State.accountLabels?.[t.account]||State.accounts[t.account]?.name||t.account)} | -${fmt(t.amount)} | -
No transactions in selected period.
`}`; - root.appendChild(recentCard); +// One account card on the Overview: balance, a sparkline (cash) or utilization bar (card), +// and where the balance comes from. +function accountCardHtml(a, bal, seriesEnd, pairsAll) { + const own=State.transactions.filter(t=>t.account===a.id); + const name=acctName(a.id); + const manual=State.manualBalances[a.id]!=null; + const kind=a.kind; + const tile=kind==='bank_savings'?['t-good',ICON.piggy]:kind==='credit_card'?['t-card',ICON.card]:['',ICON.bank]; + let sub=`${KIND_LABEL[kind]||'Account'} · ${plural(own.length,'transaction')}`; + let middle='', foot=''; + const sparkVals=()=>{ + if (!own.length||!seriesEnd) return []; + const first=dataSpan(own).first.getTime(), end=seriesEnd.getTime(); + if (end<=first) return []; + const n=24, out=[]; + for (let i=0;iNothing due in the next 3 weeks.
`} + ${spotted&&rows?`Spotted in your transactions, not confirmed as bills yet.
`:''} + ${spotted?'Review in Bills →':'All bills →'}`; +} -/* =================== TRANSACTIONS =================== */ +/* =================== TRANSACTIONS (All · Payments) =================== */ let txSort={key:'date',dir:'desc'}; let txPage=1; let txSearch=''; let txCatFilter='all'; -let txPillFilter='all'; // all | income | spending | bills | payments | transfers +let txPillFilter='all'; // the current pill: all | income | spending | bills | payments | transfers let txAmtMode=''; let txAmtVal=null; let txAmtVal2=null; let selectedTxIds=new Set(); +const TX_PAGE_SIZE=50; +const TX_SORTS=[['date-desc','Newest first'],['date-asc','Oldest first'],['amount-desc','Largest amount'],['amount-asc','Smallest amount'],['description-asc','Description A–Z']]; +const FLAG_LABEL={bill:'Bill',recurring:'Recurring',subscription:'Subscription'}; registerView('transactions','Transactions',(root)=>{ - const txs=filteredTx(); - const TRANSFER_CATS=['Transfer in','Transfer out']; - const cats=['all','(Uncategorized)',...new Set(txs.flatMap(t=>t.categories||[t.category]).filter(c=>c&&!TRANSFER_CATS.includes(c)&&c!=='Other'))]; - - // Filter pills - const pillBar=document.createElement('div'); - pillBar.style.cssText='display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px'; - const PILLS=[['all','All'],['income','Income'],['spending','Spending'],['bills','Bills'],['payments','Payments'],['transfers','Transfers']]; - pillBar.innerHTML=PILLS.map(([k,l])=>``).join(''); - root.appendChild(pillBar); - pillBar.querySelectorAll('[data-pill]').forEach(btn=>btn.onclick=()=>{txPillFilter=btn.dataset.pill;txPage=1;renderActive();}); + // Income, Spending, Bills and Transfers are their own screens; this one lists All or Payments. + if (!['all','payments'].includes(txPillFilter)) txPillFilter='all'; + const pay=txPillFilter==='payments'; + const all=filteredTx(); + const base=pay?all.filter(isCardPayment):all; + wireLinks(root); + const files=Object.values(State.accounts).filter(a=>a.sourceFile&&a.sourceFile!=='manual').length; + pageActions(root, files?plural(files,'CSV file'):'', + `Transaction rules + `); + renderTxPills(root, txPillFilter); + + if (pay) { + const total=base.reduce((s,t)=>s+t.amount,0); + const bals=currentBalances(); + const owed=orderedAccounts().filter(isCardAcct).reduce((s,a)=>s+debtOf(bals[a.id]),0); + appendHtml(root,kpiTiles([ + {label:'Card payments',value:base.length.toLocaleString()}, + {label:'Total paid',value:fmt(total)}, + {label:'Average payment',value:base.length?fmt(total/base.length):'—'}, + {label:'Card balance now',value:fmt(owed),cls:'c-card'}, + ])); + } else { + const inc=sumIncome(base), out=sumExpense(base); + appendHtml(root,kpiTiles([ + {label:'Transactions',value:base.length.toLocaleString()}, + {label:'Money in',value:fmtSigned(inc),cls:'c-good'}, + {label:'Money out',value:fmtSigned(-out,'−')}, + {label:'Net',value:fmtSigned(inc-out)}, + ])); + } - const ctrl=document.createElement('div'); ctrl.className='card'; - ctrl.innerHTML=` -${empty}
Automatically flag transactions as Bill, Subscription, or Recurring when their description contains a keyword.
-${escapeHtml(r.contains)} → ${r.flag}
-
- Flag matching transactions automatically, now and on every future import.
${escapeHtml(g.contains)}${g.flags.map(f=>`${FLAG_LABEL[f]||escapeHtml(f)}`).join('')}${plural(matchCount(g.contains),'match','matches')}No rules yet. Add one below, e.g. NETFLIX → Subscription.
'} +${escapeHtml(t._originalDesc||t.description)}
Edits are stored separately from the imported row, so re-importing the CSV never overwrites them.
+| Source | Avg Amount | Frequency | Last seen |
|---|---|---|---|
| ${escapeHtml(r.source)} | ${fmt(r.avg)} | ${r.freq} | ${dayjs(r.last).format('MMM D, YYYY')} |
| Date | Source | Account | Amount |
|---|---|---|---|
| ${dayjs(t.date).format('MMM D')} | ${escapeHtml(t.description)} | ${State.accounts[t.account]?.name||t.account} | +${fmt(t.amount).replace('-','')} |
| Date | Description | Account | Category | Amount |
|---|---|---|---|---|
| ${dayjs(t.date).format('MMM D, YYYY')} | -${escapeHtml(t.description)}${t.isBill?'bill':''}${t.isSubscription?'sub':''} | -${State.accounts[t.account]?.name||t.account} | -${(t.categories||[t.category]).join(', ')} | -${fmt(t.amount)} | -
Confirm to add to bills calendar. Subscriptions are marked automatically.
-| Merchant | Category | Avg | Frequency | Next Due | Confidence | |
|---|---|---|---|---|---|---|
| ${escapeHtml(r.merchant)}${r.isSubscription?' sub':''} | -${r.category} | -${fmt(r.avg)} | -${r.freq} | -${dayjs(r.nextDue).format('MMM D')} | -${Math.round(r.confidence*100)}% | -${status==='confirmed'?'Confirmed':status==='dismissed'?'Dismissed':` `} | -
| No recurring charges detected — load more history. | ||||||
| Merchant | Category | Amount | Frequency | Next Due | Status |
|---|
Detected from deposits with a steady amount and rhythm
| Source | Frequency | Deposits | Last | Next expected | Confidence | Typical amount |
|---|---|---|---|---|---|---|
${escapeHtml(r.source)} ${r.account?`${escapeHtml(acctName(r.account))} `:''} |
+ ${FREQ_LABEL[r.freq]||r.freq} | ${r.count} | +${dayjs(r.last).format('MMM D')} | +${r.next?dayjs(r.next).format('MMM D'):'—'} | +${r.confidence} | +${r.steady?'':'~'}${fmt(r.avg)} |
No deposits with a regular rhythm in this period.
'} +| Date | Description | Account | Amount |
|---|---|---|---|
| ${dayjs(t.date).format('MMM D')} | ++ + | ${fmtSigned(t.amount)} |
${fmt(c.amount)} · ${plural(list.length,'transaction')}
${list.length-8} more in Transactions
`:''} + Open in Transactions →`; + }; + drawDrill(); + $$('[data-cat-i]',row).forEach(b=>b.onclick=()=>{ + spendingDrillCategory=cats[+b.dataset.catI].category; + $$('[data-cat-i]',row).forEach(x=>x.setAttribute('aria-pressed',String(x===b))); + drawDrill(); + // one column: the drill-down sits below the list, so bring it into view + if (getComputedStyle(row).gridTemplateColumns.split(' ').length===1) $('#spDrill').scrollIntoView({behavior:'smooth',block:'start'}); + }); - const row2=document.createElement('div'); row2.className='grid grid-2'; + /* ---- daily heatmap + monthly trend ---- */ + const r=State.range; + let hmStart=new Date(Math.max(span.first.getTime(), r.start?r.start.getTime():-Infinity)); + const hmEnd=new Date(Math.min(span.last.getTime(), r.end?r.end.getTime():Infinity)); + if (hmEnd-hmStart>370*DAY) hmStart=new Date(hmEnd.getTime()-370*DAY); + const lastAll=dataSpan(State.transactions).last; + const lastM=months[months.length-1]; + const lastPartial=lastM&&monthKey(lastM.date)===monthKey(lastAll)&&lastAll.getDate()${lastPartial?`${dayjs(lastM.date).format('MMMM')} is partial (through the ${ordinal(lastAll.getDate())}).`:''}${why}
+One month of data so far.
`; + + /* ---- top merchants + category rules ---- */ + const merch={}; + txs.forEach(t=>{ + const k=(t.description||'').replace(/\d+/g,'').replace(/\s+/g,' ').trim().slice(0,40)||t.description; + const m=merch[k]=merch[k]||{name:k,amount:0,count:0,cats:{}}; + m.amount+=Math.abs(t.amount); m.count++; m.cats[t.category]=(m.cats[t.category]||0)+1; + }); + const topM=Object.values(merch).sort((a,b)=>b.amount-a.amount).slice(0,7); + const row3=document.createElement('div'); row3.className='cols-3'; + row3.innerHTML=` +| Merchant | Visits | Total |
|---|---|---|
| ${escapeHtml(m.name)} | ${m.count} | ${fmt(m.amount)} |
Teach FinLens your merchants. Rules apply to every import.
${escapeHtml(r.contains)}→ ${escapeHtml(r.category)}No rules yet.
'} + + + `; + parent.appendChild(sec); + $('#ruleAdd').onclick=()=>{ const i=$('#ruleContains'); if (!i.value.trim()){ i.setAttribute('aria-invalid','true'); i.focus(); return; } addCatRule(); }; + $('#ruleContains').onkeydown=(e)=>{ if (e.key==='Enter'){ e.preventDefault(); $('#ruleAdd').click(); } }; + $('#ruleReapply').onclick=()=>recategorizeAll(); + $$('[data-catrule-del]',sec).forEach(b=>b.onclick=()=>delCatRule(+b.dataset.catruleDel)); +} + +/* =================== BILLS =================== */ +let billsCalOpen=true; +let billFormOpen=false; - const merchantMap={}; - txs.forEach(t=>{ const k=(t.description||'').replace(/\d+/g,'').trim().slice(0,40)||t.description; if (!merchantMap[k]) merchantMap[k]={amount:0,count:0}; merchantMap[k].amount+=Math.abs(t.amount); merchantMap[k].count++; }); - const top=Object.entries(merchantMap).map(([k,v])=>({merchant:k,...v,avg:v.amount/v.count})).sort((a,b)=>b.amount-a.amount).slice(0,15); - const merchCard=document.createElement('div'); merchCard.className='card'; - merchCard.innerHTML=`| Merchant | Total | Frequency | Avg |
|---|---|---|---|
| ${escapeHtml(t.merchant)} | ${fmt(t.amount)} | ${t.count}× | ${fmt(t.avg)} |
Click any row to edit.
-| Date | Merchant | Account | Amount |
|---|---|---|---|
| ${dayjs(t.date).format('MMM D, YYYY')} | -${escapeHtml(t.description)} | -${State.accounts[t.account]?.name||t.account} | -${fmt(t.amount)} | -
When a description contains "X", assign category "Y".
-${escapeHtml(r.contains)} → ${r.category}
- FinLens found these repeating. Confirm the real bills so they get due dates and reminders.
Nothing repeating found yet. Import a few months of history.
'}`; + root.appendChild(sugSec); + const refocus=(key,sel)=>{ const row=$(`#content .sug[data-sug-key="${CSS.escape(key)}"]`); const el=row&&(row.querySelector(sel)||row.querySelector('button,.done-chip')); if (el){ if (!el.matches('button')) el.tabIndex=-1; el.focus({preventScroll:true}); } }; + $$('[data-confirm]',sugSec).forEach(b=>b.onclick=()=>{ const r=recurring[+b.dataset.confirm]; confirmRecurring(r); refocus(r.key,'.done-chip'); }); + $$('[data-dismiss]',sugSec).forEach(b=>b.onclick=()=>{ const r=recurring[+b.dataset.dismiss]; dismissRecurring(r.key); refocus(r.key,'[data-undo]'); }); + $$('[data-undo]',sugSec).forEach(b=>b.onclick=()=>{ const r=recurring[+b.dataset.undo]; undoDismissRecurring(r.key); refocus(r.key,'[data-confirm]'); }); + + /* ---- month calendar ---- */ + const now=new Date(), y=now.getFullYear(), m=now.getMonth(); + const mStart=new Date(y,m,1), mEnd=new Date(y,m+1,0,23,59,59); + const byDay={}; + bills.forEach(b=>billDatesBetween(b,mStart,mEnd).forEach(d=>{ (byDay[d.getDate()]=byDay[d.getDate()]||[]).push(b.merchant); })); + const lead=mStart.getDay(), days=mEnd.getDate(); + const cells=[]; + for (let i=0;i| Bill | Amount | Repeats | Next due | Pays from | Last paid | Status | Edit |
|---|---|---|---|---|---|---|---|
| ${escapeHtml(x.b.merchant)}${billIsSubscription(x.b)?' Subscription':''} | +${fmt(Number(x.b.amount)||0)} | +${billFreq(x.b).label} | +${dayjs(x.due).format('MMM D')} | +${x.b.account?escapeHtml(acctName(x.b.account)):'—'} | +${lp?dayjs(lp).format('MMM D'):'—'} | +${st} | ++ |
No bills yet. Confirm one FinLens spotted above, or use + Add bill.
'}`; + root.appendChild(listSec); + $$('[data-bill-edit]',listSec).forEach(b=>b.onclick=()=>showBillForm(+b.dataset.billEdit)); }); /* =================== TRANSFERS =================== */ -let txFromFilter='all', txToFilter='all', txfSort={key:'date',dir:'desc'}; +let txFromFilter='all', txToFilter='all', txfShowAll=false; registerView('transfers','Transfers',(root)=>{ - const allTransfers=filteredTx().filter(t=>t.type==='transfer'||['Transfer','Transfer in','Transfer out'].includes(t.category)); - if (!allTransfers.length){ root.innerHTML=emptyCard('No transfers detected in selected period.'); return; } - - // Build paired list — each outgoing tx is matched with its incoming counterpart - const pairs=[]; - const usedInPair=new Set(); - const outgoing=allTransfers.filter(t=>t.amount<0||t.categories?.includes('Transfer out')); - const incoming=allTransfers.filter(t=>t.amount>0||t.categories?.includes('Transfer in')); - - for (const out of outgoing) { - if (usedInPair.has(out.id)) continue; - const match=incoming.find(inn=> - !usedInPair.has(inn.id) && - inn.account!==out.account && - Math.abs(Math.abs(out.amount)-Math.abs(inn.amount))<1 && - Math.abs((out.date-inn.date)/86400000)<=2 - ); - if (match) { - pairs.push({date:out.date,from:out.account,to:match.account,amount:Math.abs(out.amount),description:out.description,outId:out.id,inId:match.id}); - usedInPair.add(out.id); usedInPair.add(match.id); - } else { - pairs.push({date:out.date,from:out.account,to:'?',amount:Math.abs(out.amount),description:out.description,unmatched:true,outId:out.id}); - usedInPair.add(out.id); - } - } - // Add any unmatched incoming - for (const inn of incoming) { - if (usedInPair.has(inn.id)) continue; - pairs.push({date:inn.date,from:'?',to:inn.account,amount:Math.abs(inn.amount),description:inn.description,unmatched:true,inId:inn.id}); + txPillFilter='transfers'; + wireLinks(root); + pageActions(root,'Money moving between accounts · both sides of each transfer are matched automatically',''); + renderTxPills(root,'transfers'); + const all=filteredTx(); + const pairs=transferPairs(all); + const kind=(id)=>id?State.accounts[id]?.kind:null; + const kws=(State.transferKeywords&&State.transferKeywords.length)?State.transferKeywords:DEFAULT_TRANSFER_KEYWORDS; + + if (pairs.length) { + const paired=pairs.filter(p=>p.paired), out=pairs.filter(p=>!p.paired&&p.from&&!p.to); + const sum=a=>a.reduce((s,p)=>s+p.amount,0); + const destWords=[...new Set(paired.map(p=>({bank_savings:'savings',credit_card:'card payments',bank_checking:'checking'})[kind(p.to)]||'other accounts'))]; + const outKw={}; + out.forEach(p=>{ const k=kws.find(w=>p.description.toLowerCase().includes(w.toLowerCase())); if (k) outKw[k]=(outKw[k]||0)+1; }); + const toSav=sum(paired.filter(p=>kind(p.to)==='bank_savings'))-sum(paired.filter(p=>kind(p.from)==='bank_savings'&&kind(p.to)!=='bank_savings')); + const span=dataSpan(all); + const hasSavings=orderedAccounts().some(a=>a.kind==='bank_savings'); + appendHtml(root,kpiTiles([ + {label:'Transfers',value:String(pairs.length),sub:`${paired.length} paired · ${pairs.length-paired.length} one-sided`}, + {label:'Between your accounts',value:fmt(sum(paired)),sub:paired.length?escapeHtml(cap(destWords.join(' and '))):'None paired'}, + {label:'Sent outside FinLens',value:fmt(sum(out)),sub:out.length?`${escapeHtml(Object.keys(outKw).map(cap).join(', ')||'Transfers')} · ${plural(out.length,'payment')}`:'None'}, + {label:'Saved to savings',value:fmt(toSav),cls:toSav>0?'c-good':'',sub:hasSavings?(toSav>0?`About ${fmt0(toSav/Math.max(1,span.months))} a month`:'Nothing moved in'):'No savings account loaded'}, + ])); + + /* ---- where money moved ---- */ + const groups={}; + pairs.forEach(p=>{ + const s=p.from||'__out', d=p.to||'__out'; + const g=groups[s]=groups[s]||{id:p.from,total:0,count:0,dests:{}}; + g.total+=p.amount; g.count++; + const dd=g.dests[d]=g.dests[d]||{id:p.to,total:0,count:0,dates:[],descs:{},autopay:0}; + dd.total+=p.amount; dd.count++; dd.dates.push(p.date); + dd.descs[p.description]=(dd.descs[p.description]||0)+1; + if (/auto\s?pay/i.test(p.description)) dd.autopay++; + }); + const srcs=Object.values(groups).sort((a,b)=>(a.id?0:1)-(b.id?0:1)||b.total-a.total); + const pspan=dataSpan(pairs.map(p=>({date:p.date}))); + const flowHtml=srcs.map(g=>{ + const dests=Object.values(g.dests).sort((a,b)=>(a.id?0:1)-(b.id?0:1)||b.total-a.total); + return `${dayjs(pspan.first).format('MMM D')} – ${dayjs(pspan.last).format('MMM D, YYYY')}
Click any row to view or edit transfer details.
-| Date | -From | To | Description | -Amount | -
|---|
Unpaired transactions whose description contains one of these count as transfers, not spending.
Changes re-run transfer detection on all transactions.
+| Date | From → To | Amount |
|---|---|---|
| ${dayjs(p.date).format('MMM D')} | ++ + | ${fmt(p.amount)} |
${pairs.length?'No transfers between those accounts.':'Nothing to show.'}
`} + ${rows.length?`- Transactions whose description contains any of these keywords are automatically classified as transfers. - Edit this list when you add a new bank that uses different terminology. -
- -To change a leg's category or type, open it from the Transactions list.
+