Spaces:
Running
Running
Download index.html from Koolbox/security-report-pro: direct link, hf CLI and curl.
- Browser
- Download file 50.6 kB
-
https://huggingface.co/spaces/Koolbox/security-report-pro/resolve/main/index.html
- Command line
-
hf download hf://spaces/Koolbox/security-report-pro/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Koolbox/security-report-pro/resolve/main/index.html
50.6 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Security Report Pro</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/papaparse@5.4.1/papaparse.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary: #6366f1;
--primary-dark: #4f46e5;
--secondary: #10b981;
--dark: #0f172a;
--light: #f8fafc;
--gray: #94a3b8;
--card-bg: #1e293b;
--border: #334155;
}
body {
font-family: 'Inter', sans-serif;
background-color: var(--dark);
color: var(--light);
}
.card {
background-color: var(--card-bg);
border: 1px solid var(--border);
border-radius: 12px;
padding: 20px;
transition: all 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.25);
}
.btn {
padding: 10px 20px;
border-radius: 8px;
font-weight: 600;
transition: all 0.2s ease;
border: none;
cursor: pointer;
}
.btn-primary {
background-color: var(--primary);
color: white;
}
.btn-primary:hover {
background-color: var(--primary-dark);
}
.btn-secondary {
background-color: var(--secondary);
color: white;
}
.btn-outline {
background: transparent;
border: 1px solid var(--border);
color: var(--light);
}
.btn-outline:hover {
background-color: rgba(255, 255, 255, 0.05);
}
.metric-card {
background: linear-gradient(135deg, #334155 0%, #1e293b 100%);
border-radius: 12px;
padding: 20px;
text-align: center;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.metric-value {
font-size: 2rem;
font-weight: 700;
margin: 10px 0;
}
.metric-label {
color: var(--gray);
font-size: 0.9rem;
}
.scenario-card {
background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
border-radius: 12px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid var(--border);
}
.chart-container {
position: relative;
height: 150px;
width: 100%;
}
.logo-placeholder {
border: 2px dashed var(--border);
border-radius: 12px;
height: 80px;
display: flex;
align-items: center;
justify-content: center;
color: var(--gray);
cursor: pointer;
transition: all 0.3s ease;
}
.logo-placeholder:hover {
background-color: rgba(255, 255, 255, 0.05);
}
.file-upload {
display: none;
}
.status-bar {
background-color: rgba(99, 102, 241, 0.1);
border: 1px solid var(--primary);
border-radius: 8px;
padding: 10px 15px;
margin: 15px 0;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
z-index: 1000;
align-items: center;
justify-content: center;
}
.modal-content {
background-color: var(--card-bg);
border-radius: 12px;
width: 90%;
max-width: 800px;
max-height: 90vh;
overflow-y: auto;
border: 1px solid var(--border);
}
.close-modal {
position: absolute;
top: 15px;
right: 15px;
cursor: pointer;
color: var(--gray);
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid var(--border);
}
th {
background-color: rgba(255, 255, 255, 0.05);
font-weight: 600;
}
tr:hover {
background-color: rgba(255, 255, 255, 0.03);
}
.scenario-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
flex-wrap: wrap;
gap: 10px;
}
.scenario-title {
font-size: 1.25rem;
font-weight: 600;
}
.scenario-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.metrics-row {
display: flex;
gap: 20px;
margin-top: 15px;
flex-wrap: wrap;
}
.metric-chip {
background-color: rgba(255, 255, 255, 0.05);
padding: 5px 12px;
border-radius: 20px;
font-size: 0.85rem;
}
textarea {
width: 100%;
background-color: rgba(255, 255, 255, 0.05);
border: 1px solid var(--border);
border-radius: 8px;
padding: 15px;
color: var(--light);
font-family: 'Inter', sans-serif;
resize: vertical;
}
textarea:focus {
outline: none;
border-color: var(--primary);
}
.ai-bar {
display: flex;
gap: 10px;
margin-bottom: 15px;
flex-wrap: wrap;
}
.error-bar {
background-color: rgba(239, 68, 68, 0.1);
border: 1px solid #ef4444;
border-radius: 8px;
padding: 15px;
margin-bottom: 20px;
display: none;
}
@media (max-width: 768px) {
.metrics-row {
flex-direction: column;
gap: 10px;
}
.scenario-header {
flex-direction: column;
align-items: flex-start;
}
.scenario-actions {
width: 100%;
justify-content: flex-end;
}
}
@media print {
.no-print, .btn, .scenario-actions, .ai-bar, .modal, .tagline, #btnExpandDetail, #btnCollapseDetail {
display: none !important;
}
body {
background-color: white;
color: black;
font-size: 12px;
margin: 0;
padding: 0;
}
header {
margin: 0 !important;
padding: 10px !important;
}
.card {
border: 1px solid #ccc;
box-shadow: none;
page-break-inside: avoid;
margin-bottom: 15px;
padding: 10px !important;
}
.scenario-card {
border: 1px solid #ccc;
box-shadow: none;
page-break-inside: avoid;
margin-bottom: 10px;
padding: 8px !important;
}
table {
page-break-inside: avoid;
font-size: 10px;
width: 100%;
}
th, td {
border: 1px solid #999;
padding: 4px 6px;
}
.metric-card {
border: 1px solid #ccc;
box-shadow: none;
margin-bottom: 8px;
padding: 8px !important;
}
.metric-value {
font-size: 1.2rem;
margin: 5px 0;
}
h1, h2, h3 {
color: black;
margin: 10px 0;
}
.chart-container {
height: 80px !important;
margin: 5px 0;
}
textarea {
border: 1px solid #999;
background: white;
}
}
</style>
</head>
<body class="min-h-screen">
<!-- Header -->
<header class="container mx-auto px-4 py-6">
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
<div class="flex items-center gap-4">
<div class="logo-placeholder w-48" id="logo-slot">
<span id="logo-text">Upload Logo</span>
<input type="file" accept="image/*" id="logo-input" class="file-upload" />
</div>
<div>
<h1 id="clientTitle" contenteditable="true" class="text-2xl md:text-3xl font-bold">Client Name Report</h1>
<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 -->
<div id="errBox" class="error-bar container mx-auto px-4"></div>
<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
<!-- KPI Cards -->
<section id="kpis" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
<div class="metric-card">
<div class="metric-label">Unique People</div>
<div class="metric-value" id="uniquePeople">0</div>
</div>
<div class="metric-card">
<div class="metric-label">Total Sends</div>
<div class="metric-value" id="totalSends">0</div>
</div>
<div class="metric-card">
<div class="metric-label">Clicked (any)</div>
<div class="metric-value" id="clickedAny">0</div>
</div>
<div class="metric-card">
<div class="metric-label">Trained (any)</div>
<div class="metric-value" id="trainedAny">0</div>
</div>
<div class="metric-card">
<div class="metric-label">Succeeded (any)</div>
<div class="metric-value" id="succeededAny">0</div>
</div>
</section>
<!-- Scenarios Section -->
<section class="mb-10">
<div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-bold">Scenarios</h2>
<div class="flex gap-3">
<button class="btn btn-secondary flex items-center gap-2" id="dlAllPage">
<i data-feather="download"></i> All Recipients
</button>
<button class="btn btn-outline flex items-center gap-2" id="dlNotPage">
<i data-feather="download"></i> Not Trained
</button>
</div>
</div>
<div id="scenarios-container" class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- Scenario cards will be dynamically inserted here -->
</div>
</section>
<!-- Executive Summary -->
<section class="card mb-10">
<h2 class="text-xl font-bold mb-4">Executive Summary & Recommendations</h2>
<div class="ai-bar">
<button class="btn btn-outline flex items-center gap-2" id="btnAIDraft">
<i data-feather="cpu"></i> Draft with AI
</button>
<button class="btn btn-outline flex items-center gap-2" id="btnExecCSV">
<i data-feather="download"></i> Download Summary CSV
</button>
</div>
<div class="mb-6">
<div class="font-medium mb-2">Executive Summary</div>
<textarea id="txtSummary" placeholder="Quarterly overview, outcomes, highlights..." rows="4"></textarea>
</div>
<div class="mb-6">
<div class="font-medium mb-2">Key Insights</div>
<textarea id="txtInsights" placeholder="Completion pockets, repeat clickers, mailbox patterns..." rows="4"></textarea>
</div>
<div>
<div class="font-medium mb-2">Recommendations (Next 90 Days)</div>
<textarea id="txtRecos" placeholder="3–6 actions…" rows="4"></textarea>
</div>
</section>
<!-- Mailbox Statistics -->
<section id="mailbox-stats" class="card mb-10">
<h2 class="text-xl font-bold mb-4">Mailbox Statistics</h2>
<div class="text-gray-400 mb-4">Clicks per mailbox (if recorded)</div>
<div id="mailboxTable" class="overflow-x-auto"></div>
</section>
<!-- Detailed Data -->
<section class="card">
<h2 class="text-xl font-bold mb-4">Detailed Data</h2>
<div class="text-gray-400 mb-4">Showing first 5 rows. Click "Expand" to see everything.</div>
<div id="detailTable" class="overflow-x-auto mb-4"></div>
<div class="flex gap-3">
<button class="btn btn-outline" id="btnExpandDetail">Expand</button>
<button class="btn btn-outline hidden" id="btnCollapseDetail">Collapse</button>
</div>
</section>
</main>
<!-- Modals -->
<div id="modalAll" class="modal">
<div class="modal-content p-6 relative">
<span class="close-modal" id="closeAllModal"><i data-feather="x"></i></span>
<h3 class="text-xl font-bold mb-4" id="modalAllTitle">All Recipients</h3>
<div id="modalAllTable" class="overflow-x-auto"></div>
<div class="mt-4 flex justify-end">
<button class="btn btn-primary flex items-center gap-2" id="dlAllCSV">
<i data-feather="download"></i> Download CSV
</button>
</div>
</div>
</div>
<div id="modalNot" class="modal">
<div class="modal-content p-6 relative">
<span class="close-modal" id="closeNotModal"><i data-feather="x"></i></span>
<h3 class="text-xl font-bold mb-4" id="modalNotTitle">Users Not Trained</h3>
<div id="modalNotTable" class="overflow-x-auto"></div>
<div class="mt-4 flex justify-end">
<button class="btn btn-primary flex items-center gap-2" id="dlNotCSV">
<i data-feather="download"></i> Download CSV
</button>
</div>
</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>
<script>
// Initialize Feather Icons
feather.replace();
// State variables
let rawRows = [], perScenPerson = [], scenarios = [];
let modalAllRows = [], modalNotRows = [];
let chartRefs = {};
let hasSucceededCol = false, hasMailbox=false, hasSubject=false, hasClickedAt=false, hasAwareSec=false, hasTypeCol=false, hasSentAt=false;
let campaignFirstSent = null, campaignLastClick = null;
const statusEl = document.getElementById('status');
// DOM Elements
const logoSlot = document.getElementById('logo-slot');
const logoInput = document.getElementById('logo-input');
const logoText = document.getElementById('logo-text');
const fileInput = document.getElementById('fileInput');
const btnExportPDF = document.getElementById('btnExportPDF');
const btnExportWord = document.getElementById('btnExportWord');
const errBox = document.getElementById('errBox');
const 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');
const dlAllCSV = document.getElementById('dlAllCSV');
const dlNotCSV = document.getElementById('dlNotCSV');
const closeAllModal = document.getElementById('closeAllModal');
const closeNotModal = document.getElementById('closeNotModal');
const modalAll = document.getElementById('modalAll');
const modalNot = document.getElementById('modalNot');
// Event Listeners
logoSlot.addEventListener('click', () => logoInput.click());
logoInput.addEventListener('change', handleLogoUpload);
fileInput.addEventListener('change', e => handleFile(e.target.files[0]));
btnExportPDF.addEventListener('click', exportPDF);
btnExportWord.addEventListener('click', exportWord);
dlAllPage.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));
dlNotCSV.addEventListener('click', () => downloadCSV('users_not_trained.csv', modalNotRows));
closeAllModal.addEventListener('click', () => modalAll.style.display = 'none');
closeNotModal.addEventListener('click', () => modalNot.style.display = 'none');
// Logo Upload Handler
function handleLogoUpload(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(event) {
logoSlot.innerHTML = `<img src="${event.target.result}" alt="Logo" class="h-full w-full object-contain rounded-lg" />`;
};
reader.readAsDataURL(file);
}
// Export Functions
function exportPDF() {
window.print();
}
function exportWord() {
const content = `
<html xmlns:o='urn:schemas-microsoft-com:office:office'
xmlns:w='urn:schemas-microsoft-com:office:word'
xmlns='http://www.w3.org/TR/REC-html40'>
<head>
<meta charset='utf-8'>
<title>Security Report</title>
<style>
body { font-family: Arial, sans-serif; }
h1, h2, h3 { color: #333; }
table { border-collapse: collapse; width: 100%; margin: 15px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
.card { border: 1px solid #ccc; padding: 20px; margin: 20px 0; }
.scenario-card { border: 1px solid #ccc; padding: 15px; margin: 15px 0; }
.metric-card { border: 1px solid #ccc; padding: 15px; text-align: center; margin: 10px 0; }
.metric-value { font-size: 24px; font-weight: bold; }
.metric-label { color: #666; }
</style>
</head>
<body>
<h1>${document.getElementById('clientTitle').innerText}</h1>
${document.querySelector('main').innerHTML}
</body>
</html>
`;
const blob = new Blob(['\ufeff', content], {
type: 'application/msword'
});
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'security_report.doc';
link.click();
}
// 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) => {
try {
if (res.data && res.data.length > 0) {
safeIngest(res.data);
} else {
showError('CSV file is empty or invalid');
}
} catch (err) {
showError('CSV parsing error: ' + err.message);
}
},
error: (err) => {
showError('CSV read error: ' + err.message);
}
});
} 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: "" });
if (json && json.length > 0) {
safeIngest(json);
} else {
showError('ODS file is empty or invalid');
}
} catch (err) {
showError('Could not read ODS: ' + err.message);
}
};
reader.onerror = function(err) {
showError('File read error: ' + err.message);
};
reader.readAsArrayBuffer(file);
} else {
showError('Unsupported file (use .csv or .ods)');
}
} catch (err) {
showError('File handling error: ' + err.message);
}
}
// Safe Data Ingestion
function safeIngest(rows) {
try {
if (!rows || !Array.isArray(rows)) {
throw new Error('Invalid data format');
}
ingest(rows);
} catch (err) {
showError('Build failed: ' + err.message);
}
}
// Data Ingestion and Processing
function ingest(rows) {
if (!rows || !Array.isArray(rows)) {
throw new Error('Invalid data format received.');
}
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();
// Initialize window.__TABLES if not exists
window.__TABLES = window.__TABLES || {};
if (!scenarios.length) {
scenariosContainer.innerHTML = '<div class="col-span-full text-center py-10">No scenarios in data.</div>';
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 = `
<div class="scenario-header">
<div class="scenario-title">${scen} <span class="text-gray-400 font-normal">(Type: ${k.Type || '—'})</span></div>
<div class="scenario-actions">
<button class="btn btn-outline btn-sm" data-all="${encodeURIComponent(scen)}">All Recipients</button>
<button class="btn btn-outline btn-sm" data-not="${encodeURIComponent(scen)}">Users Not Trained</button>
</div>
</div>
<div class="text-gray-400 text-sm mb-4">People ${k.Unique} • Sends ${k.Sends}</div>
<div class="chart-container">
<canvas id="${id}"></canvas>
</div>
<div class="metrics-row">
<div class="metric-chip">Clicked: <strong>${k.Clicked}</strong> (${pctClicked}%)</div>
<div class="metric-chip">Trained: <strong>${k.Trained}</strong> (${pctTrained}%)</div>
${hasSucceededCol && k.Succeeded != null ? `<div class="metric-chip">Succeeded: <strong>${k.Succeeded}</strong> (${pctSucc}%)</div>` : ''}
</div>
`;
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 = '<p class="text-gray-400">No mailbox clicks recorded.</p>';
}
}
// Render detailed data
const anyDetail = hasClickedAt || hasSubject || hasAwareSec || hasTypeCol || true;
if (anyDetail) {
try {
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"] = r.Subject || '';
if (hasAwareSec && r.AwarenessTimeMin) out["Awareness Time (mm:ss)"] = r.AwarenessTimeMin;
return out;
});
const cols = rows.length ? Object.keys(rows[0]) : ['Name', 'Email', 'Type', 'Clicked', 'Trained', 'Scenario'];
renderTableLimited('detailTable', rows, cols, 5);
} catch (err) {
console.error('Error rendering detailed data:', err);
if (document.getElementById('detailTable')) {
document.getElementById('detailTable').innerHTML = '<p class="text-gray-400">Error loading detailed data.</p>';
}
}
}
statusEl.textContent = `Built unified report from ${scenarios.length} scenario(s).`;
}
// Modal Functions
function openAll(scen) {
const card = [...document.querySelectorAll('.scenario-card')].find(d => d.dataset.scenario === scen);
const rows = JSON.parse(card.dataset.all || '[]');
modalAllRows = rows.map(r => ({
Email: r.Email,
Name: r.Name,
Attempts: r.Attempts,
"Clicked (any)": r.Clicked_Any ? 'Y' : 'N',
"Trained (any)": r.Trained_Any ? 'Y' : 'N',
"Trained At (latest)": r.TrainedAtLatest
}));
document.getElementById('modalAllTitle').textContent = `All Recipients — ${scen}`;
renderTable('modalAllTable', modalAllRows, ['Email', 'Name', 'Attempts', 'Clicked (any)', 'Trained (any)', 'Trained At (latest)']);
modalAll.style.display = 'flex';
}
function openNot(scen) {
const card = [...document.querySelectorAll('.scenario-card')].find(d => d.dataset.scenario === scen);
const rows = JSON.parse(card.dataset.not || '[]');
modalNotRows = rows.map(r => ({
Email: r.Email,
Name: r.Name,
Attempts: r.Attempts,
"Clicked (any)": r.Clicked_Any ? 'Y' : 'N'
}));
document.getElementById('modalNotTitle').textContent = `Users Not Trained — ${scen}`;
renderTable('modalNotTable', modalNotRows, ['Email', 'Name', 'Attempts', 'Clicked (any)']);
modalNot.style.display = 'flex';
}
// Helper Functions
function findCol(cols, cands) {
const lc = cols.map(c => c.toLowerCase());
for (const c of cands) {
const i = lc.findIndex(x => x.includes(c));
if (i !== -1) return cols[i];
}
return null;
}
function yn01(v) {
const s = String(v ?? '').trim().toUpperCase();
if (['Y', 'YES', 'TRUE', '1'].includes(s)) return 1;
if (['N', 'NO', 'FALSE', '0'].includes(s)) return 0;
if (/^\d+$/.test(s)) return Number(s) > 0 ? 1 : 0;
return 0;
}
function secondsToMMSS(v) {
const n = Number(v);
if (!isFinite(n) || n <= 0) return '';
const m = Math.floor(n / 60),
s = Math.round(n % 60).toString().padStart(2, '0');
return `${m}:${s}`;
}
function escape(s) {
return s.replace(/[&<>"]/g, ch => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"'
}[ch]));
}
function renderTable(containerId, rows, cols) {
const c = document.getElementById(containerId);
if (!rows.length) {
c.innerHTML = '<p class="text-gray-400">No data.</p>';
return;
}
const thead = '<thead><tr>' + cols.map(h => `<th>${h}</th>`).join('') + '</tr></thead>';
const tbody = '<tbody>' + rows.map(r => '<tr>' + cols.map(k => `<td>${escape(String(r[k] ?? ''))}</td>`).join('') + '</tr>').join('') + '</tbody>';
c.innerHTML = `<table>${thead}${tbody}</table>`;
}
window.__TABLES = window.__TABLES || {};
function renderTableLimited(containerId, rows, cols, limit) {
if (!window.__TABLES) window.__TABLES = {};
window.__TABLES[containerId] = { rows, cols, limit };
const slice = rows.slice(0, Math.max(0, limit || 0));
if (document.getElementById(containerId)) {
renderTable(containerId, slice, cols);
}
}
function expandDetailTable() {
const containerId = 'detailTable';
const t = window.__TABLES[containerId];
if (!t || !document.getElementById(containerId)) return;
renderTable(containerId, t.rows, t.cols);
document.getElementById('btnExpandDetail').classList.add('hidden');
document.getElementById('btnCollapseDetail').classList.remove('hidden');
}
function collapseDetailTable() {
const containerId = 'detailTable';
const t = window.__TABLES[containerId];
if (!t || !document.getElementById(containerId)) return;
const slice = t.rows.slice(0, Math.max(0, t.limit || 5));
renderTable(containerId, slice, t.cols);
document.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);
}
function collapseTable(containerId, limit) {
const t = window.__TABLES[containerId];
if (!t) return;
const slice = t.rows.slice(0, Math.max(0, limit || t.limit || 0));
renderTable(containerId, slice, t.cols);
}
function downloadCSV(filename, data) {
if (!data || !data.length) return alert('No data.');
const keys = Object.keys(data[0]);
const rows = [keys.join(',')].concat(data.map(o => keys.map(k => ('"' + String(o[k] ?? '').replace(/"/g, '""') + '"')).join(',')));
const csv = rows.join('\r\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
}
function collectPage(kind) {
const cards = [...document.querySelectorAll('.scenario-card')];
const out = [];
for (const c of cards) {
const data = JSON.parse(c.dataset[kind] || '[]');
if (kind === 'all') {
data.forEach(r => out.push({
Email: r.Email,
Name: r.Name,
Attempts: r.Attempts,
"Clicked (any)": r.Clicked_Any ? 'Y' : 'N',
"Trained (any)": r.Trained_Any ? 'Y' : 'N',
"Trained At (latest)": r.TrainedAtLatest
}));
} else {
data.forEach(r => out.push({
Email: r.Email,
Name: r.Name,
Attempts: r.Attempts,
"Clicked (any)": r.Clicked_Any ? 'Y' : 'N'
}));
}
}
return out;
}
function destroyCharts() {
Object.values(chartRefs).forEach(c => {
try {
c.destroy()
} catch {}
});
chartRefs = {};
}
function inferTypeFromScenario(name) {
const s = (name || '').toLowerCase();
if (/data|form|credential|password|survey|attachment|invoice/.test(s)) return 'Data';
return 'Hyperlink';
}
function majorityType(rows) {
const counts = {};
rows.forEach(r => {
const t = (r.Type || '').trim() || inferTypeFromScenario(r.Scenario);
counts[t] = (counts[t] || 0) + 1;
});
const best = Object.entries(counts).sort((a, b) => b[1] - a[1])[0];
return best ? best[0] : '';
}
function parseDateSafe(s) {
if (!s) return null;
const d = new Date(s);
if (!isNaN(d.getTime())) return d;
const m = String(s).match(/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2,4})(?:\s+(\d{1,2}):(\d{2}))?/);
if (m) {
const dd = +m[1],
mm = +m[2] - 1,
yy = +m[3] < 100 ? 2000 + +m[3] : +m[3];
const hh = +(m[4] || '0'),
mi = +(m[5] || '0');
const d2 = new Date(yy, mm, dd, hh, mi);
return isNaN(d2.getTime()) ? null : d2;
}
return null;
}
function showError(msg) {
errBox.textContent = String(msg || 'Unknown error');
errBox.style.display = 'block';
}
function clearError() {
errBox.textContent = '';
errBox.style.display = 'none';
}
function generateAIDraft() {
if (!document.getElementById('txtSummary').value) document.getElementById('txtSummary').value = 'Executive summary draft… (connect your AI API later).';
if (!document.getElementById('txtInsights').value) document.getElementById('txtInsights').value = '• Good completion trend with pockets to improve\n• Repeat clickers present\n• Shared mailboxes show clustered clicks';
if (!document.getElementById('txtRecos').value) document.getElementById('txtRecos').value = '1) Targeted micro-refreshers (≤10 min)\n2) Two short simulations\n3) Add smishing/voice-phishing\n4) Manager nudges + auto re-enrol\n5) One-pager reminders in staff areas';
}
function downloadExecCSV() {
const data = [
{ Section: 'Executive Summary', Text: document.getElementById('txtSummary').value },
{ Section: 'Insights', Text: document.getElementById('txtInsights').value },
{ Section: 'Recommendations (90 days)', Text: document.getElementById('txtRecos').value }
];
downloadCSV('executive_summary_recommendations.csv', data);
}
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Security Report Pro</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/papaparse@5.4.1/papaparse.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary: #6366f1;
--primary-dark: #4f46e5;
--secondary: #10b981;
--dark: #0f172a;
--light: #f8fafc;
--gray: #94a3b8;
--card-bg: #1e293b;
--border: #334155;
}
body {
font-family: 'Inter', sans-serif;
background-color: var(--dark);
color: var(--light);
}
.card {
background-color: var(--card-bg);
border: 1px solid var(--border);
border-radius: 12px;
padding: 20px;
transition: all 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.25);
}
.btn {
padding: 10px 20px;
border-radius: 8px;
font-weight: 600;
transition: all 0.2s ease;
border: none;
cursor: pointer;
}
.btn-primary {
background-color: var(--primary);
color: white;
}
.btn-primary:hover {
background-color: var(--primary-dark);
}
.btn-secondary {
background-color: var(--secondary);
color: white;
}
.btn-outline {
background: transparent;
border: 1px solid var(--border);
color: var(--light);
}
.btn-outline:hover {
background-color: rgba(255, 255, 255, 0.05);
}
.metric-card {
background: linear-gradient(135deg, #334155 0%, #1e293b 100%);
border-radius: 12px;
padding: 20px;
text-align: center;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.metric-value {
font-size: 2rem;
font-weight: 700;
margin: 10px 0;
}
.metric-label {
color: var(--gray);
font-size: 0.9rem;
}
.scenario-card {
background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
border-radius: 12px;
padding: 20px;
margin-bottom: 20px;