/* ===================================================== FraudLens — Frontend Logic Matches: fraudlens-2o2ev52.public.builtwithrocket.new ===================================================== */ 'use strict'; // ------------------------------------------------------- // LUCIDE ICONS INIT // ------------------------------------------------------- function startup() { if (window.lucide) { lucide.createIcons(); initApp(); } else { const script = document.createElement('script'); script.src = "https://unpkg.com/lucide@latest"; script.onload = () => { lucide.createIcons(); initApp(); }; document.head.appendChild(script); } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', startup); } else { startup(); } // ------------------------------------------------------- // STATE // ------------------------------------------------------- let currentResult = null; // ------------------------------------------------------- // UTILITY: Toast // ------------------------------------------------------- function showToast(message, type = 'info', duration = 3000) { const container = document.getElementById('toastContainer'); const toast = document.createElement('div'); toast.className = `toast ${type}`; const icons = { success: '✓', error: '⚠', info: 'ℹ' }; toast.innerHTML = `${icons[type] || 'ℹ'} ${message}`; container.appendChild(toast); setTimeout(() => { toast.style.transition = 'all 0.3s ease'; toast.style.opacity = '0'; toast.style.transform = 'translateX(20px)'; setTimeout(() => toast.remove(), 300); }, duration); } // ------------------------------------------------------- // NAVIGATION: switch between form / result screens // ------------------------------------------------------- function showScreen(name) { const screens = { form: 'formScreen', loading: 'loadingScreen', result: 'resultScreen' }; Object.keys(screens).forEach(k => { document.getElementById(screens[k]).classList.add('hidden'); }); document.getElementById(screens[name]).classList.remove('hidden'); // Update nav active state ['navAnalyzeBtn', 'navResultBtn'].forEach(id => { document.getElementById(id)?.classList.remove('active'); }); ['mobileNavAnalyze', 'mobileNavResult'].forEach(id => { document.getElementById(id)?.classList.remove('active'); }); if (name === 'form') { document.getElementById('navAnalyzeBtn')?.classList.add('active'); document.getElementById('mobileNavAnalyze')?.classList.add('active'); } else if (name === 'result') { document.getElementById('navResultBtn')?.classList.add('active'); document.getElementById('mobileNavResult')?.classList.add('active'); } } // ------------------------------------------------------- // COLLAPSIBLE CARDS // ------------------------------------------------------- function initCollapsible() { document.querySelectorAll('.collapsible-card').forEach(card => { const header = card.querySelector('.collapsible-header'); header.addEventListener('click', () => { card.classList.toggle('active'); }); }); } // ------------------------------------------------------- // LIVE RISK PREVIEW (sidebar) // ------------------------------------------------------- const RISK_CONFIG = { low: { label: 'LOW RISK', description: 'Transaction within normal parameters', color: 'var(--legit-green)', bg: 'var(--legit-green-muted)', border: 'var(--legit-green-border)', icon: 'shield-check' }, medium: { label: 'MEDIUM RISK', description: 'Borderline indicators — review recommended', color: 'var(--warn-amber)', bg: 'var(--warn-amber-muted)', border: 'var(--warn-amber-border)', icon: 'alert-triangle' }, high: { label: 'HIGH RISK', description: 'Multiple fraud signals detected', color: 'var(--fraud-red)', bg: 'var(--fraud-red-muted)', border: 'var(--fraud-red-border)', icon: 'shield-alert' }, critical: { label: 'CRITICAL RISK', description: 'Strong fraud indicators present — block and investigate', color: 'var(--fraud-red)', bg: 'rgba(239, 68, 68, 0.18)', border: 'var(--fraud-red-border)', icon: 'alert-octagon' } }; function computeRiskLevel(amount) { if (!amount || isNaN(amount)) return null; const a = parseFloat(amount); if (a > 5000) return 'critical'; if (a > 2000) return 'high'; if (a > 500) return 'medium'; return 'low'; } function updateRiskPreview(riskLevel) { const box = document.getElementById('liveRiskPreview'); if (!riskLevel) { box.innerHTML = `
Enter transaction amount to see a live risk preview
`; box.className = 'risk-preview-empty'; if (window.lucide) lucide.createIcons(); return; } const cfg = RISK_CONFIG[riskLevel]; box.className = 'risk-preview-filled'; box.style.background = cfg.bg; box.style.borderColor = cfg.border; box.innerHTML = `${cfg.label}
${cfg.description}
`; if (window.lucide) lucide.createIcons(); } // ------------------------------------------------------- // COMPUTE FEATURE CONTRIBUTIONS (client-side, matching original) // ------------------------------------------------------- function computeFeatureContributions(formData) { const amount = parseFloat(formData.amount) || 0; const distHome = parseFloat(formData.distanceFromHome) || 0; const distLast = parseFloat(formData.distanceFromLastTxn) || 0; const creditLimit = parseFloat(formData.creditLimit) || 1; const currentBalance = parseFloat(formData.currentBalance) || 0; const accountAge = parseFloat(formData.accountAge) || 0; const utilization = currentBalance / creditLimit; const highRiskCategories = ['crypto', 'online_retail', 'travel']; const categoryRisk = highRiskCategories.includes(formData.merchantCategory) ? 0.7 : 0.2; const contributions = [ { feature: 'Transaction Amount', contribution: Math.min(0.95, (amount / 10000) * 0.9), direction: 'positive', value: `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2 })}` }, { feature: 'Credit Utilization', contribution: utilization > 0.8 ? 0.75 : utilization * 0.7, direction: utilization > 0.5 ? 'positive' : 'negative', value: `${(utilization * 100).toFixed(0)}%` }, { feature: 'Merchant Category', contribution: categoryRisk, direction: categoryRisk > 0.5 ? 'positive' : 'negative', value: formData.merchantCategory.replace('_', ' ') }, { feature: 'Account Age', contribution: accountAge < 12 ? 0.55 : 0.15, direction: accountAge < 12 ? 'positive' : 'negative', value: `${accountAge} mo` }, { feature: 'Distance from Home', contribution: Math.min(0.8, distHome / 500), direction: distHome > 50 ? 'positive' : 'negative', value: `${distHome.toFixed(1)} km` }, { feature: 'Distance from Last Txn', contribution: Math.min(0.65, distLast / 400), direction: distLast > 30 ? 'positive' : 'negative', value: `${distLast.toFixed(1)} km` }, { feature: 'Address Match', contribution: formData.addressMatch === 'no' ? 0.6 : 0.1, direction: formData.addressMatch === 'no' ? 'positive' : 'negative', value: formData.addressMatch === 'yes' ? 'Matched' : 'Mismatch' }, { feature: 'Country Match', contribution: formData.countryMatch === 'no' ? 0.55 : 0.08, direction: formData.countryMatch === 'no' ? 'positive' : 'negative', value: formData.countryMatch === 'yes' ? 'Same' : 'Cross-border' }, { feature: 'Email Domain', contribution: ['protonmail.com', 'temp.com', 'guerrillamail.com'].some(d => (formData.emailDomain || '').includes(d)) ? 0.44 : 0.12, direction: ['protonmail.com', 'temp.com'].some(d => (formData.emailDomain || '').includes(d)) ? 'positive' : 'negative', value: formData.emailDomain || '—' }, { feature: 'Card Type', contribution: formData.cardType === 'debit' ? 0.21 : 0.38, direction: formData.cardType === 'credit' ? 'positive' : 'negative', value: formData.cardType } ]; return contributions.sort((a, b) => b.contribution - a.contribution); } function computeRiskLevelFromProb(prob) { if (prob >= 0.7) return 'critical'; if (prob >= 0.5) return 'high'; if (prob >= 0.3) return 'medium'; return 'low'; } function generateTxnId() { return 'TXN-' + Date.now().toString(36).toUpperCase() + '-' + Math.floor(Math.random() * 9000 + 1000); } // ------------------------------------------------------- // GAUGE ANIMATION // ------------------------------------------------------- const GAUGE_CIRCUMFERENCE = 251.2; // half circle circumference ≈ π * r = π * 80 function setGauge(prob) { const fill = document.getElementById('gaugeFill'); const needleLine = document.getElementById('needleLine'); const needleOuter = document.getElementById('needleCircleOuter'); const scoreText = document.getElementById('gaugeScoreText'); const riskLabel = document.getElementById('gaugeRiskLabel'); const color = prob >= 0.7 ? '#ef4444' : prob >= 0.5 ? '#f97316' : prob >= 0.3 ? '#f59e0b' : '#22c55e'; const offset = GAUGE_CIRCUMFERENCE * (1 - prob); fill.style.strokeDashoffset = offset; // Needle position: angle from 0 (left=0%) to π (right=100%) over half-circle const angle = Math.PI * prob; // 0 = left, π = right const needleX = 110 + 72 * Math.cos(Math.PI - angle); const needleY = 110 - 72 * Math.sin(Math.PI - angle); needleLine.setAttribute('x2', needleX); needleLine.setAttribute('y2', needleY); needleLine.setAttribute('stroke', color); needleLine.style.filter = `drop-shadow(0 0 4px ${color})`; needleOuter.setAttribute('fill', color); // Animate score counter const startTime = performance.now(); const duration = 1400; function tick(now) { const t = Math.min((now - startTime) / duration, 1); const eased = 1 - Math.pow(1 - t, 3); // ease-out cubic const current = eased * prob; scoreText.textContent = (current * 100).toFixed(1); scoreText.style.color = color; if (t < 1) requestAnimationFrame(tick); } requestAnimationFrame(tick); // Risk label const labels = { low: 'LOW RISK', medium: 'MEDIUM RISK', high: 'HIGH RISK', critical: 'CRITICAL RISK' }; const rl = computeRiskLevelFromProb(prob); riskLabel.textContent = labels[rl]; riskLabel.style.color = color; // Zone bars updateZoneBars(prob); } function updateZoneBars(prob) { const zones = [ { el: document.querySelector('[data-zone="safe"]'), active: prob < 0.3, color: '#22c55e' }, { el: document.querySelector('[data-zone="review"]'), active: prob >= 0.3 && prob < 0.5, color: '#f59e0b' }, { el: document.querySelector('[data-zone="high"]'), active: prob >= 0.5 && prob < 0.7, color: '#f97316' }, { el: document.querySelector('[data-zone="fraud"]'), active: prob >= 0.7, color: '#ef4444' } ]; zones.forEach(({ el, active, color }) => { if (!el) return; el.innerHTML = ` ${el.dataset.label} `; el.style.background = active ? `${color}18` : 'transparent'; el.style.borderColor = active ? `${color}40` : 'transparent'; }); } // ------------------------------------------------------- // RENDER RESULT SCREEN // ------------------------------------------------------- function renderResultScreen(result) { const prob = result.fraudProbability; const level = result.riskLevel; const formData = result.formData || {}; // --- Top verdict badge --- const isFraud = prob >= 0.5; const isReview = prob >= 0.3 && prob < 0.5; const verdictBadge = document.getElementById('verdictTopBadge'); if (isFraud) { verdictBadge.textContent = '⚠ FRAUD FLAGGED'; verdictBadge.style.background = 'var(--fraud-red-muted)'; verdictBadge.style.borderColor = 'var(--fraud-red-border)'; verdictBadge.style.color = 'var(--fraud-red)'; } else if (isReview) { verdictBadge.textContent = '◎ REVIEW REQUIRED'; verdictBadge.style.background = 'var(--warn-amber-muted)'; verdictBadge.style.borderColor = 'var(--warn-amber-border)'; verdictBadge.style.color = 'var(--warn-amber)'; } else { verdictBadge.textContent = '✓ LEGITIMATE'; verdictBadge.style.background = 'var(--legit-green-muted)'; verdictBadge.style.borderColor = 'var(--legit-green-border)'; verdictBadge.style.color = 'var(--legit-green)'; } // Gradient divider color const divider = document.getElementById('resultDivider'); if (isFraud) { divider.style.background = 'linear-gradient(90deg, var(--fraud-red) 0%, var(--border) 40%, transparent 100%)'; } else if (isReview) { divider.style.background = 'linear-gradient(90deg, var(--warn-amber) 0%, var(--border) 40%, transparent 100%)'; } else { divider.style.background = 'linear-gradient(90deg, var(--legit-green) 0%, var(--border) 40%, transparent 100%)'; } // --- Transaction ID & Timestamp --- const now = new Date(); const dateStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')} at ${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`; document.getElementById('resultTxnId').textContent = result.transactionId; document.getElementById('resultTimestamp').textContent = dateStr; document.getElementById('copyTxnIdText').textContent = result.transactionId; // --- Gauge --- setTimeout(() => setGauge(prob), 150); // --- Verdict Card --- const verdictCard = document.getElementById('verdictCard'); const verdictIcon = document.getElementById('verdictIcon'); const verdictIconBox = document.getElementById('verdictIconBox'); const verdictLabel = document.getElementById('verdictLabel'); const verdictSublabel = document.getElementById('verdictSublabel'); const verdictDesc = document.getElementById('verdictDescription'); if (isFraud) { verdictCard.className = 'verdict-card fraud animate-fade-in-up'; verdictIconBox.style.background = 'rgba(239, 68, 68, 0.2)'; verdictIconBox.style.borderColor = 'var(--fraud-red-border)'; verdictIcon.setAttribute('data-lucide', 'shield-off'); verdictLabel.textContent = 'FRAUDULENT'; verdictLabel.style.color = 'var(--fraud-red)'; verdictSublabel.textContent = 'Transaction flagged for fraud'; verdictDesc.textContent = 'This transaction has been flagged by the ML model as likely fraudulent. Immediate review and potential block recommended.'; } else if (isReview) { verdictCard.className = 'verdict-card review animate-fade-in-up'; verdictIconBox.style.background = 'rgba(245, 158, 11, 0.2)'; verdictIconBox.style.borderColor = 'var(--warn-amber-border)'; verdictIcon.setAttribute('data-lucide', 'alert-triangle'); verdictLabel.textContent = 'REVIEW REQUIRED'; verdictLabel.style.color = 'var(--warn-amber)'; verdictSublabel.textContent = 'Manual review recommended'; verdictDesc.textContent = 'Borderline risk score detected. Manual analyst review is recommended before approving or declining this transaction.'; } else { verdictCard.className = 'verdict-card legit animate-fade-in-up'; verdictIconBox.style.background = 'rgba(34, 197, 94, 0.2)'; verdictIconBox.style.borderColor = 'var(--legit-green-border)'; verdictIcon.setAttribute('data-lucide', 'check-circle'); verdictLabel.textContent = 'LEGITIMATE'; verdictLabel.style.color = 'var(--legit-green)'; verdictSublabel.textContent = 'Transaction appears genuine'; verdictDesc.textContent = 'The ML model indicates this transaction is within normal parameters. Low fraud risk detected.'; } // --- Confidence Analysis --- const confidence = isFraud ? Math.min(0.99, prob + 0.08) : Math.min(0.99, 1 - prob + 0.05); const ciLow = Math.max(0, prob - 0.06); const ciHigh = Math.min(1, prob + 0.06); document.getElementById('confidenceText').textContent = `${(confidence * 100).toFixed(1)}%`; document.getElementById('confidenceText').style.color = 'var(--foreground)'; setTimeout(() => { document.getElementById('confidenceBar').style.width = `${confidence * 100}%`; }, 300); document.getElementById('ciLow').textContent = `${(ciLow * 100).toFixed(1)}%`; document.getElementById('ciMid').textContent = `${(prob * 100).toFixed(1)}%`; document.getElementById('ciHigh').textContent = `${(ciHigh * 100).toFixed(1)}%`; // --- Feature Contributions --- const contributions = result.featureContributions || []; const maxContrib = Math.max(...contributions.map(c => c.contribution)); const list = document.getElementById('contributionsList'); list.innerHTML = ''; contributions.forEach((c, i) => { const isPositive = c.direction === 'positive'; const color = isPositive ? 'var(--fraud-red)' : 'var(--legit-green)'; const barWidth = maxContrib > 0 ? (c.contribution / maxContrib) * 100 : 0; const isTop = i === 0; const row = document.createElement('div'); row.className = 'contribution-row'; row.style.animationDelay = `${0.2 + 0.07 * i}s`; row.innerHTML = `${isBlocked ? 'Transaction Blocked' : 'Transaction Approved'}
Action recorded at ${new Date().toLocaleTimeString('en-US', { hour12: false })}