Cost of Variance
${costSign}$${costOfVariance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
`;
};
const renderCharts = () => {
destroyCharts();
// Bar Chart - Daily Production vs Target
const barCtx = document.getElementById('bar-chart')?.getContext('2d');
if (barCtx) {
const labels = dashboardData.dailyProduction.map(d => d.day);
const targetData = dashboardData.dailyProduction.map(d => d.target);
const actualData = dashboardData.dailyProduction.map(d => d.actual);
chartInstances.bar = new Chart(barCtx, {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: 'Actual Production',
data: actualData,
backgroundColor: 'rgba(22, 163, 74, 0.6)',
borderColor: 'rgba(21, 128, 61, 1)',
borderWidth: 1
},
{
label: 'Target Production',
data: targetData,
backgroundColor: 'rgba(203, 213, 225, 0.6)',
borderColor: 'rgba(100, 116, 139, 1)',
borderWidth: 1
}
]
},
options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true } } }
});
}
// Line Chart - Cumulative Variance
const lineCtx = document.getElementById('line-chart')?.getContext('2d');
if (lineCtx) {
let cumulativeVariance = 0;
const cumulativeData = dashboardData.dailyProduction.map(d => {
cumulativeVariance += (d.actual - d.target);
return cumulativeVariance;
});
const labels = dashboardData.dailyProduction.map(d => d.day);
chartInstances.line = new Chart(lineCtx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Cumulative Variance (Units)',
data: cumulativeData,
borderColor: 'rgba(37, 99, 235, 1)',
backgroundColor: 'rgba(59, 130, 246, 0.2)',
fill: true,
tension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
y: {
beginAtZero: false,
grid: {
color: (context) => (context.tick.value === 0 ? 'rgba(220, 38, 38, 0.5)' : 'rgba(0, 0, 0, 0.1)'),
lineWidth: (context) => (context.tick.value === 0 ? 2 : 1),
}
}
}
}
});
}
// Pie Chart - Variance by Line
const pieCtx = document.getElementById('pie-chart')?.getContext('2d');
if (pieCtx) {
const positiveVariance = dashboardData.varianceByLine.filter(l => l.variance > 0);
const labels = positiveVariance.map(l => `${l.line} (+${l.variance})`);
const data = positiveVariance.map(l => l.variance);
chartInstances.pie = new Chart(pieCtx, {
type: 'pie',
data: {
labels: labels,
datasets: [{
label: 'Positive Variance Contribution',
data: data,
backgroundColor: ['#16a34a', '#2563eb', '#6d28d9', '#db2777'],
hoverOffset: 4,
borderWidth: 0,
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: { position: 'bottom' },
title: { display: true, text: 'Contribution to Positive Variance' }
}
}
});
}
};
// --- 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');
updateAllViews();
alert('Dashboard updated successfully!');
showTab(0);
} 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;
const clone = dashboardElement.cloneNode(true);
const buttonInClone = clone.querySelector('#download-pdf-btn');
if (buttonInClone) buttonInClone.parentElement.remove();
const canvases = clone.querySelectorAll('canvas');
canvases.forEach(canvas => {
const chartId = canvas.id.split('-')[0];
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 = '';
pdfContainer.appendChild(clone);
html2canvas(pdfContainer, {
scale: 2,
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;
while (heightLeft > 0) {
position = heightLeft - finalImgHeight;
pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, finalImgHeight);
heightLeft -= pdfHeight;
}
pdf.save('Manufacturing_Variance_Report.pdf');
pdfContainer.innerHTML = '';
}).catch(err => {
console.error("PDF generation failed:", err);
alert("Sorry, there was an error creating the PDF.");
});
});
// --- INITIALIZATION ---
const updateAllViews = () => {
calculateMetrics();
renderKPIs();
renderCharts();
};
// Initial load
showTab(0);
updateAllViews();
populateConfigData();
});