No deal data to display.
`;
}
renderReasonsChart(metrics.reasons);
renderCompetitorChart(metrics.competitors);
};
const renderReasonsChart = (reasons) => {
const ctx = elements.reasonsChartCanvas?.getContext('2d');
if (!ctx) return;
const labels = Object.keys(reasons);
if (reasonsChart) reasonsChart.destroy();
reasonsChart = new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [
{ label: 'Won', data: labels.map(l => reasons[l].won), backgroundColor: '#22c55e' },
{ label: 'Lost', data: labels.map(l => reasons[l].lost), backgroundColor: '#ef4444' }
]
},
options: { responsive: true, maintainAspectRatio: true, scales: { x: { stacked: true }, y: { stacked: true } } }
});
};
const renderCompetitorChart = (competitors) => {
const ctx = elements.competitorChartCanvas?.getContext('2d');
if (!ctx) return;
const labels = Object.keys(competitors);
if (competitorChart) competitorChart.destroy();
competitorChart = new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [
{ label: 'Won', data: labels.map(l => competitors[l].won), backgroundColor: '#3b82f6' },
{ label: 'Lost', data: labels.map(l => competitors[l].lost), backgroundColor: '#f97316' }
]
},
options: { responsive: true, maintainAspectRatio: true, indexAxis: 'y', plugins: { legend: { position: 'top' } } }
});
};
const renderConfigPanel = () => {
const container = elements.editableList;
if (!container) return;
container.innerHTML = '';
dealData.forEach(d => {
const card = document.createElement('div');
card.className = 'grid grid-cols-1 md:grid-cols-4 gap-4 items-center bg-white p-3 rounded-lg border';
card.innerHTML = `
`;
container.appendChild(card);
});
};
const handleAddLog = (e) => {
e.preventDefault();
try {
const newLog = {
id: dealData.length > 0 ? Math.max(...dealData.map(d => d.id)) + 1 : 1,
name: document.getElementById('dealName').value,
competitor: document.getElementById('competitor').value,
value: parseFloat(document.getElementById('dealValue').value) || 0,
cycle: parseInt(document.getElementById('salesCycle').value) || 0,
status: document.getElementById('status').value,
reason: document.getElementById('reason').value,
};
dealData.push(newLog);
elements.addForm.reset();
renderAll();
showToast('Deal record added!');
} catch (error) {
console.error("Error adding record:", error);
showToast("Error: Could not add record.");
}
};
const handleConfigListClick = (e) => {
const target = e.target.closest('button');
if (!target) return;
const action = target.dataset.action;
const id = parseInt(target.dataset.id, 10);
if (action === 'update') {
const index = dealData.findIndex(d => d.id === id);
if (index === -1) return;
const inputs = target.closest('.grid').querySelectorAll('input');
inputs.forEach(input => {
const field = input.dataset.field;
let value = input.value;
if (input.type === 'number') value = parseFloat(value) || 0;
dealData[index][field] = value;
});
} else if (action === 'delete') {
dealData = dealData.filter(d => d.id !== id);
}
renderAll();
showToast(`Record ${action}d successfully!`);
};
const handleGeneratePDF = () => {
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const metrics = calculateMetrics();
doc.setFontSize(20);
doc.text("Win/Loss Analysis Report", 105, 20, null, null, 'center');
doc.setFontSize(10);
doc.text(`Generated on: ${new Date().toLocaleDateString()}`, 105, 26, null, null, 'center');
doc.autoTable({ startY: 35, head: [['Metric', 'Value']], body: [ ['Win Rate', `${metrics.winRate.toFixed(1)}%`], ['Avg. Won Deal Size', formatCurrency(metrics.avgWin)], ['Avg. Lost Deal Size', formatCurrency(metrics.avgLoss)], ['Avg. Sales Cycle (Days)', metrics.avgCycle.toFixed(0)] ], theme: 'grid' });
let finalY = doc.lastAutoTable.finalY || 60;
doc.setFontSize(14);
doc.text("Win/Loss Reasons", 14, finalY + 15);
doc.addImage(elements.reasonsChartCanvas.toDataURL('image/png', 1.0), 'PNG', 14, finalY + 20, 180, 80);
finalY += 95;
doc.setFontSize(14);
doc.text("Deal Log", 14, finalY);
const sortedData = [...dealData].sort((a, b) => b.id - a.id);
const tableBody = sortedData.slice(0, 20).map(d => [d.name, d.status, d.reason, formatCurrency(d.value)]);
doc.autoTable({ head: [['Deal', 'Status', 'Reason', 'Value']], body: tableBody, startY: finalY + 5, theme: 'striped', headStyles: { fillColor: [220, 38, 38] } });
doc.save('Win-Loss-Analysis-Report.pdf');
} catch (error) {
console.error("Failed to generate PDF:", error);
showToast("Error: Could not generate PDF.");
}
};
const switchTab = (tabName) => {
currentTab = tabName;
Object.values(elements.tabs).forEach(tab => tab.classList.add('hidden'));
Object.values(elements.tabButtons).forEach(btn => btn.classList.remove('active'));
elements.tabs[tabName].classList.remove('hidden');
elements.tabButtons[tabName].classList.add('active');
updateNavButtons();
};
const navigateTabs = (direction) => {
const currentIndex = tabOrder.indexOf(currentTab);
const newIndex = direction === 'next' ? Math.min(currentIndex + 1, tabOrder.length - 1) : Math.max(currentIndex - 1, 0);
if (newIndex !== currentIndex) switchTab(tabOrder[newIndex]);
};
const updateNavButtons = () => {
const currentIndex = tabOrder.indexOf(currentTab);
elements.navButtons.prev.disabled = currentIndex === 0;
elements.navButtons.next.disabled = currentIndex === tabOrder.length - 1;
};
const showToast = (message) => {
if (!elements.toast) return;
elements.toast.textContent = message;
elements.toast.classList.add('show');
setTimeout(() => { elements.toast.classList.remove('show'); }, 3000);
}
elements.addForm.addEventListener('submit', handleAddLog);
elements.editableList.addEventListener('click', handleConfigListClick);
elements.pdfButton.addEventListener('click', handleGeneratePDF);
elements.tabButtons.dashboard.addEventListener('click', () => switchTab('dashboard'));
elements.tabButtons.config.addEventListener('click', () => switchTab('config'));
elements.navButtons.prev.addEventListener('click', () => navigateTabs('prev'));
elements.navButtons.next.addEventListener('click', () => navigateTabs('next'));
renderAll();
updateNavButtons();
});