Spaces:
Running
Because 95% of attacks have a human interaction
Browse files'); printWindow.document.close(); printWindow.print(); } // File Handling function handleFile(file) { try { clearError(); if (!file) return; statusEl.textContent = 'Loaded: ' + file.name; const ext = (file.name.split('.').pop() || '').toLowerCase(); if (ext === 'csv') { Papa.parse(file, { header: true, skipEmptyLines: true, complete: (res) => safeIngest(res.data) }); } else if (ext === 'ods') { const reader = new FileReader(); reader.onload = function(ev) { try { const data = new Uint8Array(ev.target.result); const wb = XLSX.read(data, { type: 'array' }); const ws = wb.Sheets[wb.SheetNames[0]]; const json = XLSX.utils.sheet_to_json(ws, { defval: "" }); safeIngest(json); } catch (err) { showError('Could not read ODS: ' + err.message); } }; reader.readAsArrayBuffer(file); } else { showError('Unsupported file (use .csv or .ods)'); } } catch (err) { showError(err.message); } } // Safe Data Ingestion function safeIngest(rows) { try { ingest(rows); } catch (err) { showError('Build failed: ' + err.message); } } // Data Ingestion and Processing function ingest(rows) { rawRows = rows || []; if (!rawRows.length) { throw new Error('No rows found in file.'); } const cols = Object.keys(rawRows[0] || {}).map(c => c.replace(/^\uFEFF/, '')); if (!cols.length) { throw new Error('No columns detected. Ensure the first row has headers.'); } const colEmail = findCol(cols, ['email']); const colName = findCol(cols, ['name', 'full name']); const colScenario = findCol(cols, ['scenario', 'campaign', 'module']); const colClicked = findCol(cols, ['clicked', 'click']); const colTrained = findCol(cols, ['trained', 'completed', 'complete']); const colTrainedAt = findCol(cols, ['trained at', 'trained_at', 'trainedat', 'completed at', 'completion']); const missing = []; if (!colEmail) missing.push('Email'); if (!colScenario) missing.push('Scenario'); if (!colClicked) missing.push('Clicked (Y/N)'); if (!colTrained) missing.push('Trained (Y/N)'); if (missing.length) { throw new Error( 'Missing expected column(s): ' + missing.join(', ') + '\nFound columns: ' + cols.join(', ') + '\nTip: headers can include these keywords:\n' + 'Email → "email"\nScenario → "scenario"/"campaign"/"module"\nClicked → "clicked"/"click"\nTrained → "trained"/"completed"/"complete"' ); } const colSucceeded = findCol(cols, ['succeed', 'succeeded', 'success']); const colMailbox = findCol(cols, ['mailbox', 'mbox', 'mb']); const colSubject = findCol(cols, ['subject', 'email subject']); const colClickedAt = findCol(cols, ['clicked at', 'click time', 'clicked_time']); const colAwareSec = findCol(cols, ['awareness_time', 'awareness seconds', 'training time (s)']); const colType = findCol(cols, ['type', 'attack type', 'vector', 'payload']); const colSentAt = findCol(cols, ['sent at', 'send time', 'delivered at', 'sent']); hasSucceededCol = !!colSucceeded; hasMailbox = !!colMailbox; hasSubject = !!colSubject; hasClickedAt = !!colClickedAt; hasAwareSec = !!colAwareSec; hasTypeCol = !!colType; hasSentAt = !!colSentAt; campaignFirstSent = null; campaignLastClick = null; const base = rawRows.map(r => { const sentAtStr = hasSentAt ? (r[colSentAt] ?? '') : ''; const clickAtStr = hasClickedAt ? (r[colClickedAt] ?? '') : ''; const sentAt = parseDateSafe(sentAtStr); const clickAt = parseDateSafe(clickAtStr); if (sentAt) campaignFirstSent = (!campaignFirstSent || sentAt < campaignFirstSent) ? sentAt : campaignFirstSent; if (clickAt) campaignLastClick = (!campaignLastClick || clickAt > campaignLastClick) ? clickAt : campaignLastClick; const scenario = String(r[colScenario] ?? '').trim() || '(none)'; const rowType = hasTypeCol ? String(r[colType] ?? '') : ''; const inferredType = rowType ? rowType : inferTypeFromScenario(scenario); return { Email: String(r[colEmail] ?? '').trim().toLowerCase(), Name: (colName ? r[colName] : '') ?? '', Scenario: scenario, Clicked_any: yn01(r[colClicked]), Trained_any: yn01(r[colTrained]), TrainedAt: (colTrainedAt ? r[colTrainedAt] : '') ?? '', Attempts: 1, Succeeded: hasSucceededCol ? yn01(r[colSucceeded]) : null, Mailbox: hasMailbox ? String(r[colMailbox] ?? '') : '', Subject: hasSubject ? String(r[colSubject] ?? '') : '', ClickedAt: hasClickedAt ? (clickAtStr || '') : '', AwarenessTimeMin: hasAwareSec ? secondsToMMSS(r[colAwareSec]) : '', Type: inferredType }; }); const bySp = {}; for (const r of base) { const k = r.Scenario + '|' + r.Email + '|' + r.Name; if (!bySp[k]) { bySp[k] = { Scenario: r.Scenario, Email: r.Email, Name: r.Name, Type: r.Type, Attempts: 0, Clicked_Any: 0, Trained_Any: 0, TrainedAtLatest: '', Succeeded: r.Succeeded ?? null, Mailbox: r.Mailbox, Subject: r.Subject, ClickedAt: r.ClickedAt, AwarenessTimeMin: r.AwarenessTimeMin }; } const o = bySp[k]; o.Attempts += 1; o.Clicked_Any = Math.max(o.Clicked_Any, r.Clicked_any); o.Trained_Any = Math.max(o.Trained_Any, r.Trained_any); if (String(r.TrainedAt || '').trim() !== '') o.TrainedAtLatest = r.TrainedAt; if (r.Succeeded != null) o.Succeeded = Math.max(o.Succeeded ?? 0, r.Succeeded); if (r.ClickedAt && !o.ClickedAt) o.ClickedAt = r.ClickedAt; if (r.AwarenessTimeMin && !o.AwarenessTimeMin) o.AwarenessTimeMin = r.AwarenessTimeMin; if (r.Type && !o.Type) o.Type = r.Type; } perScenPerson = Object.values(bySp); scenarios = Array.from(new Set(perScenPerson.map(x => x.Scenario))).sort(); build(); } // Build Report function build() { // Clear previous content scenariosContainer.innerHTML = ''; destroyCharts(); if (!scenarios.length) { scenariosContainer.innerHTML = '
No scenarios in data.
'; return; } const groups = {}; scenarios.forEach(s => groups[s] = []); for (const r of perScenPerson) { groups[r.Scenario].push(r); } const kpis = Object.keys(groups).map(s => { const g = groups[s]; const uniq = new Set(g.map(x => x.Email)).size; const sends = g.reduce((a, b) => a + b.Attempts, 0); const clicked = g.reduce((a, b) => a + (b.Clicked_Any ? 1 : 0), 0); const trained = g.reduce((a, b) => a + (b.Trained_Any ? 1 : 0), 0); const succ = (hasSucceededCol && g.some(x => x.Succeeded != null)) ? g.reduce((a, b) => a + (b.Succeeded ? 1 : 0), 0) : null; const type = majorityType(g); return { Scenario: s, Unique: uniq, Sends: sends, Clicked: clicked, Trained: trained, Succeeded: succ, Type: type }; }).sort((a, b) => a.Scenario.localeCompare(b.Scenario)); const totals = kpis.reduce((a, k) => ({ Unique: a.Unique + k.Unique, Sends: a.Sends + k.Sends, Clicked: a.Clicked + k.Clicked, Trained: a.Trained + k.Trained, Succeeded: (a.Succeeded ?? 0) + (k.Succeeded ?? 0) }), { Unique: 0, Sends: 0, Clicked: 0, Trained: 0, Succeeded: 0 }); // Update KPI cards document.getElementById('uniquePeople').textContent = totals.Unique; document.getElementById('totalSends').textContent = totals.Sends; document.getElementById('clickedAny').textContent = totals.Clicked; document.getElementById('trainedAny').textContent = totals.Trained; document.getElementById('succeededAny').textContent = totals.Succeeded; // Create scenario cards kpis.forEach(k => { const scen = k.Scenario; const sub = groups[scen].slice().sort((a, b) => a.Email.localeCompare(b.Email)); const not = sub.filter(x => !x.Trained_Any).sort((a, b) => a.Email.localeCompare(b.Email)); const id = 'c_' + scen.replace(/[^a-z0-9]/gi, '_') + '_' + Math.random().toString(36).slice(2, 6); const pct = (num, den) => den ? Math.round((num / den) * 100) : 0; const pctClicked = pct(k.Clicked, k.Unique); const pctTrained = pct(k.Trained, k.Unique); const pctSucc = hasSucceededCol && k.Succeeded != null ? pct(k.Succeeded, k.Unique) : null; const card = document.createElement('div'); card.className = 'scenario-card'; card.dataset.scenario = scen; card.innerHTML = `
${scen} (Type: ${k.Type || '—'})
All Recipients
Users Not Trained
People ${k.Unique} • Sends ${k.Sends}
Clicked: ${k.Clicked} (${pctClicked}%)
Trained: ${k.Trained} (${pctTrained}%)
${hasSucceededCol && k.Succeeded != null ? `
Succeeded: ${k.Succeeded} (${pctSucc}%)
` : ''}
`; scenariosContainer.appendChild(card); // Create chart const ctx = document.getElementById(id).getContext('2d'); const datasets = [ { label: 'Sends', data: [k.Sends], backgroundColor: '#60a5fa' }, { label: 'Clicked (any)', data: [k.Clicked], backgroundColor: '#f59e0b' }, { label: 'Trained (any)', data: [k.Trained], backgroundColor: '#0fb9b9' } ]; if (hasSucceededCol && k.Succeeded != null) { datasets.push({ label: 'Succeeded (any)', data: [k.Succeeded], backgroundColor: '#94a3b8' }); } const ref = new Chart(ctx, { type: 'bar', data: { labels: [scen], datasets: datasets }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { display: false, grid: { display: false } }, y: { display: false, grid: { display: false } } } } }); chartRefs[id] = ref; card.dataset.all = JSON.stringify(sub); card.dataset.not = JSON.stringify(not); }); // Add event listeners to scenario buttons document.querySelectorAll('.scenario-card .btn').forEach(btn => { btn.addEventListener('click', function() { const scenario = this.closest('.scenario-card').dataset.scenario; if (this.dataset.all) { openAll(scenario); } else if (this.dataset.not) { openNot(scenario); } }); }); // Render mailbox statistics const anyMailbox = hasMailbox && perScenPerson.some(r => r.Mailbox && r.Clicked_Any); if (anyMailbox) { const rows = perScenPerson .filter(r => r.Clicked_Any && r.Mailbox) .map(r => ({ Mailbox: r.Mailbox, Email: r.Email, Name: r.Name, Scenario: r.Scenario, "Clicked At": (hasClickedAt ? r.ClickedAt : '') })); if (rows.length) { renderTable('mailboxTable', rows, ['Mailbox', 'Email', 'Name', 'Scenario', 'Clicked At']); } else { document.getElementById('mailboxTable').innerHTML = '
No mailbox clicks recorded.
'; } } // Render detailed data const anyDetail = hasClickedAt || hasSubject || hasAwareSec || hasTypeCol || true; if (anyDetail) { const rows = perScenPerson.map(r => { const out = { Name: r.Name, Email: r.Email, Type: r.Type || '', "Clicked": r.Clicked_Any ? 'Y' : 'N', "Trained": r.Trained_Any ? 'Y' : 'N', "Scenario": r.Scenario }; if (hasClickedAt) out["Clicked At"] = r.ClickedAt || ''; if (hasSucceededCol && r.Succeeded != null) out["Succeeded"] = r.Succeeded ? 'Y' : 'N'; if (hasSubject) out["Email subject"]
185 unmodified lines18618718818919019119219319419519619719876 unmodified lines27527627727827928010 unmodified lines291292293294295296297298299300301302303304305306307308309119 unmodified lines42943043143243343443521 unmodified lines45745845946046146246313 unmodified lines47747847948048148248315 unmodified lines4995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285 unmodified lines534535536537538539540405 unmodified lines9469479489499509515 unmodified lines957958959960961962963114 unmodified lines1078107910801081185 unmodified linesbackground-color: rgba(255, 255, 255, 0.03);}.tagline {text-align: center;color: var(--gray);font-size: 0.9rem;margin-top: 30px;}.scenario-header {display: flex;justify-content: space-between;76 unmodified linesjustify-content: flex-end;}}</style></head><body class="min-h-screen">10 unmodified lines<div class="text-sm text-gray-400 mt-1" id="status">Choose CSV/ODS → Report builds automatically → Export PDF</div></div></div><div class="flex flex-wrap gap-3"><input type="file" id="fileInput" accept=".csv,.ods" class="file-upload" /><label for="fileInput" class="btn btn-outline flex items-center gap-2"><i data-feather="upload"></i> Upload Data</label><button class="btn btn-primary flex items-center gap-2" id="btnExportPDF"><i data-feather="download"></i> Export PDF</button><button class="btn btn-secondary flex items-center gap-2" id="btnExportWord"><i data-feather="file-text"></i> Export Word</button></div></div></header><!-- Error Bar -->119 unmodified lines</div></div><div class="tagline container mx-auto px-4 py-6">Because 95% of attacks have a human interaction</div>21 unmodified linesconst scenariosContainer = document.getElementById('scenarios-container');const dlAllPage = document.getElementById('dlAllPage');const dlNotPage = document.getElementById('dlNotPage');const btnAIDraft = document.getElementById('btnAIDraft');const btnExecCSV = document.getElementById('btnExecCSV');const btnExpandDetail = document.getElementById('btnExpandDetail');const btnCollapseDetail = document.getElementById('btnCollapseDetail');13 unmodified linesdlAllPage.addEventListener('click', () => downloadCSV('all_recipients_page.csv', collectPage('all')));dlNotPage.addEventListener('click', () => downloadCSV('users_not_trained_page.csv', collectPage('not')));btnAIDraft.addEventListener('click', generateAIDraft);btnExecCSV.addEventListener('click', downloadExecCSV);btnExpandDetail.addEventListener('click', expandDetailTable);btnCollapseDetail.addEventListener('click', collapseDetailTable);dlAllCSV.addEventListener('click', () => downloadCSV('all_recipients.csv', modalAllRows));15 unmodified lines// Export Functionsfunction exportPDF() {// Hide elements that shouldn't appear in PDFconst elementsToHide = document.querySelectorAll('.no-print, .btn, .scenario-actions, .ai-bar');elementsToHide.forEach(el => {el.classList.add('hidden-in-pdf');el.style.display = 'none';});// Generate PDFwindow.print();// Restore elements after a short delaysetTimeout(() => {elementsToHide.forEach(el => {el.classList.remove('hidden-in-pdf');el.style.display = '';});}, 1000);}function exportWord() {// Create a new window with only the contentconst printWindow = window.open('', '', 'height=600,width=800');printWindow.document.write('<html><head><title>Security Report</title>');printWindow.document.write('</head><body>');printWindow.document.write(document.querySelector('main').innerHTML);printWindow.document.write('</body></html>');printWindow.document.close();5 unmodified linestry {clearError();if (!file) return;statusEl.textContent = 'Loaded: ' + file.name;const ext = (file.name.split('.').pop() || '').toLowerCase();if (ext === 'csv') {405 unmodified linesconst slice = rows.slice(0, Math.max(0, limit || 0));renderTable(containerId, slice, cols);}function expandDetailTable() {expandTable('detailTable');document.getElementById('btnExpandDetail').classList.add('hidden');5 unmodified linesdocument.getElementById('btnCollapseDetail').classList.add('hidden');document.getElementById('btnExpandDetail').classList.remove('hidden');}function expandTable(containerId) {const t = window.__TABLES[containerId];if (!t) return;renderTable(containerId, t.rows, t.cols);114 unmodified lines}</script></body></html>185 unmodified lines18618718818919019176 unmodified lines26826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330410 unmodified lines315316317318319320321322323324325326327328329330331332333119 unmodified lines45345445545645745845921 unmodified lines48148248348448548648713 unmodified lines50150250350450550650715 unmodified lines5235245255265275285295305315325335345355365375385395405415425435445455 unmodified lines551552553554555556557405 unmodified lines9639649659669679689695 unmodified lines975976977978979980981982114 unmodified lines1097109810991100185 unmodified linesbackground-color: rgba(255, 255, 255, 0.03);}.scenario-header {display: flex;justify-content: space-between;76 unmodified linesjustify-content: flex-end;}}@media print {.no-print, .btn, .scenario-actions, .ai-bar, .modal {display: none !important;}body {background-color: white;color: black;}.card {border: 1px solid #ccc;box-shadow: none;page-break-inside: avoid;}.scenario-card {border: 1px solid #ccc;box-shadow: none;page-break-inside: avoid;}table {page-break-inside: avoid;}th, td {border: 1px solid #ccc;}}</style></head><body class="min-h-screen">10 unmodified lines<div class="text-sm text-gray-400 mt-1" id="status">Choose CSV/ODS → Report builds automatically → Export PDF</div></div></div><div class="flex flex-wrap gap-3"><input type="file" id="fileInput" accept=".csv,.ods" class="file-upload" /><label for="fileInput" class="btn btn-outline flex items-center gap-2"><i data-feather="upload"></i> Upload Data</label><button class="btn btn-primary flex items-center gap-2" id="btnExportPDF"><i data-feather="download"></i> Export PDF</button><button class="btn btn-secondary flex items-center gap-2" id="btnExportWord"><i data-feather="file-text"></i> Export Word</button></div></div></header><!-- Error Bar -->119 unmodified lines</div></div><div class="tagline container mx-auto px-4 py-6 text-center text-gray-400">Because 95% of attacks have a human interaction</div>21 unmodified linesconst scenariosContainer = document.getElementById('scenarios-container');const dlAllPage = document.getElementById('dlAllPage');const dlNotPage = document.getElementById('dlNotPage');const btnAIDraft = document.getElementById('btnAIDraft');const btnExecCSV = document.getElementById('btnExecCSV');const btnExpandDetail = document.getElementById('btnExpandDetail');const btnCollapseDetail = document.getElementById('btnCollapseDetail');13 unmodified linesdlAllPage.addEventListener('click', () => downloadCSV('all_recipients_page.csv', collectPage('all')));dlNotPage.addEventListener('click', () => downloadCSV('users_not_trained_page.csv', collectPage('not')));btnAIDraft.addEventListener('click', generateAIDraft);btnExecCSV.addEventListener('click', downloadExecCSV);btnExpandDetail.addEventListener('click', expandDetailTable);btnCollapseDetail.addEventListener('click', collapseDetailTable);dlAllCSV.addEventListener('click', () => downloadCSV('all_recipients.csv', modalAllRows));15 unmodified lines// Export Functionsfunction exportPDF() {window.print();}function exportWord() {// Create a new window with only the contentconst printWindow = window.open('', '', 'height=600,width=800');printWindow.document.write('<html><head><title>Security Report</title>');printWindow.document.write('<style>');printWindow.document.write('body { font-family: Arial, sans-serif; }');printWindow.document.write('table { border-collapse: collapse; width: 100%; }');printWindow.document.write('th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }');printWindow.document.write('th { background-color: #f2f2f2; }');printWindow.document.write('.card { border: 1px solid #ccc; padding: 20px; margin: 20px 0; }');printWindow.document.write('h1, h2, h3 { color: #333; }');printWindow.document.write('</style>');printWindow.document.write('</head><body>');printWindow.document.write('<h1>' + document.getElementById('clientTitle').innerText + '</h1>');printWindow.document.write(document.querySelector('main').innerHTML);printWindow.document.write('</body></html>');printWindow.document.close();5 unmodified linestry {clearError();if (!file) return;statusEl.textContent = 'Loaded: ' + file.name;const ext = (file.name.split('.').pop() || '').toLowerCase();if (ext === 'csv') {405 unmodified linesconst slice = rows.slice(0, Math.max(0, limit || 0));renderTable(containerId, slice, cols);}function expandDetailTable() {expandTable('detailTable');document.getElementById('btnExpandDetail').classList.add('hidden');5 unmodified linesdocument.getElementById('btnCollapseDetail').classList.add('hidden');document.getElementById('btnExpandDetail').classList.remove('hidden');}function expandTable(containerId) {const t = window.__TABLES[containerId];if (!t) return;renderTable(containerId, t.rows, t.cols);114 unmodified lines}</script></body></html>