Nicolasmed26 commited on
Commit
128f124
·
verified ·
1 Parent(s): c0dc35b

Deploy MedMembers OFT 2026

Browse files
api/admin.py CHANGED
@@ -1,10 +1,18 @@
1
  import json
 
 
2
  from flask import Blueprint, request, jsonify
3
  from werkzeug.security import generate_password_hash
4
  from models.database import get_db
5
  from auth.middleware import require_admin
6
  from auth.session_manager import invalidate_user_sessions
7
 
 
 
 
 
 
 
8
  admin_bp = Blueprint('admin', __name__, url_prefix='/api/admin')
9
 
10
 
@@ -53,6 +61,95 @@ def create_user():
53
  return jsonify({'message': f'Usuário {email} criado com sucesso'}), 201
54
 
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  @admin_bp.route('/users/<int:uid>', methods=['PUT'])
57
  @require_admin
58
  def update_user(uid):
 
1
  import json
2
+ import random
3
+ import string
4
  from flask import Blueprint, request, jsonify
5
  from werkzeug.security import generate_password_hash
6
  from models.database import get_db
7
  from auth.middleware import require_admin
8
  from auth.session_manager import invalidate_user_sessions
9
 
10
+
11
+ def _generate_random_password(length=8):
12
+ """Generate a random password with letters and digits."""
13
+ chars = string.ascii_letters + string.digits
14
+ return ''.join(random.choices(chars, k=length))
15
+
16
  admin_bp = Blueprint('admin', __name__, url_prefix='/api/admin')
17
 
18
 
 
61
  return jsonify({'message': f'Usuário {email} criado com sucesso'}), 201
62
 
63
 
64
+ @admin_bp.route('/users/batch-create', methods=['POST'])
65
+ @require_admin
66
+ def batch_create_users():
67
+ data = request.get_json()
68
+ if not data or not data.get('users'):
69
+ return jsonify({'error': 'Lista de usuários é obrigatória'}), 400
70
+
71
+ user_list = data['users']
72
+ if not isinstance(user_list, list) or len(user_list) == 0:
73
+ return jsonify({'error': 'Lista vazia'}), 400
74
+
75
+ if len(user_list) > 100:
76
+ return jsonify({'error': 'Máximo de 100 usuários por lote'}), 400
77
+
78
+ db = get_db()
79
+ results = []
80
+ errors = []
81
+
82
+ for item in user_list:
83
+ email = (item.get('email') or '').strip().lower()
84
+ name = (item.get('name') or '').strip()
85
+
86
+ if not email:
87
+ errors.append({'email': email, 'error': 'Email vazio'})
88
+ continue
89
+
90
+ existing = db.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone()
91
+ if existing:
92
+ errors.append({'email': email, 'error': 'Email já cadastrado'})
93
+ continue
94
+
95
+ password = _generate_random_password()
96
+ db.execute(
97
+ "INSERT INTO users (email, password_hash, display_name, role) VALUES (?, ?, ?, ?)",
98
+ (email, generate_password_hash(password), name, 'user')
99
+ )
100
+ results.append({'email': email, 'name': name, 'password': password})
101
+
102
+ db.commit()
103
+
104
+ return jsonify({
105
+ 'created': results,
106
+ 'errors': errors,
107
+ 'total_created': len(results),
108
+ 'total_errors': len(errors)
109
+ }), 201
110
+
111
+
112
+ @admin_bp.route('/users/<int:uid>/toggle', methods=['PUT'])
113
+ @require_admin
114
+ def toggle_user(uid):
115
+ db = get_db()
116
+ user = db.execute("SELECT id, is_active, role FROM users WHERE id = ?", (uid,)).fetchone()
117
+ if not user:
118
+ return jsonify({'error': 'Usuário não encontrado'}), 404
119
+
120
+ new_status = 0 if user['is_active'] else 1
121
+ db.execute("UPDATE users SET is_active = ? WHERE id = ?", (new_status, uid))
122
+ db.commit()
123
+
124
+ if new_status == 0:
125
+ invalidate_user_sessions(uid, 'admin_deactivated')
126
+
127
+ label = 'ativado' if new_status else 'desativado'
128
+ return jsonify({'message': f'Usuário {label}', 'is_active': new_status})
129
+
130
+
131
+ @admin_bp.route('/users/<int:uid>/reset-password', methods=['POST'])
132
+ @require_admin
133
+ def reset_user_password(uid):
134
+ db = get_db()
135
+ user = db.execute("SELECT id, email FROM users WHERE id = ?", (uid,)).fetchone()
136
+ if not user:
137
+ return jsonify({'error': 'Usuário não encontrado'}), 404
138
+
139
+ new_password = _generate_random_password()
140
+ db.execute(
141
+ "UPDATE users SET password_hash = ? WHERE id = ?",
142
+ (generate_password_hash(new_password), uid)
143
+ )
144
+ db.commit()
145
+
146
+ return jsonify({
147
+ 'message': f'Senha de {user["email"]} redefinida',
148
+ 'email': user['email'],
149
+ 'new_password': new_password
150
+ })
151
+
152
+
153
  @admin_bp.route('/users/<int:uid>', methods=['PUT'])
154
  @require_admin
155
  def update_user(uid):
api/questions.py CHANGED
@@ -1,5 +1,9 @@
1
  import json
2
- from flask import Blueprint, request, jsonify
 
 
 
 
3
  from auth.middleware import require_auth
4
  from models.database import get_db
5
 
@@ -27,19 +31,43 @@ def get_questions(slug):
27
  page = request.args.get('page', 1, type=int)
28
  per_page = request.args.get('per_page', 20, type=int)
29
  per_page = min(per_page, 50)
 
30
  offset = (page - 1) * per_page
31
 
32
  db = get_db()
33
 
34
- total = db.execute("SELECT COUNT(*) as c FROM questions WHERE track_slug = ?", (slug,)).fetchone()['c']
 
 
 
 
 
 
35
 
36
  rows = db.execute("""
37
  SELECT id, track, track_slug, numero, question_id, year, enunciado, imagens_enunciado, alternativas, media_files
38
  FROM questions
39
- WHERE track_slug = ?
40
  ORDER BY numero
41
  LIMIT ? OFFSET ?
42
- """, (slug, per_page, offset)).fetchall()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  questions = []
45
  for r in rows:
@@ -55,6 +83,7 @@ def get_questions(slug):
55
  if m.get('type') == 'image':
56
  enunciado_imgs.append(m.get('filename', ''))
57
 
 
58
  q = {
59
  'id': r['id'],
60
  'numero': r['numero'],
@@ -64,6 +93,8 @@ def get_questions(slug):
64
  'imagens_enunciado': json.loads(r['imagens_enunciado'] or '[]') or enunciado_imgs,
65
  'alternativas': raw_alts,
66
  'has_video': any(m.get('type') == 'video' for m in raw_media),
 
 
67
  }
68
  questions.append(q)
69
 
@@ -88,12 +119,122 @@ def check_answer(qid):
88
  return jsonify({'error': 'Questão não encontrada'}), 404
89
 
90
  correct = q['gabarito_correta'] or ''
 
 
 
 
 
 
 
 
 
 
91
  return jsonify({
92
  'correct': answer == correct,
93
  'gabarito_correta': correct
94
  })
95
 
96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  @questions_bp.route('/questions/<int:qid>/solution', methods=['GET'])
98
  @require_auth
99
  def get_solution(qid):
@@ -119,3 +260,143 @@ def get_solution(qid):
119
  'imagens_gabarito': json.loads(q['imagens_gabarito'] or '[]'),
120
  'videos': videos
121
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import json
2
+ import math
3
+ import re
4
+ import time
5
+ import random
6
+ from flask import Blueprint, request, jsonify, g
7
  from auth.middleware import require_auth
8
  from models.database import get_db
9
 
 
31
  page = request.args.get('page', 1, type=int)
32
  per_page = request.args.get('per_page', 20, type=int)
33
  per_page = min(per_page, 50)
34
+ year = request.args.get('year', '').strip()
35
  offset = (page - 1) * per_page
36
 
37
  db = get_db()
38
 
39
+ params = [slug]
40
+ year_clause = ''
41
+ if year:
42
+ year_clause = ' AND year = ?'
43
+ params.append(year)
44
+
45
+ total = db.execute("SELECT COUNT(*) as c FROM questions WHERE track_slug = ?" + year_clause, params).fetchone()['c']
46
 
47
  rows = db.execute("""
48
  SELECT id, track, track_slug, numero, question_id, year, enunciado, imagens_enunciado, alternativas, media_files
49
  FROM questions
50
+ WHERE track_slug = ?""" + year_clause + """
51
  ORDER BY numero
52
  LIMIT ? OFFSET ?
53
+ """, params + [per_page, offset]).fetchall()
54
+
55
+ # Fetch user answers for these questions
56
+ user_id = g.current_user['id']
57
+ question_ids = [r['id'] for r in rows]
58
+ user_answers_map = {}
59
+ if question_ids:
60
+ placeholders = ','.join('?' * len(question_ids))
61
+ ua_rows = db.execute(f"""
62
+ SELECT question_id, selected_answer, is_correct
63
+ FROM user_answers
64
+ WHERE user_id = ? AND question_id IN ({placeholders})
65
+ """, [user_id] + question_ids).fetchall()
66
+ for ua in ua_rows:
67
+ user_answers_map[ua['question_id']] = {
68
+ 'user_answer': ua['selected_answer'],
69
+ 'user_correct': bool(ua['is_correct'])
70
+ }
71
 
72
  questions = []
73
  for r in rows:
 
83
  if m.get('type') == 'image':
84
  enunciado_imgs.append(m.get('filename', ''))
85
 
86
+ ua = user_answers_map.get(r['id'], {})
87
  q = {
88
  'id': r['id'],
89
  'numero': r['numero'],
 
93
  'imagens_enunciado': json.loads(r['imagens_enunciado'] or '[]') or enunciado_imgs,
94
  'alternativas': raw_alts,
95
  'has_video': any(m.get('type') == 'video' for m in raw_media),
96
+ 'user_answer': ua.get('user_answer', None),
97
+ 'user_correct': ua.get('user_correct', None),
98
  }
99
  questions.append(q)
100
 
 
119
  return jsonify({'error': 'Questão não encontrada'}), 404
120
 
121
  correct = q['gabarito_correta'] or ''
122
+ is_correct = 1 if answer == correct else 0
123
+
124
+ # Save/update user answer
125
+ user_id = g.current_user['id']
126
+ db.execute("""
127
+ INSERT OR REPLACE INTO user_answers (user_id, question_id, selected_answer, is_correct, answered_at)
128
+ VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
129
+ """, (user_id, qid, answer, is_correct))
130
+ db.commit()
131
+
132
  return jsonify({
133
  'correct': answer == correct,
134
  'gabarito_correta': correct
135
  })
136
 
137
 
138
+ @questions_bp.route('/user/stats', methods=['GET'])
139
+ @require_auth
140
+ def user_stats():
141
+ user_id = g.current_user['id']
142
+ db = get_db()
143
+
144
+ # Overall stats
145
+ overall = db.execute("""
146
+ SELECT COUNT(*) as total_answered,
147
+ SUM(is_correct) as total_correct
148
+ FROM user_answers WHERE user_id = ?
149
+ """, (user_id,)).fetchone()
150
+
151
+ total_answered = overall['total_answered'] or 0
152
+ total_correct = overall['total_correct'] or 0
153
+ accuracy = round((total_correct / total_answered * 100), 1) if total_answered > 0 else 0
154
+
155
+ # Per-track breakdown
156
+ tracks = db.execute("""
157
+ SELECT q.track, q.track_slug,
158
+ COUNT(*) as total,
159
+ SUM(ua.is_correct) as correct
160
+ FROM user_answers ua
161
+ JOIN questions q ON q.id = ua.question_id
162
+ WHERE ua.user_id = ?
163
+ GROUP BY q.track_slug
164
+ ORDER BY q.track
165
+ """, (user_id,)).fetchall()
166
+
167
+ track_stats = []
168
+ for t in tracks:
169
+ t_total = t['total'] or 0
170
+ t_correct = t['correct'] or 0
171
+ track_stats.append({
172
+ 'track': t['track'],
173
+ 'slug': t['track_slug'],
174
+ 'total': t_total,
175
+ 'correct': t_correct,
176
+ 'percentage': round((t_correct / t_total * 100), 1) if t_total > 0 else 0
177
+ })
178
+
179
+ return jsonify({
180
+ 'total_answered': total_answered,
181
+ 'total_correct': total_correct,
182
+ 'accuracy': accuracy,
183
+ 'tracks': track_stats
184
+ })
185
+
186
+
187
+ @questions_bp.route('/user/history', methods=['GET'])
188
+ @require_auth
189
+ def user_history():
190
+ user_id = g.current_user['id']
191
+ page = request.args.get('page', 1, type=int)
192
+ per_page = request.args.get('per_page', 20, type=int)
193
+ per_page = min(per_page, 50)
194
+ offset = (page - 1) * per_page
195
+
196
+ db = get_db()
197
+
198
+ total = db.execute("SELECT COUNT(*) as c FROM user_answers WHERE user_id = ?", (user_id,)).fetchone()['c']
199
+
200
+ rows = db.execute("""
201
+ SELECT ua.question_id, ua.selected_answer, ua.is_correct, ua.answered_at,
202
+ q.enunciado, q.numero, q.track, q.track_slug, q.gabarito_correta
203
+ FROM user_answers ua
204
+ JOIN questions q ON q.id = ua.question_id
205
+ WHERE ua.user_id = ?
206
+ ORDER BY ua.answered_at DESC
207
+ LIMIT ? OFFSET ?
208
+ """, (user_id, per_page, offset)).fetchall()
209
+
210
+ history = []
211
+ for r in rows:
212
+ # Text snippet: strip HTML and truncate
213
+ enunciado = r['enunciado'] or ''
214
+ snippet = re.sub(r'<[^>]+>', '', enunciado)
215
+ snippet = snippet[:120] + '...' if len(snippet) > 120 else snippet
216
+
217
+ history.append({
218
+ 'question_id': r['question_id'],
219
+ 'numero': r['numero'],
220
+ 'track': r['track'],
221
+ 'track_slug': r['track_slug'],
222
+ 'selected_answer': r['selected_answer'],
223
+ 'correct_answer': r['gabarito_correta'] or '',
224
+ 'is_correct': bool(r['is_correct']),
225
+ 'answered_at': r['answered_at'],
226
+ 'snippet': snippet
227
+ })
228
+
229
+ return jsonify({
230
+ 'history': history,
231
+ 'total': total,
232
+ 'page': page,
233
+ 'per_page': per_page,
234
+ 'total_pages': math.ceil(total / per_page) if per_page > 0 else 0
235
+ })
236
+
237
+
238
  @questions_bp.route('/questions/<int:qid>/solution', methods=['GET'])
239
  @require_auth
240
  def get_solution(qid):
 
260
  'imagens_gabarito': json.loads(q['imagens_gabarito'] or '[]'),
261
  'videos': videos
262
  })
263
+
264
+
265
+ @questions_bp.route('/years', methods=['GET'])
266
+ @require_auth
267
+ def list_years():
268
+ """Return distinct years available in the questions table."""
269
+ db = get_db()
270
+ rows = db.execute("""
271
+ SELECT DISTINCT year FROM questions
272
+ WHERE year IS NOT NULL AND year != ''
273
+ ORDER BY year DESC
274
+ """).fetchall()
275
+ years = [r['year'] for r in rows]
276
+ return jsonify({'years': years})
277
+
278
+
279
+ @questions_bp.route('/simulado/generate', methods=['GET'])
280
+ @require_auth
281
+ def simulado_generate():
282
+ """Generate a simulated exam with random questions."""
283
+ count = request.args.get('count', 50, type=int)
284
+ count = max(1, min(count, 100))
285
+ tracks = request.args.get('tracks', 'all').strip()
286
+ year = request.args.get('year', '').strip()
287
+
288
+ db = get_db()
289
+
290
+ where_clauses = ["gabarito_correta IS NOT NULL", "gabarito_correta != ''"]
291
+ params = []
292
+
293
+ if tracks and tracks != 'all':
294
+ slugs = [s.strip() for s in tracks.split(',') if s.strip()]
295
+ if slugs:
296
+ placeholders = ','.join('?' * len(slugs))
297
+ where_clauses.append(f"track_slug IN ({placeholders})")
298
+ params.extend(slugs)
299
+
300
+ if year:
301
+ where_clauses.append("year = ?")
302
+ params.append(year)
303
+
304
+ where_sql = ' AND '.join(where_clauses)
305
+
306
+ total_available = db.execute(
307
+ f"SELECT COUNT(*) as c FROM questions WHERE {where_sql}", params
308
+ ).fetchone()['c']
309
+
310
+ if total_available == 0:
311
+ return jsonify({'error': 'Nenhuma questao encontrada com os filtros selecionados'}), 404
312
+
313
+ actual_count = min(count, total_available)
314
+
315
+ rows = db.execute(f"""
316
+ SELECT id, track, track_slug, numero, year, enunciado, alternativas
317
+ FROM questions
318
+ WHERE {where_sql}
319
+ ORDER BY RANDOM()
320
+ LIMIT ?
321
+ """, params + [actual_count]).fetchall()
322
+
323
+ questions = []
324
+ for r in rows:
325
+ raw_alts = json.loads(r['alternativas'] or '[]')
326
+ for alt in raw_alts:
327
+ alt.pop('correta', None)
328
+ questions.append({
329
+ 'id': r['id'],
330
+ 'numero': r['numero'],
331
+ 'track': r['track'],
332
+ 'year': r['year'] or '',
333
+ 'enunciado': r['enunciado'],
334
+ 'alternativas': raw_alts
335
+ })
336
+
337
+ simulado_id = f"sim-{int(time.time())}-{random.randint(1000, 9999)}"
338
+ time_limit = actual_count # 1 minute per question
339
+
340
+ return jsonify({
341
+ 'simulado_id': simulado_id,
342
+ 'questions': questions,
343
+ 'total': actual_count,
344
+ 'time_limit_minutes': time_limit
345
+ })
346
+
347
+
348
+ @questions_bp.route('/simulado/submit', methods=['POST'])
349
+ @require_auth
350
+ def simulado_submit():
351
+ """Submit exam answers and return results."""
352
+ data = request.get_json()
353
+ if not data:
354
+ return jsonify({'error': 'Dados nao fornecidos'}), 400
355
+
356
+ simulado_id = data.get('simulado_id', '')
357
+ answers = data.get('answers', {})
358
+ time_spent = data.get('time_spent_seconds', 0)
359
+
360
+ if not answers:
361
+ return jsonify({'error': 'Nenhuma resposta enviada'}), 400
362
+
363
+ db = get_db()
364
+ question_ids = list(answers.keys())
365
+ placeholders = ','.join('?' * len(question_ids))
366
+ int_ids = [int(qid) for qid in question_ids]
367
+
368
+ rows = db.execute(f"""
369
+ SELECT id, gabarito_correta, gabarito_texto
370
+ FROM questions WHERE id IN ({placeholders})
371
+ """, int_ids).fetchall()
372
+
373
+ correct_map = {r['id']: r for r in rows}
374
+
375
+ details = []
376
+ score = 0
377
+ for qid_str, selected in answers.items():
378
+ qid = int(qid_str)
379
+ q = correct_map.get(qid)
380
+ correct_letter = q['gabarito_correta'] if q else ''
381
+ is_correct = selected.upper() == correct_letter.upper() if correct_letter else False
382
+ if is_correct:
383
+ score += 1
384
+ details.append({
385
+ 'question_id': qid,
386
+ 'selected': selected,
387
+ 'correct': correct_letter,
388
+ 'is_correct': is_correct,
389
+ 'explanation': (q['gabarito_texto'] or '') if q else ''
390
+ })
391
+
392
+ total = len(answers)
393
+ percentage = round((score / total) * 100, 1) if total > 0 else 0
394
+
395
+ return jsonify({
396
+ 'simulado_id': simulado_id,
397
+ 'score': score,
398
+ 'total': total,
399
+ 'percentage': percentage,
400
+ 'time_spent_seconds': time_spent,
401
+ 'details': details
402
+ })
models/database.py CHANGED
@@ -102,6 +102,19 @@ def init_db():
102
  CREATE INDEX IF NOT EXISTS idx_reset_codes_email ON password_reset_codes(email);
103
  CREATE INDEX IF NOT EXISTS idx_reset_codes_code ON password_reset_codes(code);
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  CREATE TABLE IF NOT EXISTS media_files (
106
  id INTEGER PRIMARY KEY AUTOINCREMENT,
107
  file_id TEXT NOT NULL DEFAULT '',
 
102
  CREATE INDEX IF NOT EXISTS idx_reset_codes_email ON password_reset_codes(email);
103
  CREATE INDEX IF NOT EXISTS idx_reset_codes_code ON password_reset_codes(code);
104
 
105
+ CREATE TABLE IF NOT EXISTS user_answers (
106
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
107
+ user_id INTEGER NOT NULL,
108
+ question_id INTEGER NOT NULL,
109
+ selected_answer TEXT NOT NULL,
110
+ is_correct INTEGER NOT NULL DEFAULT 0,
111
+ answered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
112
+ UNIQUE(user_id, question_id)
113
+ );
114
+
115
+ CREATE INDEX IF NOT EXISTS idx_ua_user ON user_answers(user_id);
116
+ CREATE INDEX IF NOT EXISTS idx_ua_question ON user_answers(question_id);
117
+
118
  CREATE TABLE IF NOT EXISTS media_files (
119
  id INTEGER PRIMARY KEY AUTOINCREMENT,
120
  file_id TEXT NOT NULL DEFAULT '',
static/css/main.css CHANGED
@@ -251,6 +251,148 @@ body {
251
  .step-dot.active { background: var(--primary); }
252
  .step-dot.done { background: var(--correct); }
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  /* ===== RESPONSIVE ===== */
255
  @media (max-width: 600px) {
256
  .container { padding: 16px 12px; }
@@ -264,4 +406,27 @@ body {
264
  .data-table { font-size: 12px; }
265
  .data-table th, .data-table td { padding: 8px; }
266
  .admin-tabs { overflow-x: auto; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  }
 
251
  .step-dot.active { background: var(--primary); }
252
  .step-dot.done { background: var(--correct); }
253
 
254
+ /* ===== ANSWER BADGES ===== */
255
+ .answer-badge { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border-radius: 50%; font-size: 14px; font-weight: 700; flex-shrink: 0; margin-left: auto; }
256
+ .answer-badge-correct { background: var(--correct-bg); color: var(--correct); }
257
+ .answer-badge-wrong { background: var(--wrong-bg); color: var(--wrong); }
258
+
259
+ /* ===== STATS PAGE ===== */
260
+ .stats-overview { display: flex; gap: 20px; margin-bottom: 28px; align-items: stretch; }
261
+ .stats-big-card { background: var(--card-bg); border-radius: var(--r); padding: 32px 40px; box-shadow: var(--shadow); text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; min-width: 180px; }
262
+ .stats-big-number { font-size: 56px; font-weight: 800; line-height: 1; }
263
+ .stats-big-number.stats-good { color: var(--correct); }
264
+ .stats-big-number.stats-ok { color: var(--accent); }
265
+ .stats-big-number.stats-low { color: var(--wrong); }
266
+ .stats-big-label { font-size: 14px; color: var(--text-sec); margin-top: 8px; font-weight: 500; }
267
+ .stats-summary-cards { display: flex; flex: 1; gap: 16px; }
268
+ .stats-summary-cards .stat-card { flex: 1; }
269
+
270
+ .stats-section-title { font-size: 18px; font-weight: 600; margin-bottom: 16px; margin-top: 8px; }
271
+
272
+ .stats-tracks { background: var(--card-bg); border-radius: var(--r); padding: 20px; box-shadow: var(--shadow); margin-bottom: 28px; }
273
+ .stats-track-row { display: flex; align-items: center; gap: 12px; padding: 8px 0; border-bottom: 1px solid var(--border); }
274
+ .stats-track-row:last-child { border-bottom: none; }
275
+ .stats-track-name { width: 180px; font-size: 13px; font-weight: 500; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
276
+ .stats-track-bar-wrap { flex: 1; height: 20px; background: var(--bg); border-radius: 10px; overflow: hidden; }
277
+ .stats-track-bar { height: 100%; border-radius: 10px; transition: width 0.5s ease; min-width: 4px; }
278
+ .stats-track-pct { width: 48px; text-align: right; font-weight: 700; font-size: 14px; flex-shrink: 0; }
279
+ .stats-track-count { width: 48px; text-align: right; font-size: 12px; color: var(--text-sec); flex-shrink: 0; }
280
+
281
+ .stats-history { background: var(--card-bg); border-radius: var(--r); box-shadow: var(--shadow); overflow: hidden; }
282
+ .stats-history-item { display: flex; align-items: center; gap: 12px; padding: 14px 18px; border-bottom: 1px solid var(--border); cursor: pointer; transition: background var(--transition); }
283
+ .stats-history-item:last-child { border-bottom: none; }
284
+ .stats-history-item:hover { background: #f8f9fa; }
285
+ .stats-history-info { flex: 1; min-width: 0; }
286
+ .stats-history-track { font-size: 13px; font-weight: 600; color: var(--primary-dark); }
287
+ .stats-history-snippet { font-size: 12px; color: var(--text-sec); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; }
288
+ .stats-history-meta { text-align: right; flex-shrink: 0; }
289
+ .stats-history-answer { display: block; font-size: 12px; font-weight: 600; color: var(--text); }
290
+ .stats-history-date { display: block; font-size: 11px; color: var(--text-sec); margin-top: 2px; }
291
+
292
+ /* ===== SIMULADO CONFIG ===== */
293
+ .simulado-config { background: var(--card-bg); border-radius: var(--r); padding: 32px; box-shadow: var(--shadow); }
294
+ .simulado-config-section { margin-bottom: 28px; }
295
+ .simulado-config-section h3 { font-size: 16px; font-weight: 600; margin-bottom: 12px; color: var(--text); }
296
+
297
+ .simulado-count-options { display: flex; gap: 10px; }
298
+ .simulado-count-btn { padding: 12px 24px; border: 2px solid var(--border); border-radius: 8px; background: var(--card-bg); cursor: pointer; font-size: 18px; font-weight: 700; transition: all var(--transition); color: var(--text); }
299
+ .simulado-count-btn:hover { border-color: var(--primary); color: var(--primary); }
300
+ .simulado-count-btn.active { background: var(--primary); color: white; border-color: var(--primary); }
301
+
302
+ .simulado-select { width: 100%; max-width: 300px; padding: 10px 14px; border: 2px solid var(--border); border-radius: 8px; font-size: 15px; background: var(--card-bg); color: var(--text); outline: none; transition: border-color var(--transition); }
303
+ .simulado-select:focus { border-color: var(--primary); }
304
+
305
+ .simulado-track-actions { display: flex; gap: 8px; margin-bottom: 12px; }
306
+
307
+ .simulado-tracks { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 6px; max-height: 320px; overflow-y: auto; padding: 4px 0; }
308
+ .simulado-check { display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-size: 14px; transition: background var(--transition); }
309
+ .simulado-check:hover { background: var(--bg); }
310
+ .simulado-check input { width: 18px; height: 18px; accent-color: var(--primary); cursor: pointer; }
311
+ .simulado-check small { color: var(--text-sec); }
312
+
313
+ .simulado-config-error { background: var(--wrong-bg); color: var(--wrong); padding: 12px; border-radius: 8px; margin-bottom: 16px; font-size: 14px; display: none; }
314
+
315
+ .simulado-start-btn { font-size: 18px; padding: 14px 32px; }
316
+
317
+ /* ===== SIMULADO TIMER ===== */
318
+ .simulado-timer { position: sticky; top: 60px; z-index: 90; background: var(--card-bg); border-bottom: 1px solid var(--border); padding: 10px 24px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 6px rgba(0,0,0,.08); gap: 12px; }
319
+ .simulado-timer.warning { background: #fff8e1; border-bottom-color: #f9a825; }
320
+ .simulado-timer.danger { background: var(--wrong-bg); border-bottom-color: var(--wrong); }
321
+ .simulado-timer-left { display: flex; align-items: center; gap: 8px; }
322
+ .simulado-timer-icon { font-size: 20px; }
323
+ .simulado-timer-text { font-size: 22px; font-weight: 700; font-family: monospace; color: var(--text); min-width: 80px; }
324
+ .simulado-timer.warning .simulado-timer-text { color: #f57f17; }
325
+ .simulado-timer.danger .simulado-timer-text { color: var(--wrong); }
326
+ .simulado-timer-center { font-size: 14px; color: var(--text-sec); font-weight: 500; }
327
+ .simulado-timer-right { display: flex; align-items: center; gap: 8px; }
328
+
329
+ /* ===== SIMULADO BODY LAYOUT ===== */
330
+ .simulado-body { display: flex; gap: 20px; max-width: 1200px; margin: 0 auto; padding: 20px; }
331
+ .simulado-content { flex: 1; min-width: 0; }
332
+
333
+ /* ===== SIMULADO NAV SIDEBAR ===== */
334
+ .simulado-nav { width: 200px; flex-shrink: 0; position: sticky; top: 120px; align-self: flex-start; background: var(--card-bg); border-radius: var(--r); padding: 16px; box-shadow: var(--shadow); max-height: calc(100vh - 140px); overflow-y: auto; }
335
+ .simulado-nav-title { font-size: 14px; font-weight: 600; margin-bottom: 12px; color: var(--text-sec); text-transform: uppercase; letter-spacing: 0.5px; }
336
+ .simulado-nav-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; margin-bottom: 12px; }
337
+ .simulado-nav-btn { width: 100%; aspect-ratio: 1; border: 2px solid var(--border); border-radius: 6px; background: var(--card-bg); cursor: pointer; font-size: 12px; font-weight: 600; transition: all var(--transition); color: var(--text-sec); padding: 0; }
338
+ .simulado-nav-btn:hover { border-color: var(--primary); color: var(--primary); }
339
+ .simulado-nav-btn.current { border-color: var(--primary); background: var(--primary-light); color: var(--primary); }
340
+ .simulado-nav-btn.answered { background: var(--primary); color: white; border-color: var(--primary); }
341
+ .simulado-nav-btn.answered.current { box-shadow: 0 0 0 2px var(--primary-dark); }
342
+
343
+ .simulado-nav-legend { display: flex; flex-direction: column; gap: 4px; }
344
+ .legend-item { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-sec); }
345
+ .legend-dot { width: 12px; height: 12px; border-radius: 3px; border: 2px solid var(--border); background: var(--card-bg); flex-shrink: 0; }
346
+ .legend-dot.answered { background: var(--primary); border-color: var(--primary); }
347
+ .legend-dot.current { background: var(--primary-light); border-color: var(--primary); }
348
+
349
+ /* ===== SIMULADO QUESTION EXTRAS ===== */
350
+ .simulado-question { }
351
+ .simulado-track-badge { display: inline-block; background: var(--primary-light); color: var(--primary-dark); font-size: 11px; font-weight: 600; padding: 2px 10px; border-radius: 12px; margin-left: auto; }
352
+
353
+ .simulado-arrows { display: flex; justify-content: space-between; margin-top: 16px; gap: 12px; }
354
+ .simulado-arrows .btn { flex: 1; }
355
+
356
+ /* ===== SIMULADO RESULTS ===== */
357
+ .simulado-results { text-align: center; }
358
+ .simulado-results-header h2 { font-size: 24px; margin-bottom: 24px; }
359
+
360
+ .simulado-score-circle { width: 180px; height: 180px; border-radius: 50%; display: flex; flex-direction: column; align-items: center; justify-content: center; margin: 0 auto 28px; box-shadow: var(--shadow); }
361
+ .simulado-score-circle.results-green { background: var(--correct-bg); border: 4px solid var(--correct); }
362
+ .simulado-score-circle.results-yellow { background: #fff8e1; border: 4px solid var(--accent); }
363
+ .simulado-score-circle.results-red { background: var(--wrong-bg); border: 4px solid var(--wrong); }
364
+ .score-percentage { font-size: 42px; font-weight: 800; line-height: 1; }
365
+ .results-green .score-percentage { color: var(--correct); }
366
+ .results-yellow .score-percentage { color: #f57f17; }
367
+ .results-red .score-percentage { color: var(--wrong); }
368
+ .score-fraction { font-size: 16px; color: var(--text-sec); margin-top: 4px; font-weight: 500; }
369
+
370
+ .simulado-results-stats { display: flex; justify-content: center; gap: 32px; margin-bottom: 28px; }
371
+ .results-stat { text-align: center; }
372
+ .results-stat-value { font-size: 28px; font-weight: 700; color: var(--text); }
373
+ .results-stat-label { font-size: 13px; color: var(--text-sec); margin-top: 2px; }
374
+
375
+ .simulado-results-actions { display: flex; justify-content: center; gap: 12px; margin-bottom: 36px; }
376
+
377
+ /* ===== SIMULADO REVIEW ===== */
378
+ .simulado-review-section { text-align: left; margin-top: 12px; }
379
+ .simulado-review-section h3 { font-size: 18px; font-weight: 600; margin-bottom: 16px; color: var(--text); }
380
+ .simulado-review-card { background: var(--card-bg); border-radius: var(--r); padding: 20px; margin-bottom: 12px; box-shadow: var(--shadow); border-left: 4px solid var(--wrong); }
381
+ .simulado-review-header { margin-bottom: 8px; }
382
+ .simulado-review-track { font-size: 12px; font-weight: 600; color: var(--primary); background: var(--primary-light); padding: 2px 10px; border-radius: 10px; }
383
+ .simulado-review-snippet { font-size: 14px; color: var(--text); line-height: 1.6; margin-bottom: 12px; }
384
+ .simulado-review-answers { display: flex; gap: 16px; flex-wrap: wrap; }
385
+ .review-wrong { font-size: 13px; font-weight: 600; color: var(--wrong); background: var(--wrong-bg); padding: 4px 12px; border-radius: 6px; }
386
+ .review-correct { font-size: 13px; font-weight: 600; color: var(--correct); background: var(--correct-bg); padding: 4px 12px; border-radius: 6px; }
387
+ .simulado-review-explanation { margin-top: 12px; padding: 12px; background: var(--correct-bg); border-radius: 8px; border-left: 3px solid var(--correct); font-size: 14px; line-height: 1.7; color: #1a1a1a; }
388
+ .simulado-review-explanation img { max-width: 100%; border-radius: 6px; margin: 8px 0; }
389
+
390
+ /* ===== YEAR FILTER ===== */
391
+ .year-filter-wrap { display: flex; align-items: center; gap: 8px; }
392
+ .year-filter-wrap label { font-size: 13px; font-weight: 500; color: var(--text-sec); white-space: nowrap; }
393
+ .year-filter-select { padding: 6px 12px; border: 2px solid var(--border); border-radius: 6px; font-size: 13px; background: white; color: var(--text); outline: none; cursor: pointer; }
394
+ .year-filter-select:focus { border-color: var(--primary); }
395
+
396
  /* ===== RESPONSIVE ===== */
397
  @media (max-width: 600px) {
398
  .container { padding: 16px 12px; }
 
406
  .data-table { font-size: 12px; }
407
  .data-table th, .data-table td { padding: 8px; }
408
  .admin-tabs { overflow-x: auto; }
409
+ .stats-overview { flex-direction: column; }
410
+ .stats-big-card { padding: 24px; }
411
+ .stats-big-number { font-size: 42px; }
412
+ .stats-summary-cards { flex-wrap: wrap; }
413
+ .stats-track-name { width: 100px; font-size: 11px; }
414
+ .stats-track-pct { width: 40px; }
415
+ .stats-track-count { display: none; }
416
+ .stats-history-snippet { display: none; }
417
+ .stats-history-meta { font-size: 11px; }
418
+
419
+ /* Simulado responsive */
420
+ .simulado-body { flex-direction: column; padding: 12px; }
421
+ .simulado-nav { width: 100%; position: static; max-height: none; }
422
+ .simulado-nav-grid { grid-template-columns: repeat(10, 1fr); }
423
+ .simulado-timer { top: 56px; padding: 8px 12px; flex-wrap: wrap; }
424
+ .simulado-timer-text { font-size: 18px; }
425
+ .simulado-count-options { flex-wrap: wrap; }
426
+ .simulado-config { padding: 20px; }
427
+ .simulado-tracks { grid-template-columns: 1fr; }
428
+ .simulado-score-circle { width: 140px; height: 140px; }
429
+ .score-percentage { font-size: 32px; }
430
+ .simulado-results-stats { gap: 20px; }
431
+ .results-stat-value { font-size: 22px; }
432
  }
static/index.html CHANGED
@@ -44,6 +44,7 @@
44
  <script src="/static/js/protection.js?v=1"></script>
45
  <script src="/static/js/heartbeat.js?v=1"></script>
46
  <script src="/static/js/questions.js?v=1"></script>
 
47
  <script src="/static/js/admin.js?v=1"></script>
48
  <script src="/static/js/app.js?v=1"></script>
49
  </body>
 
44
  <script src="/static/js/protection.js?v=1"></script>
45
  <script src="/static/js/heartbeat.js?v=1"></script>
46
  <script src="/static/js/questions.js?v=1"></script>
47
+ <script src="/static/js/simulado.js?v=1"></script>
48
  <script src="/static/js/admin.js?v=1"></script>
49
  <script src="/static/js/app.js?v=1"></script>
50
  </body>
static/js/admin.js CHANGED
@@ -45,6 +45,43 @@ const Admin = {
45
  </div>
46
  </div>
47
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  `;
49
  },
50
 
@@ -116,8 +153,9 @@ const Admin = {
116
 
117
  renderUsers(users) {
118
  let html = `
119
- <div style="margin-bottom:16px; display:flex; justify-content:flex-end;">
120
- <button class="btn btn-primary" style="width:auto" onclick="Admin.openModal('modal-create-user')">+ Novo Usuario</button>
 
121
  </div>
122
  <table class="data-table">
123
  <thead><tr><th>Email</th><th>Nome</th><th>Role</th><th>Status</th><th>Sessoes</th><th>Tempo Total</th><th>Ultimo Login</th><th>Acoes</th></tr></thead>
@@ -201,26 +239,98 @@ const Admin = {
201
  },
202
 
203
  async resetPassword(uid, email) {
204
- const newPass = prompt(`Nova senha para ${email}:\n(minimo 6 caracteres)`);
205
- if (!newPass) return;
206
- if (newPass.length < 6) { alert('Senha deve ter no minimo 6 caracteres'); return; }
207
  try {
208
- const res = await fetch(`/api/admin/users/${uid}`, { method: 'PUT', headers: Auth.headers(), body: JSON.stringify({ password: newPass }) });
209
  const data = await res.json();
210
  if (!res.ok) throw new Error(data.error);
211
- alert(`Senha de ${email} alterada com sucesso!`);
 
 
 
 
 
 
212
  } catch (e) { alert('Erro: ' + e.message); }
213
  },
214
 
 
 
 
 
 
 
 
215
  async toggleUser(uid, activate) {
216
  if (!confirm(activate ? 'Ativar este usuario?' : 'Desativar este usuario?')) return;
217
  try {
218
- const res = await fetch(`/api/admin/users/${uid}`, { method: 'PUT', headers: Auth.headers(), body: JSON.stringify({ is_active: activate }) });
219
- if (!res.ok) throw new Error('Erro ao atualizar');
 
220
  this.switchTab('users');
221
  } catch (e) { alert('Erro: ' + e.message); }
222
  },
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  async kickSession(sid) {
225
  if (!confirm('Encerrar esta sessao?')) return;
226
  try {
 
45
  </div>
46
  </div>
47
  </div>
48
+
49
+ <!-- Batch Create Modal -->
50
+ <div class="modal-overlay" id="modal-batch-create">
51
+ <div class="modal" style="max-width:600px">
52
+ <h2>Cadastro em Lote</h2>
53
+ <div id="batch-form">
54
+ <div class="form-group">
55
+ <label>Lista de alunos (um por linha)</label>
56
+ <textarea id="batch-input" rows="10" placeholder="email@exemplo.com, Nome do Aluno&#10;outro@email.com, Outro Nome&#10;apenas@email.com" style="width:100%;font-family:monospace;font-size:13px;padding:10px;border:1px solid #ddd;border-radius:8px;resize:vertical;"></textarea>
57
+ <small style="color:var(--text-sec);display:block;margin-top:6px;">Formato: email ou email, nome (um por linha). Senhas serao geradas automaticamente.</small>
58
+ </div>
59
+ <div class="modal-actions">
60
+ <button class="btn btn-secondary" onclick="Admin.closeModal('modal-batch-create')">Cancelar</button>
61
+ <button class="btn btn-primary" style="width:auto" onclick="Admin.batchCreate()">Criar Usuarios</button>
62
+ </div>
63
+ </div>
64
+ <div id="batch-results" style="display:none">
65
+ <div id="batch-results-content"></div>
66
+ <div class="modal-actions">
67
+ <button class="btn btn-secondary" onclick="Admin.closeBatchResults()">Fechar</button>
68
+ <button class="btn btn-primary" style="width:auto" onclick="Admin.copyBatchResults()">Copiar Tabela</button>
69
+ </div>
70
+ </div>
71
+ </div>
72
+ </div>
73
+
74
+ <!-- Password Result Modal -->
75
+ <div class="modal-overlay" id="modal-password-result">
76
+ <div class="modal">
77
+ <h2>Senha Redefinida</h2>
78
+ <div id="password-result-content"></div>
79
+ <div class="modal-actions">
80
+ <button class="btn btn-secondary" onclick="Admin.closeModal('modal-password-result')">Fechar</button>
81
+ <button class="btn btn-primary" style="width:auto" onclick="Admin.copyPasswordResult()">Copiar</button>
82
+ </div>
83
+ </div>
84
+ </div>
85
  `;
86
  },
87
 
 
153
 
154
  renderUsers(users) {
155
  let html = `
156
+ <div style="margin-bottom:16px; display:flex; justify-content:flex-end; gap:8px;">
157
+ <button class="btn btn-secondary" style="width:auto" onclick="Admin.openModal('modal-batch-create')">Cadastro em Lote</button>
158
+ <button class="btn btn-primary" style="width:auto" onclick="Admin.openModal('modal-create-user')">+ Novo Aluno</button>
159
  </div>
160
  <table class="data-table">
161
  <thead><tr><th>Email</th><th>Nome</th><th>Role</th><th>Status</th><th>Sessoes</th><th>Tempo Total</th><th>Ultimo Login</th><th>Acoes</th></tr></thead>
 
239
  },
240
 
241
  async resetPassword(uid, email) {
242
+ if (!confirm(`Redefinir senha de ${email}?\nUma nova senha aleatoria sera gerada.`)) return;
 
 
243
  try {
244
+ const res = await fetch(`/api/admin/users/${uid}/reset-password`, { method: 'POST', headers: Auth.headers() });
245
  const data = await res.json();
246
  if (!res.ok) throw new Error(data.error);
247
+ this._lastPasswordResult = `${data.email}: ${data.new_password}`;
248
+ document.getElementById('password-result-content').innerHTML = `
249
+ <p style="margin-bottom:12px">Nova senha gerada para <strong>${this.esc(data.email)}</strong>:</p>
250
+ <code style="display:block;background:#f5f5f5;padding:12px;border-radius:8px;font-size:16px;text-align:center;user-select:all">${this.esc(data.new_password)}</code>
251
+ <p style="margin-top:12px;color:var(--text-sec);font-size:13px">Compartilhe esta senha com o usuario. Ela nao podera ser visualizada novamente.</p>
252
+ `;
253
+ this.openModal('modal-password-result');
254
  } catch (e) { alert('Erro: ' + e.message); }
255
  },
256
 
257
+ async copyPasswordResult() {
258
+ if (this._lastPasswordResult) {
259
+ await navigator.clipboard.writeText(this._lastPasswordResult);
260
+ alert('Copiado!');
261
+ }
262
+ },
263
+
264
  async toggleUser(uid, activate) {
265
  if (!confirm(activate ? 'Ativar este usuario?' : 'Desativar este usuario?')) return;
266
  try {
267
+ const res = await fetch(`/api/admin/users/${uid}/toggle`, { method: 'PUT', headers: Auth.headers() });
268
+ const data = await res.json();
269
+ if (!res.ok) throw new Error(data.error || 'Erro ao atualizar');
270
  this.switchTab('users');
271
  } catch (e) { alert('Erro: ' + e.message); }
272
  },
273
 
274
+ async batchCreate() {
275
+ const raw = document.getElementById('batch-input').value.trim();
276
+ if (!raw) { alert('Insira pelo menos um email'); return; }
277
+
278
+ const lines = raw.split('\n').filter(l => l.trim());
279
+ const users = lines.map(line => {
280
+ const parts = line.split(',').map(p => p.trim());
281
+ return { email: parts[0], name: parts[1] || '' };
282
+ });
283
+
284
+ if (users.length === 0) { alert('Nenhum email valido encontrado'); return; }
285
+ if (!confirm(`Criar ${users.length} usuario(s)?`)) return;
286
+
287
+ try {
288
+ const res = await fetch('/api/admin/users/batch-create', {
289
+ method: 'POST', headers: Auth.headers(), body: JSON.stringify({ users })
290
+ });
291
+ const data = await res.json();
292
+ if (!res.ok) throw new Error(data.error);
293
+
294
+ let html = '';
295
+ if (data.total_created > 0) {
296
+ html += `<p style="margin-bottom:8px;color:var(--correct);font-weight:600">${data.total_created} usuario(s) criado(s)</p>`;
297
+ html += '<table class="data-table" style="font-size:13px"><thead><tr><th>Email</th><th>Nome</th><th>Senha</th></tr></thead><tbody>';
298
+ this._batchResultText = 'Email\tNome\tSenha\n';
299
+ for (const u of data.created) {
300
+ html += `<tr><td>${this.esc(u.email)}</td><td>${this.esc(u.name || '—')}</td><td><code style="user-select:all">${this.esc(u.password)}</code></td></tr>`;
301
+ this._batchResultText += `${u.email}\t${u.name || ''}\t${u.password}\n`;
302
+ }
303
+ html += '</tbody></table>';
304
+ }
305
+ if (data.total_errors > 0) {
306
+ html += `<p style="margin-top:12px;margin-bottom:8px;color:var(--wrong);font-weight:600">${data.total_errors} erro(s)</p><ul style="font-size:13px">`;
307
+ for (const e of data.errors) {
308
+ html += `<li>${this.esc(e.email)}: ${this.esc(e.error)}</li>`;
309
+ }
310
+ html += '</ul>';
311
+ }
312
+
313
+ document.getElementById('batch-form').style.display = 'none';
314
+ document.getElementById('batch-results').style.display = 'block';
315
+ document.getElementById('batch-results-content').innerHTML = html;
316
+ } catch (e) { alert('Erro: ' + e.message); }
317
+ },
318
+
319
+ async copyBatchResults() {
320
+ if (this._batchResultText) {
321
+ await navigator.clipboard.writeText(this._batchResultText);
322
+ alert('Tabela copiada!');
323
+ }
324
+ },
325
+
326
+ closeBatchResults() {
327
+ document.getElementById('batch-form').style.display = 'block';
328
+ document.getElementById('batch-results').style.display = 'none';
329
+ document.getElementById('batch-input').value = '';
330
+ this.closeModal('modal-batch-create');
331
+ this.switchTab('users');
332
+ },
333
+
334
  async kickSession(sid) {
335
  if (!confirm('Encerrar esta sessao?')) return;
336
  try {
static/js/app.js CHANGED
@@ -83,6 +83,8 @@ const App = {
83
  <span class="logo" onclick="App.navigate('/')"><span class="brand-text">MedMembers OFT 2026</span></span>
84
  <div class="user-menu">
85
  <button class="btn btn-secondary btn-sm" onclick="App.navigate('/')" title="Banco de Questoes">&#128221; Questoes</button>
 
 
86
  ${user.role === 'admin' ? '<button class="btn btn-secondary btn-sm" onclick="App.navigate(\'/admin\')">Admin</button>' : ''}
87
  <span class="user-email">${this.escapeHtml(user.email)}</span>
88
  <button class="btn btn-sm" style="background:#f0f0f0" onclick="Auth.logout()">Sair</button>
@@ -99,6 +101,11 @@ const App = {
99
  app.innerHTML = '<div class="loading"><div class="spinner"></div>Carregando...</div>';
100
 
101
  try {
 
 
 
 
 
102
  if (hash === '/' || hash === '') {
103
  await this.showTopics();
104
  } else if (hash.startsWith('/topic/')) {
@@ -106,7 +113,14 @@ const App = {
106
  const slug = parts[0].replace('/topic/', '');
107
  const params = new URLSearchParams(parts[1] || '');
108
  const page = parseInt(params.get('page')) || 1;
109
- await this.showQuestions(slug, page);
 
 
 
 
 
 
 
110
  } else if (hash === '/admin') {
111
  await this.showAdmin();
112
  } else {
@@ -132,21 +146,130 @@ const App = {
132
  document.getElementById('app').innerHTML = Questions.renderTopicsPage(this.topicsCache);
133
  },
134
 
135
- async showQuestions(slug, page) {
136
  if (!this.topicsCache) {
137
  this.topicsCache = await Questions.loadTopics();
138
  }
139
  const topic = this.topicsCache.find(t => t.slug === slug);
140
  const topicName = topic ? topic.name : slug;
141
 
142
- const data = await Questions.loadQuestions(slug, page);
143
- document.getElementById('app').innerHTML = Questions.renderQuestionsPage(data, topicName, slug);
 
 
 
 
 
 
 
 
 
 
 
144
  },
145
 
146
  async showAdmin() {
147
  document.getElementById('app').innerHTML = await Admin.render();
148
  },
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  navigate(path) {
151
  window.location.hash = '#' + path;
152
  },
 
83
  <span class="logo" onclick="App.navigate('/')"><span class="brand-text">MedMembers OFT 2026</span></span>
84
  <div class="user-menu">
85
  <button class="btn btn-secondary btn-sm" onclick="App.navigate('/')" title="Banco de Questoes">&#128221; Questoes</button>
86
+ <button class="btn btn-secondary btn-sm" onclick="App.navigate('/simulado')" title="Simulado">&#127919; Simulado</button>
87
+ <button class="btn btn-secondary btn-sm" onclick="App.navigate('/stats')" title="Estatisticas">&#128202; Estatisticas</button>
88
  ${user.role === 'admin' ? '<button class="btn btn-secondary btn-sm" onclick="App.navigate(\'/admin\')">Admin</button>' : ''}
89
  <span class="user-email">${this.escapeHtml(user.email)}</span>
90
  <button class="btn btn-sm" style="background:#f0f0f0" onclick="Auth.logout()">Sair</button>
 
101
  app.innerHTML = '<div class="loading"><div class="spinner"></div>Carregando...</div>';
102
 
103
  try {
104
+ // Clean up simulado timer when navigating away
105
+ if (!hash.startsWith('/simulado')) {
106
+ Simulado.cleanup();
107
+ }
108
+
109
  if (hash === '/' || hash === '') {
110
  await this.showTopics();
111
  } else if (hash.startsWith('/topic/')) {
 
113
  const slug = parts[0].replace('/topic/', '');
114
  const params = new URLSearchParams(parts[1] || '');
115
  const page = parseInt(params.get('page')) || 1;
116
+ const year = params.get('year') || '';
117
+ await this.showQuestions(slug, page, year);
118
+ } else if (hash === '/simulado') {
119
+ await this.showSimuladoConfig();
120
+ } else if (hash === '/simulado/exam') {
121
+ this.showSimuladoExam();
122
+ } else if (hash === '/stats') {
123
+ await this.showStats();
124
  } else if (hash === '/admin') {
125
  await this.showAdmin();
126
  } else {
 
146
  document.getElementById('app').innerHTML = Questions.renderTopicsPage(this.topicsCache);
147
  },
148
 
149
+ async showQuestions(slug, page, year) {
150
  if (!this.topicsCache) {
151
  this.topicsCache = await Questions.loadTopics();
152
  }
153
  const topic = this.topicsCache.find(t => t.slug === slug);
154
  const topicName = topic ? topic.name : slug;
155
 
156
+ const [data, years] = await Promise.all([
157
+ Questions.loadQuestions(slug, page, year),
158
+ Questions.loadYears()
159
+ ]);
160
+ document.getElementById('app').innerHTML = Questions.renderQuestionsPage(data, topicName, slug, year, years);
161
+ },
162
+
163
+ async showSimuladoConfig() {
164
+ document.getElementById('app').innerHTML = await Simulado.renderConfig();
165
+ },
166
+
167
+ showSimuladoExam() {
168
+ document.getElementById('app').innerHTML = Simulado.renderExam();
169
  },
170
 
171
  async showAdmin() {
172
  document.getElementById('app').innerHTML = await Admin.render();
173
  },
174
 
175
+ async showStats() {
176
+ const app = document.getElementById('app');
177
+
178
+ try {
179
+ const [statsRes, historyRes] = await Promise.all([
180
+ fetch('/api/user/stats', { headers: Auth.headers() }),
181
+ fetch('/api/user/history?page=1&per_page=15', { headers: Auth.headers() })
182
+ ]);
183
+
184
+ if (!statsRes.ok || !historyRes.ok) throw new Error('Erro ao carregar estatisticas');
185
+
186
+ const stats = await statsRes.json();
187
+ const history = await historyRes.json();
188
+
189
+ let html = `
190
+ <div class="container protected-content">
191
+ <div class="question-nav">
192
+ <a class="back-btn" onclick="App.navigate('/')">&#8592; Voltar</a>
193
+ <h2>Suas Estatisticas</h2>
194
+ </div>
195
+
196
+ <div class="stats-overview">
197
+ <div class="stats-big-card">
198
+ <div class="stats-big-number ${stats.accuracy >= 70 ? 'stats-good' : stats.accuracy >= 50 ? 'stats-ok' : 'stats-low'}">${stats.accuracy}%</div>
199
+ <div class="stats-big-label">Aproveitamento Geral</div>
200
+ </div>
201
+ <div class="stats-summary-cards">
202
+ <div class="stat-card">
203
+ <div class="stat-value">${stats.total_answered}</div>
204
+ <div class="stat-label">Respondidas</div>
205
+ </div>
206
+ <div class="stat-card">
207
+ <div class="stat-value" style="color:var(--correct)">${stats.total_correct}</div>
208
+ <div class="stat-label">Corretas</div>
209
+ </div>
210
+ <div class="stat-card">
211
+ <div class="stat-value" style="color:var(--wrong)">${stats.total_answered - stats.total_correct}</div>
212
+ <div class="stat-label">Erradas</div>
213
+ </div>
214
+ </div>
215
+ </div>
216
+ `;
217
+
218
+ // Per-track bar chart
219
+ if (stats.tracks && stats.tracks.length > 0) {
220
+ html += '<h3 class="stats-section-title">Desempenho por Topico</h3>';
221
+ html += '<div class="stats-tracks">';
222
+ for (const t of stats.tracks) {
223
+ const barColor = t.percentage >= 70 ? 'var(--correct)' : t.percentage >= 50 ? 'var(--accent)' : 'var(--wrong)';
224
+ html += `
225
+ <div class="stats-track-row">
226
+ <div class="stats-track-name">${this.escapeHtml(t.track)}</div>
227
+ <div class="stats-track-bar-wrap">
228
+ <div class="stats-track-bar" style="width:${Math.max(t.percentage, 2)}%;background:${barColor}"></div>
229
+ </div>
230
+ <div class="stats-track-pct">${t.percentage}%</div>
231
+ <div class="stats-track-count">${t.correct}/${t.total}</div>
232
+ </div>
233
+ `;
234
+ }
235
+ html += '</div>';
236
+ }
237
+
238
+ // Recent history
239
+ if (history.history && history.history.length > 0) {
240
+ html += '<h3 class="stats-section-title">Historico Recente</h3>';
241
+ html += '<div class="stats-history">';
242
+ for (const h of history.history) {
243
+ const icon = h.is_correct
244
+ ? '<span class="answer-badge answer-badge-correct">&#10003;</span>'
245
+ : '<span class="answer-badge answer-badge-wrong">&#10007;</span>';
246
+ 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' }) : '';
247
+ html += `
248
+ <div class="stats-history-item" onclick="App.navigate('/topic/${this.escapeHtml(h.track_slug)}')">
249
+ ${icon}
250
+ <div class="stats-history-info">
251
+ <div class="stats-history-track">${this.escapeHtml(h.track)} - Q${h.numero}</div>
252
+ <div class="stats-history-snippet">${this.escapeHtml(h.snippet)}</div>
253
+ </div>
254
+ <div class="stats-history-meta">
255
+ <span class="stats-history-answer">Resp: ${h.selected_answer} | Gab: ${h.correct_answer}</span>
256
+ <span class="stats-history-date">${date}</span>
257
+ </div>
258
+ </div>
259
+ `;
260
+ }
261
+ html += '</div>';
262
+ } else {
263
+ html += '<p class="page-subtitle" style="margin-top:24px">Nenhuma questao respondida ainda. Comece respondendo questoes para ver suas estatisticas!</p>';
264
+ }
265
+
266
+ html += '</div>';
267
+ app.innerHTML = html;
268
+ } catch (e) {
269
+ app.innerHTML = `<div class="container"><h2>Erro</h2><p>${this.escapeHtml(e.message)}</p></div>`;
270
+ }
271
+ },
272
+
273
  navigate(path) {
274
  window.location.hash = '#' + path;
275
  },
static/js/questions.js CHANGED
@@ -11,14 +11,23 @@ const Questions = {
11
  return data.topics;
12
  },
13
 
14
- async loadQuestions(slug, page = 1) {
15
- const res = await fetch(`/api/topics/${slug}/questions?page=${page}&per_page=10`, {
 
 
16
  headers: Auth.headers()
17
  });
18
  if (!res.ok) throw new Error('Erro ao carregar questoes');
19
  return await res.json();
20
  },
21
 
 
 
 
 
 
 
 
22
  async checkAnswer(questionId, answer) {
23
  const res = await fetch(`/api/questions/${questionId}/check`, {
24
  method: 'POST',
@@ -69,9 +78,25 @@ const Questions = {
69
  `;
70
  },
71
 
72
- renderQuestionsPage(data, topicName, slug) {
73
  const { questions, total, page, per_page, total_pages } = data;
74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  let html = `
76
  <div class="container protected-content">
77
  <div class="question-nav">
@@ -80,6 +105,7 @@ const Questions = {
80
  </div>
81
  <div class="stats-bar">
82
  <span>Total: ${total.toLocaleString('pt-BR')} questoes</span>
 
83
  <span>Pagina ${page} de ${total_pages}</span>
84
  </div>
85
  `;
@@ -88,11 +114,17 @@ const Questions = {
88
  html += this.renderQuestionCard(q);
89
  }
90
 
91
- html += this.renderPagination(page, total_pages, slug);
92
  html += '</div>';
93
  return html;
94
  },
95
 
 
 
 
 
 
 
96
  renderQuestionCard(q) {
97
  const token = Auth.getToken();
98
 
@@ -136,11 +168,22 @@ const Questions = {
136
 
137
  const yearBadge = q.year ? `<span style="font-size:12px;color:var(--text-sec);font-weight:400;"> (${this.escapeHtml(q.year)})</span>` : '';
138
 
 
 
 
 
 
 
 
 
 
 
139
  return `
140
  <div class="question-card" id="q-${q.id}">
141
  <div class="question-header">
142
  <div class="question-number">${q.numero}</div>
143
  <h3>Questao ${q.numero}${yearBadge}</h3>
 
144
  </div>
145
  <div class="enunciado">${enunciadoHtml}</div>
146
  <div class="alternativas" data-qid="${q.id}">
@@ -270,30 +313,32 @@ const Questions = {
270
  }
271
  },
272
 
273
- renderPagination(currentPage, totalPages, slug) {
274
  if (totalPages <= 1) return '';
275
 
 
 
276
  let html = '<div class="pagination">';
277
- html += `<button ${currentPage <= 1 ? 'disabled' : ''} onclick="App.navigate('/topic/${slug}?page=${currentPage - 1}')">&#8592; Anterior</button>`;
278
 
279
  const start = Math.max(1, currentPage - 2);
280
  const end = Math.min(totalPages, currentPage + 2);
281
 
282
  if (start > 1) {
283
- html += `<button onclick="App.navigate('/topic/${slug}?page=1')">1</button>`;
284
  if (start > 2) html += '<span>...</span>';
285
  }
286
 
287
  for (let i = start; i <= end; i++) {
288
- html += `<button class="${i === currentPage ? 'active' : ''}" onclick="App.navigate('/topic/${slug}?page=${i}')">${i}</button>`;
289
  }
290
 
291
  if (end < totalPages) {
292
  if (end < totalPages - 1) html += '<span>...</span>';
293
- html += `<button onclick="App.navigate('/topic/${slug}?page=${totalPages}')">${totalPages}</button>`;
294
  }
295
 
296
- html += `<button ${currentPage >= totalPages ? 'disabled' : ''} onclick="App.navigate('/topic/${slug}?page=${currentPage + 1}')">Proxima &#8594;</button>`;
297
  html += '</div>';
298
  return html;
299
  },
 
11
  return data.topics;
12
  },
13
 
14
+ async loadQuestions(slug, page = 1, year = '') {
15
+ let url = `/api/topics/${slug}/questions?page=${page}&per_page=10`;
16
+ if (year) url += `&year=${encodeURIComponent(year)}`;
17
+ const res = await fetch(url, {
18
  headers: Auth.headers()
19
  });
20
  if (!res.ok) throw new Error('Erro ao carregar questoes');
21
  return await res.json();
22
  },
23
 
24
+ async loadYears() {
25
+ const res = await fetch('/api/years', { headers: Auth.headers() });
26
+ if (!res.ok) return [];
27
+ const data = await res.json();
28
+ return data.years || [];
29
+ },
30
+
31
  async checkAnswer(questionId, answer) {
32
  const res = await fetch(`/api/questions/${questionId}/check`, {
33
  method: 'POST',
 
78
  `;
79
  },
80
 
81
+ renderQuestionsPage(data, topicName, slug, currentYear, years) {
82
  const { questions, total, page, per_page, total_pages } = data;
83
 
84
+ let yearFilterHtml = '';
85
+ if (years && years.length > 0) {
86
+ const yearOpts = years.map(y =>
87
+ `<option value="${y}" ${y === currentYear ? 'selected' : ''}>${y}</option>`
88
+ ).join('');
89
+ yearFilterHtml = `
90
+ <div class="year-filter-wrap">
91
+ <label>Ano:</label>
92
+ <select class="year-filter-select" onchange="Questions.filterByYear('${slug}', this.value)">
93
+ <option value="">Todos</option>
94
+ ${yearOpts}
95
+ </select>
96
+ </div>
97
+ `;
98
+ }
99
+
100
  let html = `
101
  <div class="container protected-content">
102
  <div class="question-nav">
 
105
  </div>
106
  <div class="stats-bar">
107
  <span>Total: ${total.toLocaleString('pt-BR')} questoes</span>
108
+ ${yearFilterHtml}
109
  <span>Pagina ${page} de ${total_pages}</span>
110
  </div>
111
  `;
 
114
  html += this.renderQuestionCard(q);
115
  }
116
 
117
+ html += this.renderPagination(page, total_pages, slug, currentYear);
118
  html += '</div>';
119
  return html;
120
  },
121
 
122
+ filterByYear(slug, year) {
123
+ let path = `/topic/${slug}?page=1`;
124
+ if (year) path += `&year=${encodeURIComponent(year)}`;
125
+ App.navigate(path);
126
+ },
127
+
128
  renderQuestionCard(q) {
129
  const token = Auth.getToken();
130
 
 
168
 
169
  const yearBadge = q.year ? `<span style="font-size:12px;color:var(--text-sec);font-weight:400;"> (${this.escapeHtml(q.year)})</span>` : '';
170
 
171
+ // Answer status badge
172
+ let answerBadge = '';
173
+ if (q.user_answer !== null && q.user_answer !== undefined) {
174
+ if (q.user_correct) {
175
+ answerBadge = '<span class="answer-badge answer-badge-correct" title="Respondida corretamente">&#10003;</span>';
176
+ } else {
177
+ answerBadge = '<span class="answer-badge answer-badge-wrong" title="Respondida incorretamente">&#10007;</span>';
178
+ }
179
+ }
180
+
181
  return `
182
  <div class="question-card" id="q-${q.id}">
183
  <div class="question-header">
184
  <div class="question-number">${q.numero}</div>
185
  <h3>Questao ${q.numero}${yearBadge}</h3>
186
+ ${answerBadge}
187
  </div>
188
  <div class="enunciado">${enunciadoHtml}</div>
189
  <div class="alternativas" data-qid="${q.id}">
 
313
  }
314
  },
315
 
316
+ renderPagination(currentPage, totalPages, slug, year) {
317
  if (totalPages <= 1) return '';
318
 
319
+ const yearParam = year ? `&year=${encodeURIComponent(year)}` : '';
320
+
321
  let html = '<div class="pagination">';
322
+ html += `<button ${currentPage <= 1 ? 'disabled' : ''} onclick="App.navigate('/topic/${slug}?page=${currentPage - 1}${yearParam}')">&#8592; Anterior</button>`;
323
 
324
  const start = Math.max(1, currentPage - 2);
325
  const end = Math.min(totalPages, currentPage + 2);
326
 
327
  if (start > 1) {
328
+ html += `<button onclick="App.navigate('/topic/${slug}?page=1${yearParam}')">1</button>`;
329
  if (start > 2) html += '<span>...</span>';
330
  }
331
 
332
  for (let i = start; i <= end; i++) {
333
+ html += `<button class="${i === currentPage ? 'active' : ''}" onclick="App.navigate('/topic/${slug}?page=${i}${yearParam}')">${i}</button>`;
334
  }
335
 
336
  if (end < totalPages) {
337
  if (end < totalPages - 1) html += '<span>...</span>';
338
+ html += `<button onclick="App.navigate('/topic/${slug}?page=${totalPages}${yearParam}')">${totalPages}</button>`;
339
  }
340
 
341
+ html += `<button ${currentPage >= totalPages ? 'disabled' : ''} onclick="App.navigate('/topic/${slug}?page=${currentPage + 1}${yearParam}')">Proxima &#8594;</button>`;
342
  html += '</div>';
343
  return html;
344
  },
static/js/simulado.js ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ===== Simulado (Simulated Exam) Module =====
2
+
3
+ const Simulado = {
4
+ // State
5
+ simuladoId: null,
6
+ questions: [],
7
+ answers: {}, // { questionId: 'A' }
8
+ currentIndex: 0,
9
+ viewMode: 'single', // 'single' or 'all'
10
+ timeLimit: 0, // seconds
11
+ timeRemaining: 0, // seconds
12
+ timerInterval: null,
13
+ startTime: null,
14
+ submitted: false,
15
+ topicsCache: null,
16
+ yearsCache: null,
17
+
18
+ // ===== API =====
19
+ async loadTopics() {
20
+ if (this.topicsCache) return this.topicsCache;
21
+ const res = await fetch('/api/topics', { headers: Auth.headers() });
22
+ if (!res.ok) throw new Error('Erro ao carregar topicos');
23
+ const data = await res.json();
24
+ this.topicsCache = data.topics;
25
+ return this.topicsCache;
26
+ },
27
+
28
+ async loadYears() {
29
+ if (this.yearsCache) return this.yearsCache;
30
+ const res = await fetch('/api/years', { headers: Auth.headers() });
31
+ if (!res.ok) throw new Error('Erro ao carregar anos');
32
+ const data = await res.json();
33
+ this.yearsCache = data.years;
34
+ return this.yearsCache;
35
+ },
36
+
37
+ async generateExam(count, tracks, year) {
38
+ const params = new URLSearchParams({ count, tracks, year });
39
+ const res = await fetch(`/api/simulado/generate?${params}`, { headers: Auth.headers() });
40
+ if (!res.ok) {
41
+ const err = await res.json();
42
+ throw new Error(err.error || 'Erro ao gerar simulado');
43
+ }
44
+ return await res.json();
45
+ },
46
+
47
+ async submitExam() {
48
+ const timeSpent = Math.floor((Date.now() - this.startTime) / 1000);
49
+ const res = await fetch('/api/simulado/submit', {
50
+ method: 'POST',
51
+ headers: Auth.headers(),
52
+ body: JSON.stringify({
53
+ simulado_id: this.simuladoId,
54
+ answers: this.answers,
55
+ time_spent_seconds: timeSpent
56
+ })
57
+ });
58
+ if (!res.ok) throw new Error('Erro ao enviar simulado');
59
+ return await res.json();
60
+ },
61
+
62
+ // ===== CONFIG SCREEN =====
63
+ async renderConfig() {
64
+ const [topics, years] = await Promise.all([this.loadTopics(), this.loadYears()]);
65
+
66
+ const topicChecks = topics.map(t => `
67
+ <label class="simulado-check">
68
+ <input type="checkbox" value="${t.slug}" checked>
69
+ <span>${this.escapeHtml(t.name)} <small>(${t.count})</small></span>
70
+ </label>
71
+ `).join('');
72
+
73
+ const yearOpts = years.map(y => `<option value="${y}">${y}</option>`).join('');
74
+
75
+ return `
76
+ <div class="container protected-content">
77
+ <div class="question-nav">
78
+ <a class="back-btn" onclick="App.navigate('/')">&#8592; Voltar</a>
79
+ <h2>Simulado</h2>
80
+ </div>
81
+ <div class="simulado-config">
82
+ <div class="simulado-config-section">
83
+ <h3>Numero de questoes</h3>
84
+ <div class="simulado-count-options">
85
+ <button class="simulado-count-btn" data-count="10" onclick="Simulado.selectCount(this)">10</button>
86
+ <button class="simulado-count-btn" data-count="25" onclick="Simulado.selectCount(this)">25</button>
87
+ <button class="simulado-count-btn active" data-count="50" onclick="Simulado.selectCount(this)">50</button>
88
+ <button class="simulado-count-btn" data-count="100" onclick="Simulado.selectCount(this)">100</button>
89
+ </div>
90
+ </div>
91
+
92
+ <div class="simulado-config-section">
93
+ <h3>Ano (opcional)</h3>
94
+ <select id="simulado-year" class="simulado-select">
95
+ <option value="">Todos os anos</option>
96
+ ${yearOpts}
97
+ </select>
98
+ </div>
99
+
100
+ <div class="simulado-config-section">
101
+ <h3>Topicos</h3>
102
+ <div class="simulado-track-actions">
103
+ <button class="btn btn-sm btn-secondary" onclick="Simulado.toggleAllTracks(true)">Selecionar todos</button>
104
+ <button class="btn btn-sm btn-secondary" onclick="Simulado.toggleAllTracks(false)">Desmarcar todos</button>
105
+ </div>
106
+ <div class="simulado-tracks" id="simulado-tracks">
107
+ ${topicChecks}
108
+ </div>
109
+ </div>
110
+
111
+ <div class="simulado-config-error" id="simulado-config-error"></div>
112
+
113
+ <button class="btn btn-primary simulado-start-btn" id="simulado-start-btn" onclick="Simulado.startExam()">
114
+ Iniciar Simulado
115
+ </button>
116
+ </div>
117
+ </div>
118
+ `;
119
+ },
120
+
121
+ selectCount(btn) {
122
+ document.querySelectorAll('.simulado-count-btn').forEach(b => b.classList.remove('active'));
123
+ btn.classList.add('active');
124
+ },
125
+
126
+ toggleAllTracks(checked) {
127
+ document.querySelectorAll('#simulado-tracks input[type="checkbox"]').forEach(cb => {
128
+ cb.checked = checked;
129
+ });
130
+ },
131
+
132
+ async startExam() {
133
+ const btn = document.getElementById('simulado-start-btn');
134
+ const errorEl = document.getElementById('simulado-config-error');
135
+ errorEl.style.display = 'none';
136
+
137
+ const countBtn = document.querySelector('.simulado-count-btn.active');
138
+ const count = countBtn ? parseInt(countBtn.dataset.count) : 50;
139
+ const year = document.getElementById('simulado-year').value;
140
+
141
+ const checkedBoxes = document.querySelectorAll('#simulado-tracks input:checked');
142
+ if (checkedBoxes.length === 0) {
143
+ errorEl.textContent = 'Selecione pelo menos um topico.';
144
+ errorEl.style.display = 'block';
145
+ return;
146
+ }
147
+
148
+ const allBoxes = document.querySelectorAll('#simulado-tracks input[type="checkbox"]');
149
+ let tracks = 'all';
150
+ if (checkedBoxes.length < allBoxes.length) {
151
+ tracks = Array.from(checkedBoxes).map(cb => cb.value).join(',');
152
+ }
153
+
154
+ btn.disabled = true;
155
+ btn.textContent = 'Gerando simulado...';
156
+
157
+ try {
158
+ const data = await this.generateExam(count, tracks, year);
159
+ this.simuladoId = data.simulado_id;
160
+ this.questions = data.questions;
161
+ this.answers = {};
162
+ this.currentIndex = 0;
163
+ this.viewMode = 'single';
164
+ this.timeLimit = data.time_limit_minutes * 60;
165
+ this.timeRemaining = this.timeLimit;
166
+ this.startTime = Date.now();
167
+ this.submitted = false;
168
+
169
+ window.location.hash = '#/simulado/exam';
170
+ } catch (e) {
171
+ errorEl.textContent = e.message;
172
+ errorEl.style.display = 'block';
173
+ btn.disabled = false;
174
+ btn.textContent = 'Iniciar Simulado';
175
+ }
176
+ },
177
+
178
+ // ===== EXAM SCREEN =====
179
+ renderExam() {
180
+ if (!this.questions.length) {
181
+ return '<div class="container"><p>Nenhum simulado ativo. <a onclick="App.navigate(\'/simulado\')">Configurar novo simulado</a></p></div>';
182
+ }
183
+
184
+ this.startTimer();
185
+
186
+ const navButtons = this.questions.map((q, i) => {
187
+ const answered = this.answers[q.id] ? 'answered' : '';
188
+ const current = i === this.currentIndex ? 'current' : '';
189
+ return `<button class="simulado-nav-btn ${answered} ${current}" onclick="Simulado.goToQuestion(${i})">${i + 1}</button>`;
190
+ }).join('');
191
+
192
+ const answeredCount = Object.keys(this.answers).length;
193
+ const totalCount = this.questions.length;
194
+
195
+ let questionsHtml;
196
+ if (this.viewMode === 'single') {
197
+ questionsHtml = this.renderSingleQuestion(this.currentIndex);
198
+ } else {
199
+ questionsHtml = this.questions.map((q, i) => this.renderExamQuestion(q, i)).join('');
200
+ }
201
+
202
+ return `
203
+ <div class="simulado-timer" id="simulado-timer">
204
+ <div class="simulado-timer-left">
205
+ <span class="simulado-timer-icon">&#9200;</span>
206
+ <span class="simulado-timer-text" id="simulado-timer-text">${this.formatTime(this.timeRemaining)}</span>
207
+ </div>
208
+ <div class="simulado-timer-center">
209
+ <span>${answeredCount}/${totalCount} respondidas</span>
210
+ </div>
211
+ <div class="simulado-timer-right">
212
+ <button class="btn btn-sm btn-secondary" onclick="Simulado.toggleViewMode()">
213
+ ${this.viewMode === 'single' ? 'Ver todas' : 'Ver uma'}
214
+ </button>
215
+ <button class="btn btn-sm btn-primary" onclick="Simulado.confirmFinish()" id="simulado-finish-btn">
216
+ Finalizar
217
+ </button>
218
+ </div>
219
+ </div>
220
+ <div class="simulado-body">
221
+ <div class="simulado-nav" id="simulado-nav">
222
+ <div class="simulado-nav-title">Questoes</div>
223
+ <div class="simulado-nav-grid">
224
+ ${navButtons}
225
+ </div>
226
+ <div class="simulado-nav-legend">
227
+ <span class="legend-item"><span class="legend-dot answered"></span> Respondida</span>
228
+ <span class="legend-item"><span class="legend-dot current"></span> Atual</span>
229
+ <span class="legend-item"><span class="legend-dot"></span> Pendente</span>
230
+ </div>
231
+ </div>
232
+ <div class="simulado-content" id="simulado-content">
233
+ ${questionsHtml}
234
+ ${this.viewMode === 'single' ? this.renderNavArrows() : ''}
235
+ </div>
236
+ </div>
237
+ `;
238
+ },
239
+
240
+ renderSingleQuestion(index) {
241
+ const q = this.questions[index];
242
+ if (!q) return '';
243
+ return this.renderExamQuestion(q, index);
244
+ },
245
+
246
+ renderExamQuestion(q, index) {
247
+ const token = Auth.getToken();
248
+ let enunciadoHtml = q.enunciado || '';
249
+ enunciadoHtml = enunciadoHtml.replace(
250
+ /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi,
251
+ (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"`
252
+ );
253
+ enunciadoHtml = enunciadoHtml.replace(
254
+ /https?:\/\/r2\.seudominio\.com\/([^"'?\s]+)/gi,
255
+ (match, path) => `/api/images/${encodeURIComponent(path)}?token=${token}`
256
+ );
257
+
258
+ const selectedAnswer = this.answers[q.id] || null;
259
+
260
+ const alts = (q.alternativas || []).map(alt => {
261
+ let altTexto = alt.texto || '';
262
+ const hasHtml = /<img\s|<br|<p\s|<div\s|<span\s/i.test(altTexto);
263
+ if (hasHtml) {
264
+ altTexto = altTexto.replace(
265
+ /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi,
266
+ (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"`
267
+ );
268
+ altTexto = altTexto.replace(
269
+ /https?:\/\/r2\.seudominio\.com\/([^"'?\s]+)/gi,
270
+ (match, path) => `/api/images/${encodeURIComponent(path)}?token=${token}`
271
+ );
272
+ } else {
273
+ altTexto = this.escapeHtml(altTexto);
274
+ }
275
+
276
+ const selected = selectedAnswer === alt.letra ? 'selected' : '';
277
+ return `
278
+ <div class="alternativa ${selected}" data-qid="${q.id}" data-letra="${alt.letra}"
279
+ onclick="Simulado.selectAnswer(${q.id}, '${alt.letra}', this)">
280
+ <div class="alt-letter">${alt.letra}</div>
281
+ <div class="alt-text">${altTexto}</div>
282
+ </div>
283
+ `;
284
+ }).join('');
285
+
286
+ const yearBadge = q.year ? `<span style="font-size:12px;color:var(--text-sec);font-weight:400;"> (${this.escapeHtml(q.year)})</span>` : '';
287
+ const trackBadge = `<span class="simulado-track-badge">${this.escapeHtml(q.track)}</span>`;
288
+
289
+ return `
290
+ <div class="question-card simulado-question" id="sim-q-${q.id}" data-index="${index}">
291
+ <div class="question-header">
292
+ <div class="question-number">${index + 1}</div>
293
+ <h3>Questao ${index + 1} de ${this.questions.length}${yearBadge}</h3>
294
+ ${trackBadge}
295
+ </div>
296
+ <div class="enunciado">${enunciadoHtml}</div>
297
+ <div class="alternativas">
298
+ ${alts}
299
+ </div>
300
+ </div>
301
+ `;
302
+ },
303
+
304
+ renderNavArrows() {
305
+ const hasPrev = this.currentIndex > 0;
306
+ const hasNext = this.currentIndex < this.questions.length - 1;
307
+ return `
308
+ <div class="simulado-arrows">
309
+ <button class="btn btn-secondary" ${hasPrev ? '' : 'disabled'} onclick="Simulado.goToQuestion(${this.currentIndex - 1})">
310
+ &#8592; Anterior
311
+ </button>
312
+ <button class="btn btn-secondary" ${hasNext ? '' : 'disabled'} onclick="Simulado.goToQuestion(${this.currentIndex + 1})">
313
+ Proxima &#8594;
314
+ </button>
315
+ </div>
316
+ `;
317
+ },
318
+
319
+ selectAnswer(qid, letra, el) {
320
+ if (this.submitted) return;
321
+
322
+ this.answers[qid] = letra;
323
+
324
+ // Update UI
325
+ const container = el.closest('.alternativas');
326
+ container.querySelectorAll('.alternativa').forEach(a => a.classList.remove('selected'));
327
+ el.classList.add('selected');
328
+
329
+ // Update nav button
330
+ this.updateNavButton(qid);
331
+ this.updateProgress();
332
+ },
333
+
334
+ updateNavButton(qid) {
335
+ const idx = this.questions.findIndex(q => q.id === qid);
336
+ if (idx === -1) return;
337
+ const navBtns = document.querySelectorAll('.simulado-nav-btn');
338
+ if (navBtns[idx]) {
339
+ navBtns[idx].classList.add('answered');
340
+ }
341
+ },
342
+
343
+ updateProgress() {
344
+ const answeredCount = Object.keys(this.answers).length;
345
+ const totalCount = this.questions.length;
346
+ const center = document.querySelector('.simulado-timer-center span');
347
+ if (center) center.textContent = `${answeredCount}/${totalCount} respondidas`;
348
+ },
349
+
350
+ goToQuestion(index) {
351
+ if (index < 0 || index >= this.questions.length) return;
352
+ this.currentIndex = index;
353
+
354
+ if (this.viewMode === 'single') {
355
+ const content = document.getElementById('simulado-content');
356
+ if (content) {
357
+ content.innerHTML = this.renderSingleQuestion(index) + this.renderNavArrows();
358
+ }
359
+ // Update nav highlights
360
+ document.querySelectorAll('.simulado-nav-btn').forEach((btn, i) => {
361
+ btn.classList.toggle('current', i === index);
362
+ });
363
+ } else {
364
+ // Scroll to question
365
+ const el = document.querySelector(`.simulado-question[data-index="${index}"]`);
366
+ if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
367
+ document.querySelectorAll('.simulado-nav-btn').forEach((btn, i) => {
368
+ btn.classList.toggle('current', i === index);
369
+ });
370
+ }
371
+ },
372
+
373
+ toggleViewMode() {
374
+ this.viewMode = this.viewMode === 'single' ? 'all' : 'single';
375
+ // Re-render the exam page content
376
+ document.getElementById('app').innerHTML = this.renderExam();
377
+ },
378
+
379
+ // ===== TIMER =====
380
+ startTimer() {
381
+ this.stopTimer();
382
+ this.timerInterval = setInterval(() => {
383
+ this.timeRemaining--;
384
+ const timerText = document.getElementById('simulado-timer-text');
385
+ if (timerText) {
386
+ timerText.textContent = this.formatTime(this.timeRemaining);
387
+ }
388
+
389
+ // Warning colors
390
+ const timerBar = document.getElementById('simulado-timer');
391
+ if (timerBar) {
392
+ if (this.timeRemaining <= 60) {
393
+ timerBar.classList.add('danger');
394
+ timerBar.classList.remove('warning');
395
+ } else if (this.timeRemaining <= 300) {
396
+ timerBar.classList.add('warning');
397
+ timerBar.classList.remove('danger');
398
+ }
399
+ }
400
+
401
+ if (this.timeRemaining <= 0) {
402
+ this.stopTimer();
403
+ this.finishExam();
404
+ }
405
+ }, 1000);
406
+ },
407
+
408
+ stopTimer() {
409
+ if (this.timerInterval) {
410
+ clearInterval(this.timerInterval);
411
+ this.timerInterval = null;
412
+ }
413
+ },
414
+
415
+ formatTime(seconds) {
416
+ if (seconds < 0) seconds = 0;
417
+ const h = Math.floor(seconds / 3600);
418
+ const m = Math.floor((seconds % 3600) / 60);
419
+ const s = seconds % 60;
420
+ if (h > 0) {
421
+ return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
422
+ }
423
+ return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
424
+ },
425
+
426
+ // ===== FINISH =====
427
+ confirmFinish() {
428
+ const answered = Object.keys(this.answers).length;
429
+ const total = this.questions.length;
430
+ const unanswered = total - answered;
431
+
432
+ let msg = 'Deseja finalizar o simulado?';
433
+ if (unanswered > 0) {
434
+ msg = `Voce ainda tem ${unanswered} questao(oes) sem resposta. Deseja finalizar mesmo assim?`;
435
+ }
436
+
437
+ if (confirm(msg)) {
438
+ this.finishExam();
439
+ }
440
+ },
441
+
442
+ async finishExam() {
443
+ this.stopTimer();
444
+ this.submitted = true;
445
+
446
+ const app = document.getElementById('app');
447
+ app.innerHTML = '<div class="loading"><div class="spinner"></div>Calculando resultado...</div>';
448
+
449
+ try {
450
+ const result = await this.submitExam();
451
+ app.innerHTML = this.renderResults(result);
452
+ } catch (e) {
453
+ app.innerHTML = `<div class="container"><h2>Erro</h2><p>${this.escapeHtml(e.message)}</p></div>`;
454
+ }
455
+ },
456
+
457
+ // ===== RESULTS SCREEN =====
458
+ renderResults(result) {
459
+ const { score, total, percentage, time_spent_seconds, details } = result;
460
+
461
+ let colorClass = 'results-red';
462
+ if (percentage >= 70) colorClass = 'results-green';
463
+ else if (percentage >= 50) colorClass = 'results-yellow';
464
+
465
+ const timeStr = this.formatTime(time_spent_seconds);
466
+
467
+ // Separate wrong answers for review
468
+ const wrongAnswers = details.filter(d => !d.is_correct);
469
+
470
+ let wrongHtml = '';
471
+ if (wrongAnswers.length > 0) {
472
+ const wrongCards = wrongAnswers.map(d => {
473
+ const q = this.questions.find(q => q.id === d.question_id);
474
+ if (!q) return '';
475
+
476
+ const token = Auth.getToken();
477
+ let snippet = (q.enunciado || '').replace(/<[^>]+>/g, '');
478
+ snippet = snippet.length > 200 ? snippet.substring(0, 200) + '...' : snippet;
479
+
480
+ // Process explanation
481
+ let explanationHtml = '';
482
+ if (d.explanation && !d.explanation.includes('Carregando gabarito') && d.explanation.trim().length > 20) {
483
+ let expText = d.explanation;
484
+ expText = expText.replace(
485
+ /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi,
486
+ (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"`
487
+ );
488
+ expText = expText.replace(/color:\s*white/gi, 'color: #1a1a1a');
489
+ expText = expText.replace(/color:\s*#fff(fff)?/gi, 'color: #1a1a1a');
490
+ explanationHtml = `<div class="simulado-review-explanation">${expText}</div>`;
491
+ }
492
+
493
+ return `
494
+ <div class="simulado-review-card">
495
+ <div class="simulado-review-header">
496
+ <span class="simulado-review-track">${this.escapeHtml(q.track)}</span>
497
+ </div>
498
+ <p class="simulado-review-snippet">${this.escapeHtml(snippet)}</p>
499
+ <div class="simulado-review-answers">
500
+ <span class="review-wrong">Sua resposta: ${this.escapeHtml(d.selected)}</span>
501
+ <span class="review-correct">Correta: ${this.escapeHtml(d.correct)}</span>
502
+ </div>
503
+ ${explanationHtml}
504
+ </div>
505
+ `;
506
+ }).join('');
507
+
508
+ wrongHtml = `
509
+ <div class="simulado-review-section">
510
+ <h3>Revisao de erros (${wrongAnswers.length})</h3>
511
+ ${wrongCards}
512
+ </div>
513
+ `;
514
+ }
515
+
516
+ return `
517
+ <div class="container protected-content">
518
+ <div class="simulado-results">
519
+ <div class="simulado-results-header">
520
+ <h2>Resultado do Simulado</h2>
521
+ </div>
522
+ <div class="simulado-score-circle ${colorClass}">
523
+ <div class="score-percentage">${percentage}%</div>
524
+ <div class="score-fraction">${score}/${total}</div>
525
+ </div>
526
+ <div class="simulado-results-stats">
527
+ <div class="results-stat">
528
+ <div class="results-stat-value">${score}</div>
529
+ <div class="results-stat-label">Acertos</div>
530
+ </div>
531
+ <div class="results-stat">
532
+ <div class="results-stat-value">${total - score}</div>
533
+ <div class="results-stat-label">Erros</div>
534
+ </div>
535
+ <div class="results-stat">
536
+ <div class="results-stat-value">${timeStr}</div>
537
+ <div class="results-stat-label">Tempo</div>
538
+ </div>
539
+ </div>
540
+ <div class="simulado-results-actions">
541
+ <button class="btn btn-primary" onclick="App.navigate('/simulado')">Novo Simulado</button>
542
+ <button class="btn btn-secondary" onclick="App.navigate('/')">Voltar ao inicio</button>
543
+ </div>
544
+ ${wrongHtml}
545
+ </div>
546
+ </div>
547
+ `;
548
+ },
549
+
550
+ // ===== CLEANUP =====
551
+ cleanup() {
552
+ this.stopTimer();
553
+ },
554
+
555
+ escapeHtml(str) {
556
+ if (!str) return '';
557
+ const div = document.createElement('div');
558
+ div.textContent = str;
559
+ return div.innerHTML;
560
+ }
561
+ };