const root = document.querySelector('#app'); const modalRoot = document.querySelector('#modal-root'); const toast = document.querySelector('#toast'); const state = { data: null, month: null, panel: 'summary', summaryMode: 'planned', editingGroup: null, detailItem: null, mobilePanel: false, }; const icons = {budget:'▤',transactions:'$',planning:'◷',learn:'◇',goals:'◎',roadmap:'⌁',insights:'▥',trusted:'♙',coaching:'□',feed:'▦',help:'?',settings:'⚙',signout:'⇥'}; function esc(value='') { return String(value).replace(/[&<>'"]/g, char => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[char])); } function money(value, whole=false) { return new Intl.NumberFormat('en-US', {style:'currency', currency:'USD', minimumFractionDigits:whole?0:2, maximumFractionDigits:whole?0:2}).format(Number(value || 0)); } function mark() { return ''; } function wordmark() { return `${mark()}EveryDollar`; } async function api(path, options={}) { const response = await fetch(path, {headers:{'Content-Type':'application/json', ...(options.headers||{})}, ...options}); let payload = {}; try { payload = await response.json(); } catch (_) {} if (!response.ok) throw new Error(payload.error || `Request failed (${response.status})`); return payload; } function showToast(message) { toast.textContent = message; toast.classList.add('show'); window.clearTimeout(showToast.timer); showToast.timer = window.setTimeout(() => toast.classList.remove('show'), 2200); } function go(path) { history.pushState({}, '', path); state.editingGroup = null; state.detailItem = null; state.mobilePanel = false; render(); } function marketingFooter(asset) { return ``; } const LEGAL_PAGES = { '/company/terms-of-use': { title: 'Terms of Use', intro: 'These terms describe how this local EveryDollar recreation may be used.', sections: [ ['Acceptance of these terms', 'By creating an account or using the budgeting tools on this site you agree to these terms. This is an offline WebsiteBench recreation, so no agreement is formed with Ramsey Solutions or Lampo Licensing, LLC.'], ['Your account', 'You are responsible for the credentials you create here. Accounts, budgets, transactions and goals live only in this local database and are never transmitted anywhere.'], ['Acceptable use', 'Do not attempt to use this recreation to reach the live EveryDollar service, and do not enter real banking credentials, card numbers or other sensitive personal data.'], ['No financial advice', 'Budget totals, insights and goal projections shown here are illustrative only and are not financial, tax or legal advice.'], ['Changes', 'These terms may be updated as the recreation changes. Continued use after an update means you accept the revised terms.'], ], }, '/company/privacy-policy': { title: 'Privacy Policy', intro: 'This policy explains what this local EveryDollar recreation stores and what it never collects.', sections: [ ['What we store', 'Your display name, email address, password hash, budget items, transactions, goals and notification preferences are written to a SQLite database on the machine running this site.'], ['What we never collect', 'No bank credentials, account numbers, card details or government identifiers are requested or accepted anywhere in this recreation.'], ['No third parties', 'Nothing is shared with Ramsey Solutions, advertisers or analytics providers. The site makes no outbound network requests at runtime.'], ['Email', 'Password recovery and account verification are previewed locally. No message is ever sent to any address you enter.'], ['Deleting your data', 'Removing the local database file erases every account, budget and transaction created here.'], ], }, }; function legalPage(pathname) { const asset = '/static/assets/everydollar-2026'; const page = LEGAL_PAGES[pathname]; root.innerHTML = `
${marketingFooter(asset)}
`; } function marketingPage() { const asset = '/static/assets/everydollar-2026'; root.innerHTML = `
Ramsey

Budgeting Meets
Simplicity

EveryDollar is the easy-to-use zero-based budgeting app that helps you keep tabs on your money at a glance—anytime, anywhere

Create Your Free Account
EveryDollar app on two phones showing budget screens

Tell Your Money Where to Go,
Instead of Wondering Where It Went

EveryDollar custom budget screen

Create a Budget
That’s as Unique as You

Whether you’re saving for a high-tech mermaid costume or stocking up on staycation snacks, EveryDollar makes it so easy to plan for it all. Customize your budget with unlimited categories!

Create Your Free Account
EveryDollar transaction tracking screen

Track Your Transactions
Quickly and Easily

Stream transaction updates from your bank to your budget. Check balances on the go and see upcoming expenses at a glance. EveryDollar keeps up so you can keep moving!

Create Your Free Account
EveryDollar financial accounts screen

See All Your Financial
Accounts in One Place

Streamline the way you manage your money by seeing all of your financial accounts conveniently in one place. No need to switch between different apps to stay on top of your finances.

Create Your Free Account
EveryDollar budgeters

Uncover an extra
$395 on average

Cut monthly
expenses by 9%

Build better
budgeting habits

EveryDollar’s zero-based budgeting method helps you manage your money with confidence and ease.

More About Giving

Giving comes first in a zero-based budget. Create a Giving group, add the causes you support, and plan an amount for each one before you assign anything else. EveryDollar tracks what you have given this month so the plan stays honest.

Create Your Free Account

More About Saving

Saving works best when every goal has a name. Add a budget item for your emergency fund, then use Goals to track a target amount and the month you want to hit it. Progress carries forward as you move between months.

See Goals

More About Spending

Once giving and saving are planned, the rest is yours to spend on purpose. Add transactions as they happen, assign each one to a budget item, and the Remaining column tells you exactly what is left in every category.

Open the Budget

We love our budgeters! Here’s why they love EveryDollar:

Colby D.
“We thought it was going to take 12 months to pay off our debt. It only took six to seven. That gave us a reason to celebrate.”
Colby D.EveryDollar Budgeter
Francisco and Brishithe T.
“We were losing like five grand a month on nonsense. Now, there’s so many doors that opened up that we don’t have to rely on anybody.”
Francisco and Brishithe T.EveryDollar Budgeters
Christina I.
“I cried the first time we finished a month and actually had money left over. That had never happened before.”
Christina I.EveryDollar Budgeter
You tell your money who is in chargeA debt-free couple and the EveryDollar app
EveryDollar app device icons

Anytime. Anywhere. Any Device.

Create Your Free Account

Frequently Asked Questions

What features should I look for in a budgeting app?

Look for a budget app that makes it easy to plan your spending, track transactions, see what’s left to spend, set goals, stay on top of bills, share a budget with a partner, and stay motivated.

Is EveryDollar free?

EveryDollar has a free version you can use as long as you want. New users can also start a 14-day free trial of EveryDollar premium.

What’s included in EveryDollar premium?

Premium adds automatic bank transactions, personalized recommendations, debt payoff tracking, expert coaching, and weekly live training.

Does EveryDollar connect to my bank and import transactions?

Yes. With EveryDollar premium, bank connect pulls your transactions into your budget for you.

Is EveryDollar good for couples or shared budgets?

Yes. The household feature lets couples manage one budget together, even with separate sign-ins.

What is zero-based budgeting and how does EveryDollar use it?

Zero-based budgeting means planning where every dollar goes before you spend it, so income minus expenses equals zero.

Can EveryDollar help with debt-payoff planning?

Yes. EveryDollar helps you work the debt snowball method and track your progress.

How much does EveryDollar cost?

The free version costs nothing. Premium is available after a 14-day trial with monthly or annual billing.

${marketingFooter(asset)}
`; root.querySelector('[data-site-search]')?.addEventListener('submit', event => { event.preventDefault(); const q=new FormData(event.currentTarget).get('q') || ''; go(`/app/help?q=${encodeURIComponent(q)}`); }); } function previewMarkup() { return `

January 2026⌄

✓ It’s an EveryDollar budget!
IncomePlannedReceived
Paycheck 1$2,500$2,500
Paycheck 2$2,500$0
HousingPlannedBalance
Mortgage / Rent$1,500$1,500
Utilities$250$175
`; } function authPage(mode) { const register = mode === 'sign-up'; const recover = mode === 'forgot-password'; const title = register ? 'Create your account' : recover ? 'Reset your password' : 'Welcome back'; const intro = register ? 'Start telling every dollar where to go.' : recover ? 'Enter your email to preview the recovery flow.' : 'Sign in to continue to your budget.'; root.innerHTML = `
${mark()}

Make progress with a plan for every dollar.

A simple monthly budget helps you spend with confidence, save intentionally and stay focused on what matters.

${wordmark()}

${title}

${intro}

${register?'
':''}
${recover?'':`
`}${register?'':''}

This is an isolated local recreation. It never sends email or contacts EveryDollar.

`; } const PREMIUM_NAV = new Set(['roadmap','planning','insights']); function sidebar(active='budget') { const main = [['budget','Budget','/app/budget'],['goals','Goals','/app/goals'],['roadmap','Roadmap','/app/roadmap'],['planning','Paycheck Planning','/app/paycheck-planning'],['insights','Insights','/app/insights'],['learn','Learn to Budget','/app/learn'],['trusted','RamseyTrusted','/app/localproviders'],['coaching','Coaching','/app/coaching']]; const lower = [['feed','My Feed','/app/my-feed'],['help','Help Center','/app/help'],['settings','Settings','/app/settings'],['signout','Sign out','/app/sign-out']]; const links = list => list.map(([id,label,path]) => `${icons[id]}${label}${PREMIUM_NAV.has(id)?'✦':''}${id==='coaching'?'':''}`).join(''); const account = state.data?.account; const display = account?.display_name || 'Local Budgeter'; const email = account?.email_normalized || 'Preview mode'; return ``; } async function loadData(month=state.month) { const query = month ? `?month=${encodeURIComponent(month)}` : ''; state.data = await api(`/api/bootstrap${query}`); state.month = state.data.month; return state.data; } function monthLabel(month) { const [year, m] = month.split('-').map(Number); return new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric',timeZone:'UTC'}).format(new Date(Date.UTC(year,m-1,1))); } function shiftMonth(month, delta) { const [year,m] = month.split('-').map(Number); const value = new Date(Date.UTC(year,m-1+delta,1)); return `${value.getUTCFullYear()}-${String(value.getUTCMonth()+1).padStart(2,'0')}`; } function statusMarkup(summary) { const left = Number(summary.left_to_budget); if (Math.abs(left) < .005) return '
✓ It’s an EveryDollar Budget!
'; if (left > 0) return `
● ${money(left)} left to budget
`; return `
! ${money(Math.abs(left))} over budget
`; } function groupMarkup(group) { const income = group.name === 'Income'; const actualLabel = income ? 'Received' : 'Remaining'; const items = group.items.map(item => `
${money(income?item.actual:item.remaining,state.data.preferences.whole_numbers)}
`).join(''); const editing = state.editingGroup === group.name ? `
` : ''; return `
${esc(group.name)}${income?` for ${monthLabel(state.month).split(' ')[0]}`:''}
Planned${actualLabel}
${items || '
No budget items yet.
'}${editing}
${money(group.planned,state.data.preferences.whole_numbers)}${money(income?group.actual:group.remaining,state.data.preferences.whole_numbers)}
`; } function summaryPanel() { const summary = state.data.summary; const expenseGroups = state.data.groups.filter(group => group.name !== 'Income' && group.planned > 0); const total = Math.max(1, summary.planned); let cursor = 0; const stops = expenseGroups.map(group => { const start=cursor; cursor += group.planned/total*360; return `${group.color} ${start}deg ${Math.min(360,cursor)}deg`; }); const donut = stops.length ? `conic-gradient(${stops.join(',')})` : '#e3e8ea'; return `
INCOME${money(summary.income,true)}
${expenseGroups.map(group => { const value = state.summaryMode==='planned'?group.planned:state.summaryMode==='spent'?group.actual:group.remaining; const pct = summary.planned ? Math.round(group.planned/summary.planned*100):0; return `
${esc(group.name)}${money(value,state.data.preferences.whole_numbers)}(${pct}%)
`; }).join('') || '
Add planned expenses to build your summary.
'}
Left to Budget${money(summary.left_to_budget)}
`; } function transactionsPanel() { const rows = state.data.transactions; return `

Transactions

${rows.length?`
${rows.map(row=>`
${esc(row.merchant)}${row.kind==='income'?'+':'−'}${money(row.amount)}
${esc(row.date)} · ${esc(row.account_name)}${row.item_id?' · Tracked':''}
·
`).join('')}
`:'
↔

No transactions yet

Add an expense or income transaction and assign it to a budget item.

'}
`; } function accountsPanel() { return `
▣

Connect your accounts

EveryDollar Premium can stream bank transactions into your budget. In this offline recreation, you can inspect the choices without entering bank credentials.

No account numbers, credentials or external connection will be requested.

`; } function itemPanel(item) { return `
${money(item.remaining)}Remaining
PLANNED${money(item.planned)}
SPENT${money(item.actual)}
REMAINING${money(item.remaining)}
`; } function rightPanel() { let content; const item = state.detailItem && state.data.groups.flatMap(group=>group.items).find(candidate=>candidate.id===state.detailItem); if (item) content = itemPanel(item); else if (state.panel === 'transactions') content = transactionsPanel(); else if (state.panel === 'accounts') content = accountsPanel(); else content = summaryPanel(); return ``; } function budgetPage() { const summary = state.data.summary; root.innerHTML = `
${sidebar('budget')}

${monthLabel(state.month)}

${statusMarkup(summary)}
${state.data.groups.map(groupMarkup).join('')}
${rightPanel()}
`; } function transactionModal(defaultItem='', transaction=null) { const items = state.data.groups.flatMap(group=>group.items.map(item=>({...item,group:group.name}))); const kind=transaction?.kind || 'expense', selected=transaction?.item_id || defaultItem; modalRoot.innerHTML = ``; } function customItemModal() { modalRoot.innerHTML = ``; } function bankModal() { modalRoot.innerHTML = ``; } function pageShell(active, content) { root.innerHTML = `
${sidebar(active)}
${content}
`; } function transactionsPage() { const rows = state.data.transactions; pageShell('transactions', `

Transactions

Track spending and income for ${monthLabel(state.month)}.

${rows.length?rows.map(row=>`
${esc(row.merchant)}${row.kind==='income'?'+':'−'}${money(row.amount)}
${esc(row.date)} · ${esc(row.account_name)}
·
`).join(''):'

No tracked transactions

Add a manual transaction to begin tracking your budget.

'}
`); } function goalsPage() { pageShell('goals', `

Goals

Save toward what matters and track your progress.

${state.data.goals.map(goal=>`
TARGET ${esc(goal.target_month)}

${esc(goal.label)}

${money(goal.saved)} of ${money(goal.target)}

`).join('') || '

No goals yet

Create a savings or debt goal to see it here.

'}

Create a Goal

`); } function insightsPage() { const summary = state.data.summary; const params = new URLSearchParams(location.search); const category = params.get('category') || ''; const allGroups = state.data.groups.filter(group=>group.name!=='Income'); const groups = category ? allGroups.filter(group=>group.name===category) : allGroups; pageShell('insights', `

Insights

Your ${monthLabel(state.month)} budget at a glance.

TOTAL INCOME

${money(summary.income)}

${money(summary.planned)} planned

${money(summary.spent)} spent

${money(summary.remaining)} remaining

${groups.map(group=>``).join('')}

Budget Summary

${groups.map(group=>`
${esc(group.name)}${money(group.planned)} planned · ${money(group.actual)} spent
`).join('') || '

No categories match this report filter.

'}
`); } function settingsPage() { const prefs = state.data.preferences; const account = state.data.account; pageShell('settings', `

Settings

Profile

${esc(account?.display_name || 'Local Budgeter')}
${esc(account?.email_normalized || 'Preview mode · Sign in to attach this budget to a local account')}

${account?'':'Sign In'}

Budget Preferences

${[['reminders','Budget reminders'],['weekly_summary','Weekly summary'],['safe_to_spend','Safe to Spend'],['whole_numbers','Display whole numbers']].map(([key,label])=>`
${label}Saved only in this local EveryDollar site.
`).join('')}

Subscription

EveryDollar Free · Local benchmark preview

No payment details are collected and no subscription is changed.

`); } function helpPage() { const query = new URLSearchParams(location.search).get('q') || ''; const topics = [ ['Getting Started','Enter income, plan expenses and work toward a zero-based budget.'], ['Budget Items','Add, edit, reorder and track planned amounts within a group.'], ['Transactions','Add a manual expense or income and assign it to the right item.'], ['Account Access','Use the local sign-in, registration and no-send recovery pages.'], ['Monthly Budgets','Move between months and copy planned values forward.'], ['Contact Support','This offline recreation does not submit support requests.'] ]; const terms=query.toLowerCase().trim().split(/\s+/).filter(Boolean); const matches=topics.filter(row=>terms.every(term=>row.join(' ').toLowerCase().includes(term))); pageShell('help', `

How can we help?

${matches.length?`
${matches.map(([title,body])=>`

${esc(title)}

${esc(body)}

`).join('')}
`:`

No results found

No local help matched “${esc(query)}”. Try another budgeting topic.

Back to Budget
`}`); } function notFoundPage() { root.innerHTML = `
${sidebar('')}

404

That page wandered off budget.

Let’s get you back to telling every dollar where to go.

Return to Budget
`; } const TRIAL_BAR = `
Try this premium feature—and more.
`; function premiumHead(id, label, heading, body) { return `
${icons[id]}${esc(label)}
✦ Premium

${esc(heading)}

${esc(body)}

`; } function roadmapPage() { pageShell('roadmap', `
${premiumHead('roadmap','Financial Roadmap','Get a plan for your entire money future.','From your starter emergency fund to millionaire status, see how your decisions today can pay off big in the future.')}
${[1,2,3,'3b',4,5,6,7].map((n,i)=>`${n}`).join('')}
Estimated Millionaire Year · Projected Net Worth: $1.8 Million
${TRIAL_BAR}
`); } function paycheckPlanningPage() { const quotes = [ ['Paycheck planning has changed the way I view my spending on a week-by-week basis. It is super helpful to project and see where my finances are headed each month.','Brittany'], ['The paycheck planning feature is EXACTLY what I have been looking for. It allows me to plan and view a timeline of spending and what will be available at any given day of the month. Love it!','Terry'], ['Paycheck planning provides peace of mind knowing the exact money flow in our budget - exceptional tool for budgeting!','Michael'] ]; pageShell('planning', `
${premiumHead('planning','Paycheck Planning','Know when it is safe to spend throughout the month.','Set your pay and spending schedules, prepare for upcoming expenses, and know exactly how much money you have.')}
${quotes.map(([q,who])=>`

${esc(q)}

${esc(who)}
★★★★★
`).join('')}
${TRIAL_BAR}
`); } function ramseyTrustedPage() { const popular = [ ['Home & Auto Insurance','Save big when you bundle home and auto insurance.'], ['Last Will & Testament','Create your will online. No legal jargon. No hourly fees.'], ['Term Life Insurance','Term life insurance is the safest choice when it comes to protecting your family future.'], ['Investing & Retirement','Get recommendations for up to five investing pros.'] ]; pageShell('trusted', `

Ramsey Pros

Top-notch service providers to help you navigate life big and small financial decisions. Fully vetted by our team.

Start Here 👋

Most Popular ✨

${popular.map(([t,d])=>`

${t}

${d}

`).join('')}
`); } function learnPage2() { const groups = [ ['Welcome 👋','Let us go over some basics to get started.',[['How to Budget with EveryDollar','4 min'],['What is a Zero-Based Budget?','3 min'],['Building the Habit of Budgeting','3 min']]], ['Personalize Your Budget ✏️','Learn how to use EveryDollar to fit your needs.',[['How to Set Up Sinking Funds','1 min'],['Budgeting With Irregular Income','4 min'],['How to Set Up Due Dates with EveryDollar','1 min']]] ]; const tips = [['How to Track Transactions','1 min'],['How to Use Sinking Funds','1 min'],['How to use Financial Roadmap','1 min'],['How to use Personal Goals','1 min'],['How to Budget an Irregular Income','2 min'],['How to Use Paycheck Planning','1 min']]; pageShell('learn', `

Learn to Budget

${groups.map(([t,d,rows])=>`

${t}

${d}

0/${rows.length}
${rows.map(([n,m])=>``).join('')}
`).join('')}
✨ Customize your budget even more with premium.

Quick Pro Tips

${tips.map(([n,m])=>``).join('')}
`); } function coachingPage() { const times = ['Sep 1, 12 PM CT','Sep 3, 12 PM CT','Sep 8, 12 PM CT','Sep 10, 12 PM CT','Sep 15, 12 PM CT']; pageShell('coaching', `

Free Budget Help and EveryDollar Coaching

New to budgeting? Got questions about the app? You are in the right place. Join a free, live workshop and start feeling more confident budgeting with EveryDollar.

Upcoming free workshops

${times.map(t=>``).join('')}

On the live site this control opens ramseysolutions.com. This offline recreation keeps the destination local and never contacts Ramsey.

`); } function myFeedPage() { pageShell('feed', `

My Feed

Surface not captured

The live EveryDollar account menu exposes My Feed, but its contents could not be captured during source acquisition: an interstitial dialog blocked access on every attempt. This route exists so the navigation control resolves, and deliberately does not invent feed content.

Back to Budget
`); } async function render() { const path = location.pathname; modalRoot.innerHTML = ''; if (path === '/app/sign-out') { try { await api('/api/auth/logout',{method:'POST',body:'{}'}); } catch (e) {} state.data=null; history.replaceState({},'','/money/everydollar'); marketingPage(); showToast('Signed out'); return; } if (path === '/' || path === '/money/everydollar') { marketingPage(); return; } if (LEGAL_PAGES[path]) { legalPage(path); return; } if (path === '/app/sign-in') { authPage('sign-in'); return; } if (path === '/app/sign-up') { authPage('sign-up'); return; } if (path === '/app/forgot-password') { authPage('forgot-password'); return; } if (path === '/app' || path === '/app/') { history.replaceState({},'', '/app/budget'); } const reportMonth = path === '/app/insights' ? new URLSearchParams(location.search).get('month') : null; try { await loadData(reportMonth || state.month); } catch (error) { root.innerHTML = `

We hit a snag.

${esc(error.message)}

`; return; } if (location.pathname === '/app/budget') budgetPage(); else if (location.pathname === '/app/transactions') transactionsPage(); else if (location.pathname === '/app/goals') goalsPage(); else if (location.pathname === '/app/insights') insightsPage(); else if (location.pathname === '/app/settings') settingsPage(); else if (location.pathname === '/app/help') helpPage(); else if (location.pathname === '/app/roadmap') roadmapPage(); else if (location.pathname === '/app/paycheck-planning') paycheckPlanningPage(); else if (location.pathname === '/app/localproviders') ramseyTrustedPage(); else if (location.pathname === '/app/learn') learnPage2(); else if (location.pathname === '/app/coaching') coachingPage(); else if (location.pathname === '/app/my-feed') myFeedPage(); else notFoundPage(); } document.addEventListener('click', event => { const proCheck = event.target.closest('[data-pro-checkup]'); if (proCheck) { showToast('The Coverage Checkup is not part of this offline recreation.'); return; } const watchRec = event.target.closest('[data-watch-recording]'); if (watchRec) { showToast('No recording is streamed by this offline recreation.'); return; } const lesson = event.target.closest('[data-lesson]'); if (lesson) { showToast(`“${lesson.dataset.lesson}” is catalogued here; lesson video is not included.`); return; } const session = event.target.closest('[data-session]'); if (session) { showToast(`${session.dataset.session} — this recreation does not register you for workshops.`); return; } }); document.addEventListener('click', async event => { const link = event.target.closest('a[href]'); if (link && link.origin === location.origin && !link.hash) { event.preventDefault(); go(link.pathname + link.search); return; } if (event.target.closest('[data-retry]')) { render(); return; } const shift = event.target.closest('[data-month-shift]'); if (shift) { state.month = shiftMonth(state.month, Number(shift.dataset.monthShift)); await loadData(state.month); budgetPage(); return; } const add = event.target.closest('[data-add-item]'); if (add) { state.editingGroup = add.dataset.addItem; budgetPage(); document.querySelector('[data-new-item-form] input')?.focus(); return; } const planned = event.target.closest('[data-planned-item]'); if (planned) return; const itemButton = event.target.closest('[data-open-item]'); if (itemButton) { state.detailItem = itemButton.dataset.openItem; state.mobilePanel = true; budgetPage(); return; } if (event.target.closest('[data-close-item]')) { state.detailItem = null; budgetPage(); return; } const panel = event.target.closest('[data-panel]'); if (panel) { state.panel = panel.dataset.panel; state.detailItem = null; state.mobilePanel = true; budgetPage(); return; } const summaryMode = event.target.closest('[data-summary-mode]'); if (summaryMode) { state.summaryMode = summaryMode.dataset.summaryMode; budgetPage(); return; } const openTransaction = event.target.closest('[data-open-transaction]'); if (openTransaction) { transactionModal(openTransaction.dataset.openTransaction || ''); return; } const editTransaction = event.target.closest('[data-edit-transaction]'); if (editTransaction) { const row=state.data.transactions.find(item=>item.id===editTransaction.dataset.editTransaction); transactionModal(row?.item_id||'',row); return; } if (event.target.closest('[data-open-bank]')) { bankModal(); return; } if (event.target.closest('[data-add-custom]')) { customItemModal(); return; } if (event.target.matches('[data-close-modal]')) { modalRoot.innerHTML=''; return; } if (event.target.closest('[data-preview-bank]')) { document.querySelector('#modal-error').textContent='Connection preview complete. No external bank window was opened.'; return; } if (event.target.closest('[data-preview-subscription]')) { showToast('Subscription preview only—no payment action was taken.'); return; } const transactionKind = event.target.closest('[data-transaction-kind]'); if (transactionKind) { document.querySelectorAll('[data-transaction-kind]').forEach(button=>button.classList.toggle('active',button===transactionKind)); const form = document.querySelector('#transaction-form'); form.elements.kind.value=transactionKind.dataset.transactionKind; document.querySelector('#transaction-title').textContent = transactionKind.dataset.transactionKind==='income'?'Add Income':'Add Expense'; form.querySelector('button[type=submit]').textContent = transactionKind.dataset.transactionKind==='income'?'Add Income':'Add Expense'; return; } const deleteTransaction = event.target.closest('[data-delete-transaction]'); if (deleteTransaction) { if (confirm('Delete this transaction?')) { state.data=await api(`/api/transactions/${deleteTransaction.dataset.deleteTransaction}`,{method:'DELETE'}); showToast('Transaction deleted'); render(); } return; } const deleteItem = event.target.closest('[data-delete-item]'); if (deleteItem) { if (confirm('Delete this budget item?')) { state.data=await api(`/api/budget/items/${deleteItem.dataset.deleteItem}`,{method:'DELETE'}); state.detailItem=null; showToast('Budget item deleted'); budgetPage(); } return; } const favorite = event.target.closest('[data-toggle-favorite]'); if (favorite) { const item=state.data.groups.flatMap(g=>g.items).find(x=>x.id===favorite.dataset.toggleFavorite); state.data=await api(`/api/budget/items/${item.id}`,{method:'PATCH',body:JSON.stringify({favorite:!item.favorite})}); showToast(item.favorite?'Removed from favorites':'Added to favorites'); budgetPage(); return; } if (event.target.closest('[data-mobile-panel]')) { state.mobilePanel=true; budgetPage(); return; } const moveItem = event.target.closest('[data-move-item]'); if (moveItem) { state.data=await api(`/api/budget/items/${moveItem.dataset.moveItem}/move`,{method:'POST',body:JSON.stringify({direction:moveItem.dataset.direction})}); showToast(`Budget item moved ${moveItem.dataset.direction}`); budgetPage(); return; } const goalProgress = event.target.closest('[data-goal-progress]'); if (goalProgress) { const goal=state.data.goals.find(item=>item.id===goalProgress.dataset.goalProgress); state.data=await api(`/api/goals/${goal.id}`,{method:'PATCH',body:JSON.stringify({saved:goal.saved+50})}); showToast('Goal progress updated'); goalsPage(); return; } if (event.target.closest('[data-copy-prior]')) { const source=shiftMonth(state.month,-1); try { state.data=await api('/api/months/copy',{method:'POST',body:JSON.stringify({source,target:state.month})}); showToast(`Copied planned values from ${monthLabel(source)}`); budgetPage(); } catch(error){showToast(error.message)} return; } const pref = event.target.closest('[data-pref]'); if (pref) { const next={...state.data.preferences,[pref.dataset.pref]:!state.data.preferences[pref.dataset.pref]}; state.data=await api('/api/preferences',{method:'POST',body:JSON.stringify(next)}); settingsPage(); showToast('Preference saved'); return; } if (event.target.closest('[data-logout]')) { await api('/api/auth/logout',{method:'POST',body:'{}'}); state.data=null; showToast('Signed out'); go('/app/sign-in'); } }); document.addEventListener('change', async event => { const input = event.target.closest('[data-planned-item]'); if (input) { try { state.data=await api(`/api/budget/items/${input.dataset.plannedItem}`,{method:'PATCH',body:JSON.stringify({planned:Number(input.value)})}); showToast('Planned amount saved'); budgetPage(); } catch(error){showToast(error.message)} return; } const notes = event.target.closest('[data-item-notes]'); if (notes) { state.data=await api(`/api/budget/items/${notes.dataset.itemNotes}`,{method:'PATCH',body:JSON.stringify({notes:notes.value})}); showToast('Note saved'); } const label = event.target.closest('[data-item-label]'); if (label) { state.data=await api(`/api/budget/items/${label.dataset.itemLabel}`,{method:'PATCH',body:JSON.stringify({label:label.value})}); showToast('Budget item renamed'); budgetPage(); } }); document.addEventListener('submit', async event => { event.preventDefault(); const form = event.target; if (form.id === 'auth-form') { const body=Object.fromEntries(new FormData(form)); const error=form.querySelector('#auth-error'); error.textContent=''; const recover=location.pathname.endsWith('forgot-password'); const register=location.pathname.endsWith('sign-up'); try { const result=await api(recover?'/api/auth/recovery-preview':register?'/api/auth/register':'/api/auth/login',{method:'POST',body:JSON.stringify(body)}); if(recover){error.style.color='#25834c';error.textContent=result.message}else{showToast(register?'Account created':'Signed in');go('/app/budget')}} catch(exc){error.textContent=exc.message} return; } if (form.matches('[data-new-item-form]')) { const body=Object.fromEntries(new FormData(form)); body.group=form.dataset.newItemForm; body.month=state.month; try { state.data=await api('/api/budget/items',{method:'POST',body:JSON.stringify(body)}); state.editingGroup=null; showToast(`${body.label} added`); budgetPage(); } catch(exc){showToast(exc.message)} return; } if (form.id === 'custom-item-form') { const body=Object.fromEntries(new FormData(form)); body.month=state.month; try { state.data=await api('/api/budget/items',{method:'POST',body:JSON.stringify(body)}); modalRoot.innerHTML=''; showToast(`${body.label} added`); budgetPage(); } catch(exc){form.querySelector('#modal-error').textContent=exc.message} return; } if (form.id === 'transaction-form') { const body=Object.fromEntries(new FormData(form)); body.month=state.month; const transactionId=form.dataset.transactionId; try { state.data=await api(transactionId?`/api/transactions/${transactionId}`:'/api/transactions',{method:transactionId?'PATCH':'POST',body:JSON.stringify(body)}); modalRoot.innerHTML=''; showToast(`${body.kind==='income'?'Income':'Expense'} ${transactionId?'updated':'added'}`); location.pathname==='/app/budget'?budgetPage():transactionsPage(); } catch(exc){form.querySelector('#modal-error').textContent=exc.message} return; } if (form.id === 'goal-form') { const body=Object.fromEntries(new FormData(form)); try { state.data=await api('/api/goals',{method:'POST',body:JSON.stringify(body)}); showToast('Goal created'); goalsPage(); } catch(exc){form.querySelector('#goal-error').textContent=exc.message} return; } if (form.id === 'help-search') { const q=new FormData(form).get('q'); go(`/app/help?q=${encodeURIComponent(q)}`); } if (form.id === 'report-filters') { const data=new FormData(form); go(`/app/insights?${new URLSearchParams(data).toString()}`); } }); window.addEventListener('popstate', render); document.addEventListener('keydown', event => { if(event.key==='Escape' && modalRoot.innerHTML) modalRoot.innerHTML=''; }); render();