Spaces:
Sleeping
Sleeping
File size: 34,708 Bytes
368a487 b2de624 b1ebd8d b2de624 368a487 b2de624 368a487 9c80ddd 368a487 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 | /* =====================================================
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 = `<span style="font-size:14px;">${icons[type] || 'ℹ'}</span> ${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 = `
<i data-lucide="shield" style="width:24px;height:24px;color:var(--muted-foreground);display:block;margin:0 auto 8px;"></i>
<p class="text-xs" style="color:var(--muted-foreground);">Enter transaction amount to see a live risk preview</p>
`;
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 = `
<div style="display:flex;align-items:center;gap:12px;margin-bottom:8px;">
<div style="width:32px;height:32px;border-radius:8px;background:${cfg.bg};border:1px solid ${cfg.border};display:flex;align-items:center;justify-content:center;flex-shrink:0;">
<i data-lucide="${cfg.icon}" style="width:16px;height:16px;color:${cfg.color};"></i>
</div>
<div>
<p style="font-size:12px;font-weight:700;letter-spacing:0.05em;color:${cfg.color};">${cfg.label}</p>
</div>
</div>
<p style="font-size:11px;color:var(--muted-foreground);">${cfg.description}</p>
`;
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 = `
<div style="width:100%;height:4px;border-radius:2px;background:${color};opacity:${active ? 1 : 0.3};"></div>
<span style="font-size:10px;font-family:var(--font-mono);color:${active ? color : 'var(--muted-foreground)'};">${el.dataset.label}</span>
`;
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 = `
<div class="contribution-row-top">
<div class="contribution-label-group">
${isTop ? '<span class="top-badge">TOP</span>' : ''}
<span style="font-size:13px;font-weight:500;color:var(--foreground);">${c.feature}</span>
</div>
<div class="contribution-meta">
<span class="contrib-value-badge">${c.value}</span>
<span class="contrib-pct" style="color:${color};">${isPositive ? '+' : '-'}${(c.contribution * 100).toFixed(0)}%</span>
</div>
</div>
<div class="progress-track">
<div class="progress-fill" style="background:${color};box-shadow:${isPositive ? '0 0 8px rgba(239,68,68,0.4)' : '0 0 8px rgba(34,197,94,0.4)'};" data-width="${barWidth}"></div>
</div>
`;
list.appendChild(row);
});
// Animate bars after small delay
setTimeout(() => {
list.querySelectorAll('.progress-fill').forEach(fill => {
fill.style.width = fill.dataset.width + '%';
});
}, 200);
// --- Transaction Summary ---
const creditLimit = parseFloat(formData.creditLimit) || 1;
const currentBalance = parseFloat(formData.currentBalance) || 0;
const utilization = ((currentBalance / creditLimit) * 100).toFixed(0);
const txnAmount = parseFloat(formData.amount) || 0;
const summaryFields = [
{ label: 'Amount', value: `₹${txnAmount.toLocaleString('en-IN', { minimumFractionDigits: 2 })}`, mono: true },
{ label: 'Type', value: formData.transactionType || '—', mono: false },
{ label: 'Merchant', value: formData.merchantName || '—', mono: false },
{ label: 'Category', value: (formData.merchantCategory || '—').replace('_', ' '), mono: false },
{ label: 'Product CD', value: formData.productCD || '—', mono: true },
{ label: 'Card type', value: `${formData.cardCategory || ''} ${formData.cardType || ''}`.trim(), mono: false },
{ label: 'Acct age', value: `${formData.accountAge || '—'} mo`, mono: true },
{ label: 'Credit limit', value: `₹${parseFloat(formData.creditLimit || 0).toLocaleString('en-IN')}`, mono: true },
{ label: 'Utilization', value: `${utilization}%`, mono: true, highlight: parseInt(utilization) > 80 },
{ label: 'Email domain', value: formData.emailDomain || '—', mono: false }
];
const txnList = document.getElementById('txnSummaryList');
txnList.innerHTML = '';
summaryFields.forEach(f => {
const row = document.createElement('div');
row.className = 'txn-summary-row' + (f.highlight ? ' highlight' : '');
row.innerHTML = `
<span style="color:var(--muted-foreground);">${f.label}</span>
<span style="${f.mono ? 'font-family:var(--font-mono);' : ''}font-weight:500;color:${f.highlight ? 'var(--fraud-red)' : 'var(--foreground)'};">${f.value}</span>
`;
txnList.appendChild(row);
});
// --- Analyst Actions (reset state) ---
resetAnalystActions(level);
// Re-run lucide icons
if (window.lucide) lucide.createIcons();
}
function resetAnalystActions(riskLevel) {
const panel = document.getElementById('analystActionsPanel');
const isHighRisk = riskLevel === 'critical' || riskLevel === 'high';
panel.innerHTML = `
<div style="display:flex;flex-direction:column;gap:8px;">
<button type="button" class="btn-primary" id="btnBlockTransaction" style="background:${isHighRisk ? 'var(--fraud-red)' : 'var(--muted)'};color:${isHighRisk ? 'white' : 'var(--foreground)'};">
<i data-lucide="shield-off" style="width:14px;height:14px;"></i>
Block Transaction
</button>
<button type="button" class="btn-secondary" id="btnApproveTransaction">
<i data-lucide="check" style="width:14px;height:14px;"></i>
Approve Transaction
</button>
<button type="button" class="btn-ghost" id="btnFlagEscalation" style="width:100%;justify-content:center;">
<i data-lucide="flag" style="width:13px;height:13px;"></i>
Flag for Escalation
</button>
</div>
`;
if (window.lucide) lucide.createIcons();
document.getElementById('btnBlockTransaction')?.addEventListener('click', async () => {
if (!currentResult) return;
const btn = document.getElementById('btnBlockTransaction');
btn.disabled = true;
btn.innerHTML = `<i data-lucide="loader" style="width:14px;height:14px;" class="animate-spin"></i> Blocking...`;
if (window.lucide) lucide.createIcons();
await delay(900);
showActionResult('blocked', currentResult.transactionId);
});
document.getElementById('btnApproveTransaction')?.addEventListener('click', async () => {
if (!currentResult) return;
const btn = document.getElementById('btnApproveTransaction');
btn.disabled = true;
btn.innerHTML = `<i data-lucide="loader" style="width:14px;height:14px;" class="animate-spin"></i> Approving...`;
if (window.lucide) lucide.createIcons();
await delay(900);
showActionResult('approved', currentResult.transactionId);
});
document.getElementById('btnFlagEscalation')?.addEventListener('click', () => {
showToast('Transaction flagged for escalation', 'info', 3000);
});
}
function showActionResult(action, txnId) {
const panel = document.getElementById('analystActionsPanel');
const isBlocked = action === 'blocked';
panel.innerHTML = `
<div style="background:${isBlocked ? 'var(--fraud-red-muted)' : 'var(--legit-green-muted)'};border:1px solid ${isBlocked ? 'var(--fraud-red-border)' : 'var(--legit-green-border)'};border-radius:8px;padding:16px;text-align:center;">
<p style="font-size:14px;font-weight:600;color:${isBlocked ? 'var(--fraud-red)' : 'var(--legit-green)'};">${isBlocked ? 'Transaction Blocked' : 'Transaction Approved'}</p>
<p style="font-size:11px;color:var(--muted-foreground);margin-top:4px;">Action recorded at ${new Date().toLocaleTimeString('en-US', { hour12: false })}</p>
</div>
`;
showToast(
isBlocked ? `Transaction ${txnId} has been blocked` : `Transaction ${txnId} approved`,
isBlocked ? 'error' : 'success',
4000
);
}
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
// -------------------------------------------------------
// FORM SUBMIT
// -------------------------------------------------------
async function handleFormSubmit(e) {
e.preventDefault();
const form = document.getElementById('analyzerForm');
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Basic validation
let hasError = false;
const required = ['amount', 'merchantName', 'accountAge', 'creditLimit', 'currentBalance'];
required.forEach(field => {
const errEl = document.getElementById(`error-${field}`);
const val = data[field];
if (!val || val.toString().trim() === '') {
if (errEl) { errEl.textContent = 'This field is required'; errEl.classList.remove('hidden'); }
hasError = true;
} else {
if (errEl) errEl.classList.add('hidden');
}
});
if (hasError) {
showToast('Please fill in all required fields', 'error');
return;
}
// Show loading
showScreen('loading');
document.getElementById('btnSubmit').disabled = true;
try {
// Call the Gradio backend via Gradio Client
const { client } = await import("https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js");
const app = await client(window.location.origin);
const apiResponse = await app.predict("/predict", [JSON.stringify(data)]);
const serverResult = JSON.parse(apiResponse.data[0]);
const mlProb = serverResult.fraud_probability ?? 0.5;
// Compute feature contributions client-side (matching original behaviour)
const contributions = computeFeatureContributions(data);
const riskLevel = computeRiskLevelFromProb(mlProb);
const txnId = generateTxnId();
const result = {
fraudProbability: parseFloat(mlProb.toFixed(4)),
riskLevel,
transactionId: txnId,
featureContributions: contributions,
formData: data
};
// Persist to sessionStorage
try { sessionStorage.setItem('fraudPredictionResult', JSON.stringify(result)); } catch (ex) {}
currentResult = result;
showToast('Analysis complete — reviewing fraud verdict', 'success', 2500);
showScreen('result');
renderResultScreen(result);
} catch (err) {
console.error('API error:', err);
// Fallback: use client-side computation only
const contributions = computeFeatureContributions(data);
const amount = parseFloat(data.amount) || 0;
let baseProb = Math.min(0.95, amount / 12000);
if (data.addressMatch === 'no') baseProb += 0.15;
if (data.countryMatch === 'no') baseProb += 0.12;
if (['crypto', 'online_retail'].includes(data.merchantCategory)) baseProb += 0.2;
if ((parseFloat(data.currentBalance) / (parseFloat(data.creditLimit) || 1)) > 0.85) baseProb += 0.1;
baseProb = Math.min(0.99, baseProb);
const riskLevel = computeRiskLevelFromProb(baseProb);
const txnId = generateTxnId();
const result = {
fraudProbability: parseFloat(baseProb.toFixed(4)),
riskLevel,
transactionId: txnId,
featureContributions: contributions,
formData: data
};
try { sessionStorage.setItem('fraudPredictionResult', JSON.stringify(result)); } catch (ex) {}
currentResult = result;
showToast('Analysis complete (offline mode)', 'info', 2500);
showScreen('result');
renderResultScreen(result);
} finally {
document.getElementById('btnSubmit').disabled = false;
}
}
// -------------------------------------------------------
// COPY TXN ID
// -------------------------------------------------------
function initCopyTxnId() {
document.getElementById('btnCopyTxnId')?.addEventListener('click', () => {
if (!currentResult) return;
navigator.clipboard.writeText(currentResult.transactionId).then(() => {
const btn = document.getElementById('btnCopyTxnId');
const originalHtml = btn.innerHTML;
btn.innerHTML = `<i data-lucide="check" style="width:11px;height:11px;color:var(--legit-green);"></i> <span style="font-size:10px;font-family:var(--font-mono);">Copied!</span>`;
if (window.lucide) lucide.createIcons();
showToast('Transaction ID copied', 'success', 2000);
setTimeout(() => { btn.innerHTML = originalHtml; if (window.lucide) lucide.createIcons(); }, 2000);
}).catch(() => showToast('Could not copy to clipboard', 'error'));
});
}
// -------------------------------------------------------
// INIT APP
// -------------------------------------------------------
function initApp() {
// Collapsible
initCollapsible();
// Live risk preview on amount change
document.getElementById('amount')?.addEventListener('input', e => {
updateRiskPreview(computeRiskLevel(e.target.value));
});
// Form submit
document.getElementById('analyzerForm')?.addEventListener('submit', handleFormSubmit);
// Clear form
document.getElementById('btnClearForm')?.addEventListener('click', () => {
document.getElementById('analyzerForm').reset();
updateRiskPreview(null);
document.querySelectorAll('.input-error').forEach(el => el.classList.add('hidden'));
showToast('Form cleared', 'info', 1500);
});
// Nav: Analyze Transaction
document.getElementById('navAnalyzeBtn')?.addEventListener('click', e => {
e.preventDefault();
showScreen('form');
closeMobileMenu();
});
// Nav: Last Result
document.getElementById('navResultBtn')?.addEventListener('click', e => {
e.preventDefault();
loadLastResult();
closeMobileMenu();
});
// Mobile nav links
document.getElementById('mobileNavAnalyze')?.addEventListener('click', e => {
e.preventDefault();
showScreen('form');
closeMobileMenu();
});
document.getElementById('mobileNavResult')?.addEventListener('click', e => {
e.preventDefault();
loadLastResult();
closeMobileMenu();
});
// Mobile menu toggle
document.getElementById('mobileMenuBtn')?.addEventListener('click', toggleMobileMenu);
// Back to form from result
document.getElementById('btnNewAnalysis')?.addEventListener('click', () => {
showScreen('form');
document.getElementById('navAnalyzeBtn').classList.add('active');
document.getElementById('navResultBtn').classList.remove('active');
});
// Analyze another (footer of result)
document.getElementById('btnAnalyzeAnother')?.addEventListener('click', () => {
showScreen('form');
document.getElementById('navAnalyzeBtn').classList.add('active');
document.getElementById('navResultBtn').classList.remove('active');
});
// Export Report
document.getElementById('btnExportReport')?.addEventListener('click', () => {
if (!currentResult) return;
const json = JSON.stringify(currentResult, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${currentResult.transactionId}_fraud_report.json`;
a.click();
URL.revokeObjectURL(url);
showToast('Report exported as JSON', 'success');
});
// Copy Txn ID
initCopyTxnId();
// Logo link → form
document.getElementById('logoLink')?.addEventListener('click', e => {
e.preventDefault();
showScreen('form');
document.getElementById('navAnalyzeBtn').classList.add('active');
document.getElementById('navResultBtn').classList.remove('active');
});
// Try to restore session
try {
const saved = sessionStorage.getItem('fraudPredictionResult');
if (saved) {
const parsed = JSON.parse(saved);
currentResult = parsed;
}
} catch (ex) {}
}
// -------------------------------------------------------
// LOAD LAST RESULT (from sessionStorage or demo)
// -------------------------------------------------------
function loadLastResult() {
let result = currentResult;
if (!result) {
try {
const saved = sessionStorage.getItem('fraudPredictionResult');
if (saved) result = JSON.parse(saved);
} catch (ex) {}
}
if (!result) {
// Demo data (matches original site's demo)
result = {
fraudProbability: 0.8312,
riskLevel: 'critical',
transactionId: 'TXN-M3X7K2-8841',
featureContributions: [
{ feature: 'Transaction Amount', contribution: 0.82, direction: 'positive', value: '₹3,247.00' },
{ feature: 'Credit Utilization', contribution: 0.74, direction: 'positive', value: '91%' },
{ feature: 'Merchant Category', contribution: 0.63, direction: 'positive', value: 'crypto' },
{ feature: 'Account Age', contribution: 0.51, direction: 'positive', value: '8 mo' },
{ feature: 'Email Domain', contribution: 0.44, direction: 'positive', value: 'protonmail.com' },
{ feature: 'Card Type', contribution: 0.21, direction: 'negative', value: 'credit' }
],
formData: {
amount: '3247.00', transactionType: 'purchase', merchantCategory: 'crypto',
merchantName: 'CoinBase Pro', productCD: 'R', cardType: 'credit',
cardCategory: 'visa', cardIssuerBank: '185', accountAge: '8',
creditLimit: '5000', currentBalance: '4550', previousBalance: '420',
emailDomain: 'protonmail.com', addressMatch: 'no', distanceFromHome: '312.4',
distanceFromLastTxn: '287.1', countryMatch: 'no'
}
};
}
currentResult = result;
showScreen('result');
renderResultScreen(result);
}
// -------------------------------------------------------
// MOBILE MENU
// -------------------------------------------------------
function toggleMobileMenu() {
const nav = document.getElementById('mobileNav');
const open = document.getElementById('menuIconOpen');
const close = document.getElementById('menuIconClose');
if (nav.classList.contains('hidden')) {
nav.classList.remove('hidden');
open.style.display = 'none';
close.style.display = 'block';
} else {
closeMobileMenu();
}
}
function closeMobileMenu() {
const nav = document.getElementById('mobileNav');
const open = document.getElementById('menuIconOpen');
const close = document.getElementById('menuIconClose');
nav.classList.add('hidden');
open.style.display = 'block';
close.style.display = 'none';
}
|