View all ${savingsGoals.length} goals...
`;
overviewGoalsSummary.querySelector('.pfd-switch-tab-link').addEventListener('click', (e) => {
e.preventDefault();
console.log('Goals link clicked');
const targetTab = e.target.getAttribute('data-tab-target');
tabs.forEach(t => t.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
const targetButton = dashboardContainer.querySelector(`.pfd-tab-button[data-tab="${targetTab}"]`);
const targetContent = document.getElementById(`tab-${targetTab}`);
if (targetButton && targetContent) {
targetButton.classList.add('active');
targetContent.classList.add('active');
console.log(`Switched to goals tab via link`);
} else {
console.error(`Failed to switch to goals tab: button or content not found`);
}
});
}
}
console.log('Overview updated successfully');
} catch (e) {
console.error('Error in updateOverview:', e);
}
}
// PDF Export
function handleDownloadPdf() {
console.log('Handling PDF download');
try {
if (!window.jspdf) {
console.error('jsPDF not loaded, cannot generate PDF');
alert('PDF generation is unavailable due to a loading issue.');
return;
}
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const styles = getComputedStyle(document.documentElement);
const primaryColor = styles.getPropertyValue('--pfd-primary-color').trim() || '#2a9d8f';
const infoColor = styles.getPropertyValue('--pfd-info-color').trim() || '#457b9d';
const textColor = styles.getPropertyValue('--pfd-text-color').trim() || '#343a40';
const whiteColor = styles.getPropertyValue('--pfd-white-color').trim() || '#fff';
const successColor = styles.getPropertyValue('--pfd-success-color').trim() || '#2a9d8f';
const dangerColor = styles.getPropertyValue('--pfd-danger-color').trim() || '#e76f51';
let currentY = 20;
const leftMargin = 15;
const rightMargin = doc.internal.pageSize.width - 15;
const centerPage = doc.internal.pageSize.width / 2;
doc.setFontSize(18);
doc.setTextColor(primaryColor);
doc.text('Personal Finance Summary', centerPage, currentY, { align: 'center' });
currentY += 15;
doc.setFontSize(14);
doc.setTextColor(infoColor);
doc.text('Net Worth Summary', leftMargin, currentY);
currentY += 8;
doc.setDrawColor(styles.getPropertyValue('--pfd-border-color').trim());
doc.line(leftMargin, currentY - 2, rightMargin, currentY - 2);
currentY += 8;
const { totalAssets, totalLiabilities, netWorth } = calculateNetWorth();
doc.setFontSize(11);
doc.setTextColor(textColor);
doc.text(`Total Assets: ${formatCurrency(totalAssets)}`, leftMargin, currentY);
currentY += 7;
doc.text(`Total Liabilities: ${formatCurrency(totalLiabilities)}`, leftMargin, currentY);
currentY += 7;
doc.setFont('helvetica', 'bold');
doc.setTextColor(netWorth >= 0 ? successColor : dangerColor);
doc.text(`Net Worth: ${formatCurrency(netWorth)}`, leftMargin, currentY);
doc.setFont('helvetica', 'normal');
currentY += 15;
doc.setFontSize(14);
doc.setTextColor(infoColor);
doc.text(`Budget Summary (${budget.period || 'N/A'})`, leftMargin, currentY);
currentY += 8;
doc.line(leftMargin, currentY - 2, rightMargin, currentY - 2);
currentY += 8;
const { totalBudgeted, totalActual, difference } = calculateBudgetTotals();
doc.setFontSize(11);
doc.setTextColor(textColor);
doc.text(`Total Budgeted: ${formatCurrency(totalBudgeted)}`, leftMargin, currentY);
currentY += 7;
doc.text(`Total Spent: ${formatCurrency(totalActual)}`, leftMargin, currentY);
currentY += 7;
doc.setFont('helvetica', 'bold');
doc.setTextColor(difference >= 0 ? successColor : dangerColor);
doc.text(`Difference: ${formatCurrency(difference)}`, leftMargin, currentY);
doc.setFont('helvetica', 'normal');
currentY += 10;
if (budget.categories.length > 0) {
const budgetTableData = budget.categories.map(cat => [
cat.name,
formatCurrency(cat.budgeted),
formatCurrency(cat.actual),
formatCurrency(cat.budgeted - cat.actual)
]);
budgetTableData.push([
{ content: 'Total', styles: { fontStyle: 'bold' } },
{ content: formatCurrency(totalBudgeted), styles: { fontStyle: 'bold', halign: 'right' } },
{ content: formatCurrency(totalActual), styles: { fontStyle: 'bold', halign: 'right' } },
{ content: formatCurrency(difference), styles: { fontStyle: 'bold', halign: 'right', textColor: difference >= 0 ? successColor : dangerColor } }
]);
doc.autoTable({
head: [['Category', 'Budgeted', 'Actual', 'Difference']],
body: budgetTableData,
startY: currentY,
theme: 'grid',
headStyles: { fillColor: infoColor, textColor: whiteColor, fontStyle: 'bold' },
styles: { fontSize: 9, cellPadding: 2, textColor: textColor },
columnStyles: {
1: { halign: 'right' },
2: { halign: 'right' },
3: { halign: 'right' }
},
didParseCell: function (data) {
if (data.section === 'body' && data.column.index === 3) {
const rawValue = budget.categories[data.row.index]?.budgeted - budget.categories[data.row.index]?.actual;
if (rawValue !== undefined && rawValue < 0) {
data.cell.styles.textColor = dangerColor;
} else if (rawValue !== undefined && rawValue >= 0) {
data.cell.styles.textColor = successColor;
}
}
}
});
currentY = doc.lastAutoTable.finalY + 10;
}
if (expenseChartInstance && budget.categories.filter(cat => cat.actual > 0).length > 0) {
try {
const chartImage = expenseChartCanvas.toDataURL('image/png', 1.0);
const chartHeight = 80;
const chartWidth = 100;
if (currentY + chartHeight > doc.internal.pageSize.height - 20) {
doc.addPage();
currentY = 20;
}
doc.setFontSize(14);
doc.setTextColor(infoColor);
doc.text('Expense Breakdown Chart', leftMargin, currentY);
currentY += 8;
doc.line(leftMargin, currentY - 2, rightMargin, currentY - 2);
currentY += 5;
const imgX = centerPage - chartWidth / 2;
doc.addImage(chartImage, 'PNG', imgX, currentY, chartWidth, chartHeight);
currentY += chartHeight + 10;
} catch (error) {
console.error("Error adding chart to PDF:", error);
doc.setTextColor(dangerColor);
doc.text('Error rendering chart image.', leftMargin, currentY);
currentY += 10;
}
}
if (savingsGoals.length > 0) {
if (currentY + 20 > doc.internal.pageSize.height - 20) {
doc.addPage();
currentY = 20;
}
doc.setFontSize(14);
doc.setTextColor(infoColor);
doc.text('Savings Goals Progress', leftMargin, currentY);
currentY += 8;
doc.line(leftMargin, currentY - 2, rightMargin, currentY - 2);
currentY += 8;
const goalTableData = savingsGoals.map(goal => {
const progress = goal.target > 0 ? Math.min((goal.current / goal.target) * 100, 100) : 0;
return [
goal.name,
formatCurrency(goal.target),
formatCurrency(goal.current),
`${progress.toFixed(1)}%`
];
});
doc.autoTable({
head: [['Goal Name', 'Target ($)', 'Current ($)', 'Progress']],
body: goalTableData,
startY: currentY,
theme: 'grid',
headStyles: { fillColor: infoColor, textColor: whiteColor, fontStyle: 'bold' },
styles: { fontSize: 9, cellPadding: 2, textColor: textColor },
columnStyles: {
1: { halign: 'right' },
2: { halign: 'right' },
3: { halign: 'right' }
}
});
}
doc.save('personal-finance-summary.pdf');
console.log('PDF generated successfully');
} catch (e) {
console.error('Error in handleDownloadPdf:', e);
}
}
// Event Listeners Setup
function setupEventListeners() {
console.log('Setting up event listeners');
try {
if (addAssetForm) addAssetForm.addEventListener('submit', handleAddAsset);
if (assetsTableContainer) assetsTableContainer.addEventListener('click', handleRemoveAsset);
if (addLiabilityForm) addLiabilityForm.addEventListener('submit', handleAddLiability);
if (liabilitiesTableContainer) liabilitiesTableContainer.addEventListener('click', handleRemoveLiability);
if (budgetPeriodInput) budgetPeriodInput.addEventListener('change', handleBudgetPeriodChange);
if (addBudgetCategoryForm) addBudgetCategoryForm.addEventListener('submit', handleAddBudgetCategory);
if (budgetTableContainer) {
budgetTableContainer.addEventListener('click', handleRemoveBudgetCategory);
budgetTableContainer.addEventListener('change', handleActualBudgetChange);
}
if (addGoalForm) addGoalForm.addEventListener('submit', handleAddGoal);
if (goalsListUl) {
goalsListUl.addEventListener('click', handleRemoveGoal);
goalsListUl.addEventListener('click', handleGoalCurrentChange);
}
if (downloadPdfButton) downloadPdfButton.addEventListener('click', handleDownloadPdf);
console.log('Event listeners attached successfully');
} catch (e) {
console.error('Error in setupEventListeners:', e);
}
}
// Initialization
function init() {
console.log('init called');
try {
console.log('Loading assets');
assets = loadData('pfd_assets', []);
console.log('Loading liabilities');
liabilities = loadData('pfd_liabilities', []);
console.log('Loading budget');
budget = loadData('pfd_budget', { period: "", categories: [] });
console.log('Loading savings goals');
savingsGoals = loadData('pfd_savingsGoals', []);
console.log('Rendering net worth');
renderNetWorth();
console.log('Rendering budget');
renderBudget();
console.log('Rendering savings goals');
renderSavingsGoals();
console.log('Updating overview');
updateOverview();
console.log('Setting up event listeners');
setupEventListeners();
console.log('Setting budget period input');
if (budgetPeriodInput) {
budgetPeriodInput.value = budget.period;
} else {
console.error('budgetPeriodInput not found');
}
console.log('Initialization completed');
} catch (e) {
console.error('Error during initialization:', e.message, e.stack);
throw e; // Rethrow to catch in outer try-catch
}
}
// Start the application
try {
console.log('Starting initialization');
setupTabs(); // Call setupTabs first to ensure tabs work
init();
} catch (e) {
console.error('Failed to initialize dashboard:', e.message, e.stack);
}
});