Greg Claude Opus 4.7 (1M context) commited on
Commit
8381024
·
1 Parent(s): bb8e44b

Quick wins de asistencia: auditoría, tardanzas, dashboard, portal representante y matrícula

Browse files

Check-in / asistencia:
- Check-in público: toggle Entrada/Salida MANUAL; detección de entrada tardía,
salida temprana y salida tardía (+1h) contra account.schedule + tolerancia.
- Vista docente: bloqueo de marcar antes del horario, aviso por falta de ingreso,
batch-toggle por fecha.

Cableado a EntranceLog (check-in real) — antes leían Attendance:
- Dashboard admin (KPIs, gráfica, actividad reciente).
- Reportes (historial) con filtro por rol + export CSV.
- Tardanzas: todos los roles + filtro por rol + export CSV.
- Fix: materias del docente en dashboard se cuentan vía TeacherSection (no el
legacy Section.subject_id); _teacher_section_ids ahora distinct.

Auditoría:
- Helper utils/audit.py (log_action/log_for) + wiring en login, reset de
contraseña, alta/edición/baja de usuario y matrícula/desmatrícula (con IP).

Portal Representante ("Mis Hijos"):
- Muestra ingreso al plantel (EntranceLog) + asistencia a clase (Attendance) +
alerta de discrepancia (entró al plantel pero no a clase).

Reporte de Estudiantes:
- Criterio dual (días en plantel vs días en clase + saltó clase + % clase),
nueva página StudentReportPage con filtros por nombre, sección y cédula.

Matrícula:
- Una sección por estudiante (rechazo en create/update/bulk).
- Vincular a representante existente al crear y al editar el estudiante (opcional).
- Selector de secciones sin la lista de materias (no se alarga).

Seed / deploy:
- seed_demo: account.schedule por defecto, check-ins de staff, EntranceLog con
tardanzas/salidas tempranas, AuditLogs de ejemplo.
- Dockerfile monolito (dlib-bin), entrypoint con MariaDB embebido opcional +
create_all, fly.toml, docker-compose monolito/embebido.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

Dockerfile CHANGED
@@ -27,6 +27,7 @@ ENV PYTHONUNBUFFERED=1
27
  RUN apt-get update && apt-get install -y --no-install-recommends \
28
  python3 python3-pip \
29
  libgl1 libglib2.0-0 \
 
30
  tzdata \
31
  && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone \
32
  && rm -rf /var/lib/apt/lists/*
 
27
  RUN apt-get update && apt-get install -y --no-install-recommends \
28
  python3 python3-pip \
29
  libgl1 libglib2.0-0 \
30
+ mariadb-server \
31
  tzdata \
32
  && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone \
33
  && rm -rf /var/lib/apt/lists/*
backend/app/api/v1/endpoints/attendances.py CHANGED
@@ -6,6 +6,7 @@ from typing import Optional
6
  from datetime import date, timedelta, datetime
7
  import csv
8
  import io
 
9
 
10
  from app.core.database import get_db
11
  from app.dependencies.auth import get_current_user
@@ -273,6 +274,7 @@ def today_checkins(
273
  card_id=student.card_id if student else None,
274
  user_name=student.name if student else "?",
275
  user_lastname=student.lastname if student else "",
 
276
  section_name=None,
277
  time_log=entry.checkin_time,
278
  checkout_time=entry.checkout_time,
@@ -321,6 +323,7 @@ def list_attendances(
321
  per_page: int = Query(20, ge=1, le=500),
322
  user_id: Optional[int] = None,
323
  section_id: Optional[int] = None,
 
324
  date_from: Optional[str] = None,
325
  date_to: Optional[str] = None,
326
  type: Optional[str] = None,
@@ -330,6 +333,11 @@ def list_attendances(
330
  query = db.query(EntranceLog).filter(EntranceLog.account_id == current_user.account_id)
331
  if user_id:
332
  query = query.filter(EntranceLog.user_id == user_id)
 
 
 
 
 
333
  if date_from:
334
  query = query.filter(EntranceLog.date >= date_from)
335
  if date_to:
@@ -339,7 +347,13 @@ def list_attendances(
339
  items = query.order_by(EntranceLog.checkin_time.desc()).offset((page - 1) * per_page).limit(per_page).all()
340
 
341
  def _enrich_el(el: EntranceLog, db: Session) -> AttendanceResponse:
342
- student = db.query(User).filter(User.id == el.user_id).first()
 
 
 
 
 
 
343
  return AttendanceResponse(
344
  id=el.id,
345
  user_id=el.user_id,
@@ -349,11 +363,13 @@ def list_attendances(
349
  checkout_time=el.checkout_time,
350
  note=el.note,
351
  action=None,
352
- user_name=student.name if student else None,
353
- user_lastname=student.lastname if student else None,
 
 
354
  section_name=None,
355
- is_late=el.note is not None and "RETRASO" in el.note,
356
- late_reason=None,
357
  late_authorized_by=None,
358
  )
359
 
@@ -364,6 +380,51 @@ def list_attendances(
364
  )
365
 
366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  @router.get("/heatmap/{student_id}", response_model=list[HeatmapEntry])
368
  def get_heatmap(
369
  student_id: int,
@@ -403,6 +464,23 @@ def current_mode(
403
  current_user: User = Depends(get_current_user),
404
  ):
405
  account = db.query(Account).filter(Account.id == current_user.account_id).first()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  schedule = account.schedule or {}
407
  for day in WEEKDAYS:
408
  if isinstance(schedule.get(day), dict):
@@ -413,7 +491,7 @@ def current_mode(
413
  today_schedule = schedule.get(today_name)
414
 
415
  if not today_schedule or not today_schedule.get("entry") or not today_schedule.get("exit"):
416
- return {"mode": "in", "schedule": None, "message": "No schedule configured for today"}
417
 
418
  now = datetime.now()
419
  now_minutes = now.hour * 60 + now.minute
@@ -421,26 +499,9 @@ def current_mode(
421
  entry_min = _time_to_minutes(today_schedule["entry"])
422
  exit_min = _time_to_minutes(today_schedule["exit"])
423
 
424
- transition = entry_min + (exit_min - entry_min) // 2
425
- mode = "in" if now_minutes < transition else "out"
426
-
427
  tolerance = account.tolerance or 15
428
  locked = now_minutes < entry_min or now_minutes >= (exit_min + tolerance)
429
 
430
- last_today = (
431
- db.query(EntranceLog)
432
- .filter(
433
- EntranceLog.user_id == current_user.id,
434
- EntranceLog.account_id == current_user.account_id,
435
- EntranceLog.date == date.today(),
436
- )
437
- .order_by(EntranceLog.checkin_time.desc())
438
- .first()
439
- )
440
- is_active = False
441
- if last_today:
442
- is_active = last_today.checkout_time is None
443
-
444
  return {
445
  "mode": mode,
446
  "schedule": today_schedule,
@@ -457,6 +518,10 @@ def _time_to_minutes(t: str) -> int:
457
  return int(parts[0]) * 60 + int(parts[1])
458
 
459
 
 
 
 
 
460
  def _detect_reason_type(
461
  now_minutes: int,
462
  today_schedule: Optional[dict],
@@ -469,14 +534,15 @@ def _detect_reason_type(
469
  entry_min = _time_to_minutes(today_schedule["entry"])
470
  exit_min = _time_to_minutes(today_schedule["exit"])
471
  if is_checkout:
 
 
472
  if now_minutes < exit_min:
473
  return "early_checkout"
474
- elif now_minutes > exit_min + tolerance:
475
  return "late_checkout"
476
  else:
477
- midpoint = entry_min + (exit_min - entry_min) // 2
478
- if now_minutes >= midpoint:
479
- return "past_exit"
480
  if now_minutes > entry_min + tolerance:
481
  return "late_entry"
482
  return None
@@ -525,27 +591,32 @@ def self_checkin(
525
  .order_by(EntranceLog.checkin_time.desc())
526
  .first()
527
  )
528
- is_active = False
529
- if last_today:
530
- is_active = last_today.checkout_time is None
531
-
532
- if last_today and last_today.checkout_time is not None:
533
- return {"success": False, "message": "Ya estás fuera del plantel"}
534
 
535
  tolerance = account.tolerance or 15
536
 
537
- if is_active:
 
 
 
 
 
 
 
 
 
538
  if not late_note:
539
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=True)
540
  if reason_type:
541
- return {"success": False, "needs_reason": True, "reason_type": reason_type, "card_id": card_id}
542
  note = f"Check-out by {current_user.name} {current_user.lastname}"
543
  if late_note:
544
  if today_schedule and today_schedule.get("exit"):
545
  exit_min = _time_to_minutes(today_schedule["exit"])
546
  if now_minutes < exit_min:
547
  note = f"SALIDA TEMPRANA: {late_note} / {note}"
548
- elif now_minutes >= (exit_min + tolerance):
549
  note = f"RETRASO SALIDA: {late_note} / {note}"
550
  else:
551
  note = f"{note} - {late_note}"
@@ -565,12 +636,15 @@ def self_checkin(
565
  "entry_time": last_today.checkin_time.isoformat() if last_today and last_today.checkin_time else None,
566
  }
567
 
 
 
 
 
 
568
  if not late_note:
569
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=False)
570
  if reason_type:
571
- if reason_type == "past_exit":
572
- return {"success": False, "message": "El horario de entrada ya finalizó"}
573
- return {"success": False, "needs_reason": True, "reason_type": reason_type, "card_id": card_id}
574
  note = f"Check-in by {current_user.name} {current_user.lastname}"
575
  if late_note:
576
  note = f"RETRASO: {late_note} / {note}"
 
6
  from datetime import date, timedelta, datetime
7
  import csv
8
  import io
9
+ import re
10
 
11
  from app.core.database import get_db
12
  from app.dependencies.auth import get_current_user
 
274
  card_id=student.card_id if student else None,
275
  user_name=student.name if student else "?",
276
  user_lastname=student.lastname if student else "",
277
+ role=student.role if student else None,
278
  section_name=None,
279
  time_log=entry.checkin_time,
280
  checkout_time=entry.checkout_time,
 
323
  per_page: int = Query(20, ge=1, le=500),
324
  user_id: Optional[int] = None,
325
  section_id: Optional[int] = None,
326
+ role: Optional[str] = None,
327
  date_from: Optional[str] = None,
328
  date_to: Optional[str] = None,
329
  type: Optional[str] = None,
 
333
  query = db.query(EntranceLog).filter(EntranceLog.account_id == current_user.account_id)
334
  if user_id:
335
  query = query.filter(EntranceLog.user_id == user_id)
336
+ if role:
337
+ role_user_ids = db.query(User.id).filter(
338
+ User.account_id == current_user.account_id, User.role == role,
339
+ ).subquery()
340
+ query = query.filter(EntranceLog.user_id.in_(role_user_ids))
341
  if date_from:
342
  query = query.filter(EntranceLog.date >= date_from)
343
  if date_to:
 
347
  items = query.order_by(EntranceLog.checkin_time.desc()).offset((page - 1) * per_page).limit(per_page).all()
348
 
349
  def _enrich_el(el: EntranceLog, db: Session) -> AttendanceResponse:
350
+ u = db.query(User).filter(User.id == el.user_id).first()
351
+ note = el.note or ""
352
+ is_late = ("RETRASO" in note) or ("SALIDA TEMPRANA" in note)
353
+ late_reason = None
354
+ m = re.search(r'(RETRASO SALIDA|RETRASO|SALIDA TEMPRANA):\s*([^|/]+)', note)
355
+ if m:
356
+ late_reason = f"{m.group(1).title()}: {m.group(2).strip()}"
357
  return AttendanceResponse(
358
  id=el.id,
359
  user_id=el.user_id,
 
363
  checkout_time=el.checkout_time,
364
  note=el.note,
365
  action=None,
366
+ user_name=u.name if u else None,
367
+ user_lastname=u.lastname if u else None,
368
+ role=u.role if u else None,
369
+ card_id=u.card_id if u else None,
370
  section_name=None,
371
+ is_late=is_late,
372
+ late_reason=late_reason,
373
  late_authorized_by=None,
374
  )
375
 
 
380
  )
381
 
382
 
383
+ _ROLE_LABELS = {
384
+ "student": "Estudiante", "teacher": "Docente", "administrativo": "Administrativo",
385
+ "obrero": "Obrero", "representative": "Representante", "admin": "Administrador",
386
+ }
387
+
388
+
389
+ @router.get("/report-export")
390
+ def report_export(
391
+ user_id: Optional[int] = None,
392
+ role: Optional[str] = None,
393
+ date_from: Optional[str] = None,
394
+ date_to: Optional[str] = None,
395
+ current_user: User = Depends(RBAC(["admin"])),
396
+ db: Session = Depends(get_db),
397
+ ):
398
+ q = db.query(EntranceLog, User).join(User, EntranceLog.user_id == User.id).filter(
399
+ EntranceLog.account_id == current_user.account_id,
400
+ )
401
+ if user_id:
402
+ q = q.filter(EntranceLog.user_id == user_id)
403
+ if role:
404
+ q = q.filter(User.role == role)
405
+ if date_from:
406
+ q = q.filter(EntranceLog.date >= date_from)
407
+ if date_to:
408
+ q = q.filter(EntranceLog.date <= date_to)
409
+ rows = q.order_by(EntranceLog.checkin_time.desc()).all()
410
+
411
+ buf = io.StringIO()
412
+ w = csv.writer(buf)
413
+ w.writerow(["Usuario", "Rol", "Cédula", "Fecha", "Entrada", "Salida", "Nota"])
414
+ for el, u in rows:
415
+ w.writerow([
416
+ f"{u.lastname}, {u.name}", _ROLE_LABELS.get(u.role, u.role),
417
+ u.card_id or "", el.date.isoformat() if el.date else "",
418
+ el.checkin_time.strftime("%H:%M") if el.checkin_time else "",
419
+ el.checkout_time.strftime("%H:%M") if el.checkout_time else "",
420
+ el.note or "",
421
+ ])
422
+ buf.seek(0)
423
+ fname = f"reporte_asistencia_{date_from or 'inicio'}_{date_to or 'hoy'}.csv"
424
+ return StreamingResponse(iter([buf.getvalue()]), media_type="text/csv",
425
+ headers={"Content-Disposition": f"attachment; filename={fname}"})
426
+
427
+
428
  @router.get("/heatmap/{student_id}", response_model=list[HeatmapEntry])
429
  def get_heatmap(
430
  student_id: int,
 
464
  current_user: User = Depends(get_current_user),
465
  ):
466
  account = db.query(Account).filter(Account.id == current_user.account_id).first()
467
+
468
+ # Estado real del usuario hoy: si tiene una entrada sin salida, está dentro del plantel.
469
+ last_today = (
470
+ db.query(EntranceLog)
471
+ .filter(
472
+ EntranceLog.user_id == current_user.id,
473
+ EntranceLog.account_id == current_user.account_id,
474
+ EntranceLog.date == date.today(),
475
+ )
476
+ .order_by(EntranceLog.checkin_time.desc())
477
+ .first()
478
+ )
479
+ is_active = bool(last_today and last_today.checkout_time is None)
480
+ # El modo refleja la ACCIÓN real (igual que self_checkin): dentro -> salida; fuera -> entrada.
481
+ # Así la vista nunca sugiere algo distinto de lo que ocurrirá al marcar.
482
+ mode = "out" if is_active else "in"
483
+
484
  schedule = account.schedule or {}
485
  for day in WEEKDAYS:
486
  if isinstance(schedule.get(day), dict):
 
491
  today_schedule = schedule.get(today_name)
492
 
493
  if not today_schedule or not today_schedule.get("entry") or not today_schedule.get("exit"):
494
+ return {"mode": mode, "schedule": None, "active": is_active, "message": "No schedule configured for today"}
495
 
496
  now = datetime.now()
497
  now_minutes = now.hour * 60 + now.minute
 
499
  entry_min = _time_to_minutes(today_schedule["entry"])
500
  exit_min = _time_to_minutes(today_schedule["exit"])
501
 
 
 
 
502
  tolerance = account.tolerance or 15
503
  locked = now_minutes < entry_min or now_minutes >= (exit_min + tolerance)
504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  return {
506
  "mode": mode,
507
  "schedule": today_schedule,
 
518
  return int(parts[0]) * 60 + int(parts[1])
519
 
520
 
521
+ # Salida se considera "tardía" si ocurre más de 1 hora después de la hora de fin de jornada.
522
+ LATE_CHECKOUT_GRACE_MIN = 60
523
+
524
+
525
  def _detect_reason_type(
526
  now_minutes: int,
527
  today_schedule: Optional[dict],
 
534
  entry_min = _time_to_minutes(today_schedule["entry"])
535
  exit_min = _time_to_minutes(today_schedule["exit"])
536
  if is_checkout:
537
+ # Salida temprana: antes de la hora de salida.
538
+ # Salida tardía: más de 1 hora después de la hora de salida.
539
  if now_minutes < exit_min:
540
  return "early_checkout"
541
+ elif now_minutes > exit_min + LATE_CHECKOUT_GRACE_MIN:
542
  return "late_checkout"
543
  else:
544
+ # Entrada tardía: después de la hora de entrada + tolerancia.
545
+ # No se bloquea la entrada tardía (se justifica).
 
546
  if now_minutes > entry_min + tolerance:
547
  return "late_entry"
548
  return None
 
591
  .order_by(EntranceLog.checkin_time.desc())
592
  .first()
593
  )
594
+ is_active = bool(last_today and last_today.checkout_time is None)
595
+ completed = bool(last_today and last_today.checkout_time is not None)
 
 
 
 
596
 
597
  tolerance = account.tolerance or 15
598
 
599
+ # El toggle Entrada/Salida es MANUAL: la acción la elige el usuario y aquí se
600
+ # respeta. Si no llega, se infiere por estado. Las justificaciones (tardía /
601
+ # temprana) se siguen detectando según la acción elegida.
602
+ action = payload.get("action")
603
+ if action not in ("in", "out"):
604
+ action = "out" if is_active else "in"
605
+
606
+ if action == "out":
607
+ if not is_active:
608
+ return {"success": False, "message": "No hay una entrada registrada hoy para marcar salida"}
609
  if not late_note:
610
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=True)
611
  if reason_type:
612
+ return {"success": False, "needs_reason": True, "reason_type": reason_type, "card_id": card_id, "action": "out"}
613
  note = f"Check-out by {current_user.name} {current_user.lastname}"
614
  if late_note:
615
  if today_schedule and today_schedule.get("exit"):
616
  exit_min = _time_to_minutes(today_schedule["exit"])
617
  if now_minutes < exit_min:
618
  note = f"SALIDA TEMPRANA: {late_note} / {note}"
619
+ elif now_minutes > (exit_min + LATE_CHECKOUT_GRACE_MIN):
620
  note = f"RETRASO SALIDA: {late_note} / {note}"
621
  else:
622
  note = f"{note} - {late_note}"
 
636
  "entry_time": last_today.checkin_time.isoformat() if last_today and last_today.checkin_time else None,
637
  }
638
 
639
+ # action == "in"
640
+ if is_active:
641
+ return {"success": False, "message": "Ya tienes una entrada registrada hoy (sin salida)"}
642
+ if completed:
643
+ return {"success": False, "message": "Ya registraste entrada y salida hoy"}
644
  if not late_note:
645
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=False)
646
  if reason_type:
647
+ return {"success": False, "needs_reason": True, "reason_type": reason_type, "card_id": card_id, "action": "in"}
 
 
648
  note = f"Check-in by {current_user.name} {current_user.lastname}"
649
  if late_note:
650
  note = f"RETRASO: {late_note} / {note}"
backend/app/api/v1/endpoints/auth.py CHANGED
@@ -1,11 +1,12 @@
1
  import secrets
2
  from datetime import datetime, timedelta, timezone
3
 
4
- from fastapi import APIRouter, Depends, HTTPException, status
5
  from sqlalchemy.orm import Session
6
 
7
  from app.core.database import get_db
8
  from app.core.security import hash_password, verify_password, create_access_token
 
9
  from app.dependencies.auth import get_current_user
10
  from app.schemas.auth import (
11
  LoginRequest, TokenResponse, CurrentUserResponse,
@@ -20,7 +21,7 @@ router = APIRouter(prefix="/auth", tags=["auth"])
20
 
21
 
22
  @router.post("/login", response_model=TokenResponse)
23
- def login(payload: LoginRequest, db: Session = Depends(get_db)):
24
  user = db.query(User).filter(User.email == payload.email, User.is_active == "1").first()
25
  if not user or not user.password_hash or not verify_password(payload.password, user.password_hash):
26
  raise HTTPException(
@@ -35,6 +36,7 @@ def login(payload: LoginRequest, db: Session = Depends(get_db)):
35
  }
36
  )
37
  must_change = user.must_change_password == "1"
 
38
  return TokenResponse(access_token=token, must_change_password=must_change)
39
 
40
 
@@ -62,6 +64,7 @@ def me(current_user: User = Depends(get_current_user), db: Session = Depends(get
62
  @router.post("/admin-reset-password/{user_id}", response_model=AdminResetPasswordResponse)
63
  def admin_reset_password(
64
  user_id: int,
 
65
  current_user: User = Depends(get_current_user),
66
  db: Session = Depends(get_db),
67
  ):
@@ -78,6 +81,9 @@ def admin_reset_password(
78
  user.must_change_password = "1"
79
  db.commit()
80
 
 
 
 
81
  return AdminResetPasswordResponse(
82
  reset_token=reset_token,
83
  message="Password reset token generated. Share this token with the user. It expires in 24 hours.",
 
1
  import secrets
2
  from datetime import datetime, timedelta, timezone
3
 
4
+ from fastapi import APIRouter, Depends, HTTPException, status, Request
5
  from sqlalchemy.orm import Session
6
 
7
  from app.core.database import get_db
8
  from app.core.security import hash_password, verify_password, create_access_token
9
+ from app.utils.audit import log_for
10
  from app.dependencies.auth import get_current_user
11
  from app.schemas.auth import (
12
  LoginRequest, TokenResponse, CurrentUserResponse,
 
21
 
22
 
23
  @router.post("/login", response_model=TokenResponse)
24
+ def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)):
25
  user = db.query(User).filter(User.email == payload.email, User.is_active == "1").first()
26
  if not user or not user.password_hash or not verify_password(payload.password, user.password_hash):
27
  raise HTTPException(
 
36
  }
37
  )
38
  must_change = user.must_change_password == "1"
39
+ log_for(db, user, "Inicio de sesión", "auth", request=request)
40
  return TokenResponse(access_token=token, must_change_password=must_change)
41
 
42
 
 
64
  @router.post("/admin-reset-password/{user_id}", response_model=AdminResetPasswordResponse)
65
  def admin_reset_password(
66
  user_id: int,
67
+ request: Request,
68
  current_user: User = Depends(get_current_user),
69
  db: Session = Depends(get_db),
70
  ):
 
81
  user.must_change_password = "1"
82
  db.commit()
83
 
84
+ log_for(db, current_user, "Reset de contraseña", "usuarios",
85
+ details={"target_user_id": user_id, "target": f"{user.name} {user.lastname}"}, request=request)
86
+
87
  return AdminResetPasswordResponse(
88
  reset_token=reset_token,
89
  message="Password reset token generated. Share this token with the user. It expires in 24 hours.",
backend/app/api/v1/endpoints/dashboard.py CHANGED
@@ -8,6 +8,7 @@ from app.core.database import get_db
8
  from app.dependencies.auth import get_current_user
9
  from app.models.user import User
10
  from app.models.attendance import Attendance
 
11
  from app.models.section import Section
12
  from app.models.subject import Subject
13
  from app.models.teacher_section import TeacherSection
@@ -23,7 +24,7 @@ def _teacher_section_ids(current_user: User, db: Session):
23
  rows = db.query(TeacherSection.section_id).filter(
24
  TeacherSection.teacher_id == current_user.id,
25
  TeacherSection.account_id == current_user.account_id,
26
- ).all()
27
  return [r.section_id for r in rows]
28
 
29
 
@@ -43,8 +44,11 @@ def dashboard_stats(
43
 
44
  total_sections = len(sec_ids)
45
 
46
- total_subjects = db.query(func.count(func.distinct(Section.subject_id))).filter(
47
- Section.id.in_(sec_ids),
 
 
 
48
  ).scalar() or 0
49
 
50
  today = date.today()
@@ -110,32 +114,23 @@ def dashboard_stats(
110
  Subject.account_id == account_id,
111
  ).scalar() or 0
112
 
 
113
  today = date.today()
114
- today_checkins = db.query(func.count(func.distinct(Attendance.user_id))).filter(
115
- Attendance.account_id == account_id,
116
- cast(Attendance.time_log, Date) == today,
117
  ).scalar() or 0
118
 
119
- users_out_today = db.query(func.distinct(Attendance.user_id)).filter(
120
- Attendance.account_id == account_id,
121
- cast(Attendance.time_log, Date) == today,
122
- Attendance.action == "out",
123
- ).subquery()
124
-
125
- currently_on_campus = db.query(func.count(func.distinct(Attendance.user_id))).filter(
126
- Attendance.account_id == account_id,
127
- cast(Attendance.time_log, Date) == today,
128
- Attendance.checkout_time.is_(None),
129
- ~Attendance.user_id.in_(users_out_today),
130
  ).scalar() or 0
131
 
132
- today_checkouts = db.query(func.count(func.distinct(Attendance.user_id))).filter(
133
- Attendance.account_id == account_id,
134
- cast(Attendance.time_log, Date) == today,
135
- or_(
136
- Attendance.checkout_time.isnot(None),
137
- Attendance.action == "out",
138
- ),
139
  ).scalar() or 0
140
 
141
  return {
@@ -160,26 +155,40 @@ def attendance_trend(
160
  today_ref = date.today()
161
  start_date = today_ref - timedelta(days=days - 1)
162
 
163
- filters = [
164
- Attendance.account_id == account_id,
165
- cast(Attendance.time_log, Date) >= start_date,
166
- cast(Attendance.time_log, Date) <= today_ref,
167
- ]
168
  if sec_ids is not None:
169
- filters.append(Attendance.section_id.in_(sec_ids))
170
-
171
- rows = (
172
- db.query(
173
- cast(Attendance.time_log, Date).label("log_date"),
174
- func.count(func.distinct(Attendance.user_id)).label("unique_students"),
 
 
 
 
 
 
 
 
175
  )
176
- .filter(*filters)
177
- .group_by(cast(Attendance.time_log, Date))
178
- .order_by(cast(Attendance.time_log, Date))
179
- .all()
180
- )
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
- trend_map = {row.log_date: row.unique_students for row in rows}
183
  result = []
184
  for i in range(days):
185
  d = start_date + timedelta(days=i)
@@ -200,13 +209,41 @@ def latest_activity(
200
  account_id = current_user.account_id
201
  sec_ids = _teacher_section_ids(current_user, db)
202
 
203
- filters = [
204
- Attendance.account_id == account_id,
205
- User.role != "admin",
206
- ]
207
- if sec_ids is not None:
208
- filters.append(Attendance.section_id.in_(sec_ids))
209
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  in_records = (
211
  db.query(
212
  Attendance.id,
@@ -219,7 +256,12 @@ def latest_activity(
219
  User.card_id,
220
  )
221
  .join(User, Attendance.user_id == User.id)
222
- .filter(*filters, or_(Attendance.action == "in", Attendance.action.is_(None)))
 
 
 
 
 
223
  .order_by(Attendance.time_log.desc())
224
  .limit(limit)
225
  .all()
 
8
  from app.dependencies.auth import get_current_user
9
  from app.models.user import User
10
  from app.models.attendance import Attendance
11
+ from app.models.entrance_log import EntranceLog
12
  from app.models.section import Section
13
  from app.models.subject import Subject
14
  from app.models.teacher_section import TeacherSection
 
24
  rows = db.query(TeacherSection.section_id).filter(
25
  TeacherSection.teacher_id == current_user.id,
26
  TeacherSection.account_id == current_user.account_id,
27
+ ).distinct().all()
28
  return [r.section_id for r in rows]
29
 
30
 
 
44
 
45
  total_sections = len(sec_ids)
46
 
47
+ # Materias del docente = materias que tiene asignadas vía TeacherSection
48
+ # (Section.subject_id es legacy y queda NULL con el modelo SectionSubject).
49
+ total_subjects = db.query(func.count(func.distinct(TeacherSection.subject_id))).filter(
50
+ TeacherSection.teacher_id == current_user.id,
51
+ TeacherSection.account_id == account_id,
52
  ).scalar() or 0
53
 
54
  today = date.today()
 
114
  Subject.account_id == account_id,
115
  ).scalar() or 0
116
 
117
+ # Check-in/out real proviene de EntranceLog (kiosko / facial), no de Attendance.
118
  today = date.today()
119
+ today_checkins = db.query(func.count(func.distinct(EntranceLog.user_id))).filter(
120
+ EntranceLog.account_id == account_id,
121
+ EntranceLog.date == today,
122
  ).scalar() or 0
123
 
124
+ currently_on_campus = db.query(func.count(EntranceLog.id)).filter(
125
+ EntranceLog.account_id == account_id,
126
+ EntranceLog.date == today,
127
+ EntranceLog.checkout_time.is_(None),
 
 
 
 
 
 
 
128
  ).scalar() or 0
129
 
130
+ today_checkouts = db.query(func.count(EntranceLog.id)).filter(
131
+ EntranceLog.account_id == account_id,
132
+ EntranceLog.date == today,
133
+ EntranceLog.checkout_time.isnot(None),
 
 
 
134
  ).scalar() or 0
135
 
136
  return {
 
155
  today_ref = date.today()
156
  start_date = today_ref - timedelta(days=days - 1)
157
 
 
 
 
 
 
158
  if sec_ids is not None:
159
+ # Docente: asistencia de clase por sección (Attendance)
160
+ rows = (
161
+ db.query(
162
+ cast(Attendance.time_log, Date).label("log_date"),
163
+ func.count(func.distinct(Attendance.user_id)).label("cnt"),
164
+ )
165
+ .filter(
166
+ Attendance.account_id == account_id,
167
+ Attendance.section_id.in_(sec_ids),
168
+ cast(Attendance.time_log, Date) >= start_date,
169
+ cast(Attendance.time_log, Date) <= today_ref,
170
+ )
171
+ .group_by(cast(Attendance.time_log, Date))
172
+ .all()
173
  )
174
+ trend_map = {row.log_date: row.cnt for row in rows}
175
+ else:
176
+ # Admin: check-ins reales (EntranceLog) por día
177
+ rows = (
178
+ db.query(
179
+ EntranceLog.date.label("log_date"),
180
+ func.count(func.distinct(EntranceLog.user_id)).label("cnt"),
181
+ )
182
+ .filter(
183
+ EntranceLog.account_id == account_id,
184
+ EntranceLog.date >= start_date,
185
+ EntranceLog.date <= today_ref,
186
+ )
187
+ .group_by(EntranceLog.date)
188
+ .all()
189
+ )
190
+ trend_map = {row.log_date: row.cnt for row in rows}
191
 
 
192
  result = []
193
  for i in range(days):
194
  d = start_date + timedelta(days=i)
 
209
  account_id = current_user.account_id
210
  sec_ids = _teacher_section_ids(current_user, db)
211
 
212
+ # Admin: actividad real de check-in/out (EntranceLog). Cada registro ya tiene
213
+ # entrada (checkin_time) y salida (checkout_time).
214
+ if sec_ids is None:
215
+ rows = (
216
+ db.query(EntranceLog, User)
217
+ .join(User, EntranceLog.user_id == User.id)
218
+ .filter(
219
+ EntranceLog.account_id == account_id,
220
+ User.role != "admin",
221
+ )
222
+ .order_by(EntranceLog.checkin_time.desc())
223
+ .limit(limit)
224
+ .all()
225
+ )
226
+ results = []
227
+ for el, u in rows:
228
+ entry_time = el.checkin_time
229
+ exit_time = el.checkout_time
230
+ duration_minutes = None
231
+ if entry_time and exit_time:
232
+ duration_minutes = int((exit_time - entry_time).total_seconds() / 60)
233
+ results.append({
234
+ "id": el.id,
235
+ "user_id": el.user_id,
236
+ "name": u.name,
237
+ "lastname": u.lastname,
238
+ "card_id": u.card_id,
239
+ "entry_time": entry_time.isoformat() if entry_time else None,
240
+ "exit_time": exit_time.isoformat() if exit_time else None,
241
+ "duration_minutes": duration_minutes,
242
+ "note": el.note,
243
+ })
244
+ return results
245
+
246
+ # Docente: actividad de clase de sus secciones (Attendance)
247
  in_records = (
248
  db.query(
249
  Attendance.id,
 
256
  User.card_id,
257
  )
258
  .join(User, Attendance.user_id == User.id)
259
+ .filter(
260
+ Attendance.account_id == account_id,
261
+ User.role != "admin",
262
+ Attendance.section_id.in_(sec_ids),
263
+ or_(Attendance.action == "in", Attendance.action.is_(None)),
264
+ )
265
  .order_by(Attendance.time_log.desc())
266
  .limit(limit)
267
  .all()
backend/app/api/v1/endpoints/enrollments.py CHANGED
@@ -1,7 +1,9 @@
1
- from fastapi import APIRouter, Depends, HTTPException, status, Query
2
  from sqlalchemy.orm import Session
3
  from typing import Optional
4
 
 
 
5
  from fastapi import UploadFile, File
6
  from fastapi.responses import StreamingResponse
7
  from app.core.database import get_db
@@ -67,7 +69,7 @@ def _section_at_capacity(section_id: int, account_id: int, db: Session) -> bool:
67
 
68
 
69
  @router.post("", response_model=EnrollmentResponse, status_code=status.HTTP_201_CREATED)
70
- def create_enrollment(payload: EnrollmentCreate, current_user: User = Depends(RBAC(["admin"])), db: Session = Depends(get_db)):
71
  sec = db.query(Section).filter(Section.id == payload.section_id, Section.account_id == current_user.account_id).first()
72
  if not sec:
73
  raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Section not found")
@@ -92,6 +94,8 @@ def create_enrollment(payload: EnrollmentCreate, current_user: User = Depends(RB
92
  )
93
  obj = Enrollment(account_id=current_user.account_id, **payload.model_dump())
94
  db.add(obj); db.commit(); db.refresh(obj)
 
 
95
  return EnrollmentResponse.model_validate(obj)
96
 
97
 
@@ -136,11 +140,15 @@ def update_enrollment(enrollment_id: int, payload: EnrollmentUpdate, current_use
136
 
137
 
138
  @router.delete("/{enrollment_id}", status_code=status.HTTP_204_NO_CONTENT)
139
- def remove_enrollment(enrollment_id: int, current_user: User = Depends(RBAC(["admin"])), db: Session = Depends(get_db)):
140
  obj = db.query(Enrollment).filter(Enrollment.id == enrollment_id, Enrollment.account_id == current_user.account_id).first()
141
  if not obj:
142
  raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Enrollment not found")
 
 
143
  db.delete(obj); db.commit()
 
 
144
 
145
 
146
  ENROLLMENT_TEMPLATE_HEADERS = ["email_estudiante", "nombre_sección"]
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status, Query, Request
2
  from sqlalchemy.orm import Session
3
  from typing import Optional
4
 
5
+ from app.utils.audit import log_for
6
+
7
  from fastapi import UploadFile, File
8
  from fastapi.responses import StreamingResponse
9
  from app.core.database import get_db
 
69
 
70
 
71
  @router.post("", response_model=EnrollmentResponse, status_code=status.HTTP_201_CREATED)
72
+ def create_enrollment(payload: EnrollmentCreate, request: Request, current_user: User = Depends(RBAC(["admin"])), db: Session = Depends(get_db)):
73
  sec = db.query(Section).filter(Section.id == payload.section_id, Section.account_id == current_user.account_id).first()
74
  if not sec:
75
  raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Section not found")
 
94
  )
95
  obj = Enrollment(account_id=current_user.account_id, **payload.model_dump())
96
  db.add(obj); db.commit(); db.refresh(obj)
97
+ log_for(db, current_user, "Matricular", "matrículas",
98
+ details={"student_id": payload.student_id, "section": sec.name}, request=request)
99
  return EnrollmentResponse.model_validate(obj)
100
 
101
 
 
140
 
141
 
142
  @router.delete("/{enrollment_id}", status_code=status.HTTP_204_NO_CONTENT)
143
+ def remove_enrollment(enrollment_id: int, request: Request, current_user: User = Depends(RBAC(["admin"])), db: Session = Depends(get_db)):
144
  obj = db.query(Enrollment).filter(Enrollment.id == enrollment_id, Enrollment.account_id == current_user.account_id).first()
145
  if not obj:
146
  raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Enrollment not found")
147
+ student_id = obj.student_id
148
+ section_id = obj.section_id
149
  db.delete(obj); db.commit()
150
+ log_for(db, current_user, "Desmatricular", "matrículas",
151
+ details={"student_id": student_id, "section_id": section_id}, request=request)
152
 
153
 
154
  ENROLLMENT_TEMPLATE_HEADERS = ["email_estudiante", "nombre_sección"]
backend/app/api/v1/endpoints/facial.py CHANGED
@@ -20,7 +20,7 @@ from app.schemas.facial import (
20
  FacialRecognizeResponse,
21
  )
22
  from app.face_utils import decode_base64_image, detect_face, encode_face, compare_encodings
23
- from app.api.v1.endpoints.attendances import _detect_reason_type, _time_to_minutes
24
 
25
  router = APIRouter(prefix="/facial", tags=["facial"])
26
 
@@ -301,8 +301,8 @@ def facial_self(
301
  .order_by(EntranceLog.checkin_time.desc())
302
  .first()
303
  )
304
- if last_today and last_today.checkout_time is not None:
305
- return {"success": False, "message": "Ya estás fuera del plantel"}
306
 
307
  account = db.query(Account).filter(Account.id == current_user.account_id).first()
308
  schedule = account.schedule or {} if account else {}
@@ -315,18 +315,25 @@ def facial_self(
315
  today_schedule = schedule.get(today_name) if schedule else None
316
  tolerance = account.tolerance or 15 if account else 15
317
 
318
- if active:
 
 
 
 
 
 
 
319
  if not payload.late_note:
320
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=True)
321
  if reason_type:
322
- return {"success": False, "needs_reason": True, "reason_type": reason_type}
323
  checkout_note = f"Facial check-out (confidence: {1.0 - best_dist:.2%}) | by {current_user.name} {current_user.lastname}"
324
  if payload.late_note:
325
  if today_schedule and today_schedule.get("exit"):
326
  exit_min = _time_to_minutes(today_schedule["exit"])
327
  if now_minutes < exit_min:
328
  checkout_note = f"SALIDA TEMPRANA: {payload.late_note} | {checkout_note}"
329
- elif now_minutes >= (exit_min + tolerance):
330
  checkout_note = f"RETRASO SALIDA: {payload.late_note} | {checkout_note}"
331
  else:
332
  checkout_note = f"{checkout_note} - {payload.late_note}"
@@ -347,12 +354,15 @@ def facial_self(
347
  "message": f"Hasta luego, {student.name} {student.lastname}",
348
  }
349
 
 
 
 
 
 
350
  if not payload.late_note:
351
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=False)
352
  if reason_type:
353
- if reason_type == "past_exit":
354
- return {"success": False, "message": "El horario de entrada ya finalizó"}
355
- return {"success": False, "needs_reason": True, "reason_type": reason_type}
356
  note = f"Facial check-in (confidence: {1.0 - best_dist:.2%}) | by {current_user.name} {current_user.lastname}"
357
  if payload.late_note:
358
  note = f"RETRASO: {payload.late_note} | {note}"
 
20
  FacialRecognizeResponse,
21
  )
22
  from app.face_utils import decode_base64_image, detect_face, encode_face, compare_encodings
23
+ from app.api.v1.endpoints.attendances import _detect_reason_type, _time_to_minutes, LATE_CHECKOUT_GRACE_MIN
24
 
25
  router = APIRouter(prefix="/facial", tags=["facial"])
26
 
 
301
  .order_by(EntranceLog.checkin_time.desc())
302
  .first()
303
  )
304
+ completed = bool(last_today and last_today.checkout_time is not None)
305
+ is_active = active is not None
306
 
307
  account = db.query(Account).filter(Account.id == current_user.account_id).first()
308
  schedule = account.schedule or {} if account else {}
 
315
  today_schedule = schedule.get(today_name) if schedule else None
316
  tolerance = account.tolerance or 15 if account else 15
317
 
318
+ # Toggle Entrada/Salida MANUAL: se respeta la acción elegida; si no llega, se infiere por estado.
319
+ action = payload.action
320
+ if action not in ("in", "out"):
321
+ action = "out" if is_active else "in"
322
+
323
+ if action == "out":
324
+ if not is_active:
325
+ return {"success": False, "message": "No hay una entrada registrada hoy para marcar salida"}
326
  if not payload.late_note:
327
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=True)
328
  if reason_type:
329
+ return {"success": False, "needs_reason": True, "reason_type": reason_type, "action": "out"}
330
  checkout_note = f"Facial check-out (confidence: {1.0 - best_dist:.2%}) | by {current_user.name} {current_user.lastname}"
331
  if payload.late_note:
332
  if today_schedule and today_schedule.get("exit"):
333
  exit_min = _time_to_minutes(today_schedule["exit"])
334
  if now_minutes < exit_min:
335
  checkout_note = f"SALIDA TEMPRANA: {payload.late_note} | {checkout_note}"
336
+ elif now_minutes > (exit_min + LATE_CHECKOUT_GRACE_MIN):
337
  checkout_note = f"RETRASO SALIDA: {payload.late_note} | {checkout_note}"
338
  else:
339
  checkout_note = f"{checkout_note} - {payload.late_note}"
 
354
  "message": f"Hasta luego, {student.name} {student.lastname}",
355
  }
356
 
357
+ # action == "in"
358
+ if is_active:
359
+ return {"success": False, "message": "Ya tienes una entrada registrada hoy (sin salida)"}
360
+ if completed:
361
+ return {"success": False, "message": "Ya registraste entrada y salida hoy"}
362
  if not payload.late_note:
363
  reason_type = _detect_reason_type(now_minutes, today_schedule, tolerance, is_checkout=False)
364
  if reason_type:
365
+ return {"success": False, "needs_reason": True, "reason_type": reason_type, "action": "in"}
 
 
366
  note = f"Facial check-in (confidence: {1.0 - best_dist:.2%}) | by {current_user.name} {current_user.lastname}"
367
  if payload.late_note:
368
  note = f"RETRASO: {payload.late_note} | {note}"
backend/app/api/v1/endpoints/reports.py CHANGED
@@ -1,14 +1,21 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status, Query
 
2
  from sqlalchemy.orm import Session
3
  from sqlalchemy import func, cast, Date, case
4
  from typing import Optional
5
  from datetime import date, timedelta
6
  from pydantic import BaseModel
 
 
 
 
 
7
 
8
  from app.core.database import get_db
9
  from app.dependencies.auth import get_current_user
10
  from app.models.user import User
11
  from app.models.attendance import Attendance
 
12
  from app.models.enrollment import Enrollment
13
  from app.models.section import Section
14
 
@@ -20,6 +27,7 @@ class LateArrivalItem(BaseModel):
20
  student_name: str
21
  student_lastname: str
22
  card_id: Optional[str] = None
 
23
  section_name: Optional[str] = None
24
  late_count: int
25
  early_departure_count: int
@@ -32,51 +40,45 @@ class LateArrivalsResponse(BaseModel):
32
  total: int
33
 
34
 
35
- @router.get("/late-arrivals", response_model=LateArrivalsResponse)
36
- def late_arrivals(
37
- section_id: Optional[int] = Query(None),
38
- date_from: Optional[str] = Query(None),
39
- date_to: Optional[str] = Query(None),
40
- current_user: User = Depends(get_current_user),
41
- db: Session = Depends(get_db),
42
- ):
43
- if current_user.role not in ("admin", "administrativo", "teacher"):
44
- raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized")
45
-
46
  day_from = date.fromisoformat(date_from) if date_from else date.today() - timedelta(days=30)
47
  day_to = date.fromisoformat(date_to) if date_to else date.today()
48
 
49
- student_ids_query = db.query(Enrollment.student_id).filter(
50
- Enrollment.account_id == current_user.account_id,
 
 
51
  )
 
 
52
  if section_id:
53
- student_ids_query = student_ids_query.filter(Enrollment.section_id == section_id)
54
-
55
- all_student_ids = [r[0] for r in student_ids_query.all()]
56
- if not all_student_ids:
57
- return LateArrivalsResponse(items=[], total=0)
58
-
59
- students = {u.id: u for u in db.query(User).filter(User.id.in_(all_student_ids)).all()}
 
60
 
61
- att_query = db.query(
62
- Attendance.user_id,
63
- func.count(Attendance.id).label("total"),
64
- func.sum(
65
- case((Attendance.note.like("%RETRASO:%"), 1), else_=0)
66
- ).label("late_count"),
67
- func.sum(
68
- case((Attendance.note.like("%SALIDA TEMPRANA:%"), 1), else_=0)
69
- ).label("early_count"),
70
  ).filter(
71
- Attendance.user_id.in_(all_student_ids),
72
- Attendance.account_id == current_user.account_id,
73
- cast(Attendance.time_log, Date) >= day_from,
74
- cast(Attendance.time_log, Date) <= day_to,
75
- ).group_by(Attendance.user_id).all()
76
 
77
  items = []
78
- for row in att_query:
79
- s = students.get(row.user_id)
80
  if not s:
81
  continue
82
  total = row.total or 0
@@ -87,17 +89,65 @@ def late_arrivals(
87
  student_name=s.name,
88
  student_lastname=s.lastname,
89
  card_id=s.card_id,
 
90
  late_count=late,
91
  early_departure_count=early,
92
  total_attendance_days=total,
93
  late_percentage=round((late / total) * 100, 1) if total > 0 else 0.0,
94
  ))
 
 
95
 
96
- items.sort(key=lambda x: x.late_percentage, reverse=True)
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  return LateArrivalsResponse(items=items, total=len(items))
99
 
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  class StudentListItem(BaseModel):
102
  id: int
103
  name: str
@@ -106,9 +156,12 @@ class StudentListItem(BaseModel):
106
  email: Optional[str] = None
107
  phone_number: Optional[str] = None
108
  section_names: list[str] = []
109
- total_attendances: int = 0
110
- present_count: int = 0
111
- attendance_rate: float = 0.0
 
 
 
112
 
113
 
114
  @router.get("/students", response_model=list[StudentListItem])
@@ -141,36 +194,38 @@ def student_report(
141
  today = date.today()
142
  month_start = today.replace(day=1)
143
 
144
- att_counts = db.query(
145
- Attendance.user_id,
146
- func.count(Attendance.id).label("total"),
 
 
 
147
  ).filter(
148
- Attendance.user_id.in_(student_ids),
149
- Attendance.account_id == current_user.account_id,
150
- cast(Attendance.time_log, Date) >= month_start,
151
- ).group_by(Attendance.user_id).all()
152
-
153
- att_map = {r.user_id: r.total for r in att_counts}
154
 
155
- present_counts = db.query(
156
  Attendance.user_id,
157
- func.count(Attendance.id).label("present"),
158
  ).filter(
159
  Attendance.user_id.in_(student_ids),
160
  Attendance.account_id == current_user.account_id,
161
  Attendance.action == "in",
162
  cast(Attendance.time_log, Date) >= month_start,
163
  ).group_by(Attendance.user_id).all()
164
-
165
- present_map = {r.user_id: r.present for r in present_counts}
166
 
167
  result = []
168
  for sid in student_ids:
169
  s = students.get(sid)
170
  if not s:
171
  continue
172
- total = att_map.get(sid, 0)
173
- present = present_map.get(sid, 0)
 
174
  result.append(StudentListItem(
175
  id=s.id,
176
  name=s.name,
@@ -179,9 +234,13 @@ def student_report(
179
  email=s.email,
180
  phone_number=s.phone_number,
181
  section_names=section_map.get(sid, []),
182
- total_attendances=total,
183
- present_count=present,
184
- attendance_rate=round((present / total) * 100, 1) if total > 0 else 0.0,
 
 
 
185
  ))
186
 
 
187
  return result
 
1
  from fastapi import APIRouter, Depends, HTTPException, status, Query
2
+ from fastapi.responses import StreamingResponse
3
  from sqlalchemy.orm import Session
4
  from sqlalchemy import func, cast, Date, case
5
  from typing import Optional
6
  from datetime import date, timedelta
7
  from pydantic import BaseModel
8
+ import csv
9
+ import io
10
+
11
+ # Roles que se reportan (se excluye admin/developer del control de asistencia)
12
+ REPORTABLE_ROLES = ["student", "teacher", "administrativo", "obrero", "representative"]
13
 
14
  from app.core.database import get_db
15
  from app.dependencies.auth import get_current_user
16
  from app.models.user import User
17
  from app.models.attendance import Attendance
18
+ from app.models.entrance_log import EntranceLog
19
  from app.models.enrollment import Enrollment
20
  from app.models.section import Section
21
 
 
27
  student_name: str
28
  student_lastname: str
29
  card_id: Optional[str] = None
30
+ role: Optional[str] = None
31
  section_name: Optional[str] = None
32
  late_count: int
33
  early_departure_count: int
 
40
  total: int
41
 
42
 
43
+ def _late_arrivals_rows(db, account_id, role, section_id, date_from, date_to):
44
+ """Agrega tardanzas/salidas tempranas por usuario desde EntranceLog.
45
+ Incluye TODOS los roles reportables (no solo estudiantes). 'RETRASO:' = entrada
46
+ tardía; 'SALIDA TEMPRANA' = salida temprana (RETRASO SALIDA lleva espacio, no cuenta)."""
 
 
 
 
 
 
 
47
  day_from = date.fromisoformat(date_from) if date_from else date.today() - timedelta(days=30)
48
  day_to = date.fromisoformat(date_to) if date_to else date.today()
49
 
50
+ uq = db.query(User).filter(
51
+ User.account_id == account_id,
52
+ User.role.in_(REPORTABLE_ROLES),
53
+ User.is_active == "1",
54
  )
55
+ if role:
56
+ uq = uq.filter(User.role == role)
57
  if section_id:
58
+ enrolled = db.query(Enrollment.student_id).filter(
59
+ Enrollment.section_id == section_id,
60
+ Enrollment.account_id == account_id,
61
+ ).subquery()
62
+ uq = uq.filter(User.id.in_(enrolled))
63
+ users = {u.id: u for u in uq.all()}
64
+ if not users:
65
+ return []
66
 
67
+ rows = db.query(
68
+ EntranceLog.user_id,
69
+ func.count(EntranceLog.id).label("total"),
70
+ func.sum(case((EntranceLog.note.like("%RETRASO:%"), 1), else_=0)).label("late_count"),
71
+ func.sum(case((EntranceLog.note.like("%SALIDA TEMPRANA%"), 1), else_=0)).label("early_count"),
 
 
 
 
72
  ).filter(
73
+ EntranceLog.user_id.in_(list(users.keys())),
74
+ EntranceLog.account_id == account_id,
75
+ EntranceLog.date >= day_from,
76
+ EntranceLog.date <= day_to,
77
+ ).group_by(EntranceLog.user_id).all()
78
 
79
  items = []
80
+ for row in rows:
81
+ s = users.get(row.user_id)
82
  if not s:
83
  continue
84
  total = row.total or 0
 
89
  student_name=s.name,
90
  student_lastname=s.lastname,
91
  card_id=s.card_id,
92
+ role=s.role,
93
  late_count=late,
94
  early_departure_count=early,
95
  total_attendance_days=total,
96
  late_percentage=round((late / total) * 100, 1) if total > 0 else 0.0,
97
  ))
98
+ items.sort(key=lambda x: (x.late_count + x.early_departure_count, x.late_percentage), reverse=True)
99
+ return items
100
 
 
101
 
102
+ @router.get("/late-arrivals", response_model=LateArrivalsResponse)
103
+ def late_arrivals(
104
+ role: Optional[str] = Query(None),
105
+ section_id: Optional[int] = Query(None),
106
+ date_from: Optional[str] = Query(None),
107
+ date_to: Optional[str] = Query(None),
108
+ current_user: User = Depends(get_current_user),
109
+ db: Session = Depends(get_db),
110
+ ):
111
+ if current_user.role not in ("admin", "administrativo", "teacher"):
112
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized")
113
+
114
+ items = _late_arrivals_rows(db, current_user.account_id, role, section_id, date_from, date_to)
115
  return LateArrivalsResponse(items=items, total=len(items))
116
 
117
 
118
+ ROLE_LABELS = {
119
+ "student": "Estudiante", "teacher": "Docente", "administrativo": "Administrativo",
120
+ "obrero": "Obrero", "representative": "Representante", "admin": "Administrador",
121
+ }
122
+
123
+
124
+ @router.get("/late-arrivals-export")
125
+ def late_arrivals_export(
126
+ role: Optional[str] = Query(None),
127
+ section_id: Optional[int] = Query(None),
128
+ date_from: Optional[str] = Query(None),
129
+ date_to: Optional[str] = Query(None),
130
+ current_user: User = Depends(get_current_user),
131
+ db: Session = Depends(get_db),
132
+ ):
133
+ if current_user.role not in ("admin", "administrativo", "teacher"):
134
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized")
135
+ items = _late_arrivals_rows(db, current_user.account_id, role, section_id, date_from, date_to)
136
+ buf = io.StringIO()
137
+ w = csv.writer(buf)
138
+ w.writerow(["Usuario", "Rol", "Cédula", "Tardanzas", "Salidas Tempranas", "Días Registrados", "% Tardanzas"])
139
+ for it in items:
140
+ w.writerow([
141
+ f"{it.student_lastname}, {it.student_name}", ROLE_LABELS.get(it.role or "", it.role or ""),
142
+ it.card_id or "", it.late_count, it.early_departure_count,
143
+ it.total_attendance_days, it.late_percentage,
144
+ ])
145
+ buf.seek(0)
146
+ fname = f"tardanzas_{date_from or 'inicio'}_{date_to or 'hoy'}.csv"
147
+ return StreamingResponse(iter([buf.getvalue()]), media_type="text/csv",
148
+ headers={"Content-Disposition": f"attachment; filename={fname}"})
149
+
150
+
151
  class StudentListItem(BaseModel):
152
  id: int
153
  name: str
 
156
  email: Optional[str] = None
157
  phone_number: Optional[str] = None
158
  section_names: list[str] = []
159
+ campus_days: int = 0 # días que ingresó al plantel (portón / EntranceLog)
160
+ class_days: int = 0 # días marcado en clase (Attendance)
161
+ skipped_class_days: int = 0 # vino al plantel pero no entró a clase
162
+ total_attendances: int = 0 # = campus_days (compat)
163
+ present_count: int = 0 # = class_days (compat)
164
+ attendance_rate: float = 0.0 # class_days / campus_days * 100
165
 
166
 
167
  @router.get("/students", response_model=list[StudentListItem])
 
194
  today = date.today()
195
  month_start = today.replace(day=1)
196
 
197
+ # Criterio dual (este mes):
198
+ # campus_days = días que INGRESÓ AL PLANTEL (portón / EntranceLog)
199
+ # class_days = días MARCADO EN CLASE (Attendance action="in")
200
+ campus_rows = db.query(
201
+ EntranceLog.user_id,
202
+ func.count(func.distinct(EntranceLog.date)).label("days"),
203
  ).filter(
204
+ EntranceLog.user_id.in_(student_ids),
205
+ EntranceLog.account_id == current_user.account_id,
206
+ EntranceLog.date >= month_start,
207
+ ).group_by(EntranceLog.user_id).all()
208
+ campus_map = {r.user_id: r.days for r in campus_rows}
 
209
 
210
+ class_rows = db.query(
211
  Attendance.user_id,
212
+ func.count(func.distinct(cast(Attendance.time_log, Date))).label("days"),
213
  ).filter(
214
  Attendance.user_id.in_(student_ids),
215
  Attendance.account_id == current_user.account_id,
216
  Attendance.action == "in",
217
  cast(Attendance.time_log, Date) >= month_start,
218
  ).group_by(Attendance.user_id).all()
219
+ class_map = {r.user_id: r.days for r in class_rows}
 
220
 
221
  result = []
222
  for sid in student_ids:
223
  s = students.get(sid)
224
  if not s:
225
  continue
226
+ campus = campus_map.get(sid, 0)
227
+ clase = class_map.get(sid, 0)
228
+ skipped = max(0, campus - clase)
229
  result.append(StudentListItem(
230
  id=s.id,
231
  name=s.name,
 
234
  email=s.email,
235
  phone_number=s.phone_number,
236
  section_names=section_map.get(sid, []),
237
+ campus_days=campus,
238
+ class_days=clase,
239
+ skipped_class_days=skipped,
240
+ total_attendances=campus,
241
+ present_count=clase,
242
+ attendance_rate=round((clase / campus) * 100, 1) if campus > 0 else 0.0,
243
  ))
244
 
245
+ result.sort(key=lambda x: x.skipped_class_days, reverse=True)
246
  return result
backend/app/api/v1/endpoints/representative.py CHANGED
@@ -9,6 +9,7 @@ from app.middleware.rbac import RBAC
9
  from app.models.user import User
10
  from app.models.enrollment import Enrollment
11
  from app.models.attendance import Attendance
 
12
  from app.models.section import Section
13
  from app.models.section_schedule import SectionSchedule
14
 
@@ -103,6 +104,18 @@ def my_children(
103
  ),
104
  ).scalar() or 0
105
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  result.append({
107
  "id": child.id,
108
  "name": child.name,
@@ -110,8 +123,12 @@ def my_children(
110
  "card_id": child.card_id,
111
  "section_name": section_name,
112
  "section_id": section_id,
 
 
 
113
  "is_present_today": is_present,
114
  "checkin_time": checkin_time,
 
115
  "attendance_last_30_days": total_att,
116
  "today_schedule": today_schedule,
117
  })
 
9
  from app.models.user import User
10
  from app.models.enrollment import Enrollment
11
  from app.models.attendance import Attendance
12
+ from app.models.entrance_log import EntranceLog
13
  from app.models.section import Section
14
  from app.models.section_schedule import SectionSchedule
15
 
 
104
  ),
105
  ).scalar() or 0
106
 
107
+ # Ingreso al PLANTEL hoy (portón / EntranceLog) — separado de la clase.
108
+ gate = db.query(EntranceLog).filter(
109
+ EntranceLog.user_id == child.id,
110
+ EntranceLog.account_id == current_user.account_id,
111
+ EntranceLog.date == today,
112
+ ).order_by(EntranceLog.checkin_time.desc()).first()
113
+ entered_campus = gate is not None
114
+ campus_checkin_time = gate.checkin_time.isoformat() if gate and gate.checkin_time else None
115
+ campus_checkout_time = gate.checkout_time.isoformat() if gate and gate.checkout_time else None
116
+ # Discrepancia clave: entró al plantel pero el docente NO lo marcó en clase.
117
+ skipped_class = entered_campus and not is_present
118
+
119
  result.append({
120
  "id": child.id,
121
  "name": child.name,
 
123
  "card_id": child.card_id,
124
  "section_name": section_name,
125
  "section_id": section_id,
126
+ "entered_campus_today": entered_campus,
127
+ "campus_checkin_time": campus_checkin_time,
128
+ "campus_checkout_time": campus_checkout_time,
129
  "is_present_today": is_present,
130
  "checkin_time": checkin_time,
131
+ "skipped_class": skipped_class,
132
  "attendance_last_30_days": total_att,
133
  "today_schedule": today_schedule,
134
  })
backend/app/api/v1/endpoints/users.py CHANGED
@@ -1,8 +1,10 @@
1
- from fastapi import APIRouter, Depends, HTTPException, status, Query
2
  from sqlalchemy.orm import Session
3
  from sqlalchemy import or_, func
4
  from typing import Optional
5
 
 
 
6
  import io
7
  import csv
8
  from fastapi import UploadFile, File
@@ -245,6 +247,7 @@ def get_user(
245
  @router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
246
  def create_user(
247
  payload: UserCreate,
 
248
  current_user: User = Depends(RBAC(["admin"])),
249
  db: Session = Depends(get_db),
250
  ):
@@ -273,6 +276,9 @@ def create_user(
273
  db.commit()
274
  db.refresh(user)
275
 
 
 
 
276
  return UserResponse.model_validate(user)
277
 
278
 
@@ -280,6 +286,7 @@ def create_user(
280
  def update_user(
281
  user_id: int,
282
  payload: UserUpdate,
 
283
  current_user: User = Depends(RBAC(["admin"])),
284
  db: Session = Depends(get_db),
285
  ):
@@ -294,12 +301,16 @@ def update_user(
294
 
295
  db.commit()
296
  db.refresh(user)
 
 
 
297
  return UserResponse.model_validate(user)
298
 
299
 
300
  @router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
301
  def deactivate_user(
302
  user_id: int,
 
303
  current_user: User = Depends(RBAC(["admin"])),
304
  db: Session = Depends(get_db),
305
  ):
@@ -309,3 +320,6 @@ def deactivate_user(
309
 
310
  user.is_active = "0"
311
  db.commit()
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status, Query, Request
2
  from sqlalchemy.orm import Session
3
  from sqlalchemy import or_, func
4
  from typing import Optional
5
 
6
+ from app.utils.audit import log_for
7
+
8
  import io
9
  import csv
10
  from fastapi import UploadFile, File
 
247
  @router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
248
  def create_user(
249
  payload: UserCreate,
250
+ request: Request,
251
  current_user: User = Depends(RBAC(["admin"])),
252
  db: Session = Depends(get_db),
253
  ):
 
276
  db.commit()
277
  db.refresh(user)
278
 
279
+ log_for(db, current_user, "Crear usuario", "usuarios",
280
+ details={"user_id": user.id, "nombre": f"{user.name} {user.lastname}", "rol": user.role}, request=request)
281
+
282
  return UserResponse.model_validate(user)
283
 
284
 
 
286
  def update_user(
287
  user_id: int,
288
  payload: UserUpdate,
289
+ request: Request,
290
  current_user: User = Depends(RBAC(["admin"])),
291
  db: Session = Depends(get_db),
292
  ):
 
301
 
302
  db.commit()
303
  db.refresh(user)
304
+
305
+ log_for(db, current_user, "Editar usuario", "usuarios",
306
+ details={"user_id": user.id, "nombre": f"{user.name} {user.lastname}", "campos": list(update_data.keys())}, request=request)
307
  return UserResponse.model_validate(user)
308
 
309
 
310
  @router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
311
  def deactivate_user(
312
  user_id: int,
313
+ request: Request,
314
  current_user: User = Depends(RBAC(["admin"])),
315
  db: Session = Depends(get_db),
316
  ):
 
320
 
321
  user.is_active = "0"
322
  db.commit()
323
+
324
+ log_for(db, current_user, "Desactivar usuario", "usuarios",
325
+ details={"user_id": user.id, "nombre": f"{user.name} {user.lastname}"}, request=request)
backend/app/schemas/attendance.py CHANGED
@@ -67,6 +67,8 @@ class AttendanceResponse(BaseModel):
67
  action: Optional[str] = None
68
  user_name: Optional[str] = None
69
  user_lastname: Optional[str] = None
 
 
70
  section_name: Optional[str] = None
71
  is_late: bool = False
72
  late_reason: Optional[str] = None
@@ -81,6 +83,7 @@ class TodayCheckIn(BaseModel):
81
  card_id: Optional[str] = None
82
  user_name: str
83
  user_lastname: str
 
84
  section_name: Optional[str] = None
85
  time_log: Optional[datetime] = None
86
  checkout_time: Optional[datetime] = None
 
67
  action: Optional[str] = None
68
  user_name: Optional[str] = None
69
  user_lastname: Optional[str] = None
70
+ role: Optional[str] = None
71
+ card_id: Optional[str] = None
72
  section_name: Optional[str] = None
73
  is_late: bool = False
74
  late_reason: Optional[str] = None
 
83
  card_id: Optional[str] = None
84
  user_name: str
85
  user_lastname: str
86
+ role: Optional[str] = None
87
  section_name: Optional[str] = None
88
  time_log: Optional[datetime] = None
89
  checkout_time: Optional[datetime] = None
backend/app/schemas/facial.py CHANGED
@@ -17,6 +17,7 @@ class FacialEnrollResponse(BaseModel):
17
  class FacialRecognizeRequest(BaseModel):
18
  image: str
19
  late_note: Optional[str] = None
 
20
 
21
 
22
  class FacialRecognizeResponse(BaseModel):
 
17
  class FacialRecognizeRequest(BaseModel):
18
  image: str
19
  late_note: Optional[str] = None
20
+ action: Optional[str] = None # "in" | "out" (toggle manual); si no, se infiere por estado
21
 
22
 
23
  class FacialRecognizeResponse(BaseModel):
backend/app/utils/audit.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper de auditoría: registra acciones clave en la tabla audit_log.
2
+
3
+ El registro nunca debe romper la acción principal: si algo falla, se ignora.
4
+ Llamar DESPUÉS de confirmar (commit) la acción principal del endpoint.
5
+ """
6
+ from typing import Optional
7
+
8
+ from fastapi import Request
9
+ from sqlalchemy.orm import Session
10
+
11
+ from app.models.audit_log import AuditLog
12
+ from app.models.user import User
13
+
14
+
15
+ def client_ip(request: Optional[Request]) -> Optional[str]:
16
+ if request is None:
17
+ return None
18
+ fwd = request.headers.get("x-forwarded-for")
19
+ if fwd:
20
+ return fwd.split(",")[0].strip()
21
+ return request.client.host if request.client else None
22
+
23
+
24
+ def log_action(
25
+ db: Session,
26
+ *,
27
+ account_id: int,
28
+ user_id: int,
29
+ action: str,
30
+ resource: str,
31
+ details: Optional[dict] = None,
32
+ ip: Optional[str] = None,
33
+ ) -> None:
34
+ try:
35
+ db.add(AuditLog(
36
+ account_id=account_id,
37
+ user_id=user_id,
38
+ action=action,
39
+ resource=resource,
40
+ details=details,
41
+ ip_address=ip,
42
+ ))
43
+ db.commit()
44
+ except Exception:
45
+ db.rollback()
46
+
47
+
48
+ def log_for(
49
+ db: Session,
50
+ actor: User,
51
+ action: str,
52
+ resource: str,
53
+ details: Optional[dict] = None,
54
+ request: Optional[Request] = None,
55
+ ) -> None:
56
+ """Atajo: registra una acción hecha por `actor`."""
57
+ log_action(
58
+ db,
59
+ account_id=actor.account_id,
60
+ user_id=actor.id,
61
+ action=action,
62
+ resource=resource,
63
+ details=details,
64
+ ip=client_ip(request),
65
+ )
backend/entrypoint.sh CHANGED
@@ -1,8 +1,47 @@
1
  #!/usr/bin/env sh
2
- # Monolith entrypoint: wait for DB -> migrate -> seed (if empty) -> serve.
 
 
 
3
  set -e
4
  cd /app
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  echo "[entrypoint] Esperando a la base de datos..."
7
  python3 - <<'PY'
8
  import sys, time
 
1
  #!/usr/bin/env sh
2
+ # Monolith entrypoint.
3
+ # EMBED_DB=1 -> arranca MariaDB dentro del mismo contenedor (deploy de 1 sola
4
+ # app, p.ej. fly.io via GUI). Si no, usa una DB externa (MYSQL_HOST).
5
+ # Flujo: [DB embebida] -> esperar DB -> crear esquema -> seed -> uvicorn.
6
  set -e
7
  cd /app
8
 
9
+ if [ "${EMBED_DB:-0}" = "1" ]; then
10
+ DATADIR=/var/lib/mysql
11
+ DBD=$(command -v mariadbd || command -v mysqld)
12
+ DBADMIN=$(command -v mariadb-admin || command -v mysqladmin)
13
+ DBCLI=$(command -v mariadb || command -v mysql)
14
+ DBINSTALL=$(command -v mariadb-install-db || command -v mysql_install_db)
15
+
16
+ mkdir -p "$DATADIR" /run/mysqld
17
+ chown -R mysql:mysql "$DATADIR" /run/mysqld 2>/dev/null || true
18
+
19
+ if [ ! -d "$DATADIR/mysql" ]; then
20
+ echo "[db] Inicializando datadir de MariaDB en $DATADIR ..."
21
+ "$DBINSTALL" --user=mysql --datadir="$DATADIR" --auth-root-authentication-method=normal >/dev/null 2>&1 \
22
+ || "$DBINSTALL" --user=mysql --datadir="$DATADIR" >/dev/null 2>&1 || true
23
+ fi
24
+
25
+ echo "[db] Arrancando MariaDB (local)..."
26
+ "$DBD" --user=mysql --datadir="$DATADIR" --bind-address=127.0.0.1 --skip-name-resolve \
27
+ --innodb-buffer-pool-size=128M >/var/log/mariadb.log 2>&1 &
28
+
29
+ SOCK=/run/mysqld/mysqld.sock
30
+ for i in $(seq 1 60); do
31
+ if "$DBADMIN" --protocol=socket --socket="$SOCK" -u root ping >/dev/null 2>&1; then echo "[db] MariaDB lista."; break; fi
32
+ sleep 1
33
+ done
34
+
35
+ echo "[db] Creando base y usuario (idempotente)..."
36
+ "$DBCLI" --protocol=socket --socket="$SOCK" -u root <<SQL || echo "[db] aviso: setup SQL no aplico (puede ya existir)"
37
+ CREATE DATABASE IF NOT EXISTS ${MYSQL_DATABASE:-talos_access} CHARACTER SET utf8mb4;
38
+ CREATE USER IF NOT EXISTS '${MYSQL_USER:-talos}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';
39
+ ALTER USER '${MYSQL_USER:-talos}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';
40
+ GRANT ALL PRIVILEGES ON ${MYSQL_DATABASE:-talos_access}.* TO '${MYSQL_USER:-talos}'@'%';
41
+ FLUSH PRIVILEGES;
42
+ SQL
43
+ fi
44
+
45
  echo "[entrypoint] Esperando a la base de datos..."
46
  python3 - <<'PY'
47
  import sys, time
backend/seed_demo.py CHANGED
@@ -35,6 +35,7 @@ from app.core.security import hash_password
35
  from app.models import (
36
  Plan, Account, User, Subject, Section, SectionSubject, TeacherSection,
37
  TeacherSubject, Enrollment, SectionSchedule, EntranceLog, Attendance, Holiday,
 
38
  )
39
  from app.models.holiday import HolidayType
40
 
@@ -176,6 +177,12 @@ def _ensure_base(db):
176
  acc.checkin_mode = "facial"
177
  acc.self_checkin_enabled = 0
178
  acc.is_active = True
 
 
 
 
 
 
179
  db.commit()
180
 
181
  if db.query(User).filter(User.email == "admin@talos.com").count() == 0:
@@ -316,23 +323,35 @@ def seed(reset=False):
316
 
317
  # --- TODAY's attendance snapshot ---
318
  def facial_entry(stu, when, note="Facial check-in (simulado)"):
319
- db.add(EntranceLog(account_id=account_id, user_id=stu.id, date=date.today(),
320
- method="facial", checkin_time=when, note=note))
 
 
321
 
322
  def manual_entry(stu, when):
323
- db.add(EntranceLog(account_id=account_id, user_id=stu.id, date=date.today(),
324
- method="manual", checkin_time=when, note="Check-in manual (simulado)"))
 
 
325
 
326
  def present_mark(stu, sec, when, note="Presente (simulado)"):
327
  db.add(Attendance(account_id=account_id, user_id=stu.id, section_id=sec.id,
328
  time_log=when, action="in", note=note))
329
 
330
  counts = {"presente": 0, "manual": 0, "facial_solo": 0, "tarde": 0, "ausente": 0}
 
 
331
  for stu, sec, status in students:
332
  counts[status] += 1
333
  if status == "presente":
334
- facial_entry(stu, _dt_today(7, 35))
335
  present_mark(stu, sec, _dt_today(7, 40))
 
 
 
 
 
 
336
  elif status == "manual":
337
  manual_entry(stu, _dt_today(7, 45))
338
  present_mark(stu, sec, _dt_today(7, 50))
@@ -342,14 +361,36 @@ def seed(reset=False):
342
  facial_entry(stu, _dt_today(8, 20), note="RETRASO: 20 min | Facial check-in (simulado)")
343
  present_mark(stu, sec, _dt_today(8, 22), note="RETRASO: 20 min - llegó tarde")
344
  # "ausente" -> no records
345
- print(f"✓ Asistencia de HOY: {counts}")
346
-
347
- # --- A couple of early-departure records today (SALIDA TEMPRANA -> report) ---
348
- present_students = [t for t in students if t[2] in ("presente", "manual")]
349
- for stu, sec, _ in present_students[:2]:
350
- db.add(Attendance(account_id=account_id, user_id=stu.id, section_id=sec.id,
351
- time_log=_dt_today(11, 0), checkout_time=_dt_today(11, 0),
352
- action="out", note="SALIDA TEMPRANA: retiro autorizado"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
  # --- Light history (~10 past school days) for the regular attenders ---
355
  hist_days = 0
@@ -366,9 +407,14 @@ def seed(reset=False):
366
  hh, mm = (8, 15) if late else (7, random.choice([30, 35, 40]))
367
  when = datetime.combine(d, time(hh, mm))
368
  note = "RETRASO: llegó tarde" if late else "Presente"
369
- db.add(EntranceLog(account_id=account_id, user_id=stu.id, date=d,
370
- method="facial", checkin_time=when,
371
- note=("RETRASO: 15 min | Facial" if late else "Facial check-in")))
 
 
 
 
 
372
  db.add(Attendance(account_id=account_id, user_id=stu.id, section_id=sec.id,
373
  time_log=when, action="in", note=note))
374
  hist_days += 1
@@ -389,6 +435,31 @@ def seed(reset=False):
389
 
390
  db.commit()
391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  today_name = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"][date.today().weekday()]
393
  print()
394
  print("=" * 64)
 
35
  from app.models import (
36
  Plan, Account, User, Subject, Section, SectionSubject, TeacherSection,
37
  TeacherSubject, Enrollment, SectionSchedule, EntranceLog, Attendance, Holiday,
38
+ AuditLog,
39
  )
40
  from app.models.holiday import HolidayType
41
 
 
177
  acc.checkin_mode = "facial"
178
  acc.self_checkin_enabled = 0
179
  acc.is_active = True
180
+ # Horario de jornada (Configuración → Horario por Día). Alimenta la detección
181
+ # en vivo de entrada tardía / salida temprana/tardía en el check-in del kiosko.
182
+ acc.schedule = {
183
+ d: {"entry": "07:00", "exit": "14:00"}
184
+ for d in ["monday", "tuesday", "wednesday", "thursday", "friday"]
185
+ }
186
  db.commit()
187
 
188
  if db.query(User).filter(User.email == "admin@talos.com").count() == 0:
 
323
 
324
  # --- TODAY's attendance snapshot ---
325
  def facial_entry(stu, when, note="Facial check-in (simulado)"):
326
+ e = EntranceLog(account_id=account_id, user_id=stu.id, date=date.today(),
327
+ method="facial", checkin_time=when, note=note)
328
+ db.add(e)
329
+ return e
330
 
331
  def manual_entry(stu, when):
332
+ e = EntranceLog(account_id=account_id, user_id=stu.id, date=date.today(),
333
+ method="manual", checkin_time=when, note="Check-in manual (simulado)")
334
+ db.add(e)
335
+ return e
336
 
337
  def present_mark(stu, sec, when, note="Presente (simulado)"):
338
  db.add(Attendance(account_id=account_id, user_id=stu.id, section_id=sec.id,
339
  time_log=when, action="in", note=note))
340
 
341
  counts = {"presente": 0, "manual": 0, "facial_solo": 0, "tarde": 0, "ausente": 0}
342
+ early_count = 0
343
+ present_idx = 0
344
  for stu, sec, status in students:
345
  counts[status] += 1
346
  if status == "presente":
347
+ e = facial_entry(stu, _dt_today(7, 35))
348
  present_mark(stu, sec, _dt_today(7, 40))
349
+ # 1 de cada 4 presentes se retira temprano (SALIDA TEMPRANA en EntranceLog)
350
+ if present_idx % 4 == 0:
351
+ e.checkout_time = _dt_today(11, 0)
352
+ e.note = e.note + " | SALIDA TEMPRANA: retiro autorizado por el representante"
353
+ early_count += 1
354
+ present_idx += 1
355
  elif status == "manual":
356
  manual_entry(stu, _dt_today(7, 45))
357
  present_mark(stu, sec, _dt_today(7, 50))
 
361
  facial_entry(stu, _dt_today(8, 20), note="RETRASO: 20 min | Facial check-in (simulado)")
362
  present_mark(stu, sec, _dt_today(8, 22), note="RETRASO: 20 min - llegó tarde")
363
  # "ausente" -> no records
364
+ print(f"✓ Asistencia de HOY: {counts} (+{early_count} salidas tempranas)")
365
+
366
+ # --- Check-ins de STAFF (para que Reportes/Tardanzas muestren TODOS los roles) ---
367
+ staff = db.query(User).filter(
368
+ User.account_id == account_id,
369
+ User.role.in_(["teacher", "administrativo", "obrero"]),
370
+ ).all()
371
+ staff_late = 0
372
+ for i, st in enumerate(staff):
373
+ late_today = (i % 4 == 0)
374
+ e = facial_entry(st, _dt_today(7, 50) if late_today else _dt_today(7, 5),
375
+ note=("RETRASO: 50 min | Facial check-in (simulado)" if late_today else "Facial check-in (simulado)"))
376
+ if late_today:
377
+ staff_late += 1
378
+ if i % 5 == 0: # algunos se retiran temprano
379
+ e.checkout_time = _dt_today(12, 0)
380
+ e.note = e.note + " | SALIDA TEMPRANA: diligencia personal"
381
+ # historial de staff (~6 días hábiles previos, solo EntranceLog)
382
+ dd = date.today() - timedelta(days=1)
383
+ seen = 0
384
+ while seen < 6:
385
+ if dd.weekday() < 5:
386
+ seen += 1
387
+ if random.random() >= 0.10: # 90% asisti��
388
+ lt = random.random() < 0.2
389
+ w = datetime.combine(dd, time(7, 55) if lt else time(7, random.choice([0, 5, 8])))
390
+ db.add(EntranceLog(account_id=account_id, user_id=st.id, date=dd, method="facial",
391
+ checkin_time=w, note=("RETRASO: 25 min | Facial" if lt else "Facial check-in")))
392
+ dd -= timedelta(days=1)
393
+ print(f"✓ Check-ins de staff: {len(staff)} (hoy {staff_late} tardíos) + historial")
394
 
395
  # --- Light history (~10 past school days) for the regular attenders ---
396
  hist_days = 0
 
407
  hh, mm = (8, 15) if late else (7, random.choice([30, 35, 40]))
408
  when = datetime.combine(d, time(hh, mm))
409
  note = "RETRASO: llegó tarde" if late else "Presente"
410
+ el = EntranceLog(account_id=account_id, user_id=stu.id, date=d,
411
+ method="facial", checkin_time=when,
412
+ note=("RETRASO: 15 min | Facial" if late else "Facial check-in"))
413
+ # salida temprana ocasional (alimenta analítica de salidas tempranas)
414
+ if random.random() < 0.10:
415
+ el.checkout_time = datetime.combine(d, time(11, 30))
416
+ el.note += " | SALIDA TEMPRANA: retiro autorizado"
417
+ db.add(el)
418
  db.add(Attendance(account_id=account_id, user_id=stu.id, section_id=sec.id,
419
  time_log=when, action="in", note=note))
420
  hist_days += 1
 
435
 
436
  db.commit()
437
 
438
+ # --- Auditoría de ejemplo (para poblar el visor de auditoría) ---
439
+ audit_samples = [
440
+ (admin, "Inicio de sesión", "auth", None, 5),
441
+ (teachers[0], "Inicio de sesión", "auth", None, 12),
442
+ (admin, "Crear usuario", "usuarios", {"nombre": f"{teachers[0].name} {teachers[0].lastname}", "rol": "teacher"}, 95),
443
+ (admin, "Crear sección", "secciones", {"nombre": secs[0][0].name}, 92),
444
+ (admin, "Matricular", "matrículas", {"student_id": students[0][0].id, "section": secs[0][0].name}, 88),
445
+ (admin, "Editar usuario", "usuarios", {"campos": ["phone_number"]}, 70),
446
+ (admin, "Reset de contraseña", "usuarios", {"target": f"{reps[0].name} {reps[0].lastname}"}, 1450),
447
+ (admin, "Crear materia", "materias", {"nombre": "Matemática"}, 1460),
448
+ (teachers[1], "Inicio de sesión", "auth", None, 1500),
449
+ (admin, "Desmatricular", "matrículas", {"student_id": students[-1][0].id}, 2900),
450
+ (admin, "Editar configuración", "configuración", {"campo": "tolerancia", "valor": 15}, 2950),
451
+ (admin, "Inicio de sesión", "auth", None, 4350),
452
+ ]
453
+ ip_pool = ["190.202.10.5", "200.44.32.18", "10.0.0.7"]
454
+ for i, (actor, action, resource, details, mins_ago) in enumerate(audit_samples):
455
+ db.add(AuditLog(
456
+ account_id=account_id, user_id=actor.id, action=action, resource=resource,
457
+ details=details, ip_address=ip_pool[i % len(ip_pool)],
458
+ created_at=datetime.now() - timedelta(minutes=mins_ago),
459
+ ))
460
+ db.commit()
461
+ print(f"✓ {len(audit_samples)} registros de auditoría de ejemplo.")
462
+
463
  today_name = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"][date.today().weekday()]
464
  print()
465
  print("=" * 64)
deploy/docker-compose.embedded.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prueba LOCAL del monolito con MariaDB EMBEBIDA (igual que el deploy fly.io).
2
+ # Un solo contenedor: MariaDB + FastAPI + SPA.
3
+ # docker compose -p talosemb -f deploy/docker-compose.embedded.yml up --build
4
+ # Luego: http://localhost:8090 (admin@talos.com / admin123)
5
+ services:
6
+ app:
7
+ build:
8
+ context: ..
9
+ dockerfile: Dockerfile
10
+ restart: unless-stopped
11
+ environment:
12
+ EMBED_DB: "1"
13
+ MYSQL_HOST: "127.0.0.1"
14
+ MYSQL_PORT: "3306"
15
+ MYSQL_DATABASE: talos_access
16
+ MYSQL_USER: talos
17
+ MYSQL_PASSWORD: talos_demo_2026
18
+ JWT_SECRET_KEY: local_test_secret_not_for_prod
19
+ TZ: America/Caracas
20
+ SEED_DEMO: "1"
21
+ ports:
22
+ - "8090:8000"
23
+ volumes:
24
+ - talos_embedded_data:/var/lib/mysql
25
+
26
+ volumes:
27
+ talos_embedded_data:
fly.toml CHANGED
@@ -1,23 +1,30 @@
1
- # Talos Access — monolith app (FastAPI + built SPA). Deploy with: fly deploy
2
- # Requires a separate MySQL app (see deploy/fly.db.toml and deploy/DEPLOY.md).
3
- app = "talos-access"
4
- primary_region = "ord" # Chicago (misma región que la app desplegada)
 
 
5
 
6
  [build]
7
  dockerfile = "Dockerfile"
8
 
9
  [env]
10
- MYSQL_HOST = "talos-access-db.internal"
 
11
  MYSQL_PORT = "3306"
12
  MYSQL_DATABASE = "talos_access"
13
  MYSQL_USER = "talos"
14
  TZ = "America/Caracas"
15
  SEED_DEMO = "1"
16
- # CORS no es necesario (mismo origen), pero se deja explícito:
17
  CORS_ORIGINS = '["*"]'
18
- # Secrets (NO van aquí) — definir con `fly secrets set`:
19
  # JWT_SECRET_KEY (ej: openssl rand -hex 32)
20
- # MYSQL_PASSWORD (igual al de la app de base de datos)
 
 
 
 
 
21
 
22
  [http_service]
23
  internal_port = 8000
@@ -29,10 +36,10 @@ primary_region = "ord" # Chicago (misma región que la app desplegada)
29
  [[http_service.checks]]
30
  interval = "15s"
31
  timeout = "3s"
32
- grace_period = "40s"
33
  method = "GET"
34
  path = "/health"
35
 
36
  [[vm]]
37
  size = "shared-cpu-1x"
38
- memory = "2gb" # face_recognition/dlib + opencv necesitan holgura de RAM
 
1
+ # Talos Access — app monolítica (FastAPI + SPA + MariaDB embebida).
2
+ # Una sola app: el contenedor corre MariaDB y la app juntos (EMBED_DB=1).
3
+ # Requiere un volumen llamado "talos_data" (créalo en la GUI o con:
4
+ # fly volumes create talos_data --size 1 -r ord)
5
+ app = "talos-access-lkgsqw"
6
+ primary_region = "ord"
7
 
8
  [build]
9
  dockerfile = "Dockerfile"
10
 
11
  [env]
12
+ EMBED_DB = "1"
13
+ MYSQL_HOST = "127.0.0.1"
14
  MYSQL_PORT = "3306"
15
  MYSQL_DATABASE = "talos_access"
16
  MYSQL_USER = "talos"
17
  TZ = "America/Caracas"
18
  SEED_DEMO = "1"
 
19
  CORS_ORIGINS = '["*"]'
20
+ # Secrets (NO van aquí) — definir en la GUI (Secrets) o con `fly secrets set`:
21
  # JWT_SECRET_KEY (ej: openssl rand -hex 32)
22
+ # MYSQL_PASSWORD (clave del usuario 'talos' de la MariaDB embebida)
23
+
24
+ # Volumen persistente para los datos de MariaDB.
25
+ [mounts]
26
+ source = "talos_data"
27
+ destination = "/var/lib/mysql"
28
 
29
  [http_service]
30
  internal_port = 8000
 
36
  [[http_service.checks]]
37
  interval = "15s"
38
  timeout = "3s"
39
+ grace_period = "120s" # da tiempo a init de MariaDB + seed antes del 1er check
40
  method = "GET"
41
  path = "/health"
42
 
43
  [[vm]]
44
  size = "shared-cpu-1x"
45
+ memory = "2gb" # MariaDB + face_recognition/dlib + opencv
frontend/src/App.tsx CHANGED
@@ -20,6 +20,7 @@ import RepresentativeChildrenPage from './pages/RepresentativeChildrenPage'
20
  import HolidaysPage from './pages/HolidaysPage'
21
  import AuditLogsPage from './pages/AuditLogsPage'
22
  import LateArrivalsPage from './pages/LateArrivalsPage'
 
23
  import ResetPasswordPage from './pages/ResetPasswordPage'
24
  import Layout from './components/Layout'
25
  import ProtectedRoute from './components/ProtectedRoute'
@@ -57,6 +58,7 @@ export default function App() {
57
  <Route path="holidays" element={<HolidaysPage />} />
58
  <Route path="audit-logs" element={<AuditLogsPage />} />
59
  <Route path="late-arrivals" element={<LateArrivalsPage />} />
 
60
  </Route>
61
  <Route path="*" element={<Navigate to="/login" replace />} />
62
  </Routes>
 
20
  import HolidaysPage from './pages/HolidaysPage'
21
  import AuditLogsPage from './pages/AuditLogsPage'
22
  import LateArrivalsPage from './pages/LateArrivalsPage'
23
+ import StudentReportPage from './pages/StudentReportPage'
24
  import ResetPasswordPage from './pages/ResetPasswordPage'
25
  import Layout from './components/Layout'
26
  import ProtectedRoute from './components/ProtectedRoute'
 
58
  <Route path="holidays" element={<HolidaysPage />} />
59
  <Route path="audit-logs" element={<AuditLogsPage />} />
60
  <Route path="late-arrivals" element={<LateArrivalsPage />} />
61
+ <Route path="student-report" element={<StudentReportPage />} />
62
  </Route>
63
  <Route path="*" element={<Navigate to="/login" replace />} />
64
  </Routes>
frontend/src/components/Sidebar.tsx CHANGED
@@ -1,7 +1,7 @@
1
  import { NavLink } from 'react-router-dom';
2
  import { useAuthStore } from '../store/authStore';
3
  import { translateRole } from '../utils/roles';
4
- import { Users, LayoutDashboard, BookOpen, ClipboardCheck, LogOut, GraduationCap, BarChart3, Settings, CreditCard, Clock, Code2, IdCard, Heart, Calendar, Search } from 'lucide-react';
5
 
6
  const navItems = [
7
  { to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] },
@@ -15,6 +15,7 @@ const navItems = [
15
  { to: '/dashboard/public-checkin', label: 'Mi Asistencia', icon: Clock, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] },
16
  { to: '/dashboard/teacher-attendance', label: 'Asistencia', icon: CreditCard, roles: ['teacher'] },
17
  { to: '/dashboard/attendance', label: 'Reportes', icon: BarChart3, roles: ['admin', 'administrativo'] },
 
18
  { to: '/dashboard/late-arrivals', label: 'Tardanzas', icon: Clock, roles: ['admin', 'administrativo', 'teacher'] },
19
  { to: '/dashboard/audit-logs', label: 'Auditoría', icon: Search, roles: ['admin'] },
20
  { to: '/dashboard/holidays', label: 'Calendario', icon: Calendar, roles: ['admin'] },
 
1
  import { NavLink } from 'react-router-dom';
2
  import { useAuthStore } from '../store/authStore';
3
  import { translateRole } from '../utils/roles';
4
+ import { Users, LayoutDashboard, BookOpen, ClipboardCheck, LogOut, GraduationCap, BarChart3, Settings, CreditCard, Clock, Code2, IdCard, Heart, Calendar, Search, FileText } from 'lucide-react';
5
 
6
  const navItems = [
7
  { to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] },
 
15
  { to: '/dashboard/public-checkin', label: 'Mi Asistencia', icon: Clock, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] },
16
  { to: '/dashboard/teacher-attendance', label: 'Asistencia', icon: CreditCard, roles: ['teacher'] },
17
  { to: '/dashboard/attendance', label: 'Reportes', icon: BarChart3, roles: ['admin', 'administrativo'] },
18
+ { to: '/dashboard/student-report', label: 'Rep. Estudiantes', icon: FileText, roles: ['admin', 'administrativo'] },
19
  { to: '/dashboard/late-arrivals', label: 'Tardanzas', icon: Clock, roles: ['admin', 'administrativo', 'teacher'] },
20
  { to: '/dashboard/audit-logs', label: 'Auditoría', icon: Search, roles: ['admin'] },
21
  { to: '/dashboard/holidays', label: 'Calendario', icon: Calendar, roles: ['admin'] },
frontend/src/pages/AttendanceReportsPage.tsx CHANGED
@@ -1,9 +1,9 @@
1
  import { useState, useEffect, useCallback } from 'react';
2
- import { listAttendances, type Attendance } from '../services/attendanceService';
3
- import { listSections } from '../services/sectionService';
4
  import { listUsers } from '../services/userService';
5
- import type { Section, User } from '../types';
6
- import { BarChart3, Search } from 'lucide-react';
 
7
  import HeatmapModal from '../components/HeatmapModal';
8
 
9
  export default function AttendanceReportsPage() {
@@ -11,9 +11,8 @@ export default function AttendanceReportsPage() {
11
  const [total, setTotal] = useState(0);
12
  const [page, setPage] = useState(1);
13
  const [totalPages, setTotalPages] = useState(1);
14
- const [sections, setSections] = useState<Section[]>([]);
15
  const [students, setStudents] = useState<User[]>([]);
16
- const [filters, setFilters] = useState({ section_id: '', date_from: '', date_to: '' });
17
  const [studentSearch, setStudentSearch] = useState('');
18
  const [selectedStudent, setSelectedStudent] = useState<User | null>(null);
19
  const [showSuggestions, setShowSuggestions] = useState(false);
@@ -21,15 +20,14 @@ export default function AttendanceReportsPage() {
21
  const [tab, setTab] = useState<'all' | 'entry' | 'exit'>('all');
22
 
23
  const load = useCallback(async () => {
24
- try { const secs = await listSections({ per_page: 200 }); setSections(secs.items); } catch { /* ignore */ }
25
- try { const stds = await listUsers({ role: 'student', is_active: '1', per_page: 500 }); setStudents(stds.items); } catch { /* ignore */ }
26
  }, []);
27
 
28
  const loadAttendances = useCallback(async () => {
29
  try {
30
  const atts = await listAttendances({
31
  page, per_page: 20,
32
- section_id: filters.section_id ? Number(filters.section_id) : undefined,
33
  user_id: selectedStudent?.id,
34
  date_from: filters.date_from || undefined,
35
  date_to: filters.date_to || undefined,
@@ -53,10 +51,14 @@ export default function AttendanceReportsPage() {
53
  </div>
54
  <div className="flex gap-3 items-end flex-wrap">
55
  <div>
56
- <label className="block text-xs text-gray-500 mb-1">Sección</label>
57
- <select value={filters.section_id} onChange={(e) => { setFilters({ ...filters, section_id: e.target.value }); setPage(1); }} className="border border-gray-300 rounded-lg px-3 py-2" style={{ width: 'auto', minWidth: 160 }}>
58
- <option value="">Todas las secciones</option>
59
- {sections.map((s) => <option key={s.id} value={s.id}>{s.name} {s.subjects?.length ? `— ${s.subjects.map((sr) => sr.subject_name).filter(Boolean).join(', ')}` : ''}</option>)}
 
 
 
 
60
  </select>
61
  </div>
62
  <div>
@@ -69,9 +71,9 @@ export default function AttendanceReportsPage() {
69
  </div>
70
 
71
  <div>
72
- <label className="block text-xs text-gray-500 mb-1">Estudiante</label>
73
  <div className="relative" style={{ minWidth: 220 }}>
74
- <input placeholder="Buscar estudiante..." value={studentSearch}
75
  onChange={(e) => { setStudentSearch(e.target.value); setShowSuggestions(true); setSelectedStudent(null); }}
76
  onFocus={() => setShowSuggestions(true)}
77
  onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
@@ -99,6 +101,12 @@ export default function AttendanceReportsPage() {
99
  Limpiar filtro
100
  </button>
101
  )}
 
 
 
 
 
 
102
  </div>
103
 
104
  <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
@@ -115,38 +123,26 @@ export default function AttendanceReportsPage() {
115
  <table className="w-full text-sm min-w-[700px] lg:min-w-0">
116
  <thead>
117
  <tr className="border-b border-gray-200 text-left text-gray-500">
118
- <th className="pb-2 font-medium pl-3 pr-2 pt-2">Estudiante</th><th className="pb-2 font-medium pr-2 pt-2">Sección</th><th className="pb-2 font-medium pr-2 pt-2">Fecha / Hora</th><th className="pb-2 font-medium pr-2 pt-2">Tipo</th><th className="pb-2 font-medium pr-2 pt-2">Tardanza</th><th className="pb-2 font-medium pr-2 pt-2">Autorizado por</th><th className="pb-2 font-medium pr-2 pt-2">Nota</th><th className="pb-2 font-medium pt-2">Heatmap</th>
119
  </tr>
120
  </thead>
121
  <tbody>
122
  {items.length === 0 && <tr><td colSpan={8} className="text-gray-400 text-sm text-center py-8">Sin registros de asistencia</td></tr>}
123
- {items.map((a) => (
 
 
124
  <tr key={a.id} className="border-b border-gray-100">
125
  <td className="py-2 font-medium pl-3 pr-2">{a.user_lastname ? `${a.user_lastname}, ${a.user_name}` : `#${a.user_id}`}</td>
126
- <td className="py-2 text-gray-500 pr-2">{a.section_name || '-'}</td>
127
- <td className="py-2 text-gray-500 pr-2">{a.time_log ? new Date(a.time_log).toLocaleString() : '-'}</td>
128
- <td className="py-2 pr-2">
129
- {(() => {
130
- const act = a.action;
131
- if (act === 'in') return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">Entrada</span>;
132
- if (act === 'out') return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">Salida</span>;
133
- const note = a.note || '';
134
- const hasLateEntry = note.includes('RETRASO:');
135
- const hasEarlyExit = note.includes('SALIDA TEMPRANA:');
136
- if (hasLateEntry && hasEarlyExit) return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-700">Ambos</span>;
137
- if (hasLateEntry) return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">Entrada</span>;
138
- if (hasEarlyExit) return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700">Salida</span>;
139
- if (!!a.checkout_time) return <span className="inline-flex gap-1"><span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">Entrada</span><span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">Salida</span></span>;
140
- return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">Entrada</span>;
141
- })()}
142
- </td>
143
  <td className="py-2 pr-2">
144
  {a.is_late ? (
145
- <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700" title={a.late_reason || ''}>{a.late_reason}</span>
146
  ) : '-'}
147
  </td>
148
- <td className="py-2 text-gray-500 text-xs pr-2">{a.late_authorized_by || '-'}</td>
149
- <td className="py-2 text-gray-500 max-w-[150px] truncate text-xs pr-2" title={a.note || ''}>{a.note || '-'}</td>
150
  <td className="py-2">
151
  <button className="px-3 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-sm hover:bg-blue-50 hover:border-blue-300 transition-colors disabled:opacity-30 inline-flex items-center justify-center gap-2" title="Mapa de calor"
152
  onClick={() => setHeatmapTarget({ id: a.user_id, name: a.user_name ? `${a.user_lastname}, ${a.user_name}` : `#${a.user_id}` })}>
@@ -154,7 +150,8 @@ export default function AttendanceReportsPage() {
154
  </button>
155
  </td>
156
  </tr>
157
- ))}
 
158
  </tbody>
159
  </table>
160
  </div>
 
1
  import { useState, useEffect, useCallback } from 'react';
2
+ import { listAttendances, downloadReportCSV, type Attendance } from '../services/attendanceService';
 
3
  import { listUsers } from '../services/userService';
4
+ import type { User } from '../types';
5
+ import { BarChart3, Search, Download } from 'lucide-react';
6
+ import { translateRole } from '../utils/roles';
7
  import HeatmapModal from '../components/HeatmapModal';
8
 
9
  export default function AttendanceReportsPage() {
 
11
  const [total, setTotal] = useState(0);
12
  const [page, setPage] = useState(1);
13
  const [totalPages, setTotalPages] = useState(1);
 
14
  const [students, setStudents] = useState<User[]>([]);
15
+ const [filters, setFilters] = useState({ role: '', date_from: '', date_to: '' });
16
  const [studentSearch, setStudentSearch] = useState('');
17
  const [selectedStudent, setSelectedStudent] = useState<User | null>(null);
18
  const [showSuggestions, setShowSuggestions] = useState(false);
 
20
  const [tab, setTab] = useState<'all' | 'entry' | 'exit'>('all');
21
 
22
  const load = useCallback(async () => {
23
+ try { const stds = await listUsers({ is_active: '1', per_page: 500 }); setStudents(stds.items); } catch { /* ignore */ }
 
24
  }, []);
25
 
26
  const loadAttendances = useCallback(async () => {
27
  try {
28
  const atts = await listAttendances({
29
  page, per_page: 20,
30
+ role: filters.role || undefined,
31
  user_id: selectedStudent?.id,
32
  date_from: filters.date_from || undefined,
33
  date_to: filters.date_to || undefined,
 
51
  </div>
52
  <div className="flex gap-3 items-end flex-wrap">
53
  <div>
54
+ <label className="block text-xs text-gray-500 mb-1">Rol</label>
55
+ <select value={filters.role} onChange={(e) => { setFilters({ ...filters, role: e.target.value }); setPage(1); }} className="border border-gray-300 rounded-lg px-3 py-2" style={{ width: 'auto', minWidth: 160 }}>
56
+ <option value="">Todos los roles</option>
57
+ <option value="student">Estudiantes</option>
58
+ <option value="teacher">Docentes</option>
59
+ <option value="administrativo">Administrativos</option>
60
+ <option value="obrero">Obreros</option>
61
+ <option value="representative">Representantes</option>
62
  </select>
63
  </div>
64
  <div>
 
71
  </div>
72
 
73
  <div>
74
+ <label className="block text-xs text-gray-500 mb-1">Usuario</label>
75
  <div className="relative" style={{ minWidth: 220 }}>
76
+ <input placeholder="Buscar usuario..." value={studentSearch}
77
  onChange={(e) => { setStudentSearch(e.target.value); setShowSuggestions(true); setSelectedStudent(null); }}
78
  onFocus={() => setShowSuggestions(true)}
79
  onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
 
101
  Limpiar filtro
102
  </button>
103
  )}
104
+
105
+ <button
106
+ onClick={() => downloadReportCSV({ role: filters.role || undefined, date_from: filters.date_from || undefined, date_to: filters.date_to || undefined, user_id: selectedStudent?.id })}
107
+ className="px-3 py-2 bg-emerald-600 text-white rounded-lg text-sm hover:bg-emerald-700 transition-colors inline-flex items-center justify-center gap-2">
108
+ <Download size={16} /> Descargar CSV
109
+ </button>
110
  </div>
111
 
112
  <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
 
123
  <table className="w-full text-sm min-w-[700px] lg:min-w-0">
124
  <thead>
125
  <tr className="border-b border-gray-200 text-left text-gray-500">
126
+ <th className="pb-2 font-medium pl-3 pr-2 pt-2">Usuario</th><th className="pb-2 font-medium pr-2 pt-2">Rol</th><th className="pb-2 font-medium pr-2 pt-2">Cédula</th><th className="pb-2 font-medium pr-2 pt-2">Entrada</th><th className="pb-2 font-medium pr-2 pt-2">Salida</th><th className="pb-2 font-medium pr-2 pt-2">Tardanza</th><th className="pb-2 font-medium pr-2 pt-2">Nota</th><th className="pb-2 font-medium pt-2">Heatmap</th>
127
  </tr>
128
  </thead>
129
  <tbody>
130
  {items.length === 0 && <tr><td colSpan={8} className="text-gray-400 text-sm text-center py-8">Sin registros de asistencia</td></tr>}
131
+ {items.map((a) => {
132
+ const fmt = (s?: string | null) => s ? new Date(s).toLocaleString('es-VE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }) : null;
133
+ return (
134
  <tr key={a.id} className="border-b border-gray-100">
135
  <td className="py-2 font-medium pl-3 pr-2">{a.user_lastname ? `${a.user_lastname}, ${a.user_name}` : `#${a.user_id}`}</td>
136
+ <td className="py-2 text-gray-500 pr-2">{translateRole(a.role || undefined)}</td>
137
+ <td className="py-2 text-gray-500 font-mono text-xs pr-2">{a.card_id || '-'}</td>
138
+ <td className="py-2 text-gray-600 pr-2 tabular-nums">{fmt(a.time_log) || '-'}</td>
139
+ <td className="py-2 text-gray-600 pr-2 tabular-nums">{fmt(a.checkout_time) || '—'}</td>
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  <td className="py-2 pr-2">
141
  {a.is_late ? (
142
+ <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700" title={a.late_reason || ''}>{a.late_reason || 'Novedad'}</span>
143
  ) : '-'}
144
  </td>
145
+ <td className="py-2 text-gray-500 max-w-[180px] truncate text-xs pr-2" title={a.note || ''}>{a.note || '-'}</td>
 
146
  <td className="py-2">
147
  <button className="px-3 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-sm hover:bg-blue-50 hover:border-blue-300 transition-colors disabled:opacity-30 inline-flex items-center justify-center gap-2" title="Mapa de calor"
148
  onClick={() => setHeatmapTarget({ id: a.user_id, name: a.user_name ? `${a.user_lastname}, ${a.user_name}` : `#${a.user_id}` })}>
 
150
  </button>
151
  </td>
152
  </tr>
153
+ );
154
+ })}
155
  </tbody>
156
  </table>
157
  </div>
frontend/src/pages/EnrollmentsPage.tsx CHANGED
@@ -44,12 +44,19 @@ export default function EnrollmentsPage() {
44
  const [showCreateStudent, setShowCreateStudent] = useState(false);
45
  const [newStudentName, setNewStudentName] = useState('');
46
  const [newStudentLastname, setNewStudentLastname] = useState('');
 
 
 
47
  const [tooltip, setTooltip] = useState<{text: string; x: number; y: number} | null>(null);
48
  const [showEditModal, setShowEditModal] = useState(false);
49
  const [editStudent, setEditStudent] = useState<User | null>(null);
50
  const [editRepresentative, setEditRepresentative] = useState<User | null>(null);
51
  const [editForm, setEditForm] = useState({ name: '', lastname: '', card_id: '', birthdate: '', sex: '', phone_number: '', secondary_phone_number: '', email: '' });
52
  const [editParentForm, setEditParentForm] = useState({ name: '', lastname: '', phone_number: '', email: '' });
 
 
 
 
53
  const [showSchedule, setShowSchedule] = useState(false);
54
  const [scheduleSectionId, setScheduleSectionId] = useState(0);
55
  const [showBulkUpload, setShowBulkUpload] = useState(false);
@@ -75,6 +82,7 @@ export default function EnrollmentsPage() {
75
  useEffect(() => {
76
  listUsers({ role: 'student', per_page: 500 }).then((r) => setAllStudents(r.items)).catch(() => {});
77
  listUsers({ role: 'teacher', per_page: 200 }).then((r) => setAllTeachers(r.items)).catch(() => {});
 
78
  listSubjects({ per_page: 200 }).then((r) => setSubjects(r.items)).catch(() => {});
79
  loadAllEnrollments();
80
  }, []);
@@ -155,11 +163,14 @@ export default function EnrollmentsPage() {
155
  const created = await api.post('/users', {
156
  name: newStudentName.trim(), lastname: newStudentLastname.trim(),
157
  role: 'student', password: 'talos123',
 
158
  });
159
  const newStu = created.data;
160
  setAllStudents((prev) => [...prev, newStu]);
161
  setNewStudentName('');
162
  setNewStudentLastname('');
 
 
163
  setShowCreateStudent(false);
164
  if (!selectedStudentIds.includes(newStu.id)) {
165
  setSelectedStudentIds((prev) => [...prev, newStu.id]);
@@ -252,6 +263,9 @@ export default function EnrollmentsPage() {
252
 
253
  const openEditStudent = async (student: User) => {
254
  setEditStudent(student);
 
 
 
255
  setEditForm({
256
  name: student.name, lastname: student.lastname,
257
  card_id: student.card_id || '', birthdate: student.birthdate || '', sex: student.sex || '',
@@ -292,7 +306,11 @@ export default function EnrollmentsPage() {
292
  setEditStudent(updated);
293
  }
294
 
295
- if (editParentForm.name || editParentForm.lastname) {
 
 
 
 
296
  const parentPayload: Record<string, any> = {
297
  role: 'representative', name: editParentForm.name, lastname: editParentForm.lastname,
298
  phone_number: editParentForm.phone_number || null, email: editParentForm.email || null,
@@ -379,7 +397,7 @@ export default function EnrollmentsPage() {
379
  className="border border-gray-300 rounded-lg px-3 py-2" style={{ width: 'auto', minWidth: 260 }}>
380
  {sections.map((s) => (
381
  <option key={s.id} value={s.id}>
382
- {s.name}{s.level ? ` (${s.level})` : ''} {s.subjects?.length ? `— ${s.subjects.map((sr) => sr.subject_name).filter(Boolean).join(', ')}` : ''}
383
  </option>
384
  ))}
385
  </select>
@@ -514,8 +532,38 @@ export default function EnrollmentsPage() {
514
  <input placeholder="Nombre *" value={newStudentName} onChange={(e) => setNewStudentName(e.target.value)} className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm" />
515
  <input placeholder="Apellido *" value={newStudentLastname} onChange={(e) => setNewStudentLastname(e.target.value)} className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm" />
516
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  <div className="flex justify-end gap-2">
518
- <button type="button" className="bg-gray-200 text-gray-700 px-3 py-1.5 rounded-lg hover:bg-gray-300 transition text-sm" onClick={() => { setShowCreateStudent(false); setNewStudentName(''); setNewStudentLastname(''); }}>
519
  Cancelar
520
  </button>
521
  <button type="button" className="bg-green-600 text-white px-3 py-1.5 rounded-lg hover:bg-green-700 transition text-sm" onClick={handleCreateStudent} disabled={!newStudentName.trim() || !newStudentLastname.trim()}>
@@ -746,6 +794,41 @@ export default function EnrollmentsPage() {
746
  </div>
747
  <div className="border-t border-gray-200 pt-4">
748
  <h3 className="text-lg font-semibold mb-3">Datos del Representante</h3>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
750
  <div>
751
  <label className="block text-sm font-medium text-gray-700 mb-1">Nombre</label>
@@ -768,6 +851,7 @@ export default function EnrollmentsPage() {
768
  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
769
  </div>
770
  </div>
 
771
  </div>
772
  <div className="flex justify-end gap-2 pt-2">
773
  <button type="button" className="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition text-sm" onClick={() => setShowEditModal(false)}>
 
44
  const [showCreateStudent, setShowCreateStudent] = useState(false);
45
  const [newStudentName, setNewStudentName] = useState('');
46
  const [newStudentLastname, setNewStudentLastname] = useState('');
47
+ const [newStudentRepId, setNewStudentRepId] = useState<number | null>(null);
48
+ const [newRepSearch, setNewRepSearch] = useState('');
49
+ const [showNewRepSug, setShowNewRepSug] = useState(false);
50
  const [tooltip, setTooltip] = useState<{text: string; x: number; y: number} | null>(null);
51
  const [showEditModal, setShowEditModal] = useState(false);
52
  const [editStudent, setEditStudent] = useState<User | null>(null);
53
  const [editRepresentative, setEditRepresentative] = useState<User | null>(null);
54
  const [editForm, setEditForm] = useState({ name: '', lastname: '', card_id: '', birthdate: '', sex: '', phone_number: '', secondary_phone_number: '', email: '' });
55
  const [editParentForm, setEditParentForm] = useState({ name: '', lastname: '', phone_number: '', email: '' });
56
+ const [allReps, setAllReps] = useState<User[]>([]);
57
+ const [linkRepId, setLinkRepId] = useState<number | null>(null);
58
+ const [repSearch, setRepSearch] = useState('');
59
+ const [showRepSug, setShowRepSug] = useState(false);
60
  const [showSchedule, setShowSchedule] = useState(false);
61
  const [scheduleSectionId, setScheduleSectionId] = useState(0);
62
  const [showBulkUpload, setShowBulkUpload] = useState(false);
 
82
  useEffect(() => {
83
  listUsers({ role: 'student', per_page: 500 }).then((r) => setAllStudents(r.items)).catch(() => {});
84
  listUsers({ role: 'teacher', per_page: 200 }).then((r) => setAllTeachers(r.items)).catch(() => {});
85
+ listUsers({ role: 'representative', per_page: 500 }).then((r) => setAllReps(r.items)).catch(() => {});
86
  listSubjects({ per_page: 200 }).then((r) => setSubjects(r.items)).catch(() => {});
87
  loadAllEnrollments();
88
  }, []);
 
163
  const created = await api.post('/users', {
164
  name: newStudentName.trim(), lastname: newStudentLastname.trim(),
165
  role: 'student', password: 'talos123',
166
+ ...(newStudentRepId ? { parent_id: newStudentRepId } : {}),
167
  });
168
  const newStu = created.data;
169
  setAllStudents((prev) => [...prev, newStu]);
170
  setNewStudentName('');
171
  setNewStudentLastname('');
172
+ setNewStudentRepId(null);
173
+ setNewRepSearch('');
174
  setShowCreateStudent(false);
175
  if (!selectedStudentIds.includes(newStu.id)) {
176
  setSelectedStudentIds((prev) => [...prev, newStu.id]);
 
263
 
264
  const openEditStudent = async (student: User) => {
265
  setEditStudent(student);
266
+ setLinkRepId(null);
267
+ setRepSearch('');
268
+ setShowRepSug(false);
269
  setEditForm({
270
  name: student.name, lastname: student.lastname,
271
  card_id: student.card_id || '', birthdate: student.birthdate || '', sex: student.sex || '',
 
306
  setEditStudent(updated);
307
  }
308
 
309
+ if (linkRepId) {
310
+ // Vincular a un representante EXISTENTE (emparejar otro hijo al mismo padre)
311
+ await updateUser(editStudent.id, { parent_id: linkRepId });
312
+ setAllStudents((prev) => prev.map((s) => s.id === editStudent.id ? { ...s, parent_id: linkRepId } : s));
313
+ } else if (editParentForm.name || editParentForm.lastname) {
314
  const parentPayload: Record<string, any> = {
315
  role: 'representative', name: editParentForm.name, lastname: editParentForm.lastname,
316
  phone_number: editParentForm.phone_number || null, email: editParentForm.email || null,
 
397
  className="border border-gray-300 rounded-lg px-3 py-2" style={{ width: 'auto', minWidth: 260 }}>
398
  {sections.map((s) => (
399
  <option key={s.id} value={s.id}>
400
+ {s.name}{s.level ? ` (${s.level})` : ''}
401
  </option>
402
  ))}
403
  </select>
 
532
  <input placeholder="Nombre *" value={newStudentName} onChange={(e) => setNewStudentName(e.target.value)} className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm" />
533
  <input placeholder="Apellido *" value={newStudentLastname} onChange={(e) => setNewStudentLastname(e.target.value)} className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm" />
534
  </div>
535
+ <div className="relative">
536
+ {newStudentRepId ? (
537
+ <div className="flex items-center gap-2 bg-blue-50 border border-blue-200 rounded-lg px-3 py-1.5 text-sm">
538
+ <span className="text-blue-700">Representante: <b>{newRepSearch}</b></span>
539
+ <button type="button" className="ml-auto text-gray-400 hover:text-gray-600 text-lg leading-none" onClick={() => { setNewStudentRepId(null); setNewRepSearch(''); }}>&times;</button>
540
+ </div>
541
+ ) : (
542
+ <>
543
+ <input value={newRepSearch} placeholder="Representante (opcional) — buscar por nombre o cédula"
544
+ onChange={(e) => { setNewRepSearch(e.target.value); setShowNewRepSug(true); }}
545
+ onFocus={() => setShowNewRepSug(true)}
546
+ onBlur={() => setTimeout(() => setShowNewRepSug(false), 200)}
547
+ className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
548
+ {showNewRepSug && newRepSearch && (() => {
549
+ const matches = allReps.filter((r) => `${r.lastname} ${r.name}`.toLowerCase().includes(newRepSearch.toLowerCase()) || (r.card_id || '').toLowerCase().includes(newRepSearch.toLowerCase())).slice(0, 8);
550
+ return (
551
+ <div className="absolute z-10 left-0 right-0 bg-white rounded-lg shadow-lg border border-gray-200 mt-1 max-h-40 overflow-y-auto">
552
+ {matches.length === 0 && <div className="px-3 py-2 text-sm text-gray-400">Sin representantes con ese criterio</div>}
553
+ {matches.map((r) => (
554
+ <div key={r.id} className="px-3 py-2 text-sm cursor-pointer hover:bg-gray-50"
555
+ onMouseDown={() => { setNewStudentRepId(r.id); setNewRepSearch(`${r.lastname}, ${r.name}`); setShowNewRepSug(false); }}>
556
+ {r.lastname}, {r.name} {r.card_id ? `(${r.card_id})` : ''}
557
+ </div>
558
+ ))}
559
+ </div>
560
+ );
561
+ })()}
562
+ </>
563
+ )}
564
+ </div>
565
  <div className="flex justify-end gap-2">
566
+ <button type="button" className="bg-gray-200 text-gray-700 px-3 py-1.5 rounded-lg hover:bg-gray-300 transition text-sm" onClick={() => { setShowCreateStudent(false); setNewStudentName(''); setNewStudentLastname(''); setNewStudentRepId(null); setNewRepSearch(''); }}>
567
  Cancelar
568
  </button>
569
  <button type="button" className="bg-green-600 text-white px-3 py-1.5 rounded-lg hover:bg-green-700 transition text-sm" onClick={handleCreateStudent} disabled={!newStudentName.trim() || !newStudentLastname.trim()}>
 
794
  </div>
795
  <div className="border-t border-gray-200 pt-4">
796
  <h3 className="text-lg font-semibold mb-3">Datos del Representante</h3>
797
+
798
+ <div className="relative mb-3">
799
+ <label className="block text-sm font-medium text-gray-700 mb-1">Vincular a representante existente</label>
800
+ {linkRepId ? (
801
+ <div className="flex items-center gap-2 bg-blue-50 border border-blue-200 rounded-lg px-3 py-2 text-sm">
802
+ <span className="text-blue-700">Se vinculará a: <b>{repSearch}</b></span>
803
+ <button type="button" className="ml-auto text-gray-400 hover:text-gray-600 text-lg leading-none" onClick={() => { setLinkRepId(null); setRepSearch(''); }}>&times;</button>
804
+ </div>
805
+ ) : (
806
+ <>
807
+ <input value={repSearch} placeholder="Buscar por nombre o cédula..."
808
+ onChange={(e) => { setRepSearch(e.target.value); setShowRepSug(true); }}
809
+ onFocus={() => setShowRepSug(true)}
810
+ onBlur={() => setTimeout(() => setShowRepSug(false), 200)}
811
+ className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
812
+ {showRepSug && repSearch && (() => {
813
+ const matches = allReps.filter((r) => `${r.lastname} ${r.name}`.toLowerCase().includes(repSearch.toLowerCase()) || (r.card_id || '').toLowerCase().includes(repSearch.toLowerCase())).slice(0, 8);
814
+ return (
815
+ <div className="absolute z-10 left-0 right-0 bg-white rounded-lg shadow-lg border border-gray-200 mt-1 max-h-44 overflow-y-auto">
816
+ {matches.length === 0 && <div className="px-3 py-2 text-sm text-gray-400">Sin representantes con ese criterio</div>}
817
+ {matches.map((r) => (
818
+ <div key={r.id} className="px-3 py-2 text-sm cursor-pointer hover:bg-gray-50"
819
+ onMouseDown={() => { setLinkRepId(r.id); setRepSearch(`${r.lastname}, ${r.name}`); setShowRepSug(false); }}>
820
+ {r.lastname}, {r.name} {r.card_id ? `(${r.card_id})` : ''}
821
+ </div>
822
+ ))}
823
+ </div>
824
+ );
825
+ })()}
826
+ <p className="text-xs text-gray-400 mt-1">Si el padre ya existe (otro hijo inscrito), búscalo aquí. Si no, créalo abajo.</p>
827
+ </>
828
+ )}
829
+ </div>
830
+
831
+ {!linkRepId && (
832
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
833
  <div>
834
  <label className="block text-sm font-medium text-gray-700 mb-1">Nombre</label>
 
851
  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
852
  </div>
853
  </div>
854
+ )}
855
  </div>
856
  <div className="flex justify-end gap-2 pt-2">
857
  <button type="button" className="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition text-sm" onClick={() => setShowEditModal(false)}>
frontend/src/pages/LateArrivalsPage.tsx CHANGED
@@ -1,11 +1,14 @@
1
  import { useState, useEffect } from 'react';
2
  import api from '../services/api';
 
 
3
 
4
  interface LateArrival {
5
  student_id: number;
6
  student_name: string;
7
  student_lastname: string;
8
  card_id: string | null;
 
9
  section_name: string | null;
10
  late_count: number;
11
  early_departure_count: number;
@@ -15,20 +18,38 @@ interface LateArrival {
15
 
16
  export default function LateArrivalsPage() {
17
  const [items, setItems] = useState<LateArrival[]>([]);
 
18
  const [dateFrom, setDateFrom] = useState(() => {
19
  const d = new Date(); d.setDate(d.getDate() - 30);
20
  return d.toISOString().split('T')[0];
21
  });
22
  const [dateTo, setDateTo] = useState(() => new Date().toISOString().split('T')[0]);
23
 
 
 
 
 
 
 
 
 
24
  const load = async () => {
25
  try {
26
- const { data } = await api.get(`/reports/late-arrivals?date_from=${dateFrom}&date_to=${dateTo}`);
27
  setItems(data.items);
28
  } catch { /* ignore */ }
29
  };
30
 
31
- useEffect(() => { load(); }, [dateFrom, dateTo]);
 
 
 
 
 
 
 
 
 
32
 
33
  return (
34
  <div className="space-y-6">
@@ -37,6 +58,17 @@ export default function LateArrivalsPage() {
37
  </div>
38
 
39
  <div className="flex gap-3 items-end flex-wrap">
 
 
 
 
 
 
 
 
 
 
 
40
  <div>
41
  <label className="block text-xs text-gray-500 mb-1">Desde</label>
42
  <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} className="border border-gray-300 rounded-lg px-3 py-2 text-sm" />
@@ -45,6 +77,10 @@ export default function LateArrivalsPage() {
45
  <label className="block text-xs text-gray-500 mb-1">Hasta</label>
46
  <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} className="border border-gray-300 rounded-lg px-3 py-2 text-sm" />
47
  </div>
 
 
 
 
48
  </div>
49
 
50
  <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
@@ -55,7 +91,8 @@ export default function LateArrivalsPage() {
55
  <table className="w-full text-sm min-w-[600px]">
56
  <thead>
57
  <tr className="border-b border-gray-200 text-left text-gray-500">
58
- <th className="pb-2 font-medium pl-3 pr-2 pt-2">Estudiante</th>
 
59
  <th className="pb-2 font-medium pr-2 pt-2">Cédula</th>
60
  <th className="pb-2 font-medium pr-2 pt-2 text-center">Tardanzas</th>
61
  <th className="pb-2 font-medium pr-2 pt-2 text-center">Salidas Tempranas</th>
@@ -66,7 +103,8 @@ export default function LateArrivalsPage() {
66
  <tbody>
67
  {items.map((item) => (
68
  <tr key={item.student_id} className="border-b border-gray-100 hover:bg-gray-50/50">
69
- <td className="py-2 pl-3 pr-2 font-medium">{item.student_name} {item.student_lastname}</td>
 
70
  <td className="py-2 pr-2 text-gray-500">{item.card_id || '-'}</td>
71
  <td className="py-2 pr-2 text-center">
72
  <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
 
1
  import { useState, useEffect } from 'react';
2
  import api from '../services/api';
3
+ import { Download } from 'lucide-react';
4
+ import { translateRole } from '../utils/roles';
5
 
6
  interface LateArrival {
7
  student_id: number;
8
  student_name: string;
9
  student_lastname: string;
10
  card_id: string | null;
11
+ role: string | null;
12
  section_name: string | null;
13
  late_count: number;
14
  early_departure_count: number;
 
18
 
19
  export default function LateArrivalsPage() {
20
  const [items, setItems] = useState<LateArrival[]>([]);
21
+ const [roleFilter, setRoleFilter] = useState('');
22
  const [dateFrom, setDateFrom] = useState(() => {
23
  const d = new Date(); d.setDate(d.getDate() - 30);
24
  return d.toISOString().split('T')[0];
25
  });
26
  const [dateTo, setDateTo] = useState(() => new Date().toISOString().split('T')[0]);
27
 
28
+ const buildParams = () => {
29
+ const params = new URLSearchParams();
30
+ if (dateFrom) params.set('date_from', dateFrom);
31
+ if (dateTo) params.set('date_to', dateTo);
32
+ if (roleFilter) params.set('role', roleFilter);
33
+ return params;
34
+ };
35
+
36
  const load = async () => {
37
  try {
38
+ const { data } = await api.get(`/reports/late-arrivals?${buildParams()}`);
39
  setItems(data.items);
40
  } catch { /* ignore */ }
41
  };
42
 
43
+ const downloadCSV = async () => {
44
+ try {
45
+ const { data } = await api.get(`/reports/late-arrivals-export?${buildParams()}`, { responseType: 'blob' });
46
+ const url = URL.createObjectURL(data);
47
+ const a = document.createElement('a'); a.href = url; a.download = 'tardanzas.csv'; a.click();
48
+ URL.revokeObjectURL(url);
49
+ } catch { /* ignore */ }
50
+ };
51
+
52
+ useEffect(() => { load(); }, [dateFrom, dateTo, roleFilter]);
53
 
54
  return (
55
  <div className="space-y-6">
 
58
  </div>
59
 
60
  <div className="flex gap-3 items-end flex-wrap">
61
+ <div>
62
+ <label className="block text-xs text-gray-500 mb-1">Rol</label>
63
+ <select value={roleFilter} onChange={(e) => setRoleFilter(e.target.value)} className="border border-gray-300 rounded-lg px-3 py-2 text-sm" style={{ minWidth: 150 }}>
64
+ <option value="">Todos los roles</option>
65
+ <option value="student">Estudiantes</option>
66
+ <option value="teacher">Docentes</option>
67
+ <option value="administrativo">Administrativos</option>
68
+ <option value="obrero">Obreros</option>
69
+ <option value="representative">Representantes</option>
70
+ </select>
71
+ </div>
72
  <div>
73
  <label className="block text-xs text-gray-500 mb-1">Desde</label>
74
  <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} className="border border-gray-300 rounded-lg px-3 py-2 text-sm" />
 
77
  <label className="block text-xs text-gray-500 mb-1">Hasta</label>
78
  <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} className="border border-gray-300 rounded-lg px-3 py-2 text-sm" />
79
  </div>
80
+ <button onClick={downloadCSV}
81
+ className="px-3 py-2 bg-emerald-600 text-white rounded-lg text-sm hover:bg-emerald-700 transition-colors inline-flex items-center justify-center gap-2">
82
+ <Download size={16} /> Descargar CSV
83
+ </button>
84
  </div>
85
 
86
  <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
 
91
  <table className="w-full text-sm min-w-[600px]">
92
  <thead>
93
  <tr className="border-b border-gray-200 text-left text-gray-500">
94
+ <th className="pb-2 font-medium pl-3 pr-2 pt-2">Usuario</th>
95
+ <th className="pb-2 font-medium pr-2 pt-2">Rol</th>
96
  <th className="pb-2 font-medium pr-2 pt-2">Cédula</th>
97
  <th className="pb-2 font-medium pr-2 pt-2 text-center">Tardanzas</th>
98
  <th className="pb-2 font-medium pr-2 pt-2 text-center">Salidas Tempranas</th>
 
103
  <tbody>
104
  {items.map((item) => (
105
  <tr key={item.student_id} className="border-b border-gray-100 hover:bg-gray-50/50">
106
+ <td className="py-2 pl-3 pr-2 font-medium">{item.student_lastname}, {item.student_name}</td>
107
+ <td className="py-2 pr-2 text-gray-500">{translateRole(item.role || undefined)}</td>
108
  <td className="py-2 pr-2 text-gray-500">{item.card_id || '-'}</td>
109
  <td className="py-2 pr-2 text-center">
110
  <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
frontend/src/pages/PublicCheckInPage.tsx CHANGED
@@ -52,6 +52,7 @@ export default function PublicCheckInPage() {
52
  const [cardId, setCardId] = useState('');
53
  const inputRef = useRef<HTMLInputElement>(null);
54
  const pollRef = useRef<ReturnType<typeof setInterval>>();
 
55
 
56
  const [showReasonModal, setShowReasonModal] = useState(false);
57
  const [reasonType, setReasonType] = useState<'late_entry' | 'late_checkout' | 'early_checkout' | null>(null);
@@ -108,7 +109,9 @@ export default function PublicCheckInPage() {
108
 
109
  const refreshMode = useCallback(() => {
110
  getCurrentMode().then((m: CurrentMode) => {
111
- setMode(m.mode as 'in' | 'out');
 
 
112
  setActive(m.active ?? false);
113
  setSchedule(m.schedule);
114
  setTolerance(m.tolerance ?? 15);
@@ -140,7 +143,7 @@ export default function PublicCheckInPage() {
140
  try {
141
  let data: any;
142
  if (method === 'manual') {
143
- const body: any = {};
144
  if (cardId.trim()) body.card_id = cardId.trim();
145
  if (lateNote) body.late_note = lateNote;
146
  const r = await api.post('/attendances/self', body);
@@ -148,7 +151,7 @@ export default function PublicCheckInPage() {
148
  } else {
149
  const image = captureImage();
150
  if (!image) { showResult(false, 'No se pudo capturar la imagen'); setLoading(false); return; }
151
- const r = await api.post('/facial/self', { image, late_note: lateNote });
152
  data = r.data;
153
  }
154
 
@@ -234,14 +237,16 @@ export default function PublicCheckInPage() {
234
 
235
  <div className="flex rounded-xl bg-gray-100 p-1">
236
  <button
237
- className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors ${mode === 'in' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-400 cursor-not-allowed'}`}
238
- disabled={mode !== 'in'}
 
239
  >
240
  Entrada
241
  </button>
242
  <button
243
- className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors ${mode === 'out' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-400 cursor-not-allowed'}`}
244
- disabled={mode !== 'out'}
 
245
  >
246
  Salida
247
  </button>
 
52
  const [cardId, setCardId] = useState('');
53
  const inputRef = useRef<HTMLInputElement>(null);
54
  const pollRef = useRef<ReturnType<typeof setInterval>>();
55
+ const modeInitRef = useRef(false);
56
 
57
  const [showReasonModal, setShowReasonModal] = useState(false);
58
  const [reasonType, setReasonType] = useState<'late_entry' | 'late_checkout' | 'early_checkout' | null>(null);
 
109
 
110
  const refreshMode = useCallback(() => {
111
  getCurrentMode().then((m: CurrentMode) => {
112
+ // El toggle es manual: solo sugerimos el modo inicial una vez; luego no
113
+ // pisamos la selección del usuario en cada poll.
114
+ if (!modeInitRef.current) { setMode(m.mode as 'in' | 'out'); modeInitRef.current = true; }
115
  setActive(m.active ?? false);
116
  setSchedule(m.schedule);
117
  setTolerance(m.tolerance ?? 15);
 
143
  try {
144
  let data: any;
145
  if (method === 'manual') {
146
+ const body: any = { action: mode };
147
  if (cardId.trim()) body.card_id = cardId.trim();
148
  if (lateNote) body.late_note = lateNote;
149
  const r = await api.post('/attendances/self', body);
 
151
  } else {
152
  const image = captureImage();
153
  if (!image) { showResult(false, 'No se pudo capturar la imagen'); setLoading(false); return; }
154
+ const r = await api.post('/facial/self', { image, late_note: lateNote, action: mode });
155
  data = r.data;
156
  }
157
 
 
237
 
238
  <div className="flex rounded-xl bg-gray-100 p-1">
239
  <button
240
+ type="button"
241
+ onClick={() => setMode('in')}
242
+ className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors ${mode === 'in' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
243
  >
244
  Entrada
245
  </button>
246
  <button
247
+ type="button"
248
+ onClick={() => setMode('out')}
249
+ className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors ${mode === 'out' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
250
  >
251
  Salida
252
  </button>
frontend/src/pages/RepresentativeChildrenPage.tsx CHANGED
@@ -1,6 +1,9 @@
1
  import { useState, useEffect } from 'react';
2
  import { getMyChildren, ChildAttendance } from '../services/representativeService';
3
- import { Clock, CheckCircle, XCircle, ChevronDown, ChevronUp, Calendar } from 'lucide-react';
 
 
 
4
 
5
  const STATUS_COLORS: Record<string, string> = {
6
  active: 'bg-green-500',
@@ -54,7 +57,7 @@ export default function RepresentativeChildrenPage() {
54
  <div className="p-5">
55
  <div className="flex items-start justify-between">
56
  <div className="flex items-center gap-3">
57
- <div className={`w-3 h-3 rounded-full ${child.is_present_today ? 'bg-green-500' : 'bg-red-400'}`} />
58
  <div>
59
  <h2 className="text-lg font-semibold">
60
  {child.name} {child.lastname}
@@ -72,31 +75,45 @@ export default function RepresentativeChildrenPage() {
72
  </button>
73
  </div>
74
 
 
 
 
 
 
 
 
75
  <div className="mt-4 grid grid-cols-2 gap-3">
76
  <div className="bg-gray-50 rounded-xl p-3">
77
  <div className="flex items-center gap-2 text-sm text-gray-600 mb-1">
78
- <CheckCircle size={14} />
79
- <span>Estado hoy</span>
80
  </div>
81
- <span className={`font-semibold ${child.is_present_today ? 'text-green-600' : 'text-red-500'}`}>
82
- {child.is_present_today ? 'Presente' : 'Ausente'}
83
  </span>
84
- {child.checkin_time && (
85
  <p className="text-xs text-gray-400 mt-0.5">
86
- {new Date(child.checkin_time).toLocaleTimeString('es-VE', { hour: '2-digit', minute: '2-digit' })}
 
87
  </p>
88
  )}
89
  </div>
90
  <div className="bg-gray-50 rounded-xl p-3">
91
  <div className="flex items-center gap-2 text-sm text-gray-600 mb-1">
92
- <Calendar size={14} />
93
- <span>Últimos 30 días</span>
94
  </div>
95
- <span className="font-semibold text-blue-600">
96
- {child.attendance_last_30_days} asistencias
97
  </span>
 
 
 
98
  </div>
99
  </div>
 
 
 
100
  </div>
101
 
102
  {expanded === child.id && child.today_schedule && (
 
1
  import { useState, useEffect } from 'react';
2
  import { getMyChildren, ChildAttendance } from '../services/representativeService';
3
+ import { Clock, CheckCircle, ChevronDown, ChevronUp, Calendar, AlertTriangle, Building2 } from 'lucide-react';
4
+
5
+ const fmtTime = (t: string | null) =>
6
+ t ? new Date(t).toLocaleTimeString('es-VE', { hour: '2-digit', minute: '2-digit' }) : '';
7
 
8
  const STATUS_COLORS: Record<string, string> = {
9
  active: 'bg-green-500',
 
57
  <div className="p-5">
58
  <div className="flex items-start justify-between">
59
  <div className="flex items-center gap-3">
60
+ <div className={`w-3 h-3 rounded-full ${child.entered_campus_today ? 'bg-green-500' : 'bg-red-400'}`} />
61
  <div>
62
  <h2 className="text-lg font-semibold">
63
  {child.name} {child.lastname}
 
75
  </button>
76
  </div>
77
 
78
+ {child.skipped_class && (
79
+ <div className="mt-3 flex items-start gap-2 bg-amber-50 border border-amber-200 rounded-xl px-3 py-2 text-amber-800 text-sm">
80
+ <AlertTriangle size={16} className="shrink-0 mt-0.5" />
81
+ <span>Ingresó al plantel pero <b>no fue marcado en clase</b>.</span>
82
+ </div>
83
+ )}
84
+
85
  <div className="mt-4 grid grid-cols-2 gap-3">
86
  <div className="bg-gray-50 rounded-xl p-3">
87
  <div className="flex items-center gap-2 text-sm text-gray-600 mb-1">
88
+ <Building2 size={14} />
89
+ <span>En el plantel</span>
90
  </div>
91
+ <span className={`font-semibold ${child.entered_campus_today ? 'text-green-600' : 'text-red-500'}`}>
92
+ {child.entered_campus_today ? 'Ingresó' : 'No ingresó'}
93
  </span>
94
+ {child.campus_checkin_time && (
95
  <p className="text-xs text-gray-400 mt-0.5">
96
+ Entrada {fmtTime(child.campus_checkin_time)}
97
+ {child.campus_checkout_time ? ` · Salida ${fmtTime(child.campus_checkout_time)}` : ''}
98
  </p>
99
  )}
100
  </div>
101
  <div className="bg-gray-50 rounded-xl p-3">
102
  <div className="flex items-center gap-2 text-sm text-gray-600 mb-1">
103
+ <CheckCircle size={14} />
104
+ <span>En clase</span>
105
  </div>
106
+ <span className={`font-semibold ${child.is_present_today ? 'text-green-600' : 'text-red-500'}`}>
107
+ {child.is_present_today ? 'Presente' : 'Ausente'}
108
  </span>
109
+ {child.checkin_time && (
110
+ <p className="text-xs text-gray-400 mt-0.5">{fmtTime(child.checkin_time)}</p>
111
+ )}
112
  </div>
113
  </div>
114
+ <p className="text-xs text-gray-400 mt-2 flex items-center gap-1">
115
+ <Calendar size={12} /> {child.attendance_last_30_days} asistencias a clase (últimos 30 días)
116
+ </p>
117
  </div>
118
 
119
  {expanded === child.id && child.today_schedule && (
frontend/src/pages/StudentReportPage.tsx ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+ import api from '../services/api';
3
+ import { AlertTriangle, Search } from 'lucide-react';
4
+
5
+ interface StudentRow {
6
+ id: number;
7
+ name: string;
8
+ lastname: string;
9
+ card_id: string | null;
10
+ section_names: string[];
11
+ campus_days: number;
12
+ class_days: number;
13
+ skipped_class_days: number;
14
+ attendance_rate: number;
15
+ }
16
+
17
+ export default function StudentReportPage() {
18
+ const [items, setItems] = useState<StudentRow[]>([]);
19
+ const [nameFilter, setNameFilter] = useState('');
20
+ const [sectionFilter, setSectionFilter] = useState('');
21
+ const [cardFilter, setCardFilter] = useState('');
22
+
23
+ useEffect(() => {
24
+ api.get('/reports/students').then(({ data }) => setItems(data)).catch(() => {});
25
+ }, []);
26
+
27
+ const sectionOptions = Array.from(new Set(items.flatMap((i) => i.section_names))).sort();
28
+
29
+ const filtered = items.filter((s) => {
30
+ const nameOk = !nameFilter || `${s.lastname} ${s.name}`.toLowerCase().includes(nameFilter.toLowerCase());
31
+ const cardOk = !cardFilter || (s.card_id || '').toLowerCase().includes(cardFilter.toLowerCase());
32
+ const secOk = !sectionFilter || s.section_names.includes(sectionFilter);
33
+ return nameOk && cardOk && secOk;
34
+ });
35
+
36
+ return (
37
+ <div className="space-y-6">
38
+ <div className="flex items-center justify-between">
39
+ <h1>Reporte de Estudiantes</h1>
40
+ <span className="text-sm text-gray-400">{filtered.length} de {items.length}</span>
41
+ </div>
42
+ <p className="text-sm text-gray-500">
43
+ Asistencia del mes con criterio dual: <b>días que ingresó al plantel</b> (portón) vs. <b>días marcado en clase</b> (docente).
44
+ Resalta a quienes vienen al colegio pero no entran a clase.
45
+ </p>
46
+
47
+ <div className="flex gap-3 items-end flex-wrap">
48
+ <div>
49
+ <label className="block text-xs text-gray-500 mb-1">Nombre</label>
50
+ <div className="relative" style={{ minWidth: 200 }}>
51
+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
52
+ <input value={nameFilter} onChange={(e) => setNameFilter(e.target.value)} placeholder="Buscar por nombre..."
53
+ className="w-full border border-gray-300 rounded-lg pl-8 pr-3 py-2 text-sm" />
54
+ </div>
55
+ </div>
56
+ <div>
57
+ <label className="block text-xs text-gray-500 mb-1">Sección</label>
58
+ <select value={sectionFilter} onChange={(e) => setSectionFilter(e.target.value)} className="border border-gray-300 rounded-lg px-3 py-2 text-sm" style={{ minWidth: 160 }}>
59
+ <option value="">Todas las secciones</option>
60
+ {sectionOptions.map((s) => <option key={s} value={s}>{s}</option>)}
61
+ </select>
62
+ </div>
63
+ <div>
64
+ <label className="block text-xs text-gray-500 mb-1">Cédula</label>
65
+ <div className="relative" style={{ minWidth: 160 }}>
66
+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
67
+ <input value={cardFilter} onChange={(e) => setCardFilter(e.target.value)} placeholder="Buscar por cédula..."
68
+ className="w-full border border-gray-300 rounded-lg pl-8 pr-3 py-2 text-sm" />
69
+ </div>
70
+ </div>
71
+ {(nameFilter || sectionFilter || cardFilter) && (
72
+ <button onClick={() => { setNameFilter(''); setSectionFilter(''); setCardFilter(''); }}
73
+ className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm hover:bg-blue-50 hover:border-blue-300 transition-colors">
74
+ Limpiar filtros
75
+ </button>
76
+ )}
77
+ </div>
78
+
79
+ <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
80
+ {filtered.length === 0 ? (
81
+ <div className="text-center text-gray-400 py-12 text-sm">Sin resultados</div>
82
+ ) : (
83
+ <div className="overflow-x-auto">
84
+ <table className="w-full text-sm min-w-[760px]">
85
+ <thead>
86
+ <tr className="border-b border-gray-200 text-left text-gray-500">
87
+ <th className="pb-2 font-medium pl-3 pr-2 pt-2">Estudiante</th>
88
+ <th className="pb-2 font-medium pr-2 pt-2">Sección</th>
89
+ <th className="pb-2 font-medium pr-2 pt-2">Cédula</th>
90
+ <th className="pb-2 font-medium pr-2 pt-2 text-center">En el plantel</th>
91
+ <th className="pb-2 font-medium pr-2 pt-2 text-center">En clase</th>
92
+ <th className="pb-2 font-medium pr-2 pt-2 text-center">Saltó clase</th>
93
+ <th className="pb-2 font-medium pr-2 pt-2 text-center">% clase</th>
94
+ </tr>
95
+ </thead>
96
+ <tbody>
97
+ {filtered.map((s) => (
98
+ <tr key={s.id} className={`border-b border-gray-100 ${s.skipped_class_days > 0 ? 'bg-amber-50/40' : ''}`}>
99
+ <td className="py-2 pl-3 pr-2 font-medium">{s.lastname}, {s.name}</td>
100
+ <td className="py-2 pr-2 text-gray-500">{s.section_names.join(', ') || '-'}</td>
101
+ <td className="py-2 pr-2 text-gray-500 font-mono text-xs">{s.card_id || '-'}</td>
102
+ <td className="py-2 pr-2 text-center text-gray-700">{s.campus_days} d</td>
103
+ <td className="py-2 pr-2 text-center text-gray-700">{s.class_days} d</td>
104
+ <td className="py-2 pr-2 text-center">
105
+ {s.skipped_class_days > 0 ? (
106
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700">
107
+ <AlertTriangle size={12} /> {s.skipped_class_days} d
108
+ </span>
109
+ ) : (
110
+ <span className="text-gray-400">0 d</span>
111
+ )}
112
+ </td>
113
+ <td className="py-2 pr-2 text-center">
114
+ <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
115
+ s.attendance_rate >= 90 ? 'bg-green-50 text-green-700' :
116
+ s.attendance_rate >= 60 ? 'bg-amber-50 text-amber-700' :
117
+ 'bg-red-50 text-red-700'
118
+ }`}>{s.attendance_rate}%</span>
119
+ </td>
120
+ </tr>
121
+ ))}
122
+ </tbody>
123
+ </table>
124
+ </div>
125
+ )}
126
+ </div>
127
+ </div>
128
+ );
129
+ }
frontend/src/services/attendanceService.ts CHANGED
@@ -13,6 +13,8 @@ export interface Attendance {
13
  action?: string | null;
14
  user_name?: string;
15
  user_lastname?: string;
 
 
16
  section_name?: string;
17
  is_late?: boolean;
18
  late_reason?: string | null;
@@ -25,6 +27,7 @@ export interface TodayCheckIn {
25
  card_id?: string;
26
  user_name: string;
27
  user_lastname: string;
 
28
  section_name: string | null;
29
  time_log: string;
30
  checkout_time: string | null;
@@ -44,11 +47,21 @@ export interface AttendanceFilters {
44
  per_page?: number;
45
  user_id?: number;
46
  section_id?: number;
 
47
  date_from?: string;
48
  date_to?: string;
49
  type?: string;
50
  }
51
 
 
 
 
 
 
 
 
 
 
52
  export async function listAttendances(filters: AttendanceFilters = {}): Promise<PaginatedResponse<Attendance>> {
53
  const params = new URLSearchParams();
54
  Object.entries(filters).forEach(([k, v]) => { if (v !== undefined && v !== '') params.set(k, String(v)); });
 
13
  action?: string | null;
14
  user_name?: string;
15
  user_lastname?: string;
16
+ role?: string | null;
17
+ card_id?: string | null;
18
  section_name?: string;
19
  is_late?: boolean;
20
  late_reason?: string | null;
 
27
  card_id?: string;
28
  user_name: string;
29
  user_lastname: string;
30
+ role?: string | null;
31
  section_name: string | null;
32
  time_log: string;
33
  checkout_time: string | null;
 
47
  per_page?: number;
48
  user_id?: number;
49
  section_id?: number;
50
+ role?: string;
51
  date_from?: string;
52
  date_to?: string;
53
  type?: string;
54
  }
55
 
56
+ export async function downloadReportCSV(filters: { role?: string; date_from?: string; date_to?: string; user_id?: number } = {}): Promise<void> {
57
+ const params = new URLSearchParams();
58
+ Object.entries(filters).forEach(([k, v]) => { if (v !== undefined && v !== '') params.set(k, String(v)); });
59
+ const { data } = await api.get(`/attendances/report-export?${params}`, { responseType: 'blob' });
60
+ const url = URL.createObjectURL(data);
61
+ const a = document.createElement('a'); a.href = url; a.download = 'reporte_asistencia.csv'; a.click();
62
+ URL.revokeObjectURL(url);
63
+ }
64
+
65
  export async function listAttendances(filters: AttendanceFilters = {}): Promise<PaginatedResponse<Attendance>> {
66
  const params = new URLSearchParams();
67
  Object.entries(filters).forEach(([k, v]) => { if (v !== undefined && v !== '') params.set(k, String(v)); });
frontend/src/services/representativeService.ts CHANGED
@@ -7,8 +7,12 @@ export interface ChildAttendance {
7
  card_id: string | null;
8
  section_name: string | null;
9
  section_id: number | null;
 
 
 
10
  is_present_today: boolean;
11
  checkin_time: string | null;
 
12
  attendance_last_30_days: number;
13
  today_schedule: {
14
  day: number;
 
7
  card_id: string | null;
8
  section_name: string | null;
9
  section_id: number | null;
10
+ entered_campus_today: boolean;
11
+ campus_checkin_time: string | null;
12
+ campus_checkout_time: string | null;
13
  is_present_today: boolean;
14
  checkin_time: string | null;
15
+ skipped_class: boolean;
16
  attendance_last_30_days: number;
17
  today_schedule: {
18
  day: number;