Conversion Rate
${kpis.conversionRate}%
`;
};
const renderCharts = () => {
destroyCharts(); // Clear old charts first
// Bar Chart
const barCtx = document.getElementById('bar-chart')?.getContext('2d');
if (barCtx) {
chartInstances.bar = new Chart(barCtx, {
type: 'bar',
data: {
labels: dashboardData.salesByRegion.labels,
datasets: [{
label: 'Sales ($)',
data: dashboardData.salesByRegion.data,
backgroundColor: 'rgba(56, 189, 248, 0.6)',
borderColor: 'rgba(2, 132, 199, 1)',
borderWidth: 1
}]
},
options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true } } }
});
}
// Line Chart
const lineCtx = document.getElementById('line-chart')?.getContext('2d');
if (lineCtx) {
chartInstances.line = new Chart(lineCtx, {
type: 'line',
data: {
labels: dashboardData.quarterlyPerformance.labels,
datasets: [
{
label: 'Revenue ($)',
data: dashboardData.quarterlyPerformance.revenue,
borderColor: 'rgba(2, 132, 199, 1)',
backgroundColor: 'rgba(56, 189, 248, 0.2)',
fill: true,
tension: 0.3
},
{
label: 'Profit ($)',
data: dashboardData.quarterlyPerformance.profit,
borderColor: 'rgba(16, 185, 129, 1)',
backgroundColor: 'rgba(52, 211, 153, 0.2)',
fill: true,
tension: 0.3
}
]
},
options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true } } }
});
}
// Pie Chart
const pieCtx = document.getElementById('pie-chart')?.getContext('2d');
if (pieCtx) {
chartInstances.pie = new Chart(pieCtx, {
type: 'pie',
data: {
labels: dashboardData.productCategoryMix.labels,
datasets: [{
data: dashboardData.productCategoryMix.data,
backgroundColor: ['#0ea5e9', '#10b981', '#f97316', '#6366f1'],
hoverOffset: 4
}]
},
options: { responsive: true, maintainAspectRatio: true }
});
}
// Doughnut Chart
const doughnutCtx = document.getElementById('doughnut-chart')?.getContext('2d');
if (doughnutCtx) {
chartInstances.doughnut = new Chart(doughnutCtx, {
type: 'doughnut',
data: {
labels: dashboardData.leadSources.labels,
datasets: [{
data: dashboardData.leadSources.data,
backgroundColor: ['#38bdf8', '#34d399', '#fbbf24', '#818cf8'],
hoverOffset: 4
}]
},
options: { responsive: true, maintainAspectRatio: true }
});
}
};
// --- DATA CONFIGURATION LOGIC ---
const populateConfigData = () => {
dataConfigInput.value = JSON.stringify(dashboardData, null, 2);
};
updateDashboardBtn.addEventListener('click', () => {
try {
const newData = JSON.parse(dataConfigInput.value);
dashboardData = newData; // Update the main data object
jsonErrorDiv.classList.add('hidden'); // Hide error message on success
updateAllViews();
alert('Dashboard updated successfully!');
showTab(0); // Switch back to dashboard view
} catch (error) {
jsonErrorMessage.textContent = 'Invalid JSON format. Please check your data. ' + error.message;
jsonErrorDiv.classList.remove('hidden');
}
});
// --- PDF GENERATION ---
downloadPdfBtn.addEventListener('click', () => {
const { jsPDF } = window.jspdf;
const pdfContainer = document.getElementById('pdf-content-container');
const dashboardElement = document.getElementById('dashboard-tab');
if (!pdfContainer || !dashboardElement) return;
// Clone the dashboard to prepare it for PDF generation
const clone = dashboardElement.cloneNode(true);
// Remove the download button from the clone
const buttonInClone = clone.querySelector('#download-pdf-btn');
if (buttonInClone) buttonInClone.parentElement.remove();
// Replace live canvases with static images for reliable PDF rendering
const canvases = clone.querySelectorAll('canvas');
canvases.forEach(canvas => {
const chartId = canvas.id.split('-')[0]; // e.g., 'bar', 'line'
if (chartInstances[chartId]) {
const image = new Image();
image.src = chartInstances[chartId].toBase64Image();
image.style.width = '100%';
image.style.height = 'auto';
canvas.parentNode.replaceChild(image, canvas);
}
});
pdfContainer.innerHTML = ''; // Clear previous content
pdfContainer.appendChild(clone);
html2canvas(pdfContainer, {
scale: 2, // Higher scale for better quality
useCORS: true,
logging: false,
width: pdfContainer.scrollWidth,
height: pdfContainer.scrollHeight,
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'pt',
format: 'a4'
});
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const imgWidth = canvas.width;
const imgHeight = canvas.height;
const ratio = imgWidth / imgHeight;
let finalImgHeight = pdfWidth / ratio;
let heightLeft = finalImgHeight;
let position = 0;
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, finalImgHeight);
heightLeft -= pdfHeight;
// Add new pages if content is too long
while (heightLeft > 0) {
position = heightLeft - finalImgHeight;
pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, finalImgHeight);
heightLeft -= pdfHeight;
}
pdf.save('Data_Visualization_Dashboard.pdf');
pdfContainer.innerHTML = ''; // Clean up
}).catch(err => {
console.error("PDF generation failed:", err);
alert("Sorry, there was an error creating the PDF.");
});
});
// --- INITIALIZATION ---
const updateAllViews = () => {
renderKPIs();
renderCharts();
};
// Initial load
showTab(0);
updateAllViews();
populateConfigData();
});