Spaces:
Running
<!DOCTYPE html>
Browse files<html lang="en">
<head>
<meta charset="utf-8" />
<title>Client Name Report</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Libraries -->
<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>
<style>
:root{
--bg:#f1f5f9; --card:#fff; --ink:#0f172a; --ink-d:#475569; --border:#e2e8f0; --primary:#0fb9b9;
--c-sent:#60a5fa; --c-click:#f59e0b; --c-train:#0fb9b9; --c-succ:#94a3b8;
}
*{box-sizing:border-box}
html,body{background:var(--bg);color:var(--ink);font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif}
body{margin:22px}
h1,h2,h3{margin:0 0 10px}
.subtle{color:var(--ink-d)} .hidden{display:none!important}
.card{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:14px}
.btn{border:1px solid var(--border);background:#fff;color:#000;padding:10px 14px;border-radius:10px;font-weight:700;cursor:pointer}
.btn.primary{background:var(--primary);color:#fff;border-color:#0fb9b9}
.btn.min{padding:6px 10px;font-weight:600}
.btn.big{padding:14px 18px}
.btn.success{background:#16a34a;color:#fff;border-color:#16a34a}
.btn.warn{background:#f59e0b;color:#111827;border-color:#f59e0b}
header{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:12px}
.logo{width:220px;height:64px;border:2px dashed var(--border);border-radius:12px;display:flex;align-items:center;justify-content:center;color:#64748b;overflow:hidden;background:#fff}
.logo input{display:none}
.controls{display:flex;gap:8px;flex-wrap:wrap}
.grid5{display:grid;grid-template-columns:repeat(5,minmax(140px,1fr));gap:10px}
.k{font-size:12px;color:var(--ink-d)} .v{font-size:20px;font-weight:800}
.scenarios{display:grid;grid-template-columns:repeat(2,minmax(280px,1fr));gap:12px}
.scenario{border:1px solid var(--border);border-radius:12px;padding:12px;background:#fff}
.s-head{display:flex;align-items:center;justify-content:space-between;gap:10px}
.s-actions{display:flex;gap:6px;flex-wrap:wrap}
.mini{height:150px!important;max-height:150px;background:#fff;border:1px solid var(--border);border-radius:10px;padding:6px}
.metrics-row{margin-top:6px;font-size:12px;color:#0f172a}
.metrics-row .chip{display:inline-block;margin-right:10px}
.sep{height:1px;background:var(--border);margin:14px 0}
table{width:100%;border-collapse:collapse;background:#fff;border:1px solid var(--border);border-radius:10px;overflow:hidden}
th,td{padding:8px 10px;border-bottom:1px solid var(--border);font-size:13px;text-align:left}
thead th{background:#f8fafc}
.modal{position:fixed;inset:0;display:none;align-items:flex-start;justify-content:center;background:rgba(15,23,42,.5);z-index:10000;padding:40px 12px;overflow:auto}
.modal .content{background:#fff;border:1px solid var(--border);border-radius:14px;padding:14px;width:min(96vw,980px)}
.modal .row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px}
.tagline{margin-top:8px;color:#64748b;font-size:12px;text-align:center}
#clientTitle{outline:none;border-bottom:1px dashed transparent}
#clientTitle:focus{border-bottom-color:#cbd5e1}
/* error bar */
#errBox{display:none;margin-bottom:12px;border:1px solid #fecaca;background:#fef2f2;color:#b91c1c;padding:10px;border-radius:10px;white-space:pre-wrap}
@media (max-width:1000px){.grid5{grid-template-columns:repeat(2,1fr)}.scenarios{grid-template-columns:1fr}}
@media print{.controls,.ai-bar,.global-dl,.s-actions,#errBox{display:none!important} body{margin:12mm} .mini{height:140px!important;max-height:140px}}
</style>
</head>
<body>
<header>
<label class="logo" id="logo-slot" title="Click to replace logo">
<input type="file" accept="image/*" id="logo-input" />
<span id="logo-text">Loading logo…</span>
<img id="logo-img" alt="Logo"/>
</label>
<div>
<h1 id="clientTitle" contenteditable="true" spellcheck="false">Client Name Report</h1>
<div class="subtle" id="status">Choose CSV/ODS → Report builds automatically → Export PDF</div>
</div>
<div class="controls">
<input id="fileInput" type="file" accept=".csv,.ods" />
<button class="btn primary" id="btnExport">Export PDF</button>
</div>
</header>
<div id="errBox"></div>
<!-- Pages render below -->
<div id="pages"></div>
<!-- Executive Summary -->
<section id="exec" class="card" style="margin-top:12px;display:none">
<h2>Executive Summary & Recommendations</h2>
<div class="ai-bar" style="display:flex;gap:8px;flex-wrap:wrap;margin:8px 0">
<button class="btn min" id="btnAIDraft">Draft with AI</button>
<button class="btn min" id="btnExecCSV">Download Summary CSV</button>
</div>
<div>
<div class="k">Executive Summary</div>
<textarea id="txtSummary" style="width:100%;min-height:90px" placeholder="Quarterly overview, outcomes, highlights..."></textarea>
</div>
<div style="margin-top:8px">
<div class="k">Key Insights</div>
<textarea id="txtInsights" style="width:100%;min-height:90px" placeholder="Completion pockets, repeat clickers, mailbox patterns..."></textarea>
</div>
<div style="margin-top:8px">
<div class="k">Recommendations (Next 90 Days)</div>
<textarea id="txtRecos" style="width:100%;min-height:90px" placeholder="3–6 actions…"></textarea>
</div>
</section>
<!-- Modals -->
<div id="modalAll" class="modal" aria-hidden="true">
<div class="content">
<div class="row">
<h3 id="modalAllTitle">All Recipients</h3>
<div>
<button class="btn min" id="dlAllCSV">Download CSV</button>
<button class="btn min" data-close="modalAll">Close</button>
</div>
</div>
<div id="modalAllTable"></div>
</div>
</div>
<div id="modalNot" class="modal" aria-hidden="true">
<div class="content">
<div class="row">
<h3 id="modalNotTitle">Users Not Trained</h3>
<div>
<button class="btn min" id="dlNotCSV">Download CSV</button>
<button class="btn min" data-close="modalNot">Close</button>
</div>
</div>
<div id="modalNotTable"></div>
</div>
</div>
<noscript>JavaScript is required for this page.</noscript>
<div class="tagline">Because 95% of attacks have a human interaction</div>
<script>
/* ==============================
STATE
============================== */
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');
/* ==============================
ERROR BAR
============================== */
function showError(msg){
const box = document.getElementById('errBox');
box.textContent = String(msg || 'Unknown error');
box.style.display = 'block';
}
function clearError(){
const box = document.getElementById('errBox');
box.textContent = '';
box.style.display = 'none';
}
/* ==============================
LOGO
============================== */
(function initLogo(){
const logoImg = document.getElementById('logo-img');
const logoText = document.getElementById('logo-text');
const input = document.getElementById('logo-input');
const LOGO_URL = new URL('/admin/awareness-template/493/content/11/file/mcs.png', window.location.origin).toString();
logoImg.onload = () => logoText.classList.add('hidden');
logoImg.onerror = () => { logoText.textContent = 'Logo not found (check path)'; };
logoImg.src = LOGO_URL;
document.getElementById('logo-slot').addEventListener('click', ()=>input.click());
input.addEventListener('change', e=>{
const f=e.target.files[0]; if(!f) return;
const r=new FileReader(); r.onload=()=>{ logoImg.src=r.result; }; r.readAsDataURL(f);
});
})();
/* ==============================
CONTROLS
============================== */
document.getElementById('btnExport').addEventListener('click', ()=>window.print());
document.getElementById('fileInput').addEventListener('change', e => handleFile(e.target.files[0]));
document.addEventListener('click', e=>{
const closer = e.target.closest('[data-close]');
if(closer){ document.getElementById(closer.getAttribute('data-close')).style.display='none'; }
});
document.getElementById('dlAllCSV').addEventListener('click', ()=>downloadCSV('all_recipients.csv', modalAllRows));
document.getElementById('dlNotCSV').addEventListener('click', ()=>downloadCSV('users_not_trained.csv', modalNotRows));
document.getElementById('btnExecCSV').addEventListener('click', ()=>{
const data = [
{Section:'Executive Summary',Text:val('txtSummary')},
{Section:'Insights',Text:val('txtInsights')},
{Section:'Recommendations (90 days)',Text:val('txtRecos')}
];
downloadCSV('executive_summary_recommendations.csv', data);
});
document.getElementById('btnAIDraft').addEventListener('click', ()=>{
if(!val('txtSummary')) set('txtSummary','Executive summary draft… (connect your AI API later).');
if(!val('txtInsights')) set('txtInsights','• Good completion trend with pockets to improve\n• Repeat clickers present\n• Shared mailboxes show clustered clicks');
if(!val('txtRecos')) set('txtRecos','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');
});
/* ==============================
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'});
Files changed (2)
- README.md+7-4
- index.html+1045-18
12345678910---title: Security Report Proemoji: 💻colorFrom: bluecolorTo: yellowsdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213---title: Security Report ProcolorFrom: purplecolorTo: grayemoji: 🐳sdk: staticpinned: falsetags:- deepsite-v3---# Welcome to your new DeepSite project!This project was created with [DeepSite](https://deepsite.hf.co).
12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046<!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);}.tagline {text-align: center;color: var(--gray);font-size: 0.9rem;margin-top: 30px;}.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;}}</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="btnExport"><i data-feather="download"></i> Export PDF</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">Because 95% of attacks have a human interaction</div><script>// Initialize Feather Iconsfeather.replace();// State variableslet 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 Elementsconst logoSlot = document.getElementById('logo-slot');const logoInput = document.getElementById('logo-input');const logoText = document.getElementById('logo-text');const fileInput = document.getElementById('fileInput');const btnExport = document.getElementById('btnExport');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 ListenerslogoSlot.addEventListener('click', () => logoInput.click());logoInput.addEventListener('change', handleLogoUpload);fileInput.addEventListener('change', e => handleFile(e.target.files[0]));btnExport.addEventListener('click', () => window.print());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 Handlerfunction 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);}// File Handlingfunction 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 Ingestionfunction safeIngest(rows) {try {ingest(rows);} catch (err) {showError('Build failed: ' + err.message);}}// Data Ingestion and Processingfunction 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 Reportfunction build() {// Clear previous contentscenariosContainer.innerHTML = '';destroyCharts();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 cardsdocument.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 cardskpis.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 chartconst 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 buttonsdocument.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 statisticsconst 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 dataconst 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"] = 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);}statusEl.textContent = `Built unified report from ${scenarios.length} scenario(s).`;}// Modal Functionsfunction 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 Functionsfunction 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) {window.__TABLES[containerId] = { rows, cols, limit };const slice = rows.slice(0, Math.max(0, limit || 0));renderTable(containerId, slice, cols);}function expandDetailTable() {expandTable('detailTable');btnExpandDetail.classList.add('hidden');btnCollapseDetail.classList.remove('hidden');}function collapseDetailTable() {collapseTable('detailTable', 5);btnCollapseDetail.classList.add('hidden');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>