File size: 20,366 Bytes
12f0507 6eafbd4 12f0507 6eafbd4 12f0507 6eafbd4 12f0507 6eafbd4 12f0507 8d5289f 12f0507 128f124 12f0507 128f124 12f0507 128f124 12f0507 6eafbd4 12f0507 6eafbd4 12f0507 6eafbd4 12f0507 6eafbd4 12f0507 128f124 12f0507 128f124 12f0507 128f124 12f0507 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | // ===== Main SPA Router =====
const App = {
topicsCache: null,
_hashListenerAttached: false,
async init(skipValidation) {
if (!Auth.getToken()) {
this.showLogin();
return;
}
// Skip server validation when called right after login (token is fresh)
if (!skipValidation) {
try {
const res = await fetch('/api/auth/me', { headers: Auth.headers() });
if (!res.ok) throw new Error('Token invalid');
} catch (e) {
Auth.clearSession();
this.showLogin();
return;
}
}
// Protection.init() must never break the app
try { Protection.init(); } catch(e) { console.warn('[App] Protection.init error:', e); }
try { Heartbeat.init(); } catch(e) { console.warn('[App] Heartbeat.init error:', e); }
this.renderHeader();
this.handleRoute();
if (!this._hashListenerAttached) {
this._hashListenerAttached = true;
window.addEventListener('hashchange', () => this.handleRoute());
}
},
showLogin() {
document.getElementById('app').innerHTML = `
<div class="login-container">
<div class="login-card">
<h1>MedMembers OFT 2026</h1>
<p class="subtitle">Banco de Questoes - Acesso Restrito</p>
<div class="login-error" id="login-error"></div>
<form onsubmit="App.handleLogin(event)">
<div class="form-group">
<label>Email</label>
<input type="email" id="login-email" required autocomplete="email" placeholder="seu@email.com">
</div>
<div class="form-group">
<label>Senha</label>
<input type="password" id="login-password" required autocomplete="current-password" placeholder="Sua senha">
</div>
<button type="submit" class="btn btn-primary" id="login-btn">Entrar</button>
</form>
<a class="back-to-login" style="margin-top:16px;color:var(--primary);cursor:pointer;" onclick="App.showForgotPassword()">Esqueci minha senha</a>
</div>
</div>
`;
},
async handleLogin(e) {
e.preventDefault();
const email = document.getElementById('login-email').value;
const password = document.getElementById('login-password').value;
const btn = document.getElementById('login-btn');
const errorEl = document.getElementById('login-error');
btn.disabled = true;
btn.textContent = 'Entrando...';
errorEl.style.display = 'none';
try {
await Auth.login(email, password);
// Use replaceState to avoid hashchange firing
history.replaceState(null, '', '#/');
await this.init(true); // skip re-validation, token is fresh
} catch (err) {
errorEl.textContent = err.message;
errorEl.style.display = 'block';
btn.disabled = false;
btn.textContent = 'Entrar';
}
},
renderHeader() {
const user = Auth.getUser();
const header = document.getElementById('app-header');
if (!header) {
const h = document.createElement('header');
h.className = 'app-header';
h.id = 'app-header';
h.innerHTML = `
<span class="logo" onclick="App.navigate('/')"><span class="brand-text">MedMembers OFT 2026</span></span>
<div class="user-menu">
<button class="btn btn-secondary btn-sm" onclick="App.navigate('/')" title="Banco de Questoes">📝 Questoes</button>
<button class="btn btn-secondary btn-sm" onclick="App.navigate('/simulado')" title="Simulado">🎯 Simulado</button>
<button class="btn btn-secondary btn-sm" onclick="App.navigate('/stats')" title="Estatisticas">📊 Estatisticas</button>
${user.role === 'admin' ? '<button class="btn btn-secondary btn-sm" onclick="App.navigate(\'/admin\')">Admin</button>' : ''}
<span class="user-email">${this.escapeHtml(user.email)}</span>
<button class="btn btn-sm" style="background:#f0f0f0" onclick="Auth.logout()">Sair</button>
</div>
`;
document.body.insertBefore(h, document.getElementById('app'));
}
},
async handleRoute() {
const hash = window.location.hash.slice(1) || '/';
const app = document.getElementById('app');
app.innerHTML = '<div class="loading"><div class="spinner"></div>Carregando...</div>';
try {
// Clean up simulado timer when navigating away
if (!hash.startsWith('/simulado')) {
Simulado.cleanup();
}
if (hash === '/' || hash === '') {
await this.showTopics();
} else if (hash.startsWith('/topic/')) {
const parts = hash.split('?');
const slug = parts[0].replace('/topic/', '');
const params = new URLSearchParams(parts[1] || '');
const page = parseInt(params.get('page')) || 1;
const year = params.get('year') || '';
await this.showQuestions(slug, page, year);
} else if (hash === '/simulado') {
await this.showSimuladoConfig();
} else if (hash === '/simulado/exam') {
this.showSimuladoExam();
} else if (hash === '/stats') {
await this.showStats();
} else if (hash === '/admin') {
await this.showAdmin();
} else {
app.innerHTML = '<div class="container"><h2>Pagina nao encontrada</h2></div>';
}
} catch (e) {
console.error('[App] handleRoute error:', e);
// Only clear session on explicit 401 HTTP status, not on generic errors
if (e.message === 'HTTP 401') {
Auth.clearSession();
this.showLogin();
return;
}
app.innerHTML = `<div class="container"><h2>Erro</h2><p>${this.escapeHtml(e.message)}</p></div>`;
}
try { Protection.updateWatermark(); } catch(e) {}
window.scrollTo(0, 0);
},
async showTopics() {
if (!this.topicsCache) {
this.topicsCache = await Questions.loadTopics();
}
document.getElementById('app').innerHTML = Questions.renderTopicsPage(this.topicsCache);
},
async showQuestions(slug, page, year) {
if (!this.topicsCache) {
this.topicsCache = await Questions.loadTopics();
}
const topic = this.topicsCache.find(t => t.slug === slug);
const topicName = topic ? topic.name : slug;
const [data, years] = await Promise.all([
Questions.loadQuestions(slug, page, year),
Questions.loadYears()
]);
document.getElementById('app').innerHTML = Questions.renderQuestionsPage(data, topicName, slug, year, years);
},
async showSimuladoConfig() {
document.getElementById('app').innerHTML = await Simulado.renderConfig();
},
showSimuladoExam() {
document.getElementById('app').innerHTML = Simulado.renderExam();
},
async showAdmin() {
document.getElementById('app').innerHTML = await Admin.render();
},
async showStats() {
const app = document.getElementById('app');
try {
const [statsRes, historyRes] = await Promise.all([
fetch('/api/user/stats', { headers: Auth.headers() }),
fetch('/api/user/history?page=1&per_page=15', { headers: Auth.headers() })
]);
if (!statsRes.ok || !historyRes.ok) throw new Error('Erro ao carregar estatisticas');
const stats = await statsRes.json();
const history = await historyRes.json();
let html = `
<div class="container protected-content">
<div class="question-nav">
<a class="back-btn" onclick="App.navigate('/')">← Voltar</a>
<h2>Suas Estatisticas</h2>
</div>
<div class="stats-overview">
<div class="stats-big-card">
<div class="stats-big-number ${stats.accuracy >= 70 ? 'stats-good' : stats.accuracy >= 50 ? 'stats-ok' : 'stats-low'}">${stats.accuracy}%</div>
<div class="stats-big-label">Aproveitamento Geral</div>
</div>
<div class="stats-summary-cards">
<div class="stat-card">
<div class="stat-value">${stats.total_answered}</div>
<div class="stat-label">Respondidas</div>
</div>
<div class="stat-card">
<div class="stat-value" style="color:var(--correct)">${stats.total_correct}</div>
<div class="stat-label">Corretas</div>
</div>
<div class="stat-card">
<div class="stat-value" style="color:var(--wrong)">${stats.total_answered - stats.total_correct}</div>
<div class="stat-label">Erradas</div>
</div>
</div>
</div>
`;
// Per-track bar chart
if (stats.tracks && stats.tracks.length > 0) {
html += '<h3 class="stats-section-title">Desempenho por Topico</h3>';
html += '<div class="stats-tracks">';
for (const t of stats.tracks) {
const barColor = t.percentage >= 70 ? 'var(--correct)' : t.percentage >= 50 ? 'var(--accent)' : 'var(--wrong)';
html += `
<div class="stats-track-row">
<div class="stats-track-name">${this.escapeHtml(t.track)}</div>
<div class="stats-track-bar-wrap">
<div class="stats-track-bar" style="width:${Math.max(t.percentage, 2)}%;background:${barColor}"></div>
</div>
<div class="stats-track-pct">${t.percentage}%</div>
<div class="stats-track-count">${t.correct}/${t.total}</div>
</div>
`;
}
html += '</div>';
}
// Recent history
if (history.history && history.history.length > 0) {
html += '<h3 class="stats-section-title">Historico Recente</h3>';
html += '<div class="stats-history">';
for (const h of history.history) {
const icon = h.is_correct
? '<span class="answer-badge answer-badge-correct">✓</span>'
: '<span class="answer-badge answer-badge-wrong">✗</span>';
const date = h.answered_at ? new Date(h.answered_at + 'Z').toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : '';
html += `
<div class="stats-history-item" onclick="App.navigate('/topic/${this.escapeHtml(h.track_slug)}')">
${icon}
<div class="stats-history-info">
<div class="stats-history-track">${this.escapeHtml(h.track)} - Q${h.numero}</div>
<div class="stats-history-snippet">${this.escapeHtml(h.snippet)}</div>
</div>
<div class="stats-history-meta">
<span class="stats-history-answer">Resp: ${h.selected_answer} | Gab: ${h.correct_answer}</span>
<span class="stats-history-date">${date}</span>
</div>
</div>
`;
}
html += '</div>';
} else {
html += '<p class="page-subtitle" style="margin-top:24px">Nenhuma questao respondida ainda. Comece respondendo questoes para ver suas estatisticas!</p>';
}
html += '</div>';
app.innerHTML = html;
} catch (e) {
app.innerHTML = `<div class="container"><h2>Erro</h2><p>${this.escapeHtml(e.message)}</p></div>`;
}
},
navigate(path) {
window.location.hash = '#' + path;
},
escapeHtml(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
},
// ===== Forgot Password Flow =====
_forgotEmail: '',
showForgotPassword() {
document.getElementById('app').innerHTML = `
<div class="forgot-container">
<div class="forgot-card">
<h1>Recuperar Senha</h1>
<div class="step-indicator">
<div class="step-dot active" id="dot-1"></div>
<div class="step-dot" id="dot-2"></div>
<div class="step-dot" id="dot-3"></div>
</div>
<div class="forgot-error" id="forgot-error"></div>
<div class="forgot-success" id="forgot-success"></div>
<div class="forgot-step active" id="forgot-step-1">
<p class="subtitle">Informe seu email para receber o codigo de verificacao.</p>
<form onsubmit="App.forgotSendCode(event)">
<div class="form-group"><label>Email</label><input type="email" id="forgot-email" required autocomplete="email" placeholder="seu@email.com"></div>
<button type="submit" class="btn btn-primary" id="forgot-send-btn">Enviar codigo</button>
</form>
</div>
<div class="forgot-step" id="forgot-step-2">
<p class="subtitle">Digite o codigo de 6 digitos enviado para seu email.</p>
<form onsubmit="App.forgotVerifyCode(event)">
<div class="form-group"><label>Codigo de verificacao</label><input type="text" id="forgot-code" required maxlength="6" pattern="[0-9]{6}" placeholder="000000" class="code-input" autocomplete="one-time-code"></div>
<button type="submit" class="btn btn-primary" id="forgot-verify-btn">Verificar</button>
</form>
</div>
<div class="forgot-step" id="forgot-step-3">
<p class="subtitle">Escolha sua nova senha.</p>
<form onsubmit="App.forgotResetPassword(event)">
<div class="form-group"><label>Nova senha</label><input type="password" id="forgot-new-pass" required minlength="6" placeholder="Minimo 6 caracteres" autocomplete="new-password"></div>
<div class="form-group"><label>Confirmar nova senha</label><input type="password" id="forgot-confirm-pass" required minlength="6" placeholder="Repita a nova senha" autocomplete="new-password"></div>
<button type="submit" class="btn btn-primary" id="forgot-reset-btn">Redefinir senha</button>
</form>
</div>
<a class="back-to-login" onclick="App.showLogin()">Voltar ao login</a>
</div>
</div>
`;
},
_forgotShowError(msg) {
const el = document.getElementById('forgot-error');
el.textContent = msg; el.style.display = 'block';
const s = document.getElementById('forgot-success');
if (s) s.style.display = 'none';
},
_forgotShowSuccess(msg) {
const el = document.getElementById('forgot-success');
el.textContent = msg; el.style.display = 'block';
const e = document.getElementById('forgot-error');
if (e) e.style.display = 'none';
},
_forgotGoToStep(step) {
document.querySelectorAll('.forgot-step').forEach(el => el.classList.remove('active'));
document.getElementById(`forgot-step-${step}`).classList.add('active');
for (let i = 1; i <= 3; i++) {
const dot = document.getElementById(`dot-${i}`);
dot.classList.remove('active', 'done');
if (i < step) dot.classList.add('done');
else if (i === step) dot.classList.add('active');
}
const err = document.getElementById('forgot-error');
const suc = document.getElementById('forgot-success');
if (err) err.style.display = 'none';
if (suc) suc.style.display = 'none';
},
async forgotSendCode(e) {
e.preventDefault();
const email = document.getElementById('forgot-email').value.trim();
const btn = document.getElementById('forgot-send-btn');
btn.disabled = true; btn.textContent = 'Enviando...';
try {
const res = await fetch('/api/auth/forgot-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) });
const data = await res.json();
if (!res.ok) { this._forgotShowError(data.error || 'Erro ao enviar codigo'); btn.disabled = false; btn.textContent = 'Enviar codigo'; return; }
this._forgotEmail = email;
this._forgotGoToStep(2);
this._forgotShowSuccess('Se o email estiver cadastrado, voce recebera um codigo de verificacao.');
} catch (err) { this._forgotShowError('Erro de conexao.'); btn.disabled = false; btn.textContent = 'Enviar codigo'; }
},
async forgotVerifyCode(e) {
e.preventDefault();
const code = document.getElementById('forgot-code').value.trim();
if (code.length !== 6 || !/^\d{6}$/.test(code)) { this._forgotShowError('O codigo deve ter 6 digitos numericos.'); return; }
this._forgotCode = code;
this._forgotGoToStep(3);
},
async forgotResetPassword(e) {
e.preventDefault();
const newPass = document.getElementById('forgot-new-pass').value;
const confirmPass = document.getElementById('forgot-confirm-pass').value;
const btn = document.getElementById('forgot-reset-btn');
if (newPass !== confirmPass) { this._forgotShowError('As senhas nao coincidem.'); return; }
if (newPass.length < 6) { this._forgotShowError('A senha deve ter no minimo 6 caracteres.'); return; }
btn.disabled = true; btn.textContent = 'Redefinindo...';
try {
const res = await fetch('/api/auth/reset-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: this._forgotEmail, code: this._forgotCode, new_password: newPass }) });
const data = await res.json();
if (!res.ok) { this._forgotShowError(data.error || 'Erro ao redefinir senha'); btn.disabled = false; btn.textContent = 'Redefinir senha'; return; }
document.querySelectorAll('.forgot-step').forEach(el => el.classList.remove('active'));
for (let i = 1; i <= 3; i++) { document.getElementById(`dot-${i}`).classList.remove('active'); document.getElementById(`dot-${i}`).classList.add('done'); }
this._forgotShowSuccess('Senha redefinida com sucesso! Redirecionando para o login...');
setTimeout(() => this.showLogin(), 2500);
} catch (err) { this._forgotShowError('Erro de conexao.'); btn.disabled = false; btn.textContent = 'Redefinir senha'; }
}
};
// Boot
document.addEventListener('DOMContentLoaded', () => App.init());
|