🇨🇦 Licensed in Ontario, Canada
W
I
Z
Wisdom · Integrity · Zeal
Free Tools for Canadians

Free Financial Calculators
for Canadians.

Compound growth · RESP · CAGR · Goal planning 6 free tools. No sign-up required.

🧮 6 Calculators 🇨🇦 Built for Canada ✅ 100% Free
Choose a Calculator — Select a tool below to get started
Investment Calculator
See how monthly contributions and/or a lump sum grow over time. Set monthly to $0 for lump sum only, or set lump sum to $0 for monthly only.
Starting Lump Sum $0
$
One-time deposit on day 1. Set $0 if not using.
Monthly Investment $500
$
Set $0 for lump sum only.
Annual Return Rate 10%
%
Time Period 20 years
yrs
Projected Outcome
Total Value
$378,016
Total Invested
$120,000
Gains from Compounding
$258,016
215% return on investment
How your money breaks down
Invested
32%
Growth
68%
Portfolio Growth Over Time
For illustrative purposes only. Returns are not guaranteed. Actual market returns vary and may be higher or lower than the assumed rate. Always do your own research before investing. Shivang Goyal does not guarantee the accuracy of these projections and accepts no responsibility or liability for financial decisions made based on this calculator. This tool does not constitute financial, tax, or legal advice.
Looking to learn more about this setup? Learn More →
Goal Planner
How much do you need to invest monthly to reach a specific goal?
Target Amount $500,000
$
Annual Return Rate 10%
%
Time to Goal 20 years
yrs
What You Need to Invest
Monthly Contribution Needed
$662
To reach your goal
Total You'll Invest
$158,832
Gained from Markets
$341,168
68% of your goal comes from compounding
Monthly Contribution Needed vs Time
For illustrative purposes only. Returns are not guaranteed. Assumes consistent monthly contributions and a fixed annual return rate. Shivang Goyal does not guarantee the accuracy of these projections and accepts no responsibility or liability for financial decisions made based on this calculator. This tool does not constitute financial, tax, or legal advice.
Looking to learn more about this setup? Learn More →
Withdrawal Planner
How long will your portfolio last if you withdraw a fixed amount each month?
Starting Portfolio Value $500,000
$
Monthly Withdrawal $2,000
$
Annual Return Rate 7%
%
Portfolio Longevity
Portfolio Lasts
Indefinitely
Your returns exceed withdrawals
Total Withdrawn
$240,000+
Annual Withdrawal Rate
4.8%
The 4% rule is a common safe withdrawal guideline
Portfolio Balance Over Time
For illustrative purposes only. Withdrawal sustainability depends on market returns, inflation, and actual portfolio performance. Consult a financial advisor for retirement planning. Shivang Goyal does not guarantee the accuracy of these projections and accepts no responsibility or liability for financial decisions made based on this calculator. This tool does not constitute financial, tax, or legal advice.
CAGR Calculator
Calculate the Compound Annual Growth Rate of any investment — or find out what a position is worth at a given CAGR.
Initial Investment $10,000
$
Final Value $50,000
$
Years Held 10 years
yrs
Result
Compound Annual Growth Rate
17.46%
Total Return
400%
Gain
$40,000
Over 10 years
CAGR shows smoothed annual return and does not reflect year-to-year volatility. For illustrative purposes only. Shivang Goyal does not guarantee the accuracy of these projections and accepts no responsibility or liability for financial decisions made based on this calculator. This tool does not constitute financial, tax, or legal advice.
🇨🇦 RESP Calculator ADVANCED
Automatically calculates CESG and CLB government grants based on your child's date of birth. Enter your contribution plan to see projected growth by age 18.
📋 Your RESP Details
Enter your child's info — grants calculate automatically
Child's Date of Birth Age: —
Used to calculate grant eligibility. CESG grant room accumulates every year age 0–17. Catch-up grants available for missed years.
Add one or more periods with different amounts & frequencies — e.g. high contributions early, then lower later.
Periods run in order. $2,500/yr per period gets full $500 grant. Lifetime max $50,000. Tip: on phone, tap the month/year header in the calendar to jump to any year.
Add lump sum contribution?
One-time deposit at account opening
Lump Sum Amount
$
Applied in year 1 alongside your regular contribution. Both count toward the lifetime $50,000 limit.
Eligible for Canada Learning Bond (CLB)?
Low-income families — up to $2,000, no contribution needed
Annual Return Rate 10%
%
Projected Outcome at Age 18
Total Portfolio Value
$—
When your child is ready for post-secondary
Your Contributions
$—
Govt. Grants (CESG + CLB)
$—
CESG + CLB grants
Investment Growth
$—
Compounding returns
Total Invested
$—
Before market growth
🏛️ Government Grants Tracker
Canada Education Savings Grant (CESG)
Projected total CESG received $—
Lifetime CESG limit $7,200
Remaining CESG available $—
0% of lifetime grant used $7,200 max
Total govt. grants projected $—
Contribution limit used —
of $50,000 lifetime limit $50,000 max
Growth Over Time
Contributions
Grants
Portfolio Value
Year-by-Year Breakdown
Scroll to see all years
Year Age Your Contribution CESG Grant Year Total Balance (End of Year) Growth (Cumulative)
📋 RESP Grant Rules Reference Show / Hide
Annual CESG Grant
20% of $2,500
$500/yr max per child
Lifetime CESG Max
$7,200
Total govt. grants ever
Grant Cutoff
Age 17
CESG room stops Dec 31 of year child turns 17
Contribution Limit
$50,000
Lifetime per beneficiary
Catch-Up Grants
$1,000/yr
Contribute $5,000 to use prior unused room
Account Closes By
35 yrs after opening
Dec 31 of the 35th year
For illustrative and educational purposes only. RESP rules, grant amounts, and eligibility may change. Results assume contributions at the start of each year and a fixed annual return rate. Actual returns will vary. Enhanced CESG grants based on family income are not included. Consult a financial advisor for personalized RESP advice. Shivang Goyal does not guarantee the accuracy of these projections and accepts no responsibility or liability for financial decisions made based on this calculator. This tool does not constitute financial, tax, or legal advice.
Looking to learn more about this setup? Learn More →
Shivang Goyal
Licensed Insurance Advisor (LLQP)  ·  Ontario
(647) 995-5891  ·  shivang.goyal.financial@gmail.com
wizinsurance.ca
Life Insurance Needs Analysis
Prepared for client review  ·  wizinsurance.ca
${clientName}
Shivang Goyal
Recommended Life Insurance Coverage
${totalCoverage}
${isShortfall ? 'Existing assets already cover estimated needs — strong financial position.' : 'Estimated coverage gap based on information provided. Subject to underwriting approval.'}
Cash Needs
${cashNeeds}
Income (PV)
${incomeNeeds}
Less Assets
−${assetsTotal}
Inputs Used in This Analysis
💸 Cash Needs
Mortgage / debt${fmt(mortgage)}
Funeral & estate${fmt(funeral)}
Emergency fund${fmt(emergency)}
Education fund${fmt(education)}
Subtotal${cashNeeds}
💰 Income Replacement
Annual income${fmt(income)}
Replacement %${pct}%
Years of support${yrs} yrs
Expected return${ret}%
PV factor applied${pvFactor}
Subtotal (PV)${incomeNeeds}
✅ Assets to Deduct
Existing life insurance${fmt(ins)}
Group / employer coverage${fmt(grp)}
RRSPs / investments${fmt(rrsp)}
Savings / cash${fmt(savings)}
Already covered${assetsTotal}
${yrs} years
${pct}%
${ret}% / yr
${pvFactor}
Additional Coverage to Consider
🫀 Critical Illness Insurance
${ciAmount}
${ciMonthly > 0 ? `
Mortgage / rent${fmt(ciHousing)}/mo
Loans / credit cards${fmt(ciLoans)}/mo
RRSP / TFSA / RESP${fmt(ciSavingsInp)}/mo
Other expenses${fmt(ciOther)}/mo
× ${ciMonthsVal} mo + medical + wellness${ciMonthlyTotal} + $25,000
` : `
Tax-free lump sum on diagnosis of heart attack, cancer, stroke & more. Enter monthly commitments to calculate.
`}
🛡️ Disability Insurance
${diText}
Suggested monthly benefit · 70% of income, capped at $10,000/mo
Replaces income if illness or injury prevents you from working
Acknowledgement & Signature
Client Signature & Date
${clientName}
Advisor Signature & Date
Shivang Goyal  ·  LLQP
`; const win = window.open('', '_blank', 'width=900,height=700'); if (!win) { alert('Please allow pop-ups for this site to download the report.'); return; } win.document.write(html); win.document.close(); setTimeout(() => win.print(), 600); } // Hash routing — activate correct tab on page load based on URL anchor window.addEventListener('DOMContentLoaded', function(){ const hash = window.location.hash.replace('#',''); const validTabs = ['sip','resp','goal','swp','cagr']; if(hash && validTabs.includes(hash)) { document.querySelectorAll('.calc-tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.calc-panel').forEach(p => p.classList.remove('active')); const btn = document.querySelector('[onclick*="\''+hash+'\'"]'); if(btn) btn.classList.add('active'); const panel = document.getElementById('panel-'+hash); if(panel) panel.classList.add('active'); if(hash==='sip') { calcSIP(); } if(hash==='resp' && !respInitialized) { respInitialized = true; const today = new Date(); const y = today.getFullYear(); const m = String(today.getMonth()+1).padStart(2,'0'); const d = String(today.getDate()).padStart(2,'0'); const dob = document.getElementById('child-dob'); if(dob && !dob.value) dob.value = y+'-'+m+'-'+d; const sy = document.getElementById('start-year'); if(sy) sy.value = y; addContribRow(y+'-'+m+'-'+d, null, 'monthly', 208); setTimeout(() => calcRESP(), 0); } } else { // Default: sip tab is active switchTab && document.querySelector('[onclick*="\'sip\'"]') && document.querySelector('[onclick*="\'sip\'"]').click ? null : null; calcSIP(); } }); // (moved to top of script) function switchTab(id){ document.querySelectorAll('.calc-tab').forEach((t,i)=>t.classList.remove('active')); event.target.classList.add('active'); document.querySelectorAll('.calc-panel').forEach(p=>p.classList.remove('active')); document.getElementById('panel-'+id).classList.add('active'); // Init RESP on first open if(id==='resp' && !respInitialized){ respInitialized = true; const today = new Date(); const y = today.getFullYear(); const m = String(today.getMonth()+1).padStart(2,'0'); const d = String(today.getDate()).padStart(2,'0'); const dob = document.getElementById('child-dob'); if(dob && !dob.value) dob.value = y+'-'+m+'-'+d; const sy = document.getElementById('start-year'); if(sy) sy.value = y; const _ts = today.getFullYear()+'-'+m+'-'+d; addContribRow(_ts, null, 'monthly', 208); setTimeout(() => calcRESP(), 0); } // (needs tab removed — see needs-analysis.html) if(id==='resp'){ // Always show suggestions trigger when RESP tab is active setTimeout(()=>{ const t = document.getElementById('suggestions-trigger'); if(t) t.style.display = 'block'; }, 50); } // Re-render chart for the active tab — Chart.js can't measure hidden canvases; redraw after panel is visible setTimeout(()=>{ try{ if(id==='sip') { chartSIP(); } else if(id==='goal') { chartGoal(); } else if(id==='swp') { chartSWP(); } else if(id==='cagr') { /* no chart */ } }catch(e){ console.warn('Chart redraw:', e); } }, 100); } const fmt = n => n >= 1000000 ? '$'+(n/1000000).toFixed(2).replace(/\.?0+$/,'')+'M' : n >= 1000 ? '$'+(n/1000).toFixed(1).replace(/\.0$/,'')+'K' : '$'+Math.round(n).toLocaleString(); const fmtFull = n => '$'+Math.round(n).toLocaleString(); const syncRange = (inputId, rangeId, labelId, suffix) => { const v = parseFloat(document.getElementById(inputId).value)||0; const r = document.getElementById(rangeId); if(r) r.value = v; if(labelId) document.getElementById(labelId).textContent = suffix ? v+suffix : '$'+v.toLocaleString(); }; // ── SIP ── function calcSIP(){ const lump = parseFloat(document.getElementById('sip-lump')?.value)||0; const mo = parseFloat(document.getElementById('sip-amt').value)||0; const r = parseFloat(document.getElementById('sip-rate').value)||0; const yrs = parseInt(document.getElementById('sip-yrs').value)||0; // Sync display values if(document.getElementById('sip-lump-val')) document.getElementById('sip-lump-val').textContent = '$'+lump.toLocaleString(); document.getElementById('sip-amt-val').textContent = '$'+mo.toLocaleString(); document.getElementById('sip-rate-val').textContent = r+'%'; document.getElementById('sip-yrs-val').textContent = yrs+' year'+(yrs!==1?'s':''); // Sync sliders const lr = document.getElementById('sip-lump-r'); if(lr) lr.value = lump; const ar = document.getElementById('sip-amt-r'); if(ar) ar.value = mo; const n = yrs * 12; const mr = r / 100 / 12; // Lump sum grows at compound interest const lumpFV = lump * Math.pow(1 + mr, n); // Monthly contribution (annuity due — paid at start of period) const moFV = mr > 0 ? mo * ((Math.pow(1+mr,n)-1)/mr) * (1+mr) : mo * n; const total = lumpFV + moFV; const invested = lump + mo * n; const gain = total - invested; const pct = invested > 0 ? (gain/invested*100).toFixed(0) : 0; const invPct = total > 0 ? Math.round(invested/total*100) : 0; const gainPct = 100 - invPct; document.getElementById('sip-total').textContent = fmtFull(total); document.getElementById('sip-invested').textContent = fmtFull(invested); document.getElementById('sip-gain').textContent = '+'+fmtFull(gain); document.getElementById('sip-gain-pct').textContent = pct+'% return on investment'; document.getElementById('sip-bar-inv').style.width = invPct+'%'; document.getElementById('sip-bar-gain').style.width = gainPct+'%'; document.getElementById('sip-bar-inv-t').textContent = invPct+'%'; document.getElementById('sip-bar-gain-t').textContent = gainPct+'%'; // Chart const labels=[], invested_arr=[], total_arr=[], lump_arr=[]; for(let i=0;i<=yrs;i++){ const ni=i*12, mri=mr; const lfv=lump*Math.pow(1+mri,ni); const mfv=mri>0?mo*((Math.pow(1+mri,ni)-1)/mri)*(1+mri):mo*ni; labels.push(i===0?'Now':'Yr '+i); lump_arr.push(Math.round(lfv)); total_arr.push(Math.round(lfv+mfv)); invested_arr.push(Math.round(lump+mo*i*12)); } makeChart('chart-sip', labels, [ {label:'Portfolio Value',data:total_arr,borderColor:'#E63946',backgroundColor:'rgba(230,57,70,0.08)',fill:true,tension:0.3,pointRadius:0,borderWidth:2}, {label:'Invested',data:invested_arr,borderColor:'rgba(255,255,255,0.2)',backgroundColor:'transparent',fill:false,tension:0.3,pointRadius:0,borderWidth:1,borderDash:[4,4]} ]); } try{calcSIP();}catch(e){console.warn('calcSIP init:',e);} // ── LUMP SUM ── function calcLS(){ const p = parseFloat(document.getElementById('ls-amt').value)||0; const r = parseFloat(document.getElementById('ls-rate').value)||0; const y = parseInt(document.getElementById('ls-yrs').value)||0; document.getElementById('ls-amt-val').textContent = '$'+p.toLocaleString(); document.getElementById('ls-rate-val').textContent = r+'%'; document.getElementById('ls-yrs-val').textContent = y+' year'+(y!==1?'s':''); const total = p * Math.pow(1+r/100, y); const gain = total - p; const pct = p > 0 ? (gain/p*100).toFixed(0) : 0; const invPct = Math.round(p/total*100); document.getElementById('ls-total').textContent = fmtFull(total); document.getElementById('ls-invested').textContent = fmtFull(p); document.getElementById('ls-gain').textContent = '+'+fmtFull(gain); document.getElementById('ls-gain-pct').textContent = pct+'% return on investment'; document.getElementById('ls-bar-inv').style.width = invPct+'%'; document.getElementById('ls-bar-gain').style.width = (100-invPct)+'%'; document.getElementById('ls-bar-inv-t').textContent = invPct+'%'; document.getElementById('ls-bar-gain-t').textContent = (100-invPct)+'%'; } try{calcLS();}catch(e){console.warn("calcLS init:",e);} // ── GOAL ── function calcGoal(){ const target = parseFloat(document.getElementById('goal-target').value)||0; const r = parseFloat(document.getElementById('goal-rate').value)||0; const y = parseInt(document.getElementById('goal-yrs').value)||0; document.getElementById('goal-target-val').textContent = '$'+target.toLocaleString(); document.getElementById('goal-rate-val').textContent = r+'%'; document.getElementById('goal-yrs-val').textContent = y+' year'+(y!==1?'s':''); const n = y*12, mr = r/100/12; const mo = mr > 0 ? target * mr / ((Math.pow(1+mr,n)-1) * (1+mr)) : target/n; const invested = mo * n; const gain = target - invested; const gainPct = target > 0 ? Math.round(gain/target*100) : 0; document.getElementById('goal-monthly').textContent = fmtFull(mo); document.getElementById('goal-total-invested').textContent = fmtFull(invested); document.getElementById('goal-gain').textContent = '+'+fmtFull(gain); document.getElementById('goal-pct').textContent = gainPct+'% of your goal comes from compounding'; } try{calcGoal();}catch(e){console.warn("calcGoal init:",e);} // ── SWP ── function calcSWP(){ const start=parseFloat(document.getElementById('swp-start').value)||0; const mo=parseFloat(document.getElementById('swp-amt').value)||0; const r=parseFloat(document.getElementById('swp-rate').value)||0; document.getElementById('swp-start-val').textContent='$'+Math.round(start).toLocaleString(); document.getElementById('swp-amt-val').textContent='$'+Math.round(mo).toLocaleString(); document.getElementById('swp-rate-val').textContent=r+'%'; const mr=r/100/12; const annualRate=start>0?mo*12/start*100:0; document.getElementById('swp-rate-show').textContent=annualRate.toFixed(1)+'%'; document.getElementById('swp-rate-note').textContent=annualRate<=4?'✔ Below 4% — generally considered sustainable':annualRate<=6?'⚠ Moderate withdrawal rate — monitor portfolio':'⚠ High rate — portfolio may deplete faster'; if(mr>0&&mo<=start*mr){ document.getElementById('swp-duration').textContent='Indefinitely'; document.getElementById('swp-note').textContent='At this rate your portfolio grows faster than you withdraw.'; document.getElementById('swp-total').textContent='—'; chartSWP(start,mo,r,600,true); return; } let bal=start,months=0,totalWithdrawn=0; while(bal>0&&months<1200){ const growth=bal*mr; const withdraw=Math.min(mo,bal+growth); bal=bal+growth-withdraw; totalWithdrawn+=withdraw; months++; if(bal<=0.01){bal=0;break;} } const yrs=Math.floor(months/12),mos=months%12; const durStr=months>=1200?'Very long':yrs>0&&mos>0?yrs+' yr'+(yrs!==1?'s':'')+' '+mos+' mo':yrs>0?yrs+' yr'+(yrs!==1?'s':''):mos+' mo'; document.getElementById('swp-duration').textContent=durStr; document.getElementById('swp-note').textContent=months>=1200?'Portfolio lasts beyond 100 years':'Before portfolio is depleted'; document.getElementById('swp-total').textContent='$'+Math.round(totalWithdrawn).toLocaleString(); chartSWP(start,mo,r,months+6,false); } try{calcSWP();}catch(e){console.warn("calcSWP init:",e);} // ── CAGR ── var cagrMode = 'calc'; function setCagrMode(mode){ cagrMode = mode; document.getElementById('cagr-calc-inputs').style.display = mode==='calc' ? 'block' : 'none'; document.getElementById('cagr-proj-inputs').style.display = mode==='proj' ? 'block' : 'none'; document.getElementById('cagr-mode-calc').style.background = mode==='calc' ? '#1a1a1a' : 'transparent'; document.getElementById('cagr-mode-calc').style.color = mode==='calc' ? '#fff' : '#888'; document.getElementById('cagr-mode-proj').style.background = mode==='proj' ? '#1a1a1a' : 'transparent'; document.getElementById('cagr-mode-proj').style.color = mode==='proj' ? '#fff' : '#888'; mode==='calc' ? calcCAGR() : calcCAGRProj(); } function calcCAGR(){ const init = parseFloat(document.getElementById('cagr-initial').value)||0; const fin = parseFloat(document.getElementById('cagr-final').value)||0; const y = parseInt(document.getElementById('cagr-yrs').value)||1; document.getElementById('cagr-initial-val').textContent = '$'+init.toLocaleString(); document.getElementById('cagr-final-val').textContent = '$'+fin.toLocaleString(); document.getElementById('cagr-yrs-val').textContent = y+' year'+(y!==1?'s':''); const cagr = (Math.pow(fin/init, 1/y)-1)*100; const totalReturn = (fin-init)/init*100; document.getElementById('cagr-res-label').textContent = 'Compound Annual Growth Rate'; document.getElementById('cagr-result').textContent = cagr.toFixed(2)+'%'; document.getElementById('cagr-total-return').textContent = totalReturn.toFixed(0)+'%'; document.getElementById('cagr-gain').textContent = (fin > init ? '+' : '')+fmtFull(fin-init); document.getElementById('cagr-note').textContent = 'Over '+y+' year'+(y!==1?'s':''); } try{calcCAGR();}catch(e){console.warn("calcCAGR init:",e);} function calcCAGRProj(){ const init = parseFloat(document.getElementById('cagr-p-initial').value)||0; const rate = parseFloat(document.getElementById('cagr-p-rate').value)||0; const y = parseInt(document.getElementById('cagr-p-yrs').value)||1; document.getElementById('cagr-p-initial-val').textContent = '$'+init.toLocaleString(); document.getElementById('cagr-p-rate-val').textContent = rate+'%'; document.getElementById('cagr-p-yrs-val').textContent = y+' year'+(y!==1?'s':''); const fin = init * Math.pow(1+rate/100, y); const gain = fin - init; const totalReturn = init > 0 ? (gain/init*100).toFixed(0) : 0; document.getElementById('cagr-res-label').textContent = 'Projected Value'; document.getElementById('cagr-result').textContent = fmtFull(fin); document.getElementById('cagr-total-return').textContent = totalReturn+'%'; document.getElementById('cagr-gain').textContent = '+'+fmtFull(gain); document.getElementById('cagr-note').textContent = 'Over '+y+' year'+(y!==1?'s':''); } // ── OPTIONS ── function calcOptions(){ const shares = parseInt(document.getElementById('opt-shares').value)||0; const price = parseFloat(document.getElementById('opt-price').value)||0; const prem = parseFloat(document.getElementById('opt-prem').value)||0; const contracts = parseInt(document.getElementById('opt-contracts').value)||1; document.getElementById('opt-shares-val').textContent = shares.toLocaleString(); document.getElementById('opt-price-val').textContent = '$'+price; document.getElementById('opt-prem-val').textContent = '$'+prem.toFixed(2); document.getElementById('opt-contracts-val').textContent = contracts; const monthly = prem * contracts * 100; const annual = monthly * 12; const posVal = shares * price; const yieldPct = posVal > 0 ? (annual/posVal*100).toFixed(1) : 0; document.getElementById('opt-monthly').textContent = fmtFull(monthly); document.getElementById('opt-annual').textContent = fmtFull(annual); document.getElementById('opt-yield').textContent = yieldPct+'%'; document.getElementById('opt-pos-val').textContent = 'Position value: '+fmtFull(posVal); document.getElementById('opt-bar-mo-t').textContent = 'Monthly '+fmt(monthly); document.getElementById('opt-bar-yr-t').textContent = 'Annual '+fmt(annual); } try{calcOptions();}catch(e){console.warn("calcOptions init:",e);} // ── CHART HELPERS ── function makeChart(id, labels, datasets){ const canvas = document.getElementById(id); if(!canvas) return; if(charts[id]){ charts[id].destroy(); delete charts[id]; } // Clear stale inline dimensions set by Chart.js when canvas was hidden (display:none) canvas.removeAttribute('style'); canvas.removeAttribute('width'); canvas.removeAttribute('height'); charts[id] = new Chart(canvas, { type:'line', data:{labels, datasets}, options:{...CHART_DEFAULTS, responsive:true, maintainAspectRatio:false} }); } function makeBarChart(id, labels, datasets){ const canvas = document.getElementById(id); if(!canvas) return; if(charts[id]){ charts[id].destroy(); delete charts[id]; } // Clear stale inline dimensions set by Chart.js when canvas was hidden (display:none) canvas.removeAttribute('style'); canvas.removeAttribute('width'); canvas.removeAttribute('height'); charts[id] = new Chart(canvas, { type:'bar', data:{labels, datasets}, options:{...CHART_DEFAULTS, responsive:true, maintainAspectRatio:false, scales:{...CHART_DEFAULTS.scales, x:{...CHART_DEFAULTS.scales.x, stacked:true}, y:{...CHART_DEFAULTS.scales.y, stacked:true}}, plugins:{legend:{display:false}} } }); } function chartSIP(){ const mo = parseFloat(document.getElementById('sip-amt').value)||0; const r = parseFloat(document.getElementById('sip-rate').value)||0; const yrs = parseInt(document.getElementById('sip-yrs').value)||0; const mr = r/100/12; const labels=[], invested=[], total=[]; for(let y=1;y<=yrs;y++){ const n=y*12; const t = mr>0 ? mo*((Math.pow(1+mr,n)-1)/mr)*(1+mr) : mo*n; labels.push('Yr '+y); invested.push(Math.round(mo*n)); total.push(Math.round(t)); } makeChart('chart-sip', labels, [ {label:'Total Value',data:total,borderColor:'#E63946',backgroundColor:'rgba(230,57,70,0.08)',fill:true,tension:0.3,pointRadius:0,borderWidth:2}, {label:'Invested',data:invested,borderColor:'rgba(255,255,255,0.2)',backgroundColor:'transparent',fill:false,tension:0.3,pointRadius:0,borderWidth:1,borderDash:[4,4]} ]); } function chartLS(){ const p = parseFloat(document.getElementById('ls-amt').value)||0; const r = parseFloat(document.getElementById('ls-rate').value)||0; const y = parseInt(document.getElementById('ls-yrs').value)||0; const labels=[], total=[], gain=[]; for(let i=1;i<=y;i++){ const t = p*Math.pow(1+r/100,i); labels.push('Yr '+i); total.push(Math.round(t)); gain.push(Math.round(t-p)); } makeChart('chart-ls', labels, [ {label:'Value',data:total,borderColor:'#E63946',backgroundColor:'rgba(230,57,70,0.08)',fill:true,tension:0.3,pointRadius:0,borderWidth:2} ]); } function chartGoal(){ // Show: if I wait N years to start, how much more per month do I need? const target = parseFloat(document.getElementById('goal-target').value)||0; const r = parseFloat(document.getElementById('goal-rate').value)||0; const y = parseInt(document.getElementById('goal-yrs').value)||0; const labels=[], monthly=[]; const maxY = Math.max(y, 5); for(let yr=1;yr<=maxY;yr++){ const n=yr*12, mr=r/100/12; const mo = mr>0 ? target*mr/((Math.pow(1+mr,n)-1)*(1+mr)) : target/n; labels.push(yr+' yr'+(yr!==1?'s':'')); monthly.push(Math.round(mo)); } makeChart('chart-goal', labels, [ {label:'Monthly Needed',data:monthly,borderColor:'#4caf7d',backgroundColor:'rgba(76,175,61,0.08)',fill:true,tension:0.3,pointRadius:3,borderWidth:2, pointBackgroundColor:'#4caf7d',pointRadius:labels.indexOf(y+' yr'+(y!==1?'s':''))>=0?[...labels.map((_,i)=>i===y-1?5:0)]:3} ]); } function chartSWP(){ const start = parseFloat(document.getElementById('swp-start').value)||0; const mo = parseFloat(document.getElementById('swp-amt').value)||0; const r = parseFloat(document.getElementById('swp-rate').value)||0; const mr = r/100/12; const labels=[], bal=[]; let b=start; const maxYrs = Math.min(50, 100); for(let y=1;y<=maxYrs;y++){ for(let m=0;m<12;m++){ b=b*(1+mr)-mo; if(b<0){b=0;} } labels.push('Yr '+y); bal.push(Math.round(b)); if(b===0) break; } makeChart('chart-swp', labels, [ {label:'Balance',data:bal,borderColor:'#6aa3d5',backgroundColor:'rgba(106,163,213,0.08)',fill:true,tension:0.3,pointRadius:0,borderWidth:2} ]); } function chartOptions(){ const prem = parseFloat(document.getElementById('opt-prem').value)||0; const contracts = parseInt(document.getElementById('opt-contracts').value)||1; const monthly = prem*contracts*100; const labels=[], cumulative=[]; for(let m=1;m<=12;m++){ labels.push('Mo '+m); cumulative.push(Math.round(monthly*m)); } makeChart('chart-options', labels, [ {label:'Cumulative Income',data:cumulative,borderColor:'#4caf7d',backgroundColor:'rgba(76,175,61,0.1)',fill:true,tension:0.3,pointRadius:3,pointBackgroundColor:'#4caf7d',borderWidth:2} ]); } // Wrap each calc function to also update chart const _calcSIP=calcSIP; calcSIP=function(){_calcSIP();chartSIP();} const _calcLS=calcLS; calcLS=function(){_calcLS();chartLS();} const _calcGoal=calcGoal; calcGoal=function(){_calcGoal();chartGoal();} const _calcSWP=calcSWP; calcSWP=function(){_calcSWP();chartSWP();} const _calcOptions=calcOptions; calcOptions=function(){_calcOptions();chartOptions();} // Init all charts setTimeout(function(){chartSIP();chartLS();chartGoal();chartSWP();chartOptions();}, 100); // ── RESP CALCULATOR ── // ── UPFRONT TOGGLE ── // (moved to top of script) function toggleUpfront(suppressCalc){ upfrontEnabled = !upfrontEnabled; const toggle = document.getElementById('upfront-toggle'); const field = document.getElementById('upfront-field'); if(toggle) toggle.classList.toggle('on', upfrontEnabled); if(field) field.classList.toggle('visible', upfrontEnabled); if(!suppressCalc) calcRESP(); } // ── SYNC RANGE/INPUT ── function respSyncRange(inputId, rangeId){ const v = document.getElementById(inputId).value; const r = document.getElementById(rangeId); if(r) r.value = v; } // ── FORMATTERS ── const respFmtC = n => { if(n >= 1000000) return '$'+(n/1000000).toFixed(2).replace(/\.?0+$/,'')+'M'; if(n >= 10000) return '$'+(n/1000).toFixed(1).replace(/\.0$/,'')+'K'; return '$'+Math.round(n).toLocaleString(); }; const respFmtFull = n => '$'+Math.round(n).toLocaleString(); const respFmtPct = (n, tot) => tot > 0 ? (n/tot*100).toFixed(1)+'%' : '0%'; // ── CHART ── // (moved to top of script) function respUpdateChart(years, contribData, grantData, portfolioData){ const ctx = document.getElementById('resp-chart').getContext('2d'); if(respChart) respChart.destroy(); respChart = new Chart(ctx, { type: 'line', data: { labels: years, datasets: [ { label: 'Portfolio Value', data: portfolioData, borderColor: '#E63946', backgroundColor: 'rgba(230,57,70,0.08)', fill: true, tension: 0.4, borderWidth: 2.5, pointRadius: 2, }, { label: 'Total Contributed', data: contribData, borderColor: '#c0392b', backgroundColor: 'transparent', fill: false, tension: 0.4, borderWidth: 1.5, borderDash: [4,3], pointRadius: 0, }, { label: 'Cumulative Grants', data: grantData, borderColor: '#4caf7d', backgroundColor: 'transparent', fill: false, tension: 0.4, borderWidth: 1.5, borderDash: [2,3], pointRadius: 0, }, ] }, options: { responsive: true, maintainAspectRatio: true, interaction: { mode: 'index', intersect: false }, plugins: { legend: { display: false }, tooltip: { backgroundColor: '#111009', titleColor: 'rgba(255,255,255,0.5)', bodyColor: '#fff', borderColor: 'rgba(230,57,70,0.2)', borderWidth: 1, padding: 12, callbacks: { title: items => 'Year ' + items[0].label, label: ctx => { const icons = ['📈','💰','🎁']; return ' ' + (icons[ctx.datasetIndex]||'') + ' ' + ctx.dataset.label + ': ' + respFmtFull(ctx.parsed.y); } } } }, scales: { x: { grid: { color: 'rgba(0,0,0,0.04)' }, ticks: { font: { size: 10, family: 'DM Sans' }, color: '#999', maxTicksLimit: 10 } }, y: { grid: { color: 'rgba(0,0,0,0.04)' }, ticks: { font: { size: 10, family: 'DM Sans' }, color: '#999', callback: v => respFmtC(v) } } } } }); } // ── RESP CONTRIBUTION SCHEDULE ── // (moved to top of script) // ── CLB TOGGLE ── // (moved to top of script) function toggleCLB(){ clbEnabled = !clbEnabled; document.getElementById('clb-toggle').classList.toggle('on', clbEnabled); document.getElementById('clb-info').style.display = clbEnabled ? 'block' : 'none'; const clbHdr = document.getElementById('clb-col-header'); if(clbHdr) clbHdr.style.display = clbEnabled ? 'table-cell' : 'none'; const clbSec = document.getElementById('clb-tracker-section'); if(clbSec) clbSec.style.display = clbEnabled ? 'block' : 'none'; calcRESP(); // Rebuild suggestions with updated CLB state const dobForCLB = document.getElementById('child-dob')?.value; const byrForCLB = dobForCLB ? parseInt(dobForCLB.split('-')[0]) : new Date().getFullYear(); if(byrForCLB >= 1990){ currentSuggestions = buildSuggestions(byrForCLB, new Date().getFullYear(), clbEnabled); const t = document.getElementById('suggestions-trigger'); if(t) t.style.display = 'block'; if(suggestionsOpen) renderSuggestions(currentSuggestions); } } function markUserEdited(id){ const toEl = document.getElementById('sched-to-'+id); if(toEl) toEl.dataset.userSet = '1'; } function clearUserEdited(id){ const toEl = document.getElementById('sched-to-'+id); if(toEl) delete toEl.dataset.userSet; } function syncFirstRowYear(){ const startYr = parseInt(document.getElementById('start-year')?.value) || 0; const firstFrom = document.querySelector('.sched-from-date'); if(firstFrom && startYr > 0){ const cur = firstFrom.value || ''; const parts = cur.split('-'); firstFrom.value = startYr + '-' + (parts[1]||'01') + '-' + (parts[2]||'01'); const rowId = document.querySelector('.sched-row')?.id?.replace('sched-row-',''); if(rowId) updateSchedHint(rowId); } } function lastDayOfMonth(yr, mo){ return new Date(yr, mo, 0).getDate(); } function toDateStr(yr, mo, day){ return yr+'-'+String(mo).padStart(2,'0')+'-'+String(day).padStart(2,'0'); } function snapToMonthEnd(dateStr){ // Snap any date to Dec 31 of its year (since we always want Dec 31) const yr = parseInt(dateStr.split('-')[0]); return yr + '-12-31'; } function parseDateYr(dateStr){ return parseInt((dateStr||'').split('-')[0]) || 0; } function parseDateMo(dateStr){ return parseInt((dateStr||'').split('-')[1]) || 1; } function toAnnual(amount, freq){ if(freq === 'monthly') return amount * 12; if(freq === 'weekly') return amount * 52; return amount; // annual } function addContribRow(fromDate, toDate, freq='annual', amount=2500){ schedRowCount++; const id = schedRowCount; const startYr = new Date().getFullYear(); // always current year // Calculate default end date: Dec 31 of year child turns 17 const dob = document.getElementById('child-dob')?.value; const childBirthYr = dob ? parseInt(dob.split('-')[0]) : startYr; // parse directly — avoids timezone bug const defaultEndYr = childBirthYr + 17; const defaultEndDate = defaultEndYr + '-12-31'; if(!fromDate){ // Find max toDate of existing rows let maxDate = null; document.querySelectorAll('.sched-to-date').forEach(el => { if(!maxDate || el.value > maxDate) maxDate = el.value; }); if(maxDate){ const d = new Date(maxDate); d.setDate(d.getDate() + 1); // day after last row ends fromDate = d.toISOString().split('T')[0]; } else { // Default: today's date const _td = new Date(); fromDate = _td.getFullYear() + '-' + String(_td.getMonth()+1).padStart(2,'0') + '-' + String(_td.getDate()).padStart(2,'0'); } toDate = defaultEndDate; } const fromYr = parseInt((fromDate||'').split('-')[0]) || startYr; const fromMo = parseInt((fromDate||'').split('-')[1]) || 1; const fromDay = parseInt((fromDate||'').split('-')[2]) || 1; const toYr = parseInt((toDate||defaultEndDate).split('-')[0]) || defaultEndYr; const toMo = parseInt((toDate||defaultEndDate).split('-')[1]) || 12; const freqOpts = ['annual','monthly','weekly'].map(f => `` ).join(''); const annualEquiv = toAnnual(amount, freq); const html = `
Period ${id}
From Date
To Date
Frequency
Amount
$
`; document.getElementById('contrib-schedule-rows').insertAdjacentHTML('beforeend', html); updateRowLabels(); } function removeContribRow(id){ const el = document.getElementById('sched-row-'+id); if(el) el.remove(); updateRowLabels(); calcRESP(); } function updateRowLabels(){ const rows = document.querySelectorAll('.sched-row'); rows.forEach((row, i) => { const label = row.querySelector('.sched-row-label'); if(label) label.textContent = 'Period '+(i+1); // Don't show delete button if only 1 row const del = row.querySelector('.sched-row-del'); if(del) del.style.visibility = rows.length > 1 ? 'visible' : 'hidden'; }); } function updateSchedHint(id){ const freqEl = document.getElementById('sched-freq-'+id); const amtEl = document.getElementById('sched-amt-'+id); const fromEl = document.getElementById('sched-from-'+id); const toEl = document.getElementById('sched-to-'+id); if(!freqEl || !amtEl || !fromEl || !toEl) return; const freq = freqEl.value || 'annual'; const amt = parseFloat(amtEl.value) || 0; const annual = toAnnual(amt, freq); const fromYr2 = parseDateYr(fromEl.value), fromMo2 = parseDateMo(fromEl.value); const fromDay2 = parseInt((fromEl.value||'').split('-')[2]) || 1; const toYr2 = parseDateYr(toEl.value), toMo2 = parseDateMo(toEl.value); const toDay2 = parseInt((toEl.value||'').split('-')[2]) || 28; // Calculate fractional years more accurately // Full years = year difference, then adjust for partial start/end months let totalMonths = (toYr2 - fromYr2) * 12 + (toMo2 - fromMo2); // If start is Jan 1 and end is Dec 31, it's a clean full year span // e.g. Jan 2026 → Dec 2043 = 17 full years + Dec = 18 years total including both endpoints if(fromDay2 === 1 && toDay2 >= 28) totalMonths += 1; // include end month let durStr; if(totalMonths <= 0){ durStr = '0 mo'; } else if(totalMonths < 12){ durStr = totalMonths + ' mo'; } else { const fullYrs = Math.floor(totalMonths / 12); const remMo = totalMonths % 12; if(remMo === 0) durStr = fullYrs + ' yr' + (fullYrs !== 1 ? 's' : ''); else if(remMo <= 2) durStr = fullYrs + ' yr' + (fullYrs !== 1 ? 's' : ''); // ignore tiny fractions else durStr = fullYrs + ' yr' + (fullYrs !== 1 ? 's' : '') + ' ' + remMo + 'mo'; } const hintEl = document.getElementById('sched-hint-'+id); if(hintEl) hintEl.innerHTML = '= $'+Math.round(annual).toLocaleString()+'/yr  ·  '+durStr; } function getContribSchedule(){ const rows = document.querySelectorAll('.sched-row'); const schedule = []; rows.forEach(row => { const rid = row.id.replace('sched-row-',''); const fromEl = document.getElementById('sched-from-'+rid); const toEl = document.getElementById('sched-to-'+rid); const freq = document.getElementById('sched-freq-'+rid)?.value || 'annual'; const amt = parseFloat(document.getElementById('sched-amt-'+rid)?.value) || 0; if(!fromEl || !toEl) return; const fromDate = fromEl.value; const toDate = toEl.value; if(!fromDate || !toDate) return; const fromYr = parseDateYr(fromDate); const fromMo = parseDateMo(fromDate); const fromDay= parseInt(fromDate.split('-')[2]) || 1; const toYr = parseDateYr(toDate); const toMo = parseDateMo(toDate); const toDay = parseInt(toDate.split('-')[2]) || 31; const annualAmount = toAnnual(amt, freq); if(fromYr > 0 && toDate >= fromDate){ schedule.push({ annualAmount, fromYr, fromMo, fromDay, toYr, toMo, toDay }); } }); schedule.sort((a,b) => a.fromYr !== b.fromYr ? a.fromYr-b.fromYr : a.fromMo-b.fromMo); return schedule; } // ── INIT RESP SCHEDULE FROM DOB ── function initRESPSchedule(fromDateStr){ const dob = document.getElementById('child-dob')?.value; const startYr = new Date().getFullYear(); // always current year const childBirthYr = dob ? parseInt(dob.split('-')[0]) : startYr; // parse directly — avoids timezone bug // Build optimized schedule const opt = optimizeRESP(childBirthYr, startYr, 50000); const grantEnd = (childBirthYr + 17) + '-12-31'; // Always compute today fresh — don't rely on fromDateStr which may be stale const td2 = new Date(); const today = td2.getFullYear() + '-' + String(td2.getMonth()+1).padStart(2,'0') + '-' + String(td2.getDate()).padStart(2,'0'); // Clear existing rows const container = document.getElementById('contrib-schedule-rows'); if(container) container.innerHTML = ''; schedRowCount = 0; // Turn off lump sum (default schedule has no lump sum) if(upfrontEnabled) toggleUpfront(true); // suppress calcRESP during init if(opt.totalCESG <= 0){ // Past grant age — just contribute the full amount addContribRow(today, grantEnd, 'annual', 2500); } else if(opt.lumpSum <= 0){ // No lump sum needed — standard annual contributions addContribRow(today, grantEnd, 'annual', 2500); } else { // Option 1 style (default): lump sum upfront + annual catch-up/regular // This maximizes grants by perfectly aligning with CRA catch-up thresholds if(!upfrontEnabled) toggleUpfront(true); // suppress calcRESP during init const lumpInput = document.getElementById('lump-sum'); const lumpRange = document.getElementById('lump-range'); if(lumpInput) lumpInput.value = Math.round(opt.lumpSum); if(lumpRange) lumpRange.value = Math.round(opt.lumpSum); // Add catch-up years at $5,000/yr if(opt.catchupYrs > 0){ const cuEnd = (startYr + opt.catchupYrs - 1) + '-12-31'; addContribRow(today, cuEnd, 'annual', 5000); } // Add regular grant years at $2,500/yr if(opt.regularYrs > 0){ const regStart = startYr + opt.catchupYrs; const regEnd = (regStart + opt.regularYrs - 1) + '-12-31'; addContribRow(regStart + '-01-01', regEnd, 'annual', 2500); } } // Clear user-set flags on all rows document.querySelectorAll('.sched-to-date').forEach(el => delete el.dataset.userSet); // Build suggestions immediately and always show them open const dobForSugg = document.getElementById('child-dob')?.value; const byrForSugg = dobForSugg ? parseInt(dobForSugg.split('-')[0]) : startYr; if(byrForSugg >= 1990){ currentSuggestions = buildSuggestions(byrForSugg, startYr, typeof clbEnabled !== 'undefined' && clbEnabled); const trigger2 = document.getElementById('suggestions-trigger'); if(trigger2) trigger2.style.display = 'block'; // Always open the panel (default state) suggestionsOpen = true; const panel2 = document.getElementById('suggestions-panel'); const chevron2 = document.getElementById('suggestions-chevron'); if(panel2) panel2.style.display = 'flex'; if(chevron2) chevron2.style.transform = 'rotate(180deg)'; if(currentSuggestions.length > 0) renderSuggestions(currentSuggestions); } // Recalculate with delay so DOM rows are rendered first setTimeout(() => { autoAdjustEndDates(); }, 50); } // ── SMART SUGGESTIONS SYSTEM ── // (moved to top of script) // (moved to top of script) function toggleSuggestions(){ suggestionsOpen = !suggestionsOpen; const panel = document.getElementById('suggestions-panel'); const chevron = document.getElementById('suggestions-chevron'); if(suggestionsOpen && currentSuggestions.length > 0){ renderSuggestions(currentSuggestions); if(panel) panel.style.display = 'flex'; } else { if(panel) panel.style.display = 'none'; } if(chevron) chevron.style.transform = suggestionsOpen ? 'rotate(180deg)' : ''; } function addMonths(dateStr, n){ const d = new Date(dateStr); d.setMonth(d.getMonth() + n); // Snap to last day of that month const yr = d.getFullYear(), mo = d.getMonth()+1; const lastDay = new Date(yr, mo, 0).getDate(); return yr + '-' + String(mo).padStart(2,'0') + '-' + String(lastDay).padStart(2,'0'); } function addMonthsStart(dateStr, n){ // Start of month N months after dateStr const d = new Date(dateStr); d.setMonth(d.getMonth() + n); const yr = d.getFullYear(), mo = d.getMonth()+1; return yr + '-' + String(mo).padStart(2,'0') + '-01'; } function optimizeRESP(dobYr, startYr, lifetime){ // Advanced optimizer: accounts for catch-up grants from missed years // CRA allows $5,000/yr contribution to catch up on prior missed grant room // Each catch-up year = $1,000 grant (vs $500 regular) const grantEndYr = dobYr + 17; const missedYrs = Math.max(0, startYr - dobYr); let grantRoomUnused = missedYrs * 500; let cesgRemaining = 7200; let currentYr = startYr; let totalContrib = 0; const plan = []; while(currentYr <= grantEndYr && cesgRemaining > 0 && totalContrib < lifetime){ grantRoomUnused = Math.min(grantRoomUnused + 500, cesgRemaining); let grant, contrib; if(grantRoomUnused >= 1000){ grant = Math.min(1000, cesgRemaining, grantRoomUnused); contrib = Math.min(5000, lifetime - totalContrib); } else { grant = Math.min(500, cesgRemaining, grantRoomUnused); const minForGrant = grant > 0 ? grant / 0.20 : 2500; contrib = Math.min(minForGrant, 2500, lifetime - totalContrib); } if(contrib <= 0) break; grantRoomUnused -= grant; cesgRemaining -= grant; totalContrib += contrib; plan.push({ yr: currentYr, contrib, grant, catchup: contrib > 2500 }); currentYr++; } const totalCESG = 7200 - cesgRemaining; const grantContrib = plan.reduce((s,p)=>s+p.contrib, 0); const lumpSum = Math.max(0, lifetime - grantContrib); const catchupYrs = plan.filter(p=>p.catchup).length; const regularYrs = plan.filter(p=>!p.catchup).length; return { lumpSum, totalCESG, grantContrib, catchupYrs, regularYrs, plan }; } function buildSuggestions(childBirthYear, startYear, withCLB){ // Guard const currentYr = new Date().getFullYear(); if(!childBirthYear || childBirthYear < 1990 || childBirthYear > currentYr + 1) return []; if(!startYear || startYear < 2000) return []; const opt = optimizeRESP(childBirthYear, startYear, 50000); const grantEndYr = childBirthYear + 17; const grantEnd = grantEndYr + '-12-31'; // CLB: $500 year 1 + $100/yr ages 1-15, max $2,000 (born 2004+, no contribution needed) let totalCLBSugg = 0; if(withCLB && childBirthYear >= 2004){ const clbAge0Yr = childBirthYear; // year child turns 0 for(let age = 0; age <= 15; age++){ const yr = childBirthYear + age; if(yr < startYear) continue; // past years already missed const clbAmt = (totalCLBSugg === 0) ? 500 : 100; totalCLBSugg = Math.min(totalCLBSugg + clbAmt, 2000); } } // ── actualStart: always today's date (the RESP is being opened now) ── const td = new Date(); const actualStart = td.getFullYear() + '-' + String(td.getMonth()+1).padStart(2,'0') + '-' + String(td.getDate()).padStart(2,'0'); // Helper: annual amount for a row based on catch-up status const mo2 = Math.round(2500/12); // $208 regular monthly const suggs = []; // ════════════════════════════════════════════════════════ // OPTION 1: Basic — $2,500/yr (or $208/mo) — what most people do // Simple, no lump sum, just the grant-earning annual amount // ════════════════════════════════════════════════════════ const basicAnnual = 2500; const basicMonthly = Math.round(basicAnnual / 12); // $208 const grantEndBasic = (childBirthYear + 17) + '-12-31'; // Simulate actual CESG for basic plan — prorates first year by start month const grantYrsLeft = Math.max(0, (childBirthYear + 17) - startYear + 1); const startMoBasic = parseInt(actualStart.split('-')[1]) || 1; let basicCESGSim = 0, basicRoomSim = Math.max(0, startYear - childBirthYear) * 500; for(let yr = startYear; yr <= childBirthYear + 17; yr++){ basicRoomSim += 500; const moStart = yr === startYear ? startMoBasic : 1; const annualContrib = basicMonthly * (12 - moStart + 1); const grant = Math.min(annualContrib * 0.20, 500, basicRoomSim, 7200 - basicCESGSim); basicRoomSim -= grant; basicCESGSim += grant; } basicCESGSim = Math.round(basicCESGSim) + totalCLBSugg; const lateNote = grantYrsLeft < 14 ? ' Starting late — consider Option 2 to recover up to ' + fmtS(opt.totalCESG) + ' in grants via catch-up contributions.' : ''; suggs.push({ title: 'Simple monthly — $' + basicMonthly + '/mo', badge: 'Most popular', cesg: basicCESGSim, cesgLabel: fmtS(basicCESGSim) + ' estimated', lump: 0, rows: [{amount: basicMonthly, freq: 'monthly', fromDate: actualStart, toDate: grantEndBasic}], description: 'Contribute $' + basicMonthly + '/mo ($2,500/yr) — the most common approach. Easy to set up, no lump sum, no complexity.' + lateNote, _basic: true, }); // ════════════════════════════════════════════════════════ // OPTION 2: Lump sum on day 1 + optimal annual schedule // ════════════════════════════════════════════════════════ const s1rows = []; if(opt.catchupYrs > 0){ s1rows.push({ amount: 5000, freq: 'annual', fromDate: actualStart, toDate: (startYear + opt.catchupYrs - 1) + '-12-31' }); } if(opt.regularYrs > 0){ const rStart = startYear + opt.catchupYrs; s1rows.push({ amount: 2500, freq: 'annual', fromDate: rStart + '-01-01', toDate: (rStart + opt.regularYrs - 1) + '-12-31' }); } if(s1rows.length === 0 && opt.totalCESG === 0){ // No grants possible — just lump sum s1rows.push({amount: 0, freq: 'annual', fromDate: actualStart, toDate: grantEnd}); } suggs.push({ title: opt.lumpSum > 0 ? 'Lump sum upfront + optimal annual' : 'Optimal annual only', badge: 'Best returns', cesg: opt.totalCESG + totalCLBSugg, lump: opt.lumpSum, rows: s1rows, description: opt.lumpSum > 0 ? 'Put ' + fmtS(opt.lumpSum) + ' in on day 1 — this money earns no grant regardless of timing, so investing it early maximises compound growth. Then pay ' + fmtS(opt.catchupYrs > 0 ? 5000 : 2500) + '/yr to collect every available grant. This option earns the most grants.' : 'Contribute $2,500/yr through the grant period to collect all available grants.', }); // ════════════════════════════════════════════════════════ // OPTION 2: 12-month elevated, then catch-up rate, then regular // No lump sum — entire $50k deployed via periodic payments // ════════════════════════════════════════════════════════ if(opt.lumpSum > 0 || opt.totalCESG > 0){ const yr1Rate = opt.catchupYrs > 0 ? 5000 : 2500; // Period 1: 12 months elevated (lump + 1 yr grant-earning spread) const yr1Total = opt.lumpSum + yr1Rate; const mo1 = Math.round(yr1Total / 12); const p1end = addMonths(actualStart, 11); const p2start = addMonthsStart(actualStart, 12); const s2rows = []; s2rows.push({amount: mo1, freq: 'monthly', fromDate: actualStart, toDate: p1end}); // Remaining catch-up years (after year 1 is covered) const cu2 = Math.max(0, opt.catchupYrs - 1); if(cu2 > 0 && p2start <= grantEnd){ const cuEnd2 = addMonths(p2start, cu2 * 12 - 1); s2rows.push({amount: Math.round(5000/12), freq: 'monthly', fromDate: p2start, toDate: cuEnd2 < grantEnd ? cuEnd2 : grantEnd}); const afterCU2 = addMonthsStart(p2start, cu2 * 12); if(afterCU2 <= grantEnd){ s2rows.push({amount: mo2, freq: 'monthly', fromDate: afterCU2, toDate: grantEnd}); } } else if(p2start <= grantEnd){ // No more catch-up — regular monthly until grant end s2rows.push({amount: mo2, freq: 'monthly', fromDate: p2start, toDate: grantEnd}); } const tradeNote2 = opt.catchupYrs > 1 ? ' Note: spreading the upfront amount monthly may reduce total grants slightly vs Option 1 — the tradeoff for avoiding a lump sum payment.' : ''; suggs.push({ title: '12-month elevated, then regular monthly', badge: 'No big payment', cesg: opt.totalCESG + totalCLBSugg, lump: 0, rows: s2rows, description: 'Pay ' + fmtS(mo1) + '/mo for 12 months from day one, then drop to ' + fmtS(opt.catchupYrs > 1 ? Math.round(5000/12) : mo2) + '/mo. No large upfront payment — the ' + fmtS(opt.lumpSum) + ' is spread across the first year.' + tradeNote2, }); // ════════════════════════════════════════════════════════ // OPTION 3: 24-month elevated, then catch-up rate, then regular // ════════════════════════════════════════════════════════ const yr2Rate = opt.catchupYrs > 0 ? 5000 : 2500; const yr2Total = opt.lumpSum + yr2Rate * 2; const mo1b = Math.round(yr2Total / 24); const p2end = addMonths(actualStart, 23); const p3start = addMonthsStart(actualStart, 24); const s3rows = []; s3rows.push({amount: mo1b, freq: 'monthly', fromDate: actualStart, toDate: p2end}); const cu3 = Math.max(0, opt.catchupYrs - 2); if(cu3 > 0 && p3start <= grantEnd){ const cuEnd3 = addMonths(p3start, cu3 * 12 - 1); s3rows.push({amount: Math.round(5000/12), freq: 'monthly', fromDate: p3start, toDate: cuEnd3 < grantEnd ? cuEnd3 : grantEnd}); const afterCU3 = addMonthsStart(p3start, cu3 * 12); if(afterCU3 <= grantEnd){ s3rows.push({amount: mo2, freq: 'monthly', fromDate: afterCU3, toDate: grantEnd}); } } else if(p3start <= grantEnd){ s3rows.push({amount: mo2, freq: 'monthly', fromDate: p3start, toDate: grantEnd}); } const tradeNote3 = opt.catchupYrs > 2 ? ' Slightly fewer grants than Option 1 — the tradeoff for the easiest monthly payment.' : ' Same grants as Option 1.'; suggs.push({ title: '24-month elevated, then regular monthly', badge: 'Most gradual', cesg: opt.totalCESG + totalCLBSugg, lump: 0, rows: s3rows, description: 'Pay ' + fmtS(mo1b) + '/mo for the first 24 months — the easiest on cash flow. This spreads ' + fmtS(opt.lumpSum) + ' across 2 full years instead of one large payment. Then drops to ' + fmtS(opt.catchupYrs > 2 ? Math.round(5000/12) : mo2) + '/mo.' + tradeNote3, }); } else { // No lump sum, no catch-up — just show monthly version suggs.push({ title: 'Monthly contributions', badge: 'Monthly', cesg: opt.totalCESG, lump: 0, rows: [{amount: mo2, freq: 'monthly', fromDate: actualStart, toDate: grantEnd}], description: 'Contribute ' + fmtS(mo2) + '/mo through the grant period.', }); suggs.push({...suggs[1]}); } return suggs; } function fmtS(n){ return '$' + Math.round(n).toLocaleString(); } function renderSuggestions(suggs){ const panel = document.getElementById('suggestions-panel'); if(!panel) return; panel.innerHTML = suggs.map((s,i) => `
Option ${i+1} ${s.badge ? '' + s.badge + '' : ''}
${s.title}
✓ ${i === 0 ? (s.cesgLabel || 'Up to ' + fmtS(s.cesg)) + ' in government grants' : 'Max ' + fmtS(s.cesg) + ' — optimize grants within payment constraints'}
${s.description}
${s.lump > 0 ? '
🎯 Lump sum: ' + fmtS(s.lump) + ' on day 1
' : ''} ${s.rows.map(r => { const MONS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; const fd = (r.fromDate||'').split('-'); const td = (r.toDate||'').split('-'); const fromLabel = fd[1] ? MONS[parseInt(fd[1])-1]+' '+fd[0] : fd[0]; const toLabel = td[1] ? MONS[parseInt(td[1])-1]+' '+td[0] : td[0]; const label = fromLabel === toLabel ? fromLabel : fromLabel + ' \u2013 ' + toLabel; const freqLabel = r.freq === 'monthly' ? 'mo' : r.freq === 'weekly' ? 'wk' : 'yr'; return '
\ud83d\udcc5 ' + fmtS(r.amount) + '/' + freqLabel + '  ' + label + '
'; }).join('')}
`).join(''); } function applySuggestion(idx){ const s = currentSuggestions[idx]; if(!s) return; // Set or clear lump sum if(s.lump > 0){ if(!upfrontEnabled) toggleUpfront(); const li = document.getElementById('lump-sum'); const lr = document.getElementById('lump-range'); if(li) li.value = Math.round(s.lump); if(lr) lr.value = Math.round(s.lump); } else if(upfrontEnabled){ toggleUpfront(); } // Clear and rebuild schedule rows const container = document.getElementById('contrib-schedule-rows'); if(container) container.innerHTML = ''; schedRowCount = 0; s.rows.forEach(row => { addContribRow( row.fromDate || (row.fromYr + '-01-01'), row.toDate || (row.toYr + '-12-31'), row.freq || 'annual', row.amount ); // Clear user-set flag const lastRow = document.querySelector('.sched-row:last-child'); if(lastRow){ const rid = lastRow.id.replace('sched-row-',''); const toEl = document.getElementById('sched-to-'+rid); if(toEl) delete toEl.dataset.userSet; updateSchedHint(rid); } }); // Keep suggestions open so user can compare options calcRESP(); } function checkFrontload(schedule, lifeContribTotal, startYear, childBirthYear){ const trigger = document.getElementById('suggestions-trigger'); if(!trigger) return; if(lifeContribTotal >= 49000){ trigger.style.display='none'; return; } // Always read DOB directly from field — don't rely on calcRESP's passed value // This avoids stale-variable bugs when DOB changes const currentYr = new Date().getFullYear(); const dobVal = document.getElementById('child-dob')?.value; const actualBirthYear = dobVal ? parseInt(dobVal.split('-')[0]) : childBirthYear; const actualStartYear = currentYr; // Guard: only build suggestions when we have a valid birth year if(!actualBirthYear || actualBirthYear < 1990 || actualBirthYear > currentYr + 1) return; // Pass CLB enabled state so suggestions show correct total grants currentSuggestions = buildSuggestions(actualBirthYear, actualStartYear, typeof clbEnabled !== 'undefined' && clbEnabled); trigger.style.display = 'block'; // If panel is open, re-render with fresh suggestions if(suggestionsOpen){ renderSuggestions(currentSuggestions); } } // ── AUTO-ADJUST END DATES ── function autoAdjustEndDates(){ const dob = document.getElementById('child-dob')?.value; const startYr = new Date().getFullYear(); // always current year const childBirthYr = dob ? parseInt(dob.split('-')[0]) : startYr; // parse directly — avoids timezone bug const grantEndDate = (childBirthYr + 17) + '-12-31'; const lumpSumAmt = upfrontEnabled ? (parseFloat(document.getElementById('lump-sum')?.value) || 0) : 0; const LIFETIME = 50000; // Walk through rows in order, allocating remaining contribution room const rows = document.querySelectorAll('.sched-row'); let remainingRoom = LIFETIME - lumpSumAmt; rows.forEach((row, idx) => { const rid = row.id.replace('sched-row-',''); const fromEl = document.getElementById('sched-from-'+rid); const toEl = document.getElementById('sched-to-'+rid); const freqEl = document.getElementById('sched-freq-'+rid); const amtEl = document.getElementById('sched-amt-'+rid); if(!fromEl || !toEl || !freqEl || !amtEl) return; const annualAmt = toAnnual(parseFloat(amtEl.value)||0, freqEl.value||'annual'); const fromDate = fromEl.value; // Parse year directly from string to avoid JS timezone issues const fromYearInt = parseDateYr(fromDate); if(!fromDate || !fromYearInt || annualAmt <= 0){ if(remainingRoom <= 0){ toEl.style.borderColor='#e74c3c'; return; } } toEl.style.borderColor = ''; if(remainingRoom <= 0){ toEl.value = fromDate; return; } if(toEl.dataset.userSet === '1') { remainingRoom -= toAnnual(parseFloat(amtEl.value)||0, freqEl.value)*Math.max(1,parseDateYr(toEl.value)-parseDateYr(fromDate)+1); return; } // user-set: respect it // Years of room: always snap end to Dec 31 — never mid-year const yearsOfRoom = remainingRoom / annualAmt; // e.g. 14.4 const lastContribYear = fromYearInt + Math.ceil(yearsOfRoom) - 1; const maxByRoomStr = lastContribYear + '-12-31'; // Pick earlier of: room exhausted vs grant end date const autoEnd = maxByRoomStr < grantEndDate ? maxByRoomStr : grantEndDate; toEl.value = autoEnd; // Deduct full years (partial handled by $50k cap in calc) remainingRoom -= annualAmt * Math.floor(yearsOfRoom); updateSchedHint(rid); }); calcRESP(); } // ── MAIN CALCULATION ── function calcRESP(){ // ── Inputs — read ALL scalar inputs first ── const dob = document.getElementById('child-dob').value; const returnRate = parseFloat(document.getElementById('return-rate').value) || 0; const startYear = new Date().getFullYear(); // always use current year — RESP opens now const lumpSum = upfrontEnabled ? (parseFloat(document.getElementById('lump-sum').value) || 0) : 0; // ── Build contribution schedule map (needs startYear) ── const schedule = getContribSchedule(); if(schedule.length === 0){ // No rows yet — auto-create a default row and retry after DOM settles if(document.querySelectorAll('.sched-row').length === 0){ const _td = new Date(); const _ts = _td.getFullYear()+'-'+String(_td.getMonth()+1).padStart(2,'0')+'-'+String(_td.getDate()).padStart(2,'0'); addContribRow(_ts, null, 'monthly', 208); setTimeout(() => calcRESP(), 0); } return; // nothing to compute yet } const schedMap = {}; // yr -> contribution amount for that year (prorated for partial years) let maxSchedYr = 0; for(const seg of schedule){ for(let yr = seg.fromYr; yr <= seg.toYr; yr++){ const moStart = (yr === seg.fromYr) ? seg.fromMo : 1; const moEnd = (yr === seg.toYr) ? seg.toMo : 12; const months = moEnd - moStart + 1; const amount = seg.annualAmount * (months / 12); schedMap[yr] = (schedMap[yr] || 0) + amount; if(yr > maxSchedYr) maxSchedYr = yr; } } const lastSegAmt = 0; // 0 = no contribution beyond schedule end // Update hints document.getElementById('rate-display').textContent = returnRate + '%'; // Update account close year const closeYearEl = document.getElementById('rule-close-year'); if(closeYearEl) closeYearEl.textContent = 'By Dec 31, ' + (startYear + 35); // ── Age calculation ── let childBirthYear, childCurrentAge; if(dob){ childBirthYear = parseInt(dob.split('-')[0]) || startYear; // parse directly — avoids timezone bug const today = new Date(); const dobMo = parseInt(dob.split('-')[1]) - 1; // 0-indexed month const dobDay = parseInt(dob.split('-')[2]); childCurrentAge = today.getFullYear() - childBirthYear; if(today.getMonth() < dobMo || (today.getMonth() === dobMo && today.getDate() < dobDay)) childCurrentAge--; childCurrentAge = Math.max(0, childCurrentAge); document.getElementById('child-age-display').textContent = 'Age: ' + childCurrentAge; } else { // Default: newborn, starting this year childBirthYear = startYear; childCurrentAge = 0; document.getElementById('child-age-display').textContent = 'Age: Enter DOB'; } // ── CESG Rules ── // Grant: 20% on first $2,500/year = $500/year max // Grant eligible: years where contribution made AND child was under 18 AND year <= year child turns 17 // Catch-up: if missed years, can contribute $5,000 and get $1,000 grant (up to 1 year catch-up per year) // Lifetime CESG: $7,200 max // Lifetime contribution: $50,000 max const CESG_RATE = 0.20; const CESG_MAX_ANNUAL = 500; // on first $2,500 const CESG_CATCH_UP_MAX = 1000; // on $5,000 if catch-up available const CESG_LIFETIME = 7200; const CONTRIB_LIFETIME = 50000; const GRANT_CONTRIB_THRESHOLD = 2500; // annual amount that gets full grant const CATCH_UP_CONTRIB = 5000; // annual amount for catch-up grant // ── Run simulation from startYear to year child turns 18 ── const year18 = childBirthYear + 18; const endYear = Math.max(year18, startYear + 1); let balance = 0; let totalContrib = 0; let totalGrants = 0; let totalInvested = 0; // Initialize unused grant room with ALL years from birth to RESP opening // (missed years accumulate $500/yr of catchable grant room) const missedYearsBeforeRESP = Math.max(0, startYear - childBirthYear); let unusedGrantRoom = missedYearsBeforeRESP * CESG_MAX_ANNUAL; let lifeContrib = 0; let cumCLB = 0; let totalCLB = 0; const r = returnRate / 100; // Track for chart const chartYears = []; const chartContrib = []; const chartGrants = []; const chartPortfolio = []; const tableRows = []; for(let yr = startYear; yr <= endYear; yr++){ const childAgeThisYear = yr - childBirthYear; // age at END of calendar year (simplified) // Is this year eligible for grants? // CESG: contributions made in calendar year when child is 0-17 (and contribution year <= year child turns 17) // Last full grant year: year child turns 14 (can get $500) // Year child turns 15: can get grant on prior year's missed room but not new room - simplified: no new room after yr child is 14 // Per CRA: Beneficiary must be under 18 at end of year, AND contributions before end of year child turns 17 // CESG room accumulates from birth, stops accumulating after Dec 31 of year child turns 17 // CRA: CESG room accumulates each year child is 0-17 (inclusive) // Last eligible contribution year = calendar year child turns 17 const grantEligible = childAgeThisYear <= 17 && totalGrants < CESG_LIFETIME; // Room accumulates each year age 0-17 — but pre-RESP years are already in unusedGrantRoom // So we only add room for years DURING the RESP (yr >= startYear), capped at 17 const roomAccumulatedThisYear = (childAgeThisYear <= 17 && yr >= startYear) ? CESG_MAX_ANNUAL : 0; unusedGrantRoom += roomAccumulatedThisYear; // Determine contribution for this year from schedule const annualContrib = schedMap[yr] !== undefined ? schedMap[yr] : lastSegAmt; let yearContrib; // Year 1: lump sum PLUS annual contribution (both apply) if(yr === startYear && lumpSum > 0){ yearContrib = Math.min(lumpSum + annualContrib, CONTRIB_LIFETIME - lifeContrib); } else { yearContrib = Math.min(annualContrib, Math.max(0, CONTRIB_LIFETIME - lifeContrib)); } // ── CLB calculation ── let yearCLB = 0; if(clbEnabled && childBirthYear >= 2004 && childAgeThisYear <= 15){ const clbThisYear = (totalCLB === 0) ? 500 : (totalCLB < 2000 ? 100 : 0); yearCLB = Math.min(clbThisYear, 2000 - totalCLB); } totalCLB += yearCLB; // Calc CESG for this year — CRA rules: // 20% on first $2,500 = $500 base grant (uses current year's room) // If contribute $5,000+: also claim 1 prior year's unused room = extra $500 (total $1,000) // unusedGrantRoom tracks $ of grant entitlement available let yearGrant = 0; if(grantEligible && yearContrib > 0){ if(yearContrib >= CATCH_UP_CONTRIB && unusedGrantRoom >= CESG_MAX_ANNUAL * 2){ // Catch-up year: $5,000+ contribution uses 2 years of room → $1,000 grant yearGrant = Math.min(CESG_MAX_ANNUAL * 2, unusedGrantRoom, CESG_LIFETIME - totalGrants); } else { // Regular year: 20% on first $2,500 → up to $500 grant const baseGrantable = Math.min(yearContrib, GRANT_CONTRIB_THRESHOLD); yearGrant = Math.min(baseGrantable * CESG_RATE, unusedGrantRoom, CESG_LIFETIME - totalGrants); } yearGrant = Math.max(0, yearGrant); // Consume grant room: room consumed equals the grant amount directly unusedGrantRoom -= yearGrant; } // Update totals totalContrib += yearContrib; totalGrants += yearGrant + yearCLB; lifeContrib += yearContrib; // Note: cumCLB is incremented in the finalRows section below to avoid double-counting const yearDeposit = yearContrib + yearGrant + yearCLB; totalInvested += yearDeposit; // Balance: start of year balance grows at r, then add year deposit // Per Excel: balance_start_of_year × (1 + r) + year_deposit // Wait — Excel shows: acc_start = prev_end, then end = (acc_start + yearDeposit) * ... // Actually from Excel: year 1: start=2500, end=2750 → (2500+500)*r/2 + (2500+500) doesn't work // Excel: 2026 start=2500, end=2750 → it looks like contributions are made mid-year: 3000*(1+0.10/2)=3150? No... // 2750 = 2500 + (3000 * 0.10 / 2 + ... ) → actually 2500*(1+0.10) = 2750! // So: year 1 starts with just the cash contribution (no grant yet?), grows at r // Year 2: start=5750 = 2750 + 3000, end = 5750*(1+0.10) = 6325 ✓ // So logic: deposit at START of year, then balance grows at r by year end // Year 1: deposit 3000, end = 3000*(1+r/2) = 3000*1.05 = 3150? No = 2750 // Actually: year1 end = (2500)*(1+r) = 2500*1.1 = 2750. Grant is added to START of year 2? // Year 2 start = 2750 + 3000 = 5750. So grant IS included in each year's deposit. // Year 1: only 2500 contrib grows (grant of 500 added but somehow = 2750). 2500*1.1=2750. Grant not in year 1? // Looking again: year1 deposit col = 3000 (2500+500), acc_start=2500, acc_end=2750=2500*1.1 // So the pattern is: contrib is deposited at start, grant added at END of prior period, grows from year 2 // Simpler: year end = (balance + contribution) * (1+r), grant included from next year? // No — easier: balance_end = balance_start * (1+r) + yearContrib*(1+r/2) + yearGrant*(1+r/2) // Let's just do: end = (balance + yearDeposit) * (1+r) — test: (0+3000)*1.1=3300 ≠ 2750 // Try: end = balance*(1+r) + yearDeposit — year1: 0*1.1+3000=3000 ≠ 2750 // Try: end = (balance + yearContrib)*(1+r) ignoring grant for growth: (0+2500)*1.1=2750 ✓ // year2: (2750+2500)*1.1=5775 ≠ 6325. Nope. // Try year2: (2750+3000)*1.1=6325 ✓! So year1 was special. // Actually year1: contrib=2500, grant=500 added mid-year? 2500*1.1=2750, then 2750+500=3250 start of yr2? No start=5750 // Year2 start=5750=2750+3000(new deposit). Year2 end=6325=5750*1.1. Yes! // Year1 end=2750=2500*1.1. So year1: deposit=2500 only. Grant (500) added to START of year2. // Actually simplest: contributions at start of year, grant received partway, // Model: end = (prevBalance + contrib) * (1+r) + grant [grant received at end, doesn't grow this year] // Year1: (0+2500)*1.1 + 500? = 3250 ≠ 2750. // OK let me just follow what works: year1 end=2500*(1+r), year2+ end=(prevEnd+deposit)*(1+r) // General formula that matches: balance = (balance + yearDeposit) * (1+r), but year1 contrib only gets half effect? // Most likely formula: balance_end = balance_start*(1+r) + yearDeposit // year1: 0*(1.1) + 2500 = 2500 ≠ 2750 // I think simplest match: contributions at start, balance grows at year end // year1: (0+2500+500)*(1+0.10) = 3300 ≠ 2750 // Let's accept: the Excel uses balance_start=only_contrib (not grant), end=start*(1+r), then grant added to next year start // This matches: yr1 end=2500*1.1=2750; yr2 start=2750+500+2500=5750; yr2 end=5750*1.1=6325 ✓ // So: Deposits to balance: contrib at START (included in this year's growth), grant received at YEAR END (added to next year's start) // Re-derive with correct approach: // Will track properly below using pending_grant balance = balance; // will recalculate properly tableRows.push({ yr, childAgeThisYear, yearContrib, yearGrant, yearCLB, yearDeposit, grantEligible }); chartYears.push(yr); } // ── Balance calculation: contrib + grant both deposited at start of year ── let bal = 0; let cumContrib = 0, cumGrants = 0, cumInvested = 0, cumLifeContrib = 0; const finalRows = []; for(let i = 0; i < tableRows.length; i++){ const row = tableRows[i]; const contrib = row.yearContrib; const grant = row.yearGrant; const clb = row.yearCLB || 0; // Contribution + CESG grant + CLB all deposited at start of year, earn full year growth bal = (bal + contrib + grant + clb) * (1 + r); cumContrib += contrib; cumGrants += grant; // CESG only — never mix with CLB cumCLB += clb; // CLB tracked separately cumInvested += contrib + grant + clb; cumLifeContrib += contrib; const totalGovtSoFar = cumGrants + cumCLB; const cumGrowth = Math.max(0, bal - cumContrib - totalGovtSoFar); finalRows.push({ yr: row.yr, age: row.childAgeThisYear, contrib: contrib, grant: grant, yearCLB: clb, yearTotal: contrib + grant + clb, endBal: bal, cumContrib: cumContrib, cumGrants: cumGrants, cumCLB: cumCLB, cumGrowth: cumGrowth, }); } // Last row = projection at 18 const last = finalRows[finalRows.length - 1] || {}; const projTotal = last.endBal || 0; const projContrib = last.cumContrib || 0; const projCESG = last.cumGrants || 0; const projCLB = clbEnabled ? (last.cumCLB || 0) : 0; const projGrants = projCESG + projCLB; // total govt grants = CESG + CLB const projGrowth = projTotal - projContrib - projGrants; // Grant calculations const grantCollected = projCESG; // CESG only for CESG tracker const grantRemaining = Math.max(0, CESG_LIFETIME - grantCollected); const grantPct = Math.min(100, grantCollected / CESG_LIFETIME * 100); const contribLifetime = Math.min(lifeContrib, 50000); const contribPct = Math.min(100, contribLifetime / CONTRIB_LIFETIME * 100); // Grant eligibility years remaining const today = new Date(); const currentYear = today.getFullYear(); const grantEndYear = childBirthYear + 17; // last year can get grant const grantYearsLeft = Math.max(0, grantEndYear - currentYear + 1); // ── Update UI ── document.getElementById('res-total').textContent = respFmtFull(projTotal); document.getElementById('res-contrib').textContent = respFmtFull(projContrib); document.getElementById('res-contrib-pct').textContent = respFmtPct(projContrib, projTotal) + ' of total'; document.getElementById('res-grants').textContent = '+' + respFmtFull(projGrants); document.getElementById('res-grants-note').textContent = respFmtPct(projGrants, projTotal) + ' of total value'; document.getElementById('res-growth').textContent = '+' + respFmtFull(Math.max(0, projGrowth)); document.getElementById('res-total-invested').textContent = respFmtFull(projContrib + projGrants); document.getElementById('res-years').textContent = 'Projected value at age 18 (' + (childBirthYear + 18) + ')'; const overLimit = contribLifetime >= CONTRIB_LIFETIME; document.getElementById('over-limit-strip').style.display = overLimit ? 'flex' : 'none'; if(overLimit) document.getElementById('res-limit-warn').textContent = 'At $50,000 limit — no more contributions'; // Over-limit error banner const errBanner = document.getElementById('over-limit-error'); const totalScheduleContrib = schedule.reduce((s,seg)=>{ const mos = (seg.toYr-seg.fromYr)*12+(seg.toMo-seg.fromMo+1); return s + seg.annualAmount * (mos/12); }, 0) + lumpSum; if(errBanner) errBanner.style.display = totalScheduleContrib > 50000 ? 'block' : 'none'; // Frontloading suggestion checkFrontload(schedule, contribLifetime, startYear, childBirthYear); // ── Find which year/month the $50K limit is hit ── let limitHitRow = null; let runningContrib = 0; for(const row of finalRows){ runningContrib += row.contrib; if(runningContrib >= 50000 && !limitHitRow){ limitHitRow = row; break; } } const limitWidget = document.getElementById('limit-widget'); if(limitHitRow){ limitWidget.style.display = 'block'; document.getElementById('limit-year').textContent = limitHitRow.yr; document.getElementById('limit-age').textContent = 'Age ' + limitHitRow.age; // Estimate which month — if annual contrib fills the remaining gap const prevRunning = runningContrib - limitHitRow.contrib; const remaining = 50000 - prevRunning; const monthNum = limitHitRow.contrib > 0 ? Math.ceil((remaining / limitHitRow.contrib) * 12) : 12; const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; const mo = Math.min(12, Math.max(1, monthNum)); document.getElementById('limit-month').textContent = months[mo-1] + ' ' + limitHitRow.yr; } else { limitWidget.style.display = 'none'; } // Grant tracker // ── CESG rows ── document.getElementById('gt-collected').textContent = respFmtFull(grantCollected); document.getElementById('gt-remaining').textContent = respFmtFull(grantRemaining); document.getElementById('gt-pct-label').textContent = grantPct.toFixed(0) + '% of lifetime CESG used'; document.getElementById('gt-bar').style.width = grantPct + '%'; // ── CLB rows (show/hide section) ── const clbSection = document.getElementById('clb-tracker-section'); const totalClbProjected = finalRows.reduce((s, r) => s + (r.yearCLB || 0), 0); if(clbEnabled && clbSection){ clbSection.style.display = 'block'; const clbRemaining = Math.max(0, 2000 - totalClbProjected); const clbBarPct = Math.min(100, totalClbProjected / 2000 * 100); document.getElementById('gt-clb-received').textContent = '+' + respFmtFull(totalClbProjected); document.getElementById('gt-clb-remaining').textContent = respFmtFull(clbRemaining); document.getElementById('gt-clb-pct-label').textContent = clbBarPct.toFixed(0) + '% of CLB received'; document.getElementById('gt-clb-bar').style.width = clbBarPct + '%'; } else if(clbSection){ clbSection.style.display = 'none'; } // ── Total govt. grants ── const totalGovt = grantCollected + (clbEnabled ? totalClbProjected : 0); document.getElementById('gt-total-grants').textContent = '+' + respFmtFull(totalGovt); // ── Contribution limit ── document.getElementById('gt-contrib-pct').textContent = respFmtFull(contribLifetime); document.getElementById('gt-contrib-label').textContent = contribPct.toFixed(0) + '% of $50,000 lifetime limit'; document.getElementById('gt-contrib-bar').style.width = contribPct + '%'; // ── Table ── const tbody = document.getElementById('resp-table-body'); tbody.innerHTML = finalRows.map(row => ` ${row.yr} Age ${row.age} ${row.contrib > 0 ? respFmtFull(row.contrib) : '—'} ${row.grant > 0 ? '+'+respFmtFull(row.grant) : '—'} ${(row.yearCLB||0) > 0 ? '+'+respFmtFull(row.yearCLB||0) : '—'} ${respFmtFull(row.yearTotal)} ${respFmtFull(row.endBal)} ${row.cumGrowth > 0 ? '+'+respFmtFull(row.cumGrowth) : '—'} `).join(''); // ── Chart ── const cYears = finalRows.map(r => r.yr); const cContrib = finalRows.map(r => r.cumContrib); const cGrants = finalRows.map(r => r.cumGrants); const cPortfolio = finalRows.map(r => r.endBal); respUpdateChart(cYears, cContrib, cGrants, cPortfolio); } // RESP initialized on first tab open
💬 WhatsApp 📞 Call