Jesús Altuve commited on
Commit
e9ee232
·
unverified ·
2 Parent(s): 05267715c95596

Merge pull request #3 from Yisus32/feat/ta-01

Browse files

TA-01: photo storage, admin attendance, gate decouple + responsive UI

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .opencode/ARCHITECTURE.md +0 -63
  2. .opencode/skills/boilerpalette/SKILLS.md +0 -58
  3. .opencode/skills/containerization/SKILLS.md +0 -39
  4. .opencode/skills/frontend/SKILLS.md +0 -63
  5. .opencode/skills/ui-ux/SKILLS.md +0 -20
  6. backend/.env.example +8 -0
  7. backend/Dockerfile +1 -0
  8. backend/alembic/versions/028_ta01_storage_and_attendance_attribution.py +79 -0
  9. backend/app/api/v1/endpoints/admin_attendance.py +147 -0
  10. backend/app/api/v1/endpoints/dashboard.py +185 -85
  11. backend/app/api/v1/endpoints/facial.py +30 -1
  12. backend/app/api/v1/endpoints/photos.py +29 -0
  13. backend/app/api/v1/endpoints/teacher.py +58 -94
  14. backend/app/api/v1/endpoints/users.py +76 -1
  15. backend/app/api/v1/router.py +3 -1
  16. backend/app/models/attendance.py +2 -0
  17. backend/app/models/face_encoding.py +3 -3
  18. .opencode/ARCHITECTURE.txt → backend/app/services/__init__.py +0 -0
  19. backend/app/services/attendance.py +160 -0
  20. backend/app/services/photo_pipeline.py +24 -0
  21. backend/app/storage/__init__.py +20 -0
  22. backend/app/storage/base.py +15 -0
  23. backend/app/storage/in_memory.py +17 -0
  24. backend/app/storage/local_disk.py +32 -0
  25. backend/app/storage/supabase.py +22 -0
  26. backend/requirements.txt +3 -0
  27. backend/tests/services/__init__.py +0 -0
  28. backend/tests/services/test_photo_pipeline.py +51 -0
  29. backend/tests/storage/__init__.py +0 -0
  30. backend/tests/storage/test_factory.py +22 -0
  31. backend/tests/storage/test_in_memory.py +30 -0
  32. backend/tests/storage/test_local_disk.py +35 -0
  33. backend/tests/storage/test_supabase.py +13 -0
  34. backend/tests/test_admin_attendance.py +353 -0
  35. backend/tests/test_attendance_service.py +209 -0
  36. backend/tests/test_dashboard_sex_by_section.py +63 -0
  37. backend/tests/test_dashboard_stats_union.py +240 -0
  38. backend/tests/test_teacher_attendance_gate_decouple.py +182 -0
  39. backend/tests/test_users_photo_upload.py +232 -0
  40. docker-compose.yml +8 -0
  41. docs/sprints/2026-06-05_TA-01.md +24 -0
  42. docs/superpowers/plans/2026-06-05-ta01-storage-and-attendance.md +2247 -0
  43. docs/superpowers/specs/2026-06-05-ta01-storage-and-attendance-design.md +357 -0
  44. frontend/src/App.tsx +2 -0
  45. frontend/src/components/AuthImage.tsx +76 -0
  46. frontend/src/components/CameraCapture.tsx +23 -6
  47. frontend/src/components/Layout.tsx +32 -2
  48. frontend/src/components/Sidebar.tsx +30 -6
  49. frontend/src/pages/AdminAttendancePage.tsx +288 -0
  50. frontend/src/pages/SectionsPage.tsx +18 -2
.opencode/ARCHITECTURE.md DELETED
@@ -1,63 +0,0 @@
1
- # Prompt de Desarrollo: Sistema SaaS de Control de Asistencias (MVP)
2
-
3
- ### Nombre del proyecto: Talos - Access
4
-
5
- Actúa como un Arquitecto de Software Senior y Especialista en Ciberseguridad. Vamos a diseñar y maquetar un sistema SaaS para la gestión y control de asistencias, enfocado en su primera etapa como un MVP para un plantel educativo (alumnos y docentes).
6
-
7
- Diseña la arquitectura, el modelo de datos modular y los endpoints necesarios basándote en los siguientes requerimientos estrictos:
8
-
9
- ---
10
-
11
- ## 1. Stack Tecnológico & Arquitectura
12
- - **Backend:** FastAPI (Python), implementando arquitectura limpia por capas o basada en routers/features.
13
- - **Frontend:** React + Vite + Tailwind CSS (Estructura empresarial modular, no SPA plana).
14
- - **Base de Datos:** MySQL (Relacional, optimizada con índices para consultas de alta concurrencia en horas pico de entrada/salida).
15
- - **Caché y Mensajería:** Redis (Para gestionar colas de procesamiento de imágenes de OpenCV, sesiones activas y limitación de peticiones/Rate Limiting).
16
- - **Visión Artificial:** OpenCV (Procesamiento de streams de video/imágenes para reconocimiento facial).
17
-
18
- ---
19
-
20
- ## 2. Lógica de Negocio y Niveles de Suscripción (SaaS)
21
- El sistema debe alternar el método de entrada en el módulo de "Check-In / Check-Out" basándose estrictamente en el plan de suscripción activo de la institución:
22
-
23
- - **Plan Basic (Manual):** Entrada/Salida mediante teclado introduciendo el documento de identidad (DNI).
24
- - **Plan Premium (Hardware):** Entrada/Salida automatizada mediante la lectura de códigos de barras/QR impresos en los carnets escolares.
25
- - **Plan Pro (Biométrico):** Entrada/Salida mediante reconocimiento facial utilizando OpenCV (procesado de forma asíncrona a través de Redis para no bloquear el hilo principal de FastAPI).
26
-
27
- ---
28
-
29
- ## 3. Matriz de Permisología y Control de Acceso (RBAC / ABAC)
30
- El sistema debe implementar un Middleware estricto en FastAPI y políticas de acceso a nivel de datos para asegurar los endpoints según el rol:
31
-
32
- - **Rol: Admin (Administrador del Plantel)**
33
- - Acceso total al sistema (CRUD completo de usuarios, alumnos, docentes y planes).
34
- - Acceso a un **Dashboard General** en tiempo real que muestre métricas globales (porcentaje de asistencia diaria, ausentismo recurrente, alertas de alumnos rezagados y picos de tráfico por hora).
35
- - Acceso a reportes globales consolidados.
36
-
37
- - **Rol: Usuario (Docentes / Profesores)**
38
- - Acceso exclusivo a la lectura de reportes y asistencias **únicamente de los alumnos que tiene asignados** en sus respectivas materias o secciones (Control de acceso basado en atributos/relaciones). No puede ver datos de otras aulas.
39
-
40
- - **Rol: Representante (Padres / Tutores)**
41
- - Acceso exclusivo a un perfil de consulta externa para verificar el historial de asistencia, retrasos y reportes **únicamente de sus representados (hijos)**.
42
-
43
- *Nota de seguridad:* Si un usuario intenta consumir un endpoint o consultar un ID de alumno que no está enlazado a su cuenta (docente asignado o padre), el middleware o policy debe retornar un error `403 Forbidden` inmediatamente.
44
-
45
- ---
46
-
47
- ## 4. Requerimientos de Frontend, Visualización y Datos
48
- Para el frontend en React, el sistema requiere dos componentes de alta complejidad de datos:
49
-
50
- - **Mapa de Calor de Asistencia:** Cada perfil de alumno debe incluir un gráfico de mapa de calor (estilo GitHub Contributions) que visualice de forma intuitiva su consistencia de asistencia a lo largo del año escolar (marcando en verde los días asistidos a tiempo, amarillo los retrasos y rojo las ausencias).
51
- - **Filtrabilidad Avanzada (Backend Driven):** Todos los módulos de reportes deben incluir un panel de filtros especiales y combinables:
52
- - Rango de fechas dinámico.
53
- - Estado de asistencia (A tiempo, Retraso, Falta Justificada, Falta Injustificada).
54
- - Sección / Aula / Grado.
55
- - Filtro por docente o alumno específico.
56
- - Los datos deben paginarse desde el backend para evitar problemas de rendimiento.
57
-
58
- ---
59
-
60
- ## ¿Qué necesito que generes primero?
61
- 1. El **Modelo de Entidad-Relación (SQL)** en formato de código (o scripts de SQLAlchemy) que soporte la multi-tenencia (SaaS), los roles y las relaciones estrictas entre padres-hijos y profesores-aulas.
62
- 2. La estructura de endpoints esenciales en FastAPI para el flujo de Check-In/Check-Out considerando los 3 planes.
63
- 3. La configuración del middleware de seguridad para validar el acceso cruzado de profesores y representantes.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.opencode/skills/boilerpalette/SKILLS.md DELETED
@@ -1,58 +0,0 @@
1
- ---
2
- name: fastapi-opencv-boilerplate
3
- description: Scaffolds a professional FastAPI project integrated with OpenCV and MySQL using architectural best practices.
4
- license: MIT
5
- compatibility: opencode
6
- metadata:
7
- audience: developers
8
- workflow: project-initialization
9
- ---
10
-
11
- ## What I do
12
-
13
- - **Generate a structured FastAPI boilerplate** following the official template guidelines (Clean Architecture / Router-based separation).
14
- - **Configure MySQL integration** via SQLAlchemy ORM (async/sync ready) including base models and session management.
15
- - **Inject basic OpenCV utility modules** for processing images or video streams within background tasks or endpoints.
16
- - **Create environmental setups** including a `.env.example`, `requirements.txt`, and a `Dockerfile`.
17
-
18
- ## When to use me
19
-
20
- Use this when starting a computer vision backend application from scratch and you want to bypass the repetitive setup of directories, database connections, and dependency injections.
21
-
22
- ---
23
-
24
- ### Suggested Project Structure
25
-
26
- ```text
27
- my_fastapi_app/
28
- │
29
- ├── app/
30
- │ ├── __init__.py
31
- │ ├── main.py # Application entrypoint
32
- │ ├── core/
33
- │ │ ├── config.py # Pydantic environment settings
34
- │ │ └── security.py
35
- │ │
36
- │ ├── database/
37
- │ │ ├── session.py # MySQL engine and sessionmaker
38
- │ │ └── base_class.py # Declarative base for SQLAlchemy
39
- │ │
40
- │ ├── models/ # SQLAlchemy ORM models
41
- │ │ └── __init__.py
42
- │ │
43
- │ ├── schemas/ # Pydantic data validation schemas
44
- │ │ └── __init__.py
45
- │ │
46
- │ ├── api/ # API Endpoints (V1)
47
- │ │ ├── router.py # Main APIRouter orchestrator
48
- │ │ └── endpoints/
49
- │ │ ├── vision.py # OpenCV processing routes
50
- │ │ └── auth.py
51
- │ │
52
- │ └── services/ # Core business logic / Vision pipelines
53
- │ └── vision_service.py # OpenCV image manipulation logic
54
- │
55
- ├── .env.example
56
- ├── Dockerfile
57
- ├── README.md
58
- └── requirements.txt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.opencode/skills/containerization/SKILLS.md DELETED
@@ -1,39 +0,0 @@
1
- ---
2
- name: dockerize-fastapi-react-mysql
3
- description: Provisions production-ready Docker and Docker Compose configurations for orchestrating a complex FastAPI (OpenCV) backend, React frontend, and MySQL database.
4
- license: MIT
5
- compatibility: opencode
6
- metadata:
7
- audience: devops-and-developers
8
- workflow: containerization
9
- ---
10
-
11
- ## What I do
12
-
13
- - **Generate highly optimized Dockerfiles** for both Backend (Python/OpenCV multi-stage build to minimize weight and manage heavy native dependencies) and Frontend (Vite multi-stage build using Node and an Nginx production reverse-proxy reverse layer).
14
- - **Orchestrate a unified multi-container system** via `docker-compose.yml` including internal networking, configuration overrides, structural data volumes, and healthcheck sequencing.
15
- - **Configure automated service dependency tracking**, ensuring the FastAPI backend waits specifically for the MySQL engine to be fully accepting connection pools before attempting initialization scripts.
16
-
17
- ## When to use me
18
-
19
- Use this when your multi-tier application architecture is ready for local containerized development or staging deployment, ensuring standard multi-system environments function identically across different infrastructures.
20
-
21
- ---
22
-
23
- ### Suggested Containerization Setup
24
-
25
- ```text
26
- my_project_root/
27
- │
28
- ├── backend/ # (Your structured FastAPI codebase)
29
- │ ├── app/
30
- │ ├── Dockerfile
31
- │ └── requirements.txt
32
- │
33
- ├── frontend/ # (Your enterprise React codebase)
34
- │ ├── src/
35
- │ ├── Dockerfile
36
- │ └── nginx.conf # Nginx config for handling React SPA routes internally
37
- │
38
- ├── docker-compose.yml # Central orchestration manifest
39
- └── .env # Global environment configurations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.opencode/skills/frontend/SKILLS.md DELETED
@@ -1,63 +0,0 @@
1
- ---
2
- name: react-enterprise-fastapi-bridge
3
- description: Scaffolds a production-ready, highly modular React frontend using Vite and Tailwind CSS, architected for large-scale enterprise systems connecting to FastAPI backends.
4
- license: MIT
5
- compatibility: opencode
6
- metadata:
7
- audience: architects-and-developers
8
- workflow: enterprise-frontend-initialization
9
- ---
10
-
11
- ## What I do
12
-
13
- - **Establish a Domain-Driven / Feature-Based Architecture** instead of a flat SPA layout, making it highly maintainable for complex business logic, large teams, and heavy feature scaling.
14
- - **Implement Robust State Management and Server-Cache synchronization** using `@tanstack/react-query` to handle complex server-state, automatic re-fetching, and background synchronization with FastAPI.
15
- - **Configure Advanced Tailwind Utilities** utilizing `tailwind-merge` and `clsx` to construct production-ready, dynamic, and highly reusable design-system components.
16
- - **Inject Enterprise API Routing and Layering** providing strict abstraction layers between the HTTP transport layer (Axios), domain-specific services, and global layout managers.
17
-
18
- ## When to use me
19
-
20
- Use this when building complex, data-heavy, multi-module business systems (like dashboards, real-time analytics platforms, or multi-role management consoles) that require a strict separation of concerns, high performance, and explicit scaling paths.
21
-
22
- ---
23
-
24
- ### Suggested Enterprise Project Structure
25
-
26
- ```text
27
- my_enterprise_app/
28
- │
29
- ├── src/
30
- │ ├── assets/ # Global assets (images, logos, fonts)
31
- │ ├── components/ # Base Design System / Atomic UI (Unbound to domain)
32
- │ │ ├── ui/ # Button, Input, Modal, Table, Dropdown
33
- │ │ └── feedback/ # Skeletons, Spinners, Toast notifications
34
- │ │
35
- │ ├── config/ # Core configurations and Axios transport layers
36
- │ │ └── axios.instance.js # Interceptors for Auth, Refresh Tokens, and Logging
37
- │ │
38
- │ ├── features/ # Domain-Driven Modules (Self-contained boundaries)
39
- │ │ ├── auth/ # Components, hooks, types, and api endpoints for Auth
40
- │ │ ├── dashboard/ # Layouts and widgets for general entry metrics
41
- │ │ └── vision-pipelines/ # Enterprise module for OpenCV stream/batch management
42
- │ │ ├── api/ # Localized api calls: getPipeline(), processBatch()
43
- │ │ ├── components/ # CanvasViewer, LiveStreamPlayer, MetricsTable
44
- │ │ ├── hooks/ # usePipelineMutation, useStreamMetrics
45
- │ │ └── pages/ # Full views: PipelineConfigPage, LiveMonitorPage
46
- │ │
47
- │ ├── layouts/ # Structural Shells (AdminLayout, PublicLayout)
48
- │ │ └── RootLayout.jsx
49
- │ │
50
- │ ├── routes/ # Advanced Router definition with lazy-loading & guards
51
- │ │ ├── AppRoutes.jsx # Route tree orchestration
52
- │ │ └── GuardedRoute.jsx # Role-based access control (RBAC) handling
53
- │ │
54
- │ ├── store/ # Client-side State (Zustand / Redux Toolkit)
55
- │ │ └── useUIStore.js # Global UI behaviors (sidebars, persistent preferences)
56
- │ │
57
- │ ├── App.jsx # Global Providers (QueryClientProvider, Theme, Router)
58
- │ ├── main.jsx # DOM Mount point
59
- │ └── index.css # Design-system design variables and Tailwind directives
60
- │
61
- ├── tailwind.config.js # Design-system extended schema definitions
62
- ├── vite.config.js # Advanced aliases mapping (@/features, @/components)
63
- └── package.json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.opencode/skills/ui-ux/SKILLS.md DELETED
@@ -1,20 +0,0 @@
1
- ---
2
- name: ui-ux-soft-ui-master
3
- description: Enforces high-fidelity UI/UX principles, modern design systems, and Soft UI design trends using Tailwind CSS.
4
- license: MIT
5
- compatibility: opencode
6
- metadata:
7
- audience: frontend-developers
8
- workflow: UI-refactoring-and-styling
9
- ---
10
-
11
- ## What I do
12
-
13
- - **Transform raw/ugly HTML/React components** into visually stunning, premium interfaces using **Soft UI / Modern Neumorphism** aesthetics.
14
- - **Enforce UX best practices:** Visual hierarchy, optimal cognitive load, accessible contrast ratios (WCAG), interactive states (`hover`, `focus`, `active`), and smooth micro-interactions.
15
- - **Construct cohesive design systems:** Implement unified spacing scales, precise border-radii, consistent shadow structures, and semantic color palettes.
16
- - **Refactor layout patterns:** Optimize mobile-first responsiveness, grid systems, and dashboard information density.
17
-
18
- ## When to use me
19
-
20
- Use this when your application's functional code is ready, but the interface looks like a basic bootstrap template, sterile, or lacks emotional design, and you want to lift it to a premium SaaS product level.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/.env.example CHANGED
@@ -24,3 +24,11 @@ APP_NAME=Talos Access
24
  DEBUG=true
25
  API_V1_PREFIX=/api/v1
26
  CORS_ORIGINS=["http://localhost:5173"]
 
 
 
 
 
 
 
 
 
24
  DEBUG=true
25
  API_V1_PREFIX=/api/v1
26
  CORS_ORIGINS=["http://localhost:5173"]
27
+
28
+ # Bloque A — Storage de fotos
29
+ PHOTO_STORAGE_BACKEND=local
30
+ LOCAL_PHOTO_ROOT=/data/photos
31
+ LOCAL_PHOTO_URL_PREFIX=/api/v1/photos
32
+ SUPABASE_URL=
33
+ SUPABASE_SERVICE_KEY=
34
+ SUPABASE_PHOTO_BUCKET=user-photos
backend/Dockerfile CHANGED
@@ -7,6 +7,7 @@ RUN apt-get update && apt-get install -y \
7
  cmake \
8
  build-essential \
9
  tzdata \
 
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  WORKDIR /app
 
7
  cmake \
8
  build-essential \
9
  tzdata \
10
+ libmagic1 \
11
  && rm -rf /var/lib/apt/lists/*
12
 
13
  WORKDIR /app
backend/alembic/versions/028_ta01_storage_and_attendance_attribution.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TA-01: storage paths and attendance attribution
2
+
3
+ WARNING: Upgrade deletes all existing face_encodings.photo data
4
+ (was base64; now URL/path). Admins must re-upload after deployment.
5
+ Downgrade does NOT restore the deleted photos.
6
+
7
+ Bloque A: face_encodings.photo Text(base64) → VARCHAR(500) URL/path;
8
+ face_encodings.encoding allowed to be NULL.
9
+ Bloque B: attendances gets marked_by_role + marked_by_user_id for
10
+ attribution traceability (teacher | admin | kiosco).
11
+
12
+ Revision ID: 028
13
+ Revises: 027
14
+ Create Date: 2026-06-05
15
+ """
16
+
17
+ from alembic import op
18
+ import sqlalchemy as sa
19
+
20
+ revision = "028"
21
+ down_revision = "027"
22
+ branch_labels = None
23
+ depends_on = None
24
+
25
+
26
+ def upgrade() -> None:
27
+ # Bloque A: face_encodings.photo de Text(base64) a VARCHAR(500) URL/path.
28
+ # Cleanup de filas existentes: vaciar photo (el admin re-sube) y permitir encoding NULL.
29
+ op.execute("UPDATE face_encodings SET photo = NULL")
30
+ op.alter_column(
31
+ "face_encodings", "photo",
32
+ existing_type=sa.Text(),
33
+ type_=sa.String(length=500),
34
+ existing_nullable=True,
35
+ )
36
+ op.alter_column(
37
+ "face_encodings", "encoding",
38
+ existing_type=sa.Text(),
39
+ nullable=True,
40
+ )
41
+
42
+ # Bloque B: trazabilidad de origen de la marca.
43
+ op.add_column(
44
+ "attendances",
45
+ sa.Column("marked_by_role", sa.String(length=20), nullable=True),
46
+ )
47
+ op.add_column(
48
+ "attendances",
49
+ sa.Column("marked_by_user_id", sa.BigInteger(), nullable=True),
50
+ )
51
+ op.create_foreign_key(
52
+ "fk_attendances_marked_by_user",
53
+ "attendances", "users",
54
+ ["marked_by_user_id"], ["id"],
55
+ ondelete="SET NULL",
56
+ )
57
+ op.create_index(
58
+ "ix_attendances_marked_by_user_id",
59
+ "attendances", ["marked_by_user_id"],
60
+ )
61
+
62
+
63
+ def downgrade() -> None:
64
+ # NOTE: Photo data deleted in upgrade is NOT restored here.
65
+ op.drop_index("ix_attendances_marked_by_user_id", table_name="attendances")
66
+ op.drop_constraint("fk_attendances_marked_by_user", "attendances", type_="foreignkey")
67
+ op.drop_column("attendances", "marked_by_user_id")
68
+ op.drop_column("attendances", "marked_by_role")
69
+ op.alter_column(
70
+ "face_encodings", "encoding",
71
+ existing_type=sa.Text(),
72
+ nullable=False,
73
+ )
74
+ op.alter_column(
75
+ "face_encodings", "photo",
76
+ existing_type=sa.String(length=500),
77
+ type_=sa.Text(),
78
+ existing_nullable=True,
79
+ )
backend/app/api/v1/endpoints/admin_attendance.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, date as date_type, time, timezone
2
+ from typing import Optional, List
3
+
4
+ from fastapi import APIRouter, Depends, HTTPException, Query
5
+ from pydantic import BaseModel
6
+ from sqlalchemy.orm import Session
7
+
8
+ from app.core.database import get_db
9
+ from app.middleware.rbac import RBAC
10
+ from app.models.user import User
11
+ from app.models.section import Section
12
+ from app.services.attendance import record_attendance, list_section_roster
13
+
14
+ router = APIRouter(prefix="/admin", tags=["admin-attendance"])
15
+
16
+
17
+ @router.get("/sections")
18
+ def admin_list_sections(
19
+ current_user: User = Depends(RBAC(["admin"])),
20
+ db: Session = Depends(get_db),
21
+ ):
22
+ rows = (
23
+ db.query(Section)
24
+ .filter(Section.account_id == current_user.account_id)
25
+ .order_by(Section.name)
26
+ .all()
27
+ )
28
+ return [{"id": s.id, "name": s.name} for s in rows]
29
+
30
+
31
+ @router.get("/sections/{section_id}/roster")
32
+ def admin_section_roster(
33
+ section_id: int,
34
+ on_date: Optional[str] = Query(None, alias="date"),
35
+ current_user: User = Depends(RBAC(["admin"])),
36
+ db: Session = Depends(get_db),
37
+ ):
38
+ section = (
39
+ db.query(Section)
40
+ .filter(
41
+ Section.id == section_id,
42
+ Section.account_id == current_user.account_id,
43
+ )
44
+ .first()
45
+ )
46
+ if not section:
47
+ raise HTTPException(status_code=404, detail="section not found")
48
+
49
+ day = (
50
+ datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date_type.today()
51
+ )
52
+ items = list_section_roster(
53
+ db,
54
+ account_id=current_user.account_id,
55
+ section_id=section_id,
56
+ on_date=day,
57
+ )
58
+ return [it.__dict__ for it in items]
59
+
60
+
61
+ class AdminSwipeRecord(BaseModel):
62
+ student_id: int
63
+ present: bool
64
+
65
+
66
+ class AdminSwipeRequest(BaseModel):
67
+ section_id: int
68
+ subject_id: Optional[int] = None
69
+ records: List[AdminSwipeRecord]
70
+
71
+
72
+ def _ensure_admin_section(payload_section_id: int, account_id: int, db: Session) -> Section:
73
+ section = (
74
+ db.query(Section)
75
+ .filter(
76
+ Section.id == payload_section_id,
77
+ Section.account_id == account_id,
78
+ )
79
+ .first()
80
+ )
81
+ if not section:
82
+ raise HTTPException(status_code=404, detail="section not found")
83
+ return section
84
+
85
+
86
+ @router.post("/attendance/swipe", status_code=201)
87
+ def admin_attendance_swipe(
88
+ payload: AdminSwipeRequest,
89
+ current_user: User = Depends(RBAC(["admin"])),
90
+ db: Session = Depends(get_db),
91
+ ):
92
+ _ensure_admin_section(payload.section_id, current_user.account_id, db)
93
+ when = datetime.now(timezone.utc)
94
+ created = 0
95
+ for rec in payload.records:
96
+ if not rec.present:
97
+ continue
98
+ record_attendance(
99
+ db,
100
+ account_id=current_user.account_id,
101
+ user_id=rec.student_id,
102
+ section_id=payload.section_id,
103
+ subject_id=payload.subject_id,
104
+ action="in",
105
+ marked_by_role="admin",
106
+ marked_by_user_id=current_user.id,
107
+ when=when,
108
+ note="Admin: contingencia",
109
+ )
110
+ created += 1
111
+ return {"created": created, "total": len(payload.records), "skipped": []}
112
+
113
+
114
+ @router.post("/attendance/batch-toggle")
115
+ def admin_batch_toggle(
116
+ payload: AdminSwipeRequest,
117
+ on_date: Optional[str] = Query(None, alias="date"),
118
+ current_user: User = Depends(RBAC(["admin"])),
119
+ db: Session = Depends(get_db),
120
+ ):
121
+ _ensure_admin_section(payload.section_id, current_user.account_id, db)
122
+ day = (
123
+ datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date_type.today()
124
+ )
125
+ when = (
126
+ datetime.now(timezone.utc)
127
+ if day == date_type.today()
128
+ else datetime.combine(day, time(12, 0), tzinfo=timezone.utc)
129
+ )
130
+ created = 0
131
+ for rec in payload.records:
132
+ if not rec.present:
133
+ continue
134
+ record_attendance(
135
+ db,
136
+ account_id=current_user.account_id,
137
+ user_id=rec.student_id,
138
+ section_id=payload.section_id,
139
+ subject_id=payload.subject_id,
140
+ action="in",
141
+ marked_by_role="admin",
142
+ marked_by_user_id=current_user.id,
143
+ when=when,
144
+ note="Admin batch: contingencia",
145
+ )
146
+ created += 1
147
+ return {"created": created, "total": len(payload.records), "skipped": []}
backend/app/api/v1/endpoints/dashboard.py CHANGED
@@ -29,6 +29,137 @@ def _teacher_section_ids(current_user: User, db: Session):
29
  return [r.section_id for r in rows]
30
 
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  @router.get("/stats")
33
  def dashboard_stats(
34
  db: Session = Depends(get_db),
@@ -53,36 +184,15 @@ def dashboard_stats(
53
  ).scalar() or 0
54
 
55
  today = date.today()
56
- today_checkins = db.query(func.count(func.distinct(Attendance.user_id))).filter(
57
- Attendance.section_id.in_(sec_ids),
58
- Attendance.account_id == account_id,
59
- cast(Attendance.time_log, Date) == today,
60
- ).scalar() or 0
61
-
62
- users_out_today = db.query(func.distinct(Attendance.user_id)).filter(
63
- Attendance.section_id.in_(sec_ids),
64
- Attendance.account_id == account_id,
65
- cast(Attendance.time_log, Date) == today,
66
- Attendance.action == "out",
67
- ).subquery()
68
-
69
- currently_on_campus = db.query(func.count(func.distinct(Attendance.user_id))).filter(
70
- Attendance.section_id.in_(sec_ids),
71
- Attendance.account_id == account_id,
72
- cast(Attendance.time_log, Date) == today,
73
- Attendance.checkout_time.is_(None),
74
- ~Attendance.user_id.in_(users_out_today),
75
- ).scalar() or 0
76
-
77
- today_checkouts = db.query(func.count(func.distinct(Attendance.user_id))).filter(
78
- Attendance.section_id.in_(sec_ids),
79
- Attendance.account_id == account_id,
80
- cast(Attendance.time_log, Date) == today,
81
- or_(
82
- Attendance.checkout_time.isnot(None),
83
- Attendance.action == "out",
84
- ),
85
- ).scalar() or 0
86
 
87
  return {
88
  "total_students": total_students,
@@ -115,24 +225,18 @@ def dashboard_stats(
115
  Subject.account_id == account_id,
116
  ).scalar() or 0
117
 
118
- # Check-in/out real proviene de EntranceLog (kiosko / facial), no de Attendance.
 
119
  today = date.today()
120
- today_checkins = db.query(func.count(func.distinct(EntranceLog.user_id))).filter(
121
- EntranceLog.account_id == account_id,
122
- EntranceLog.date == today,
123
- ).scalar() or 0
124
-
125
- currently_on_campus = db.query(func.count(EntranceLog.id)).filter(
126
- EntranceLog.account_id == account_id,
127
- EntranceLog.date == today,
128
- EntranceLog.checkout_time.is_(None),
129
- ).scalar() or 0
130
-
131
- today_checkouts = db.query(func.count(EntranceLog.id)).filter(
132
- EntranceLog.account_id == account_id,
133
- EntranceLog.date == today,
134
- EntranceLog.checkout_time.isnot(None),
135
- ).scalar() or 0
136
 
137
  return {
138
  "total_students": total_students,
@@ -156,39 +260,15 @@ def attendance_trend(
156
  today_ref = date.today()
157
  start_date = today_ref - timedelta(days=days - 1)
158
 
159
- if sec_ids is not None:
160
- # Docente: asistencia de clase por sección (Attendance)
161
- rows = (
162
- db.query(
163
- cast(Attendance.time_log, Date).label("log_date"),
164
- func.count(func.distinct(Attendance.user_id)).label("cnt"),
165
- )
166
- .filter(
167
- Attendance.account_id == account_id,
168
- Attendance.section_id.in_(sec_ids),
169
- cast(Attendance.time_log, Date) >= start_date,
170
- cast(Attendance.time_log, Date) <= today_ref,
171
- )
172
- .group_by(cast(Attendance.time_log, Date))
173
- .all()
174
- )
175
- trend_map = {row.log_date: row.cnt for row in rows}
176
- else:
177
- # Admin: check-ins reales (EntranceLog) por día
178
- rows = (
179
- db.query(
180
- EntranceLog.date.label("log_date"),
181
- func.count(func.distinct(EntranceLog.user_id)).label("cnt"),
182
- )
183
- .filter(
184
- EntranceLog.account_id == account_id,
185
- EntranceLog.date >= start_date,
186
- EntranceLog.date <= today_ref,
187
- )
188
- .group_by(EntranceLog.date)
189
- .all()
190
- )
191
- trend_map = {row.log_date: row.cnt for row in rows}
192
 
193
  result = []
194
  for i in range(days):
@@ -347,8 +427,13 @@ def sex_by_section(
347
  "totals": {"masculino": 0, "femenino": 0, "sin_especificar": 0, "total": 0},
348
  }
349
 
350
- # Students attended in range, grouped by section
351
- rows = (
 
 
 
 
 
352
  db.query(Section.id, Enrollment.student_id)
353
  .join(Enrollment, Enrollment.section_id == Section.id)
354
  .join(EntranceLog, EntranceLog.user_id == Enrollment.student_id)
@@ -362,10 +447,25 @@ def sex_by_section(
362
  .distinct()
363
  .all()
364
  )
365
- by_section: dict[int, list[int]] = {sid: [] for sid in sec_ids_in_scope}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  all_student_ids: set[int] = set()
367
- for sec_id, stu_id in rows:
368
- by_section[sec_id].append(stu_id)
369
  all_student_ids.add(stu_id)
370
 
371
  out_sections = []
 
29
  return [r.section_id for r in rows]
30
 
31
 
32
+ def _presence_user_ids_in_range(
33
+ db: Session,
34
+ *,
35
+ account_id: int,
36
+ date_from: date,
37
+ date_to: date,
38
+ section_ids: Optional[list[int]] = None,
39
+ ) -> set[int]:
40
+ """User IDs with ANY presence event in [date_from, date_to].
41
+
42
+ Presence = EntranceLog (gate / kiosk) OR Attendance.action == "in" (class).
43
+ Sources are deduped — a student with both counts once. Per TA-01,
44
+ classroom marks are valid even when the gate is down (contingency).
45
+
46
+ If `section_ids` is given, scope to students whose presence event ties
47
+ to one of those sections (Attendance.section_id directly; EntranceLog
48
+ has no section, so we join Enrollment).
49
+ """
50
+ gate_q = db.query(EntranceLog.user_id).filter(
51
+ EntranceLog.account_id == account_id,
52
+ EntranceLog.date >= date_from,
53
+ EntranceLog.date <= date_to,
54
+ )
55
+ if section_ids is not None:
56
+ gate_q = (
57
+ gate_q.join(Enrollment, Enrollment.student_id == EntranceLog.user_id)
58
+ .filter(
59
+ Enrollment.section_id.in_(section_ids),
60
+ Enrollment.account_id == account_id,
61
+ )
62
+ )
63
+ gate_ids = {row[0] for row in gate_q.distinct().all()}
64
+
65
+ class_q = db.query(Attendance.user_id).filter(
66
+ Attendance.account_id == account_id,
67
+ Attendance.action == "in",
68
+ cast(Attendance.time_log, Date) >= date_from,
69
+ cast(Attendance.time_log, Date) <= date_to,
70
+ )
71
+ if section_ids is not None:
72
+ class_q = class_q.filter(Attendance.section_id.in_(section_ids))
73
+ class_ids = {row[0] for row in class_q.distinct().all()}
74
+
75
+ return gate_ids | class_ids
76
+
77
+
78
+ def _exit_user_ids_in_range(
79
+ db: Session,
80
+ *,
81
+ account_id: int,
82
+ date_from: date,
83
+ date_to: date,
84
+ section_ids: Optional[list[int]] = None,
85
+ ) -> set[int]:
86
+ """User IDs with an exit event in [date_from, date_to].
87
+
88
+ Exit = EntranceLog.checkout_time set OR Attendance.action == "out".
89
+ Same union/dedup logic as presence.
90
+ """
91
+ gate_q = db.query(EntranceLog.user_id).filter(
92
+ EntranceLog.account_id == account_id,
93
+ EntranceLog.date >= date_from,
94
+ EntranceLog.date <= date_to,
95
+ EntranceLog.checkout_time.isnot(None),
96
+ )
97
+ if section_ids is not None:
98
+ gate_q = (
99
+ gate_q.join(Enrollment, Enrollment.student_id == EntranceLog.user_id)
100
+ .filter(
101
+ Enrollment.section_id.in_(section_ids),
102
+ Enrollment.account_id == account_id,
103
+ )
104
+ )
105
+ gate_ids = {row[0] for row in gate_q.distinct().all()}
106
+
107
+ class_q = db.query(Attendance.user_id).filter(
108
+ Attendance.account_id == account_id,
109
+ Attendance.action == "out",
110
+ cast(Attendance.time_log, Date) >= date_from,
111
+ cast(Attendance.time_log, Date) <= date_to,
112
+ )
113
+ if section_ids is not None:
114
+ class_q = class_q.filter(Attendance.section_id.in_(section_ids))
115
+ class_ids = {row[0] for row in class_q.distinct().all()}
116
+
117
+ return gate_ids | class_ids
118
+
119
+
120
+ def _presence_user_ids_by_day(
121
+ db: Session,
122
+ *,
123
+ account_id: int,
124
+ start_date: date,
125
+ end_date: date,
126
+ section_ids: Optional[list[int]] = None,
127
+ ) -> dict[date, set[int]]:
128
+ """Per-day union of presence user IDs (EntranceLog + Attendance 'in')."""
129
+ gate_q = db.query(EntranceLog.date, EntranceLog.user_id).filter(
130
+ EntranceLog.account_id == account_id,
131
+ EntranceLog.date >= start_date,
132
+ EntranceLog.date <= end_date,
133
+ )
134
+ if section_ids is not None:
135
+ gate_q = (
136
+ gate_q.join(Enrollment, Enrollment.student_id == EntranceLog.user_id)
137
+ .filter(
138
+ Enrollment.section_id.in_(section_ids),
139
+ Enrollment.account_id == account_id,
140
+ )
141
+ )
142
+
143
+ class_q = db.query(
144
+ cast(Attendance.time_log, Date).label("log_date"),
145
+ Attendance.user_id,
146
+ ).filter(
147
+ Attendance.account_id == account_id,
148
+ Attendance.action == "in",
149
+ cast(Attendance.time_log, Date) >= start_date,
150
+ cast(Attendance.time_log, Date) <= end_date,
151
+ )
152
+ if section_ids is not None:
153
+ class_q = class_q.filter(Attendance.section_id.in_(section_ids))
154
+
155
+ by_day: dict[date, set[int]] = {}
156
+ for d, uid in gate_q.all():
157
+ by_day.setdefault(d, set()).add(uid)
158
+ for d, uid in class_q.all():
159
+ by_day.setdefault(d, set()).add(uid)
160
+ return by_day
161
+
162
+
163
  @router.get("/stats")
164
  def dashboard_stats(
165
  db: Session = Depends(get_db),
 
184
  ).scalar() or 0
185
 
186
  today = date.today()
187
+ present_today = _presence_user_ids_in_range(
188
+ db, account_id=account_id, date_from=today, date_to=today, section_ids=sec_ids,
189
+ )
190
+ exited_today = _exit_user_ids_in_range(
191
+ db, account_id=account_id, date_from=today, date_to=today, section_ids=sec_ids,
192
+ )
193
+ today_checkins = len(present_today)
194
+ today_checkouts = len(exited_today)
195
+ currently_on_campus = len(present_today - exited_today)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
  return {
198
  "total_students": total_students,
 
225
  Subject.account_id == account_id,
226
  ).scalar() or 0
227
 
228
+ # Asistencia = unión deduplicada de EntranceLog (gate) + Attendance "in" (aula).
229
+ # Per TA-01, una marca de aula es válida aun sin gate (contingencia).
230
  today = date.today()
231
+ present_today = _presence_user_ids_in_range(
232
+ db, account_id=account_id, date_from=today, date_to=today,
233
+ )
234
+ exited_today = _exit_user_ids_in_range(
235
+ db, account_id=account_id, date_from=today, date_to=today,
236
+ )
237
+ today_checkins = len(present_today)
238
+ today_checkouts = len(exited_today)
239
+ currently_on_campus = len(present_today - exited_today)
 
 
 
 
 
 
 
240
 
241
  return {
242
  "total_students": total_students,
 
260
  today_ref = date.today()
261
  start_date = today_ref - timedelta(days=days - 1)
262
 
263
+ # Asistencia por día = unión deduplicada de EntranceLog + Attendance "in".
264
+ by_day = _presence_user_ids_by_day(
265
+ db,
266
+ account_id=account_id,
267
+ start_date=start_date,
268
+ end_date=today_ref,
269
+ section_ids=sec_ids,
270
+ )
271
+ trend_map = {d: len(uids) for d, uids in by_day.items()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
  result = []
274
  for i in range(days):
 
427
  "totals": {"masculino": 0, "femenino": 0, "sin_especificar": 0, "total": 0},
428
  }
429
 
430
+ # Students attended in range, grouped by section.
431
+ # A student counts as "asistente" if EITHER:
432
+ # (a) gate kiosk / facial check-in (EntranceLog), OR
433
+ # (b) teacher/admin classroom mark (Attendance.action == "in"),
434
+ # which are intentionally decoupled per TA-01: a class mark is valid
435
+ # even without a gate log when there's a contingency (power, kiosk).
436
+ gate_rows = (
437
  db.query(Section.id, Enrollment.student_id)
438
  .join(Enrollment, Enrollment.section_id == Section.id)
439
  .join(EntranceLog, EntranceLog.user_id == Enrollment.student_id)
 
447
  .distinct()
448
  .all()
449
  )
450
+ class_rows = (
451
+ db.query(Section.id, Enrollment.student_id)
452
+ .join(Enrollment, Enrollment.section_id == Section.id)
453
+ .join(Attendance, Attendance.user_id == Enrollment.student_id)
454
+ .filter(
455
+ Section.id.in_(sec_ids_in_scope),
456
+ Enrollment.account_id == account_id,
457
+ Attendance.account_id == account_id,
458
+ Attendance.action == "in",
459
+ cast(Attendance.time_log, Date) >= df,
460
+ cast(Attendance.time_log, Date) <= dt,
461
+ )
462
+ .distinct()
463
+ .all()
464
+ )
465
+ by_section: dict[int, set[int]] = {sid: set() for sid in sec_ids_in_scope}
466
  all_student_ids: set[int] = set()
467
+ for sec_id, stu_id in (*gate_rows, *class_rows):
468
+ by_section[sec_id].add(stu_id)
469
  all_student_ids.add(stu_id)
470
 
471
  out_sections = []
backend/app/api/v1/endpoints/facial.py CHANGED
@@ -1,3 +1,12 @@
 
 
 
 
 
 
 
 
 
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
  from sqlalchemy.orm import Session
3
  from sqlalchemy import cast, Date
@@ -85,11 +94,31 @@ def enroll_face(
85
  if encoding is None:
86
  raise HTTPException(status_code=400, detail="Could not extract face encoding")
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  fe = FaceEncoding(
89
  user_id=target.id,
90
  account_id=current_user.account_id,
91
  encoding=json.dumps(encoding),
92
- photo=payload.image,
93
  )
94
  db.add(fe)
95
  db.commit()
 
1
+ """Facial recognition kiosk endpoints.
2
+
3
+ NOTE (TA-01): the kiosk path only writes `EntranceLog` rows (gate check-in).
4
+ It does NOT insert into `Attendance` directly — classroom attendance is
5
+ recorded by teachers (`teacher.py`) and admins (`admin_attendance.py`),
6
+ which tag rows with `marked_by_role` accordingly. If you ever add a kiosk
7
+ write to `Attendance`, set `marked_by_role='kiosco'` and
8
+ `marked_by_user_id=None` to preserve attribution.
9
+ """
10
  from fastapi import APIRouter, Depends, HTTPException, status
11
  from sqlalchemy.orm import Session
12
  from sqlalchemy import cast, Date
 
94
  if encoding is None:
95
  raise HTTPException(status_code=400, detail="Could not extract face encoding")
96
 
97
+ # TA-01: photo goes through pipeline (WebP compression) + storage abstraction,
98
+ # never as base64 in BD (column is VARCHAR(500), too small for a dataURL).
99
+ photo_path: Optional[str] = None
100
+ try:
101
+ import base64 as _b64
102
+ from app.services.photo_pipeline import process_user_photo
103
+ from app.storage import get_storage
104
+
105
+ raw = payload.image
106
+ if "," in raw:
107
+ raw = raw.split(",")[1]
108
+ processed = process_user_photo(_b64.b64decode(raw))
109
+ photo_path = get_storage().upload(
110
+ current_user.account_id, target.id, processed, "webp",
111
+ )
112
+ except Exception:
113
+ # Photo compression/upload is best-effort. If it fails, we still
114
+ # save the encoding so facial recognition keeps working.
115
+ photo_path = None
116
+
117
  fe = FaceEncoding(
118
  user_id=target.id,
119
  account_id=current_user.account_id,
120
  encoding=json.dumps(encoding),
121
+ photo=photo_path,
122
  )
123
  db.add(fe)
124
  db.commit()
backend/app/api/v1/endpoints/photos.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from fastapi.responses import FileResponse
5
+ from app.dependencies.auth import get_current_user
6
+ from app.models.user import User
7
+
8
+ router = APIRouter(prefix="/photos", tags=["photos"])
9
+
10
+
11
+ @router.get("/{account_id}/{user_id}/{filename}")
12
+ def serve_photo(
13
+ account_id: int,
14
+ user_id: int,
15
+ filename: str,
16
+ current_user: User = Depends(get_current_user),
17
+ ):
18
+ if os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() != "local":
19
+ raise HTTPException(status_code=404, detail="not served locally")
20
+ if current_user.account_id != account_id:
21
+ raise HTTPException(status_code=404, detail="not found")
22
+ root = Path(os.getenv("LOCAL_PHOTO_ROOT", "/data/photos")).resolve()
23
+ target = (root / str(account_id) / str(user_id) / filename).resolve()
24
+ # Block path traversal (filename = "../../../etc/passwd" etc.)
25
+ if not target.is_relative_to(root):
26
+ raise HTTPException(status_code=400, detail="invalid path")
27
+ if not target.exists():
28
+ raise HTTPException(status_code=404, detail="not found")
29
+ return FileResponse(target, media_type="image/webp")
backend/app/api/v1/endpoints/teacher.py CHANGED
@@ -26,6 +26,7 @@ from app.models.section_schedule import SectionSchedule
26
  from app.utils.holiday_check import is_holiday
27
  from app.utils.sex_counts import count_by_sex
28
  from app.utils.audit import log_for
 
29
 
30
  router = APIRouter(prefix="/teacher", tags=["teacher"])
31
 
@@ -414,43 +415,25 @@ def section_students(
414
  db: Session = Depends(get_db),
415
  ):
416
  _ensure_teacher_section(section_id, current_user.id, current_user.account_id, db)
417
- enrollments = db.query(Enrollment).filter(Enrollment.section_id == section_id, Enrollment.account_id == current_user.account_id).all()
418
- student_ids = [e.student_id for e in enrollments]
419
- students = db.query(User).filter(User.id.in_(student_ids), User.is_active == "1").all()
420
-
421
  today = date.today()
422
- checked_in_ids = set()
423
- entrance_logged_ids = set()
424
- if students:
425
- student_id_list = [s.id for s in students]
426
- today_att = db.query(
427
- Attendance.user_id,
428
- Attendance.action,
429
- Attendance.checkout_time,
430
- ).filter(
431
- Attendance.user_id.in_(student_id_list),
432
- Attendance.account_id == current_user.account_id,
433
- Attendance.time_log >= today,
434
- ).order_by(Attendance.time_log.desc()).all()
435
- seen = set()
436
- for user_id, action, checkout_time in today_att:
437
- if user_id in seen:
438
- continue
439
- seen.add(user_id)
440
- if action == "out":
441
- continue
442
- if action == "in":
443
- checked_in_ids.add(user_id)
444
- elif action is None and checkout_time is None:
445
- checked_in_ids.add(user_id)
446
- entrance_logs = db.query(EntranceLog.user_id).filter(
447
- EntranceLog.user_id.in_(student_id_list),
448
- EntranceLog.account_id == current_user.account_id,
449
- EntranceLog.date == today,
450
- ).distinct().all()
451
- entrance_logged_ids = {el.user_id for el in entrance_logs}
452
-
453
- return [StudentCardResponse(id=s.id, name=s.name, lastname=s.lastname, card_id=s.card_id, phone_number=s.phone_number, already_checked_in=s.id in checked_in_ids, entrance_logged=s.id in entrance_logged_ids) for s in students]
454
 
455
 
456
  @router.post("/attendance/swipe", status_code=status.HTTP_201_CREATED)
@@ -466,17 +449,6 @@ def submit_swipe(
466
  today = now.date()
467
  created = 0
468
 
469
- student_ids = [rec.student_id for rec in payload.records]
470
- entrance_logged_ids = set()
471
- if student_ids:
472
- els = db.query(EntranceLog.user_id).filter(
473
- EntranceLog.user_id.in_(student_ids),
474
- EntranceLog.account_id == current_user.account_id,
475
- EntranceLog.date == today,
476
- ).distinct().all()
477
- entrance_logged_ids = {el.user_id for el in els}
478
-
479
- skipped_ids: list[int] = []
480
  for rec in payload.records:
481
  if not rec.present:
482
  continue
@@ -490,24 +462,23 @@ def submit_swipe(
490
  already_in = existing and existing.action is None and existing.checkout_time is None
491
  if already_in:
492
  continue
493
- if rec.student_id not in entrance_logged_ids:
494
- # student hasn't done their daily entrance at the campus gate, can't be
495
- # marked present in class. Report back to the teacher so they know why.
496
- skipped_ids.append(rec.student_id)
497
- continue
498
- db.add(Attendance(account_id=current_user.account_id, user_id=rec.student_id, section_id=payload.section_id, time_log=datetime.now(timezone.utc), action="in", note="Swipe: present"))
 
 
 
 
 
 
499
  created += 1
500
  db.commit()
501
 
502
- # Resolve skipped students to {student_id, name} for the frontend toast.
503
  skipped: list[dict] = []
504
- if skipped_ids:
505
- rows = db.query(User).filter(
506
- User.id.in_(skipped_ids),
507
- User.account_id == current_user.account_id,
508
- ).all()
509
- name_map = {u.id: f"{u.name} {u.lastname}" for u in rows}
510
- skipped = [{"student_id": sid, "name": name_map.get(sid, "")} for sid in skipped_ids]
511
 
512
  section = db.query(Section).filter(Section.id == payload.section_id).first()
513
  subject = db.query(Subject).filter(Subject.id == payload.subject_id).first() if payload.subject_id else None
@@ -577,17 +548,6 @@ def batch_toggle(
577
  _ensure_teacher_section(payload.section_id, current_user.id, current_user.account_id, db)
578
  record_time = datetime.now(timezone.utc) if day == date.today() else datetime.combine(day, time(12, 0), tzinfo=timezone.utc)
579
 
580
- student_ids = [rec.student_id for rec in payload.records]
581
- entrance_logged_ids = set()
582
- if student_ids:
583
- els = db.query(EntranceLog.user_id).filter(
584
- EntranceLog.user_id.in_(student_ids),
585
- EntranceLog.account_id == current_user.account_id,
586
- EntranceLog.date == day,
587
- ).distinct().all()
588
- entrance_logged_ids = {el.user_id for el in els}
589
-
590
- skipped_ids = []
591
  for rec in payload.records:
592
  existing = db.query(Attendance).filter(
593
  Attendance.user_id == rec.student_id,
@@ -601,23 +561,25 @@ def batch_toggle(
601
  ).first()
602
  already_present = existing is not None
603
  if rec.present:
604
- if rec.student_id not in entrance_logged_ids:
605
- skipped_ids.append(rec.student_id)
606
- continue
607
  if not already_present:
608
- db.add(Attendance(account_id=current_user.account_id, user_id=rec.student_id, section_id=payload.section_id, time_log=record_time, action="in", note="Toggle: present"))
 
 
 
 
 
 
 
 
 
 
 
609
  elif already_present:
610
  db.delete(existing)
611
  db.commit()
612
 
613
- skipped = []
614
- if skipped_ids:
615
- rows = db.query(User).filter(
616
- User.id.in_(skipped_ids),
617
- User.account_id == current_user.account_id,
618
- ).all()
619
- name_map = {u.id: f"{u.name} {u.lastname}" for u in rows}
620
- skipped = [{"student_id": sid, "name": name_map.get(sid, "")} for sid in skipped_ids]
621
 
622
  now_local = datetime.now()
623
  section = db.query(Section).filter(Section.id == payload.section_id).first()
@@ -758,16 +720,18 @@ def toggle_attendance(
758
  db.commit()
759
  return {"present": False, "attendance_id": None}
760
  else:
761
- has_entrance = db.query(EntranceLog).filter(
762
- EntranceLog.user_id == student_id,
763
- EntranceLog.account_id == current_user.account_id,
764
- EntranceLog.date == day,
765
- ).first()
766
- if not has_entrance:
767
- raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="El estudiante no tiene ingreso registrado hoy")
768
- att = Attendance(account_id=current_user.account_id, user_id=student_id, section_id=section_id, time_log=datetime.now(timezone.utc), action="in", note="Swipe: present")
769
- db.add(att)
770
- db.commit()
 
 
771
  log_for(
772
  db, current_user, "Marcar asistencia", "asistencias",
773
  details={
 
26
  from app.utils.holiday_check import is_holiday
27
  from app.utils.sex_counts import count_by_sex
28
  from app.utils.audit import log_for
29
+ from app.services.attendance import record_attendance, list_section_roster
30
 
31
  router = APIRouter(prefix="/teacher", tags=["teacher"])
32
 
 
415
  db: Session = Depends(get_db),
416
  ):
417
  _ensure_teacher_section(section_id, current_user.id, current_user.account_id, db)
 
 
 
 
418
  today = date.today()
419
+ roster = list_section_roster(
420
+ db,
421
+ account_id=current_user.account_id,
422
+ section_id=section_id,
423
+ on_date=today,
424
+ )
425
+ return [
426
+ StudentCardResponse(
427
+ id=r.id,
428
+ name=r.name,
429
+ lastname=r.lastname,
430
+ card_id=r.card_id,
431
+ phone_number=r.phone_number,
432
+ already_checked_in=r.already_checked_in,
433
+ entrance_logged=r.entrance_logged,
434
+ )
435
+ for r in roster
436
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
438
 
439
  @router.post("/attendance/swipe", status_code=status.HTTP_201_CREATED)
 
449
  today = now.date()
450
  created = 0
451
 
 
 
 
 
 
 
 
 
 
 
 
452
  for rec in payload.records:
453
  if not rec.present:
454
  continue
 
462
  already_in = existing and existing.action is None and existing.checkout_time is None
463
  if already_in:
464
  continue
465
+ record_attendance(
466
+ db,
467
+ account_id=current_user.account_id,
468
+ user_id=rec.student_id,
469
+ section_id=payload.section_id,
470
+ subject_id=payload.subject_id,
471
+ action="in",
472
+ marked_by_role="teacher",
473
+ marked_by_user_id=current_user.id,
474
+ when=datetime.now(timezone.utc),
475
+ note="Swipe: present",
476
+ )
477
  created += 1
478
  db.commit()
479
 
480
+ # `skipped` is always empty after gate decouple (TA-01). Response shape preserved.
481
  skipped: list[dict] = []
 
 
 
 
 
 
 
482
 
483
  section = db.query(Section).filter(Section.id == payload.section_id).first()
484
  subject = db.query(Subject).filter(Subject.id == payload.subject_id).first() if payload.subject_id else None
 
548
  _ensure_teacher_section(payload.section_id, current_user.id, current_user.account_id, db)
549
  record_time = datetime.now(timezone.utc) if day == date.today() else datetime.combine(day, time(12, 0), tzinfo=timezone.utc)
550
 
 
 
 
 
 
 
 
 
 
 
 
551
  for rec in payload.records:
552
  existing = db.query(Attendance).filter(
553
  Attendance.user_id == rec.student_id,
 
561
  ).first()
562
  already_present = existing is not None
563
  if rec.present:
 
 
 
564
  if not already_present:
565
+ record_attendance(
566
+ db,
567
+ account_id=current_user.account_id,
568
+ user_id=rec.student_id,
569
+ section_id=payload.section_id,
570
+ subject_id=payload.subject_id,
571
+ action="in",
572
+ marked_by_role="teacher",
573
+ marked_by_user_id=current_user.id,
574
+ when=record_time,
575
+ note="Toggle: present",
576
+ )
577
  elif already_present:
578
  db.delete(existing)
579
  db.commit()
580
 
581
+ # `skipped` is always empty after gate decouple (TA-01). Response shape preserved.
582
+ skipped: list[dict] = []
 
 
 
 
 
 
583
 
584
  now_local = datetime.now()
585
  section = db.query(Section).filter(Section.id == payload.section_id).first()
 
720
  db.commit()
721
  return {"present": False, "attendance_id": None}
722
  else:
723
+ att = record_attendance(
724
+ db,
725
+ account_id=current_user.account_id,
726
+ user_id=student_id,
727
+ section_id=section_id,
728
+ subject_id=subject_id,
729
+ action="in",
730
+ marked_by_role="teacher",
731
+ marked_by_user_id=current_user.id,
732
+ when=datetime.now(timezone.utc),
733
+ note="Swipe: present",
734
+ )
735
  log_for(
736
  db, current_user, "Marcar asistencia", "asistencias",
737
  details={
backend/app/api/v1/endpoints/users.py CHANGED
@@ -2,6 +2,9 @@ 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
 
@@ -20,6 +23,9 @@ from app.models.teacher_section import TeacherSection
20
  from app.models.enrollment import Enrollment
21
  from app.models.face_encoding import FaceEncoding
22
  from app.utils.csv_import import generate_csv_template, parse_csv_upload, process_csv_rows
 
 
 
23
 
24
  router = APIRouter(prefix="/users", tags=["users"])
25
 
@@ -90,12 +96,14 @@ def list_users(
90
  )
91
  photos = {r.user_id: r.photo for r in rows}
92
 
 
93
  items = []
94
  for u in users:
95
  ur = UserResponse.model_validate(
96
  {c.name: getattr(u, c.name) for c in u.__table__.columns},
97
  )
98
- ur.face_photo = photos.get(u.id)
 
99
  items.append(ur)
100
 
101
  return PaginatedResponse(
@@ -323,3 +331,70 @@ def deactivate_user(
323
 
324
  log_for(db, current_user, "Desactivar usuario", "usuarios",
325
  details={"user_id": user.id, "nombre": f"{user.name} {user.lastname}"}, request=request)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from sqlalchemy.orm import Session
3
  from sqlalchemy import or_, func
4
  from typing import Optional
5
+ import json
6
+ import numpy as np
7
+ import cv2
8
 
9
  from app.utils.audit import log_for
10
 
 
23
  from app.models.enrollment import Enrollment
24
  from app.models.face_encoding import FaceEncoding
25
  from app.utils.csv_import import generate_csv_template, parse_csv_upload, process_csv_rows
26
+ from app.storage import get_storage
27
+ from app.services.photo_pipeline import process_user_photo
28
+ from app.face_utils import detect_face, encode_face
29
 
30
  router = APIRouter(prefix="/users", tags=["users"])
31
 
 
96
  )
97
  photos = {r.user_id: r.photo for r in rows}
98
 
99
+ storage = get_storage()
100
  items = []
101
  for u in users:
102
  ur = UserResponse.model_validate(
103
  {c.name: getattr(u, c.name) for c in u.__table__.columns},
104
  )
105
+ raw_path = photos.get(u.id)
106
+ ur.face_photo = storage.get_url(raw_path) if raw_path else None
107
  items.append(ur)
108
 
109
  return PaginatedResponse(
 
331
 
332
  log_for(db, current_user, "Desactivar usuario", "usuarios",
333
  details={"user_id": user.id, "nombre": f"{user.name} {user.lastname}"}, request=request)
334
+
335
+
336
+ @router.post("/{user_id}/photo")
337
+ def upload_user_photo(
338
+ user_id: int,
339
+ file: UploadFile = File(...),
340
+ current_user: User = Depends(RBAC(["admin"])),
341
+ db: Session = Depends(get_db),
342
+ ):
343
+ target = db.query(User).filter(
344
+ User.id == user_id,
345
+ User.account_id == current_user.account_id,
346
+ ).first()
347
+ if not target:
348
+ raise HTTPException(status_code=404, detail="user not found")
349
+
350
+ raw = file.file.read()
351
+ try:
352
+ processed = process_user_photo(raw)
353
+ except ValueError as e:
354
+ raise HTTPException(status_code=422, detail=str(e))
355
+
356
+ # Best-effort face encoding extraction.
357
+ encoding_str = None
358
+ try:
359
+ arr = np.frombuffer(processed, np.uint8)
360
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
361
+ if img is not None:
362
+ face = detect_face(img)
363
+ if face is not None:
364
+ vec = encode_face(face)
365
+ if vec is not None:
366
+ encoding_str = json.dumps(vec)
367
+ except Exception:
368
+ encoding_str = None
369
+
370
+ storage = get_storage()
371
+
372
+ # Delete previous photo from storage (best-effort)
373
+ previous = (
374
+ db.query(FaceEncoding)
375
+ .filter(FaceEncoding.user_id == user_id, FaceEncoding.photo.isnot(None))
376
+ .order_by(FaceEncoding.id.desc())
377
+ .first()
378
+ )
379
+ if previous and previous.photo:
380
+ try:
381
+ storage.delete(previous.photo)
382
+ except Exception:
383
+ pass
384
+
385
+ new_path = storage.upload(target.account_id, user_id, processed, "webp")
386
+ fe = FaceEncoding(
387
+ user_id=user_id,
388
+ account_id=target.account_id,
389
+ encoding=encoding_str,
390
+ photo=new_path,
391
+ )
392
+ db.add(fe)
393
+ db.commit()
394
+
395
+ return {
396
+ "photo_url": storage.get_url(new_path),
397
+ "encoding_extracted": encoding_str is not None,
398
+ "warning": None if encoding_str else
399
+ "no se detectó rostro; el reconocimiento facial no funcionará hasta resubir una foto con rostro visible",
400
+ }
backend/app/api/v1/router.py CHANGED
@@ -1,6 +1,6 @@
1
  from fastapi import APIRouter
2
 
3
- from app.api.v1.endpoints import auth, users, subjects, sections, teacher_sections, enrollments, attendances, dashboard, facial, settings, teacher, section_subjects, teacher_subjects, permissions, developer, card_templates, representative, audit_logs, reports, holidays
4
 
5
  router = APIRouter(prefix="/api/v1")
6
  router.include_router(auth.router)
@@ -23,3 +23,5 @@ router.include_router(representative.router)
23
  router.include_router(audit_logs.router)
24
  router.include_router(reports.router)
25
  router.include_router(holidays.router)
 
 
 
1
  from fastapi import APIRouter
2
 
3
+ from app.api.v1.endpoints import auth, users, subjects, sections, teacher_sections, enrollments, attendances, dashboard, facial, settings, teacher, section_subjects, teacher_subjects, permissions, developer, card_templates, representative, audit_logs, reports, holidays, photos, admin_attendance
4
 
5
  router = APIRouter(prefix="/api/v1")
6
  router.include_router(auth.router)
 
23
  router.include_router(audit_logs.router)
24
  router.include_router(reports.router)
25
  router.include_router(holidays.router)
26
+ router.include_router(photos.router)
27
+ router.include_router(admin_attendance.router)
backend/app/models/attendance.py CHANGED
@@ -15,3 +15,5 @@ class Attendance(Base):
15
  coordinates = Column(JSON)
16
  note = Column(String(255))
17
  action = Column(String(10), nullable=True, comment="in or out")
 
 
 
15
  coordinates = Column(JSON)
16
  note = Column(String(255))
17
  action = Column(String(10), nullable=True, comment="in or out")
18
+ marked_by_role = Column(String(20), nullable=True)
19
+ marked_by_user_id = Column(BigInteger, ForeignKey("users.id"), nullable=True)
backend/app/models/face_encoding.py CHANGED
@@ -1,4 +1,4 @@
1
- from sqlalchemy import Column, BigInteger, Text, DateTime, ForeignKey
2
  from sqlalchemy import func
3
  from app.core.database import Base
4
 
@@ -9,6 +9,6 @@ class FaceEncoding(Base):
9
  id = Column(BigInteger, primary_key=True, autoincrement=True)
10
  user_id = Column(BigInteger, ForeignKey("users.id"), nullable=False)
11
  account_id = Column(BigInteger, ForeignKey("accounts.id"), nullable=False)
12
- encoding = Column(Text, nullable=False)
13
- photo = Column(Text, nullable=True)
14
  created_at = Column(DateTime, server_default=func.now())
 
1
+ from sqlalchemy import Column, BigInteger, Text, String, DateTime, ForeignKey
2
  from sqlalchemy import func
3
  from app.core.database import Base
4
 
 
9
  id = Column(BigInteger, primary_key=True, autoincrement=True)
10
  user_id = Column(BigInteger, ForeignKey("users.id"), nullable=False)
11
  account_id = Column(BigInteger, ForeignKey("accounts.id"), nullable=False)
12
+ encoding = Column(Text, nullable=True)
13
+ photo = Column(String(500), nullable=True)
14
  created_at = Column(DateTime, server_default=func.now())
.opencode/ARCHITECTURE.txt → backend/app/services/__init__.py RENAMED
File without changes
backend/app/services/attendance.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attendance service: shared logic for teacher + admin attendance endpoints.
2
+
3
+ Centralizes the insert of `Attendance` rows (with attribution) and the
4
+ construction of a section roster with the gate/check-in chips. Both teacher
5
+ and admin endpoints route through here so that attribution columns and
6
+ roster shape stay consistent.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from datetime import datetime, date as date_type
12
+ from typing import List, Optional
13
+
14
+ from sqlalchemy.orm import Session
15
+
16
+ from app.models.attendance import Attendance
17
+ from app.models.user import User
18
+ from app.models.enrollment import Enrollment
19
+ from app.models.entrance_log import EntranceLog
20
+
21
+
22
+ @dataclass
23
+ class RosterItem:
24
+ id: int
25
+ name: str
26
+ lastname: str
27
+ card_id: Optional[str]
28
+ phone_number: Optional[str]
29
+ sex: Optional[str]
30
+ already_checked_in: bool
31
+ entrance_logged: bool
32
+
33
+
34
+ def record_attendance(
35
+ db: Session,
36
+ *,
37
+ account_id: int,
38
+ user_id: int,
39
+ section_id: Optional[int],
40
+ subject_id: Optional[int],
41
+ action: Optional[str],
42
+ marked_by_role: str,
43
+ marked_by_user_id: Optional[int],
44
+ when: datetime,
45
+ note: Optional[str] = None,
46
+ ) -> Attendance:
47
+ """Insert an Attendance row with attribution.
48
+
49
+ Idempotent within the same calendar day for the same (user_id, section_id):
50
+ if there's already a row for that combination with matching action, it
51
+ returns the existing row.
52
+ """
53
+ day = when.date()
54
+ day_start = datetime.combine(day, datetime.min.time(), tzinfo=when.tzinfo)
55
+ day_end = datetime.combine(day, datetime.max.time(), tzinfo=when.tzinfo)
56
+
57
+ existing = (
58
+ db.query(Attendance)
59
+ .filter(
60
+ Attendance.user_id == user_id,
61
+ Attendance.account_id == account_id,
62
+ Attendance.section_id == section_id,
63
+ Attendance.time_log >= day_start,
64
+ Attendance.time_log < day_end,
65
+ )
66
+ .order_by(Attendance.time_log.desc())
67
+ .first()
68
+ )
69
+ if existing and (
70
+ existing.action == action
71
+ or (action == "in" and existing.action is None)
72
+ ):
73
+ return existing
74
+
75
+ att = Attendance(
76
+ account_id=account_id,
77
+ user_id=user_id,
78
+ section_id=section_id,
79
+ time_log=when,
80
+ action=action,
81
+ note=note,
82
+ marked_by_role=marked_by_role,
83
+ marked_by_user_id=marked_by_user_id,
84
+ )
85
+ db.add(att)
86
+ db.commit()
87
+ db.refresh(att)
88
+ return att
89
+
90
+
91
+ def list_section_roster(
92
+ db: Session,
93
+ *,
94
+ account_id: int,
95
+ section_id: int,
96
+ on_date: date_type,
97
+ ) -> List[RosterItem]:
98
+ """List active students enrolled in the section, with check-in chips.
99
+
100
+ The `entrance_logged` flag is informational — gate ↔ classroom attendance
101
+ are intentionally decoupled (TA-01). Consumers should NOT use this to
102
+ block marking attendance.
103
+ """
104
+ students = (
105
+ db.query(User)
106
+ .join(Enrollment, Enrollment.student_id == User.id)
107
+ .filter(
108
+ User.account_id == account_id,
109
+ User.role == "student",
110
+ User.is_active == "1",
111
+ Enrollment.section_id == section_id,
112
+ Enrollment.account_id == account_id,
113
+ )
114
+ .all()
115
+ )
116
+ if not students:
117
+ return []
118
+ student_ids = [s.id for s in students]
119
+
120
+ today_att = (
121
+ db.query(Attendance.user_id, Attendance.action, Attendance.checkout_time)
122
+ .filter(
123
+ Attendance.user_id.in_(student_ids),
124
+ Attendance.account_id == account_id,
125
+ Attendance.time_log >= on_date,
126
+ )
127
+ .all()
128
+ )
129
+ checked_in_ids: set[int] = set()
130
+ for user_id, action, checkout_time in today_att:
131
+ if action == "in":
132
+ checked_in_ids.add(user_id)
133
+ elif action is None and checkout_time is None:
134
+ checked_in_ids.add(user_id)
135
+
136
+ entrance_logs = (
137
+ db.query(EntranceLog.user_id)
138
+ .filter(
139
+ EntranceLog.user_id.in_(student_ids),
140
+ EntranceLog.account_id == account_id,
141
+ EntranceLog.date == on_date,
142
+ )
143
+ .distinct()
144
+ .all()
145
+ )
146
+ entrance_logged_ids = {el.user_id for el in entrance_logs}
147
+
148
+ return [
149
+ RosterItem(
150
+ id=s.id,
151
+ name=s.name,
152
+ lastname=s.lastname,
153
+ card_id=s.card_id,
154
+ phone_number=s.phone_number,
155
+ sex=s.sex,
156
+ already_checked_in=s.id in checked_in_ids,
157
+ entrance_logged=s.id in entrance_logged_ids,
158
+ )
159
+ for s in students
160
+ ]
backend/app/services/photo_pipeline.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ from PIL import Image, ImageOps
3
+ import magic
4
+
5
+ ALLOWED_MIME = {"image/png", "image/jpeg", "image/webp"}
6
+ MAX_INPUT_BYTES = 5 * 1024 * 1024
7
+ TARGET_MAX_DIM = 800
8
+ WEBP_QUALITY = 85
9
+
10
+
11
+ def process_user_photo(raw: bytes) -> bytes:
12
+ if len(raw) > MAX_INPUT_BYTES:
13
+ raise ValueError(f"photo exceeds {MAX_INPUT_BYTES} bytes")
14
+ mime = magic.from_buffer(raw, mime=True)
15
+ if mime not in ALLOWED_MIME:
16
+ raise ValueError(f"unsupported mime: {mime}")
17
+ img = Image.open(BytesIO(raw))
18
+ img = ImageOps.exif_transpose(img)
19
+ img.thumbnail((TARGET_MAX_DIM, TARGET_MAX_DIM), Image.LANCZOS)
20
+ if img.mode in ("RGBA", "P", "LA"):
21
+ img = img.convert("RGB")
22
+ out = BytesIO()
23
+ img.save(out, format="WEBP", quality=WEBP_QUALITY, method=6)
24
+ return out.getvalue()
backend/app/storage/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from app.storage.base import PhotoStorage
3
+
4
+
5
+ def get_storage() -> PhotoStorage:
6
+ backend = os.getenv("PHOTO_STORAGE_BACKEND", "local").lower()
7
+ if backend == "local":
8
+ from app.storage.local_disk import LocalDiskStorage
9
+ return LocalDiskStorage(
10
+ root=os.getenv("LOCAL_PHOTO_ROOT", "/data/photos"),
11
+ url_prefix=os.getenv("LOCAL_PHOTO_URL_PREFIX", "/api/v1/photos"),
12
+ )
13
+ if backend == "supabase":
14
+ from app.storage.supabase import SupabaseStorage
15
+ return SupabaseStorage(
16
+ url=os.getenv("SUPABASE_URL", ""),
17
+ key=os.getenv("SUPABASE_SERVICE_KEY", ""),
18
+ bucket=os.getenv("SUPABASE_PHOTO_BUCKET", "user-photos"),
19
+ )
20
+ raise ValueError(f"Unknown PHOTO_STORAGE_BACKEND: {backend}")
backend/app/storage/base.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Protocol
2
+
3
+
4
+ class PhotoStorage(Protocol):
5
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
6
+ """Persiste el archivo y devuelve la ruta/identificador canónico que se guarda en BD."""
7
+ ...
8
+
9
+ def delete(self, path_or_url: str) -> None:
10
+ """Borra el archivo. Best-effort, no levanta si no existe."""
11
+ ...
12
+
13
+ def get_url(self, path_or_url: str) -> str:
14
+ """Devuelve la URL pública/firmada que el frontend usa para mostrar la foto."""
15
+ ...
backend/app/storage/in_memory.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+
3
+
4
+ class InMemoryStorage:
5
+ def __init__(self) -> None:
6
+ self.files: dict[str, bytes] = {}
7
+
8
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
9
+ path = f"mem://{account_id}/{user_id}/{uuid.uuid4()}.{ext}"
10
+ self.files[path] = content
11
+ return path
12
+
13
+ def delete(self, path_or_url: str) -> None:
14
+ self.files.pop(path_or_url, None)
15
+
16
+ def get_url(self, path_or_url: str) -> str:
17
+ return path_or_url
backend/app/storage/local_disk.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from pathlib import Path
3
+
4
+
5
+ class LocalDiskStorage:
6
+ def __init__(self, root: str, url_prefix: str = "/api/v1/photos") -> None:
7
+ self.root = Path(root)
8
+ self.url_prefix = url_prefix.rstrip("/")
9
+
10
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
11
+ rel = f"{account_id}/{user_id}/{uuid.uuid4()}.{ext}"
12
+ target = self.root / rel
13
+ target.parent.mkdir(parents=True, exist_ok=True)
14
+ target.write_bytes(content)
15
+ return rel
16
+
17
+ def delete(self, path_or_url: str) -> None:
18
+ rel = path_or_url
19
+ if path_or_url.startswith(self.url_prefix + "/"):
20
+ rel = path_or_url[len(self.url_prefix) + 1:]
21
+ target = self.root / rel
22
+ try:
23
+ target.unlink()
24
+ except FileNotFoundError:
25
+ pass
26
+
27
+ def get_url(self, path_or_url: str) -> str:
28
+ if path_or_url.startswith("http://") or path_or_url.startswith("https://"):
29
+ return path_or_url
30
+ if path_or_url.startswith(self.url_prefix + "/"):
31
+ return path_or_url
32
+ return f"{self.url_prefix}/{path_or_url}"
backend/app/storage/supabase.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class SupabaseStorage:
2
+ """Stub. Se implementa cuando lleguen credenciales de Supabase."""
3
+
4
+ def __init__(self, url: str, key: str, bucket: str) -> None:
5
+ self.url = url
6
+ self.key = key
7
+ self.bucket = bucket
8
+
9
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
10
+ raise NotImplementedError(
11
+ "SupabaseStorage upload todavía no implementado — usar PHOTO_STORAGE_BACKEND=local"
12
+ )
13
+
14
+ def delete(self, path_or_url: str) -> None:
15
+ raise NotImplementedError(
16
+ "SupabaseStorage delete todavía no implementado"
17
+ )
18
+
19
+ def get_url(self, path_or_url: str) -> str:
20
+ raise NotImplementedError(
21
+ "SupabaseStorage get_url todavía no implementado"
22
+ )
backend/requirements.txt CHANGED
@@ -17,3 +17,6 @@ alembic==1.14.0
17
  httpx==0.28.1
18
  tzdata==2026.2
19
  openpyxl==3.1.5
 
 
 
 
17
  httpx==0.28.1
18
  tzdata==2026.2
19
  openpyxl==3.1.5
20
+ Pillow>=10.0.0
21
+ python-magic>=0.4.27
22
+ pytest>=9.0.0
backend/tests/services/__init__.py ADDED
File without changes
backend/tests/services/test_photo_pipeline.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import pytest
3
+ from PIL import Image
4
+ from app.services.photo_pipeline import process_user_photo, MAX_INPUT_BYTES, TARGET_MAX_DIM
5
+
6
+
7
+ def _png(width: int, height: int) -> bytes:
8
+ img = Image.new("RGB", (width, height), color=(123, 45, 67))
9
+ buf = BytesIO()
10
+ img.save(buf, format="PNG")
11
+ return buf.getvalue()
12
+
13
+
14
+ def _jpeg(width: int, height: int) -> bytes:
15
+ img = Image.new("RGB", (width, height), color=(10, 20, 30))
16
+ buf = BytesIO()
17
+ img.save(buf, format="JPEG")
18
+ return buf.getvalue()
19
+
20
+
21
+ def test_accepts_png_and_returns_webp():
22
+ out = process_user_photo(_png(400, 300))
23
+ img = Image.open(BytesIO(out))
24
+ assert img.format == "WEBP"
25
+ assert img.size == (400, 300)
26
+
27
+
28
+ def test_accepts_jpeg_and_resizes_large_image():
29
+ out = process_user_photo(_jpeg(2000, 1000))
30
+ img = Image.open(BytesIO(out))
31
+ assert img.format == "WEBP"
32
+ assert max(img.size) == TARGET_MAX_DIM
33
+
34
+
35
+ def test_rejects_oversize_input():
36
+ big = _png(50, 50) + b"\x00" * (MAX_INPUT_BYTES + 1)
37
+ with pytest.raises(ValueError, match="exceeds"):
38
+ process_user_photo(big)
39
+
40
+
41
+ def test_rejects_gif():
42
+ img = Image.new("RGB", (10, 10))
43
+ buf = BytesIO()
44
+ img.save(buf, format="GIF")
45
+ with pytest.raises(ValueError, match="unsupported"):
46
+ process_user_photo(buf.getvalue())
47
+
48
+
49
+ def test_rejects_non_image_bytes():
50
+ with pytest.raises(ValueError, match="unsupported"):
51
+ process_user_photo(b"not-an-image" * 10)
backend/tests/storage/__init__.py ADDED
File without changes
backend/tests/storage/test_factory.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from app.storage import get_storage
3
+ from app.storage.local_disk import LocalDiskStorage
4
+ from app.storage.supabase import SupabaseStorage
5
+
6
+
7
+ def test_default_backend_is_local(monkeypatch):
8
+ monkeypatch.delenv("PHOTO_STORAGE_BACKEND", raising=False)
9
+ s = get_storage()
10
+ assert isinstance(s, LocalDiskStorage)
11
+
12
+
13
+ def test_supabase_backend(monkeypatch):
14
+ monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "supabase")
15
+ s = get_storage()
16
+ assert isinstance(s, SupabaseStorage)
17
+
18
+
19
+ def test_unknown_backend_raises(monkeypatch):
20
+ monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "azureblobs")
21
+ with pytest.raises(ValueError, match="Unknown PHOTO_STORAGE_BACKEND"):
22
+ get_storage()
backend/tests/storage/test_in_memory.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from app.storage.in_memory import InMemoryStorage
3
+
4
+
5
+ def test_upload_returns_unique_path():
6
+ storage = InMemoryStorage()
7
+ p1 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp")
8
+ p2 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp")
9
+ assert p1 != p2
10
+ assert p1.startswith("mem://1/10/") and p1.endswith(".webp")
11
+
12
+
13
+ def test_get_url_returns_canonical_form():
14
+ storage = InMemoryStorage()
15
+ path = storage.upload(1, 10, b"x", "webp")
16
+ assert storage.get_url(path) == path
17
+
18
+
19
+ def test_delete_is_idempotent():
20
+ storage = InMemoryStorage()
21
+ path = storage.upload(1, 10, b"x", "webp")
22
+ storage.delete(path)
23
+ storage.delete(path)
24
+ storage.delete("mem://does/not/exist.webp")
25
+
26
+
27
+ def test_files_attribute_exposes_content_for_assertions():
28
+ storage = InMemoryStorage()
29
+ path = storage.upload(1, 10, b"hello", "webp")
30
+ assert storage.files[path] == b"hello"
backend/tests/storage/test_local_disk.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import pytest
3
+ from app.storage.local_disk import LocalDiskStorage
4
+
5
+
6
+ @pytest.fixture
7
+ def storage(tmp_path: Path) -> LocalDiskStorage:
8
+ return LocalDiskStorage(root=str(tmp_path), url_prefix="/api/v1/photos")
9
+
10
+
11
+ def test_upload_creates_file(storage: LocalDiskStorage, tmp_path: Path):
12
+ path = storage.upload(account_id=2, user_id=20, content=b"abc", ext="webp")
13
+ assert path.startswith("2/20/") and path.endswith(".webp")
14
+ full = tmp_path / path
15
+ assert full.read_bytes() == b"abc"
16
+
17
+
18
+ def test_upload_creates_parent_dirs(storage: LocalDiskStorage, tmp_path: Path):
19
+ path = storage.upload(99, 999, b"x", "webp")
20
+ assert (tmp_path / path).exists()
21
+
22
+
23
+ def test_get_url_prepends_prefix(storage: LocalDiskStorage):
24
+ path = storage.upload(1, 1, b"x", "webp")
25
+ assert storage.get_url(path) == f"/api/v1/photos/{path}"
26
+
27
+
28
+ def test_delete_removes_file(storage: LocalDiskStorage, tmp_path: Path):
29
+ path = storage.upload(1, 1, b"x", "webp")
30
+ storage.delete(path)
31
+ assert not (tmp_path / path).exists()
32
+
33
+
34
+ def test_delete_missing_file_does_not_raise(storage: LocalDiskStorage):
35
+ storage.delete("nope/nope.webp")
backend/tests/storage/test_supabase.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from app.storage.supabase import SupabaseStorage
3
+
4
+
5
+ def test_upload_raises_until_credentials_arrive():
6
+ storage = SupabaseStorage(url="", key="", bucket="user-photos")
7
+ with pytest.raises(NotImplementedError, match="Supabase"):
8
+ storage.upload(1, 1, b"x", "webp")
9
+
10
+
11
+ def test_constructor_stores_config_without_calling_network():
12
+ s = SupabaseStorage(url="https://example.supabase.co", key="k", bucket="b")
13
+ assert s.bucket == "b"
backend/tests/test_admin_attendance.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date
2
+ import pytest
3
+ from fastapi.testclient import TestClient
4
+
5
+ from app.main import app
6
+ from app.core.database import SessionLocal, Base, engine
7
+ from app.models.plan import Plan
8
+ from app.models.account import Account
9
+ from app.models.user import User
10
+ from app.models.section import Section
11
+ from app.models.subject import Subject
12
+ from app.models.enrollment import Enrollment
13
+ from app.models.attendance import Attendance
14
+ from app.models.entrance_log import EntranceLog
15
+ from app.core.security import hash_password
16
+
17
+
18
+ @pytest.fixture(scope="module")
19
+ def client():
20
+ Base.metadata.create_all(bind=engine)
21
+ yield TestClient(app)
22
+
23
+
24
+ def _cleanup(db, org_name):
25
+ accs = db.query(Account).filter(Account.organization_name == org_name).all()
26
+ for acc in accs:
27
+ try:
28
+ from app.models.audit_log import AuditLog
29
+ db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete()
30
+ except Exception:
31
+ pass
32
+ db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete()
33
+ db.query(Attendance).filter(Attendance.account_id == acc.id).delete()
34
+ db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete()
35
+ db.query(Section).filter(Section.account_id == acc.id).delete()
36
+ db.query(Subject).filter(Subject.account_id == acc.id).delete()
37
+ db.query(User).filter(User.account_id == acc.id).update({"parent_id": None})
38
+ db.query(User).filter(User.account_id == acc.id).delete()
39
+ db.query(Account).filter(Account.id == acc.id).delete()
40
+ db.commit()
41
+
42
+
43
+ def _seed(db, org_name, admin_email, student_email, teacher_email=None):
44
+ plan = db.query(Plan).first()
45
+ if not plan:
46
+ plan = Plan(name="basic", features=[], price=0)
47
+ db.add(plan); db.commit(); db.refresh(plan)
48
+ acc = Account(organization_name=org_name, plan_id=plan.id, category="school")
49
+ db.add(acc); db.commit(); db.refresh(acc)
50
+ admin = User(account_id=acc.id, name="A", lastname="A",
51
+ email=admin_email, password_hash=hash_password("x"),
52
+ role="admin", is_active="1")
53
+ student = User(account_id=acc.id, name="S", lastname="S",
54
+ email=student_email, password_hash=hash_password("x"),
55
+ role="student", is_active="1", sex="M")
56
+ users = [admin, student]
57
+ teacher = None
58
+ if teacher_email:
59
+ teacher = User(account_id=acc.id, name="T", lastname="T",
60
+ email=teacher_email, password_hash=hash_password("x"),
61
+ role="teacher", is_active="1")
62
+ users.append(teacher)
63
+ db.add_all(users); db.commit()
64
+ for u in users: db.refresh(u)
65
+ sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40)
66
+ subj = Subject(account_id=acc.id, name="Mate")
67
+ db.add_all([sec, subj]); db.commit(); db.refresh(sec); db.refresh(subj)
68
+ db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=student.id))
69
+ db.commit()
70
+ return acc, admin, student, sec, subj, teacher
71
+
72
+
73
+ def _login(client, email):
74
+ r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"})
75
+ return r.json()["access_token"]
76
+
77
+
78
+ # Task 20: GET /admin/sections
79
+
80
+ def test_admin_lists_all_sections_of_their_account(client):
81
+ org = "AdminAtt_ListSections"
82
+ db = SessionLocal()
83
+ try:
84
+ _cleanup(db, org)
85
+ acc, admin, _, sec, _, _ = _seed(db, org, "ad_ls_admin@talos.com", "ad_ls_s@talos.com")
86
+ section_id = sec.id
87
+ finally:
88
+ db.close()
89
+
90
+ token = _login(client, "ad_ls_admin@talos.com")
91
+ r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"})
92
+ assert r.status_code == 200, r.text
93
+ ids = [s["id"] for s in r.json()]
94
+ assert section_id in ids
95
+
96
+ db = SessionLocal()
97
+ try:
98
+ _cleanup(db, org)
99
+ finally:
100
+ db.close()
101
+
102
+
103
+ def test_admin_cannot_see_sections_of_other_account(client):
104
+ org_a = "AdminAtt_CrossA"; org_b = "AdminAtt_CrossB"
105
+ db = SessionLocal()
106
+ try:
107
+ _cleanup(db, org_a); _cleanup(db, org_b)
108
+ _, admin_a, _, _, _, _ = _seed(db, org_a, "ad_xa_admin@talos.com", "ad_xa_s@talos.com")
109
+ _, _, _, sec_b, _, _ = _seed(db, org_b, "ad_xb_admin@talos.com", "ad_xb_s@talos.com")
110
+ sec_b_id = sec_b.id
111
+ finally:
112
+ db.close()
113
+
114
+ token = _login(client, "ad_xa_admin@talos.com")
115
+ r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"})
116
+ assert r.status_code == 200
117
+ ids = [s["id"] for s in r.json()]
118
+ assert sec_b_id not in ids
119
+
120
+ db = SessionLocal()
121
+ try:
122
+ _cleanup(db, org_a); _cleanup(db, org_b)
123
+ finally:
124
+ db.close()
125
+
126
+
127
+ def test_teacher_role_is_forbidden_on_admin_sections(client):
128
+ org = "AdminAtt_TeacherForbid"
129
+ db = SessionLocal()
130
+ try:
131
+ _cleanup(db, org)
132
+ _seed(db, org, "ad_tf_admin@talos.com", "ad_tf_s@talos.com", "ad_tf_teacher@talos.com")
133
+ finally:
134
+ db.close()
135
+
136
+ token = _login(client, "ad_tf_teacher@talos.com")
137
+ r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"})
138
+ assert r.status_code in (401, 403)
139
+
140
+ db = SessionLocal()
141
+ try:
142
+ _cleanup(db, org)
143
+ finally:
144
+ db.close()
145
+
146
+
147
+ # Task 21: GET /admin/sections/{id}/roster
148
+
149
+ def test_admin_roster_returns_enrolled_students(client):
150
+ org = "AdminAtt_Roster"
151
+ db = SessionLocal()
152
+ try:
153
+ _cleanup(db, org)
154
+ acc, admin, student, sec, _, _ = _seed(db, org, "ad_r_admin@talos.com", "ad_r_s@talos.com")
155
+ sec_id, student_id = sec.id, student.id
156
+ finally:
157
+ db.close()
158
+
159
+ token = _login(client, "ad_r_admin@talos.com")
160
+ r = client.get(
161
+ f"/api/v1/admin/sections/{sec_id}/roster",
162
+ headers={"Authorization": f"Bearer {token}"},
163
+ )
164
+ assert r.status_code == 200, r.text
165
+ items = r.json()
166
+ assert any(it["id"] == student_id for it in items)
167
+ item = next(it for it in items if it["id"] == student_id)
168
+ assert "already_checked_in" in item
169
+ assert "entrance_logged" in item
170
+
171
+ db = SessionLocal()
172
+ try:
173
+ _cleanup(db, org)
174
+ finally:
175
+ db.close()
176
+
177
+
178
+ def test_admin_roster_404_for_foreign_section(client):
179
+ org_a = "AdminAtt_RostA"; org_b = "AdminAtt_RostB"
180
+ db = SessionLocal()
181
+ try:
182
+ _cleanup(db, org_a); _cleanup(db, org_b)
183
+ _, _, _, _, _, _ = _seed(db, org_a, "ad_rxa_admin@talos.com", "ad_rxa_s@talos.com")
184
+ _, _, _, sec_b, _, _ = _seed(db, org_b, "ad_rxb_admin@talos.com", "ad_rxb_s@talos.com")
185
+ sec_b_id = sec_b.id
186
+ finally:
187
+ db.close()
188
+
189
+ token = _login(client, "ad_rxa_admin@talos.com")
190
+ r = client.get(
191
+ f"/api/v1/admin/sections/{sec_b_id}/roster",
192
+ headers={"Authorization": f"Bearer {token}"},
193
+ )
194
+ assert r.status_code == 404
195
+
196
+ db = SessionLocal()
197
+ try:
198
+ _cleanup(db, org_a); _cleanup(db, org_b)
199
+ finally:
200
+ db.close()
201
+
202
+
203
+ # Task 22: POST /admin/attendance/swipe
204
+
205
+ def test_admin_swipe_marks_with_admin_attribution(client):
206
+ org = "AdminAtt_SwipeAttrib"
207
+ db = SessionLocal()
208
+ try:
209
+ _cleanup(db, org)
210
+ _, admin, student, sec, subj, _ = _seed(
211
+ db, org, "ad_sw_admin@talos.com", "ad_sw_s@talos.com"
212
+ )
213
+ admin_id, sec_id, subj_id, student_id = admin.id, sec.id, subj.id, student.id
214
+ finally:
215
+ db.close()
216
+
217
+ token = _login(client, "ad_sw_admin@talos.com")
218
+ r = client.post(
219
+ "/api/v1/admin/attendance/swipe",
220
+ headers={"Authorization": f"Bearer {token}"},
221
+ json={
222
+ "section_id": sec_id,
223
+ "subject_id": subj_id,
224
+ "records": [{"student_id": student_id, "present": True}],
225
+ },
226
+ )
227
+ assert r.status_code == 201, r.text
228
+ assert r.json()["created"] == 1
229
+
230
+ db = SessionLocal()
231
+ try:
232
+ row = (
233
+ db.query(Attendance)
234
+ .filter(
235
+ Attendance.user_id == student_id,
236
+ Attendance.section_id == sec_id,
237
+ )
238
+ .order_by(Attendance.id.desc())
239
+ .first()
240
+ )
241
+ assert row is not None
242
+ assert row.marked_by_role == "admin"
243
+ assert row.marked_by_user_id == admin_id
244
+ finally:
245
+ _cleanup(db, org)
246
+ db.close()
247
+
248
+
249
+ def test_admin_swipe_works_without_entrance_log(client):
250
+ """Admin marks should never block on gate, ever."""
251
+ org = "AdminAtt_SwipeNoGate"
252
+ db = SessionLocal()
253
+ try:
254
+ _cleanup(db, org)
255
+ _, _, student, sec, subj, _ = _seed(db, org, "ad_swng_admin@talos.com", "ad_swng_s@talos.com")
256
+ sec_id, subj_id, student_id = sec.id, subj.id, student.id
257
+ finally:
258
+ db.close()
259
+
260
+ token = _login(client, "ad_swng_admin@talos.com")
261
+ r = client.post(
262
+ "/api/v1/admin/attendance/swipe",
263
+ headers={"Authorization": f"Bearer {token}"},
264
+ json={
265
+ "section_id": sec_id,
266
+ "subject_id": subj_id,
267
+ "records": [{"student_id": student_id, "present": True}],
268
+ },
269
+ )
270
+ assert r.status_code == 201
271
+ assert r.json()["created"] == 1
272
+
273
+ db = SessionLocal()
274
+ try:
275
+ _cleanup(db, org)
276
+ finally:
277
+ db.close()
278
+
279
+
280
+ def test_admin_swipe_404_for_foreign_section(client):
281
+ org_a = "AdminAtt_SwipeXA"; org_b = "AdminAtt_SwipeXB"
282
+ db = SessionLocal()
283
+ try:
284
+ _cleanup(db, org_a); _cleanup(db, org_b)
285
+ _, _, _, _, _, _ = _seed(db, org_a, "ad_sxa_admin@talos.com", "ad_sxa_s@talos.com")
286
+ _, _, student_b, sec_b, subj_b, _ = _seed(
287
+ db, org_b, "ad_sxb_admin@talos.com", "ad_sxb_s@talos.com"
288
+ )
289
+ sec_b_id, subj_b_id, student_b_id = sec_b.id, subj_b.id, student_b.id
290
+ finally:
291
+ db.close()
292
+
293
+ token = _login(client, "ad_sxa_admin@talos.com")
294
+ r = client.post(
295
+ "/api/v1/admin/attendance/swipe",
296
+ headers={"Authorization": f"Bearer {token}"},
297
+ json={
298
+ "section_id": sec_b_id,
299
+ "subject_id": subj_b_id,
300
+ "records": [{"student_id": student_b_id, "present": True}],
301
+ },
302
+ )
303
+ assert r.status_code == 404
304
+
305
+ db = SessionLocal()
306
+ try:
307
+ _cleanup(db, org_a); _cleanup(db, org_b)
308
+ finally:
309
+ db.close()
310
+
311
+
312
+ # Task 23: POST /admin/attendance/batch-toggle
313
+
314
+ def test_admin_batch_toggle_for_past_date(client):
315
+ org = "AdminAtt_BatchPastDate"
316
+ db = SessionLocal()
317
+ try:
318
+ _cleanup(db, org)
319
+ _, admin, student, sec, subj, _ = _seed(db, org, "ad_b_admin@talos.com", "ad_b_s@talos.com")
320
+ sec_id, subj_id, student_id, admin_id = sec.id, subj.id, student.id, admin.id
321
+ finally:
322
+ db.close()
323
+
324
+ token = _login(client, "ad_b_admin@talos.com")
325
+ r = client.post(
326
+ "/api/v1/admin/attendance/batch-toggle?date=2026-06-01",
327
+ headers={"Authorization": f"Bearer {token}"},
328
+ json={
329
+ "section_id": sec_id,
330
+ "subject_id": subj_id,
331
+ "records": [{"student_id": student_id, "present": True}],
332
+ },
333
+ )
334
+ assert r.status_code == 200, r.text
335
+
336
+ db = SessionLocal()
337
+ try:
338
+ row = (
339
+ db.query(Attendance)
340
+ .filter(
341
+ Attendance.user_id == student_id,
342
+ Attendance.section_id == sec_id,
343
+ )
344
+ .order_by(Attendance.id.desc())
345
+ .first()
346
+ )
347
+ assert row is not None
348
+ assert row.marked_by_role == "admin"
349
+ assert row.marked_by_user_id == admin_id
350
+ assert row.time_log.date().isoformat() == "2026-06-01"
351
+ finally:
352
+ _cleanup(db, org)
353
+ db.close()
backend/tests/test_attendance_service.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date, datetime, timezone
2
+ import pytest
3
+
4
+ from app.core.database import SessionLocal, Base, engine
5
+ from app.models.plan import Plan
6
+ from app.models.account import Account
7
+ from app.models.user import User
8
+ from app.models.section import Section
9
+ from app.models.subject import Subject
10
+ from app.models.enrollment import Enrollment
11
+ from app.models.entrance_log import EntranceLog
12
+ from app.models.attendance import Attendance
13
+ from app.core.security import hash_password
14
+
15
+
16
+ @pytest.fixture(scope="module")
17
+ def setup_db():
18
+ Base.metadata.create_all(bind=engine)
19
+
20
+
21
+ def _cleanup(db, org_name):
22
+ accs = db.query(Account).filter(Account.organization_name == org_name).all()
23
+ for acc in accs:
24
+ try:
25
+ from app.models.audit_log import AuditLog
26
+ db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete()
27
+ except Exception:
28
+ pass
29
+ db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete()
30
+ db.query(Attendance).filter(Attendance.account_id == acc.id).delete()
31
+ db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete()
32
+ db.query(Section).filter(Section.account_id == acc.id).delete()
33
+ db.query(Subject).filter(Subject.account_id == acc.id).delete()
34
+ db.query(User).filter(User.account_id == acc.id).update({"parent_id": None})
35
+ db.query(User).filter(User.account_id == acc.id).delete()
36
+ db.query(Account).filter(Account.id == acc.id).delete()
37
+ db.commit()
38
+
39
+
40
+ def _seed_basic(db, org_name):
41
+ plan = db.query(Plan).first()
42
+ if not plan:
43
+ plan = Plan(name="basic", features=[], price=0)
44
+ db.add(plan); db.commit(); db.refresh(plan)
45
+ acc = Account(organization_name=org_name, plan_id=plan.id, category="school")
46
+ db.add(acc); db.commit(); db.refresh(acc)
47
+ admin = User(account_id=acc.id, name="A", lastname="A",
48
+ email=f"{org_name}_admin@talos.com", password_hash=hash_password("x"),
49
+ role="admin", is_active="1")
50
+ student = User(account_id=acc.id, name="S", lastname="S",
51
+ email=f"{org_name}_student@talos.com", password_hash=hash_password("x"),
52
+ role="student", is_active="1", sex="M")
53
+ db.add_all([admin, student]); db.commit()
54
+ db.refresh(admin); db.refresh(student)
55
+ sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40)
56
+ db.add(sec); db.commit(); db.refresh(sec)
57
+ db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=student.id))
58
+ db.commit()
59
+ return acc, admin, student, sec
60
+
61
+
62
+ # Task 14 tests: record_attendance
63
+
64
+ def test_record_attendance_persists_with_attribution(setup_db):
65
+ from app.services.attendance import record_attendance
66
+
67
+ org = "AttSvc_Record_Persists"
68
+ db = SessionLocal()
69
+ try:
70
+ _cleanup(db, org)
71
+ acc, admin, student, sec = _seed_basic(db, org)
72
+ att = record_attendance(
73
+ db,
74
+ account_id=acc.id,
75
+ user_id=student.id,
76
+ section_id=sec.id,
77
+ subject_id=None,
78
+ action="in",
79
+ marked_by_role="admin",
80
+ marked_by_user_id=admin.id,
81
+ when=datetime.now(timezone.utc),
82
+ note="Manual test",
83
+ )
84
+ assert att.id is not None
85
+ assert att.marked_by_role == "admin"
86
+ assert att.marked_by_user_id == admin.id
87
+ assert att.action == "in"
88
+ assert att.note == "Manual test"
89
+ finally:
90
+ _cleanup(db, org)
91
+ db.close()
92
+
93
+
94
+ def test_record_attendance_idempotent_same_day_same_section(setup_db):
95
+ from app.services.attendance import record_attendance
96
+
97
+ org = "AttSvc_Record_Idempotent"
98
+ db = SessionLocal()
99
+ try:
100
+ _cleanup(db, org)
101
+ acc, admin, student, sec = _seed_basic(db, org)
102
+ args = dict(
103
+ account_id=acc.id,
104
+ user_id=student.id,
105
+ section_id=sec.id,
106
+ subject_id=None,
107
+ action="in",
108
+ marked_by_role="teacher",
109
+ marked_by_user_id=admin.id,
110
+ when=datetime.now(timezone.utc),
111
+ note=None,
112
+ )
113
+ first = record_attendance(db, **args)
114
+ second = record_attendance(db, **args)
115
+ rows = db.query(Attendance).filter(
116
+ Attendance.user_id == student.id,
117
+ Attendance.section_id == sec.id,
118
+ ).all()
119
+ assert len(rows) == 1
120
+ assert second.id == first.id == rows[0].id
121
+ finally:
122
+ _cleanup(db, org)
123
+ db.close()
124
+
125
+
126
+ # Task 15 tests: list_section_roster
127
+
128
+ def test_list_section_roster_returns_students_with_chips(setup_db):
129
+ from app.services.attendance import list_section_roster
130
+
131
+ org = "AttSvc_Roster_Basic"
132
+ db = SessionLocal()
133
+ try:
134
+ _cleanup(db, org)
135
+ acc, _, student, sec = _seed_basic(db, org)
136
+ items = list_section_roster(
137
+ db,
138
+ account_id=acc.id,
139
+ section_id=sec.id,
140
+ on_date=date.today(),
141
+ )
142
+ assert any(it.id == student.id for it in items)
143
+ item = next(it for it in items if it.id == student.id)
144
+ assert hasattr(item, "already_checked_in")
145
+ assert hasattr(item, "entrance_logged")
146
+ # No attendance and no entrance log seeded → both False
147
+ assert item.already_checked_in is False
148
+ assert item.entrance_logged is False
149
+ finally:
150
+ _cleanup(db, org)
151
+ db.close()
152
+
153
+
154
+ def test_list_section_roster_reflects_attendance_and_entrance_log(setup_db):
155
+ from app.services.attendance import list_section_roster
156
+
157
+ org = "AttSvc_Roster_WithChips"
158
+ db = SessionLocal()
159
+ try:
160
+ _cleanup(db, org)
161
+ acc, admin, student, sec = _seed_basic(db, org)
162
+ today = date.today()
163
+ # Seed entrance log
164
+ db.add(EntranceLog(account_id=acc.id, user_id=student.id, date=today,
165
+ method="manual", checkin_time=datetime.now(timezone.utc)))
166
+ # Seed an "in" attendance
167
+ db.add(Attendance(
168
+ account_id=acc.id, user_id=student.id, section_id=sec.id,
169
+ action="in",
170
+ marked_by_role="teacher", marked_by_user_id=admin.id,
171
+ ))
172
+ db.commit()
173
+
174
+ items = list_section_roster(
175
+ db,
176
+ account_id=acc.id,
177
+ section_id=sec.id,
178
+ on_date=today,
179
+ )
180
+ item = next(it for it in items if it.id == student.id)
181
+ assert item.already_checked_in is True
182
+ assert item.entrance_logged is True
183
+ finally:
184
+ _cleanup(db, org)
185
+ db.close()
186
+
187
+
188
+ def test_list_section_roster_excludes_inactive_students(setup_db):
189
+ from app.services.attendance import list_section_roster
190
+
191
+ org = "AttSvc_Roster_InactiveExcluded"
192
+ db = SessionLocal()
193
+ try:
194
+ _cleanup(db, org)
195
+ acc, _, student, sec = _seed_basic(db, org)
196
+ # Mark student inactive
197
+ student.is_active = "0"
198
+ db.commit()
199
+
200
+ items = list_section_roster(
201
+ db,
202
+ account_id=acc.id,
203
+ section_id=sec.id,
204
+ on_date=date.today(),
205
+ )
206
+ assert not any(it.id == student.id for it in items)
207
+ finally:
208
+ _cleanup(db, org)
209
+ db.close()
backend/tests/test_dashboard_sex_by_section.py CHANGED
@@ -11,6 +11,7 @@ from app.models.section import Section
11
  from app.models.enrollment import Enrollment
12
  from app.models.teacher_section import TeacherSection
13
  from app.models.entrance_log import EntranceLog
 
14
  from app.core.security import hash_password
15
 
16
 
@@ -23,6 +24,7 @@ def client():
23
  def _cleanup(db, acc_id):
24
  """Remove all seeded data for account acc_id in FK-safe order."""
25
  db.query(EntranceLog).filter(EntranceLog.account_id == acc_id).delete()
 
26
  try:
27
  from app.models.audit_log import AuditLog
28
  db.query(AuditLog).filter(AuditLog.account_id == acc_id).delete()
@@ -204,3 +206,64 @@ def test_sex_by_section_400_on_malformed_section_ids(client):
204
  r2 = client.get("/api/v1/dashboard/sex-by-section?section_ids=abc",
205
  headers={"Authorization": f"Bearer {token}"})
206
  assert r2.status_code == 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  from app.models.enrollment import Enrollment
12
  from app.models.teacher_section import TeacherSection
13
  from app.models.entrance_log import EntranceLog
14
+ from app.models.attendance import Attendance
15
  from app.core.security import hash_password
16
 
17
 
 
24
  def _cleanup(db, acc_id):
25
  """Remove all seeded data for account acc_id in FK-safe order."""
26
  db.query(EntranceLog).filter(EntranceLog.account_id == acc_id).delete()
27
+ db.query(Attendance).filter(Attendance.account_id == acc_id).delete()
28
  try:
29
  from app.models.audit_log import AuditLog
30
  db.query(AuditLog).filter(AuditLog.account_id == acc_id).delete()
 
206
  r2 = client.get("/api/v1/dashboard/sex-by-section?section_ids=abc",
207
  headers={"Authorization": f"Bearer {token}"})
208
  assert r2.status_code == 400
209
+
210
+
211
+ def test_sex_by_section_counts_classroom_attendance_without_gate_log(client):
212
+ """TA-01 regression: student marked present in class via Attendance.action='in'
213
+ must appear in the chart even with NO EntranceLog (gate-decoupled contingency).
214
+ """
215
+ org_name = "SbsTest_ClassNoGate"
216
+ acc_id = None
217
+ db = SessionLocal()
218
+ try:
219
+ _cleanup_by_org_name(db, org_name)
220
+ plan = db.query(Plan).first()
221
+ acc = Account(organization_name=org_name, plan_id=plan.id, category="school")
222
+ db.add(acc); db.commit(); db.refresh(acc)
223
+ acc_id = acc.id
224
+ admin = User(account_id=acc.id, name="A", lastname="A",
225
+ email=f"sbs_cng_admin_{acc.id}@talos.com",
226
+ password_hash=hash_password("x"),
227
+ role="admin", is_active="1", sex="M")
228
+ db.add(admin); db.commit(); db.refresh(admin)
229
+ sec = Section(account_id=acc.id, name="Z", academic_period="2025-2026", max_students=40)
230
+ db.add(sec); db.commit(); db.refresh(sec)
231
+ # One M student, one F student. Both enrolled in sec.
232
+ # Only Attendance "in" rows — NO EntranceLog. Simulates gate-down contingency.
233
+ sm = User(account_id=acc.id, name="cng_m", lastname="X", role="student", is_active="1",
234
+ email=f"sbs_cng_m_{acc.id}@talos.com", password_hash=hash_password("x"), sex="M")
235
+ sf = User(account_id=acc.id, name="cng_f", lastname="X", role="student", is_active="1",
236
+ email=f"sbs_cng_f_{acc.id}@talos.com", password_hash=hash_password("x"), sex="F")
237
+ db.add_all([sm, sf]); db.commit(); db.refresh(sm); db.refresh(sf)
238
+ db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=sm.id))
239
+ db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=sf.id))
240
+ db.add(Attendance(
241
+ account_id=acc.id, user_id=sm.id, section_id=sec.id,
242
+ action="in", marked_by_role="admin", marked_by_user_id=admin.id,
243
+ ))
244
+ db.add(Attendance(
245
+ account_id=acc.id, user_id=sf.id, section_id=sec.id,
246
+ action="in", marked_by_role="teacher", marked_by_user_id=admin.id,
247
+ ))
248
+ db.commit()
249
+ admin_email = admin.email
250
+ finally:
251
+ db.close()
252
+
253
+ try:
254
+ token = _login(client, admin_email)
255
+ r = client.get("/api/v1/dashboard/sex-by-section",
256
+ headers={"Authorization": f"Bearer {token}"})
257
+ assert r.status_code == 200
258
+ body = r.json()
259
+ sec_z = next(s for s in body["sections"] if s["section_name"] == "Z")
260
+ assert sec_z["masculino"] == 1, f"expected 1 M, got {sec_z}"
261
+ assert sec_z["femenino"] == 1, f"expected 1 F, got {sec_z}"
262
+ assert sec_z["total"] == 2
263
+ finally:
264
+ db = SessionLocal()
265
+ try:
266
+ if acc_id is not None:
267
+ _cleanup(db, acc_id)
268
+ finally:
269
+ db.close()
backend/tests/test_dashboard_stats_union.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TA-01 regression: dashboard /stats and /attendance-trend count attendance
2
+ as union of EntranceLog (gate) and Attendance "in" (classroom), deduped per
3
+ (user, day). A student marked present in class without gate check-in (per
4
+ the TA-01 contingency path) must still appear in the counts.
5
+ """
6
+ from datetime import date, datetime, timezone
7
+
8
+ import pytest
9
+ from fastapi.testclient import TestClient
10
+
11
+ from app.main import app
12
+ from app.core.database import SessionLocal, Base, engine
13
+ from app.models.plan import Plan
14
+ from app.models.account import Account
15
+ from app.models.user import User
16
+ from app.models.section import Section
17
+ from app.models.enrollment import Enrollment
18
+ from app.models.attendance import Attendance
19
+ from app.models.entrance_log import EntranceLog
20
+ from app.core.security import hash_password
21
+
22
+
23
+ @pytest.fixture(scope="module")
24
+ def client():
25
+ Base.metadata.create_all(bind=engine)
26
+ yield TestClient(app)
27
+
28
+
29
+ def _cleanup(db, org_name):
30
+ accs = db.query(Account).filter(Account.organization_name == org_name).all()
31
+ for acc in accs:
32
+ try:
33
+ from app.models.audit_log import AuditLog
34
+ db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete()
35
+ except Exception:
36
+ pass
37
+ db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete()
38
+ db.query(Attendance).filter(Attendance.account_id == acc.id).delete()
39
+ db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete()
40
+ db.query(Section).filter(Section.account_id == acc.id).delete()
41
+ db.query(User).filter(User.account_id == acc.id).update({"parent_id": None})
42
+ db.query(User).filter(User.account_id == acc.id).delete()
43
+ db.query(Account).filter(Account.id == acc.id).delete()
44
+ db.commit()
45
+
46
+
47
+ def _seed_admin_section(db, org_name, n_students=3):
48
+ plan = db.query(Plan).first()
49
+ if not plan:
50
+ plan = Plan(name="basic", features=[], price=0)
51
+ db.add(plan); db.commit(); db.refresh(plan)
52
+ acc = Account(organization_name=org_name, plan_id=plan.id, category="school")
53
+ db.add(acc); db.commit(); db.refresh(acc)
54
+ admin = User(
55
+ account_id=acc.id, name="A", lastname="A",
56
+ email=f"sru_admin_{acc.id}@talos.com", password_hash=hash_password("x"),
57
+ role="admin", is_active="1", sex="M",
58
+ )
59
+ db.add(admin); db.commit(); db.refresh(admin)
60
+ sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40)
61
+ db.add(sec); db.commit(); db.refresh(sec)
62
+ students = []
63
+ for i in range(n_students):
64
+ s = User(
65
+ account_id=acc.id, name=f"s{i}", lastname="X", role="student", is_active="1",
66
+ email=f"sru_s{i}_{acc.id}@talos.com", password_hash=hash_password("x"), sex="M",
67
+ )
68
+ db.add(s); db.commit(); db.refresh(s)
69
+ db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=s.id))
70
+ students.append(s)
71
+ db.commit()
72
+ return acc, admin, sec, students
73
+
74
+
75
+ def _login(client, email):
76
+ r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"})
77
+ return r.json()["access_token"]
78
+
79
+
80
+ def test_stats_today_checkins_includes_class_only_marks(client):
81
+ """A student marked present in class only (no EntranceLog) counts in today_checkins."""
82
+ org = "DashStats_ClassOnly"
83
+ db = SessionLocal()
84
+ try:
85
+ _cleanup(db, org)
86
+ acc, admin, sec, students = _seed_admin_section(db, org, n_students=2)
87
+ # Student[0]: only class mark, NO gate.
88
+ db.add(Attendance(
89
+ account_id=acc.id, user_id=students[0].id, section_id=sec.id,
90
+ action="in", marked_by_role="admin", marked_by_user_id=admin.id,
91
+ ))
92
+ # Student[1]: only gate.
93
+ db.add(EntranceLog(
94
+ account_id=acc.id, user_id=students[1].id, date=date.today(),
95
+ method="manual", checkin_time=datetime.now(timezone.utc),
96
+ ))
97
+ db.commit()
98
+ admin_email = admin.email
99
+ finally:
100
+ db.close()
101
+
102
+ try:
103
+ token = _login(client, admin_email)
104
+ r = client.get("/api/v1/dashboard/stats",
105
+ headers={"Authorization": f"Bearer {token}"})
106
+ assert r.status_code == 200, r.text
107
+ body = r.json()
108
+ # Both students counted: 1 via class, 1 via gate.
109
+ assert body["today_checkins"] == 2, body
110
+ finally:
111
+ db = SessionLocal()
112
+ try:
113
+ _cleanup(db, org)
114
+ finally:
115
+ db.close()
116
+
117
+
118
+ def test_stats_today_checkins_dedupes_student_with_both_events(client):
119
+ """Student with EntranceLog AND Attendance 'in' counts ONCE."""
120
+ org = "DashStats_Dedup"
121
+ db = SessionLocal()
122
+ try:
123
+ _cleanup(db, org)
124
+ acc, admin, sec, students = _seed_admin_section(db, org, n_students=1)
125
+ # Same student: both gate + class.
126
+ db.add(EntranceLog(
127
+ account_id=acc.id, user_id=students[0].id, date=date.today(),
128
+ method="manual", checkin_time=datetime.now(timezone.utc),
129
+ ))
130
+ db.add(Attendance(
131
+ account_id=acc.id, user_id=students[0].id, section_id=sec.id,
132
+ action="in", marked_by_role="teacher", marked_by_user_id=admin.id,
133
+ ))
134
+ db.commit()
135
+ admin_email = admin.email
136
+ finally:
137
+ db.close()
138
+
139
+ try:
140
+ token = _login(client, admin_email)
141
+ r = client.get("/api/v1/dashboard/stats",
142
+ headers={"Authorization": f"Bearer {token}"})
143
+ assert r.status_code == 200
144
+ body = r.json()
145
+ assert body["today_checkins"] == 1, f"expected 1 (deduped), got {body['today_checkins']}"
146
+ finally:
147
+ db = SessionLocal()
148
+ try:
149
+ _cleanup(db, org)
150
+ finally:
151
+ db.close()
152
+
153
+
154
+ def test_stats_currently_on_campus_subtracts_exits(client):
155
+ """currently_on_campus = present_today - exited_today (union semantics)."""
156
+ org = "DashStats_OnCampus"
157
+ db = SessionLocal()
158
+ try:
159
+ _cleanup(db, org)
160
+ acc, admin, sec, students = _seed_admin_section(db, org, n_students=3)
161
+ # s0: gate in + checked out → counted in checkouts, NOT in on-campus
162
+ db.add(EntranceLog(
163
+ account_id=acc.id, user_id=students[0].id, date=date.today(),
164
+ method="manual", checkin_time=datetime.now(timezone.utc),
165
+ checkout_time=datetime.now(timezone.utc),
166
+ ))
167
+ # s1: gate in, no exit → on campus
168
+ db.add(EntranceLog(
169
+ account_id=acc.id, user_id=students[1].id, date=date.today(),
170
+ method="manual", checkin_time=datetime.now(timezone.utc),
171
+ ))
172
+ # s2: class "in" only, no exit → on campus
173
+ db.add(Attendance(
174
+ account_id=acc.id, user_id=students[2].id, section_id=sec.id,
175
+ action="in", marked_by_role="admin", marked_by_user_id=admin.id,
176
+ ))
177
+ db.commit()
178
+ admin_email = admin.email
179
+ finally:
180
+ db.close()
181
+
182
+ try:
183
+ token = _login(client, admin_email)
184
+ r = client.get("/api/v1/dashboard/stats",
185
+ headers={"Authorization": f"Bearer {token}"})
186
+ assert r.status_code == 200
187
+ body = r.json()
188
+ assert body["today_checkins"] == 3, body
189
+ assert body["today_checkouts"] == 1, body # only s0 left
190
+ assert body["currently_on_campus"] == 2, body # s1 + s2
191
+ finally:
192
+ db = SessionLocal()
193
+ try:
194
+ _cleanup(db, org)
195
+ finally:
196
+ db.close()
197
+
198
+
199
+ def test_attendance_trend_unions_and_dedupes_per_day(client):
200
+ """Per-day trend counts union of gate + class, deduped per (day, user)."""
201
+ org = "DashTrend_Union"
202
+ db = SessionLocal()
203
+ try:
204
+ _cleanup(db, org)
205
+ acc, admin, sec, students = _seed_admin_section(db, org, n_students=2)
206
+ today = date.today()
207
+ # s0: gate AND class today → 1 (deduped).
208
+ db.add(EntranceLog(
209
+ account_id=acc.id, user_id=students[0].id, date=today,
210
+ method="manual", checkin_time=datetime.now(timezone.utc),
211
+ ))
212
+ db.add(Attendance(
213
+ account_id=acc.id, user_id=students[0].id, section_id=sec.id,
214
+ action="in", marked_by_role="teacher", marked_by_user_id=admin.id,
215
+ ))
216
+ # s1: class only today → 1 (would have been zero pre-fix).
217
+ db.add(Attendance(
218
+ account_id=acc.id, user_id=students[1].id, section_id=sec.id,
219
+ action="in", marked_by_role="admin", marked_by_user_id=admin.id,
220
+ ))
221
+ db.commit()
222
+ admin_email = admin.email
223
+ finally:
224
+ db.close()
225
+
226
+ try:
227
+ token = _login(client, admin_email)
228
+ r = client.get("/api/v1/dashboard/attendance-trend?days=1",
229
+ headers={"Authorization": f"Bearer {token}"})
230
+ assert r.status_code == 200, r.text
231
+ body = r.json()
232
+ # 1-day window → today only.
233
+ today_entry = next(p for p in body if p["date"] == today.isoformat())
234
+ assert today_entry["count"] == 2, f"expected 2 (s0 deduped + s1 class-only), got {today_entry}"
235
+ finally:
236
+ db = SessionLocal()
237
+ try:
238
+ _cleanup(db, org)
239
+ finally:
240
+ db.close()
backend/tests/test_teacher_attendance_gate_decouple.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date, datetime, timezone
2
+ import pytest
3
+ from fastapi.testclient import TestClient
4
+
5
+ from app.main import app
6
+ from app.core.database import SessionLocal, Base, engine
7
+ from app.models.plan import Plan
8
+ from app.models.account import Account
9
+ from app.models.user import User
10
+ from app.models.section import Section
11
+ from app.models.subject import Subject
12
+ from app.models.enrollment import Enrollment
13
+ from app.models.teacher_section import TeacherSection
14
+ from app.models.attendance import Attendance
15
+ from app.models.entrance_log import EntranceLog
16
+ from app.core.security import hash_password
17
+
18
+
19
+ @pytest.fixture(scope="module")
20
+ def client():
21
+ Base.metadata.create_all(bind=engine)
22
+ yield TestClient(app)
23
+
24
+
25
+ def _cleanup(db, org_name):
26
+ accs = db.query(Account).filter(Account.organization_name == org_name).all()
27
+ for acc in accs:
28
+ try:
29
+ from app.models.audit_log import AuditLog
30
+ db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete()
31
+ except Exception:
32
+ pass
33
+ db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete()
34
+ db.query(Attendance).filter(Attendance.account_id == acc.id).delete()
35
+ db.query(TeacherSection).filter(TeacherSection.account_id == acc.id).delete()
36
+ db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete()
37
+ db.query(Section).filter(Section.account_id == acc.id).delete()
38
+ db.query(Subject).filter(Subject.account_id == acc.id).delete()
39
+ db.query(User).filter(User.account_id == acc.id).update({"parent_id": None})
40
+ db.query(User).filter(User.account_id == acc.id).delete()
41
+ db.query(Account).filter(Account.id == acc.id).delete()
42
+ db.commit()
43
+
44
+
45
+ def _seed(db, org_name, teacher_email, student_email):
46
+ plan = db.query(Plan).first()
47
+ if not plan:
48
+ plan = Plan(name="basic", features=[], price=0)
49
+ db.add(plan); db.commit(); db.refresh(plan)
50
+ acc = Account(organization_name=org_name, plan_id=plan.id, category="school")
51
+ db.add(acc); db.commit(); db.refresh(acc)
52
+ teacher = User(
53
+ account_id=acc.id, name="T", lastname="T",
54
+ email=teacher_email, password_hash=hash_password("x"),
55
+ role="teacher", is_active="1",
56
+ )
57
+ student = User(
58
+ account_id=acc.id, name="S", lastname="S",
59
+ email=student_email, password_hash=hash_password("x"),
60
+ role="student", is_active="1", sex="M",
61
+ )
62
+ db.add_all([teacher, student]); db.commit()
63
+ db.refresh(teacher); db.refresh(student)
64
+ sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40)
65
+ subj = Subject(account_id=acc.id, name="Mate")
66
+ db.add_all([sec, subj]); db.commit(); db.refresh(sec); db.refresh(subj)
67
+ db.add(TeacherSection(account_id=acc.id, section_id=sec.id, subject_id=subj.id, teacher_id=teacher.id))
68
+ db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=student.id))
69
+ db.commit()
70
+ return acc, teacher, sec, subj, student
71
+
72
+
73
+ def _login(client, email):
74
+ r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"})
75
+ return r.json()["access_token"]
76
+
77
+
78
+ def test_swipe_marks_student_without_entrance_log_as_present(client):
79
+ org = "GateDecouple_Swipe"
80
+ db = SessionLocal()
81
+ try:
82
+ _cleanup(db, org)
83
+ acc, teacher, sec, subj, student = _seed(
84
+ db, org, "gd_swipe_t@talos.com", "gd_swipe_s@talos.com"
85
+ )
86
+ section_id, subject_id, student_id = sec.id, subj.id, student.id
87
+ # NOTE: no EntranceLog seeded for this student
88
+ finally:
89
+ db.close()
90
+
91
+ token = _login(client, "gd_swipe_t@talos.com")
92
+ r = client.post(
93
+ "/api/v1/teacher/attendance/swipe",
94
+ headers={"Authorization": f"Bearer {token}"},
95
+ json={
96
+ "section_id": section_id,
97
+ "subject_id": subject_id,
98
+ "records": [{"student_id": student_id, "present": True}],
99
+ },
100
+ )
101
+ assert r.status_code == 201, r.text
102
+ body = r.json()
103
+ # After Task 19: should be created=1, skipped=[]
104
+ assert body["created"] == 1, f"expected created=1, got body={body}"
105
+ assert body["skipped"] == [], f"expected skipped=[], got {body['skipped']}"
106
+
107
+ db = SessionLocal()
108
+ try:
109
+ _cleanup(db, org)
110
+ finally:
111
+ db.close()
112
+
113
+
114
+ def test_batch_toggle_marks_student_without_entrance_log(client):
115
+ org = "GateDecouple_Batch"
116
+ db = SessionLocal()
117
+ try:
118
+ _cleanup(db, org)
119
+ acc, teacher, sec, subj, student = _seed(
120
+ db, org, "gd_batch_t@talos.com", "gd_batch_s@talos.com"
121
+ )
122
+ section_id, subject_id, student_id = sec.id, subj.id, student.id
123
+ finally:
124
+ db.close()
125
+
126
+ token = _login(client, "gd_batch_t@talos.com")
127
+ r = client.post(
128
+ "/api/v1/teacher/attendance/batch-toggle",
129
+ headers={"Authorization": f"Bearer {token}"},
130
+ json={
131
+ "section_id": section_id,
132
+ "subject_id": subject_id,
133
+ "records": [{"student_id": student_id, "present": True}],
134
+ },
135
+ )
136
+ assert r.status_code in (200, 201), r.text
137
+ body = r.json()
138
+ # batch_toggle should not skip students due to gate
139
+ assert body.get("skipped", []) == []
140
+
141
+ # Verify a row was actually inserted
142
+ db = SessionLocal()
143
+ try:
144
+ row = db.query(Attendance).filter(
145
+ Attendance.user_id == student_id,
146
+ Attendance.section_id == section_id,
147
+ ).first()
148
+ assert row is not None, "expected attendance row inserted despite missing entrance log"
149
+ finally:
150
+ _cleanup(db, org)
151
+ db.close()
152
+
153
+
154
+ def test_roster_still_reports_entrance_logged_false(client):
155
+ """The flag is informational and must be preserved after gate decouple."""
156
+ org = "GateDecouple_Roster"
157
+ db = SessionLocal()
158
+ try:
159
+ _cleanup(db, org)
160
+ acc, teacher, sec, _, student = _seed(
161
+ db, org, "gd_roster_t@talos.com", "gd_roster_s@talos.com"
162
+ )
163
+ section_id, student_id = sec.id, student.id
164
+ finally:
165
+ db.close()
166
+
167
+ token = _login(client, "gd_roster_t@talos.com")
168
+ r = client.get(
169
+ f"/api/v1/teacher/sections/{section_id}/students",
170
+ headers={"Authorization": f"Bearer {token}"},
171
+ )
172
+ assert r.status_code == 200, r.text
173
+ items = r.json()
174
+ target = next((it for it in items if it["id"] == student_id), None)
175
+ assert target is not None, "student missing from roster"
176
+ assert target["entrance_logged"] is False, "info flag must remain"
177
+
178
+ db = SessionLocal()
179
+ try:
180
+ _cleanup(db, org)
181
+ finally:
182
+ db.close()
backend/tests/test_users_photo_upload.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import json
3
+ import pytest
4
+ from PIL import Image
5
+ from fastapi.testclient import TestClient
6
+
7
+ from app.main import app
8
+ from app.core.database import SessionLocal, Base, engine
9
+ from app.models.account import Account
10
+ from app.models.user import User
11
+ from app.models.plan import Plan
12
+ from app.models.face_encoding import FaceEncoding
13
+ from app.core.security import hash_password
14
+ from app.storage.in_memory import InMemoryStorage
15
+ import app.api.v1.endpoints.users as users_mod
16
+
17
+
18
+ @pytest.fixture(scope="module")
19
+ def client():
20
+ Base.metadata.create_all(bind=engine)
21
+ yield TestClient(app)
22
+
23
+
24
+ @pytest.fixture
25
+ def fake_storage(monkeypatch):
26
+ fake = InMemoryStorage()
27
+ monkeypatch.setattr(users_mod, "get_storage", lambda: fake)
28
+ return fake
29
+
30
+
31
+ def _cleanup(db, org_name):
32
+ accs = db.query(Account).filter(Account.organization_name == org_name).all()
33
+ for acc in accs:
34
+ db.query(FaceEncoding).filter(FaceEncoding.account_id == acc.id).delete()
35
+ try:
36
+ from app.models.audit_log import AuditLog
37
+ db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete()
38
+ except Exception:
39
+ pass
40
+ db.query(User).filter(User.account_id == acc.id).update({"parent_id": None})
41
+ db.query(User).filter(User.account_id == acc.id).delete()
42
+ db.query(Account).filter(Account.id == acc.id).delete()
43
+ db.commit()
44
+
45
+
46
+ def _seed(db, org_name, admin_email, student_email):
47
+ plan = db.query(Plan).first()
48
+ if not plan:
49
+ plan = Plan(name="basic", features=[], price=0)
50
+ db.add(plan); db.commit(); db.refresh(plan)
51
+ acc = Account(organization_name=org_name, plan_id=plan.id, category="school")
52
+ db.add(acc); db.commit(); db.refresh(acc)
53
+ admin = User(
54
+ account_id=acc.id, name="A", lastname="A",
55
+ email=admin_email, password_hash=hash_password("x"),
56
+ role="admin", is_active="1",
57
+ )
58
+ db.add(admin); db.commit(); db.refresh(admin)
59
+ student = User(
60
+ account_id=acc.id, name="S", lastname="S",
61
+ email=student_email, password_hash=hash_password("x"),
62
+ role="student", is_active="1",
63
+ )
64
+ db.add(student); db.commit(); db.refresh(student)
65
+ return acc, admin, student
66
+
67
+
68
+ def _login(client, email):
69
+ r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"})
70
+ return r.json()["access_token"]
71
+
72
+
73
+ def _png_bytes(w=50, h=50) -> bytes:
74
+ buf = BytesIO()
75
+ Image.new("RGB", (w, h), color=(1, 2, 3)).save(buf, format="PNG")
76
+ return buf.getvalue()
77
+
78
+
79
+ def _gif_bytes() -> bytes:
80
+ buf = BytesIO()
81
+ Image.new("RGB", (10, 10)).save(buf, format="GIF")
82
+ return buf.getvalue()
83
+
84
+
85
+ def test_admin_uploads_photo_returns_url_and_creates_face_encoding(client, fake_storage):
86
+ org = "PhotoUpload_Happy"
87
+ db = SessionLocal()
88
+ try:
89
+ _cleanup(db, org)
90
+ _, admin, student = _seed(db, org, "ph_admin@talos.com", "ph_student@talos.com")
91
+ admin_id, student_id, acc_id = admin.id, student.id, admin.account_id
92
+ finally:
93
+ db.close()
94
+
95
+ token = _login(client, "ph_admin@talos.com")
96
+ r = client.post(
97
+ f"/api/v1/users/{student_id}/photo",
98
+ headers={"Authorization": f"Bearer {token}"},
99
+ files={"file": ("a.png", _png_bytes(), "image/png")},
100
+ )
101
+ assert r.status_code == 200, r.text
102
+ body = r.json()
103
+ assert "photo_url" in body
104
+ assert "encoding_extracted" in body
105
+ assert len(fake_storage.files) == 1
106
+
107
+ db = SessionLocal()
108
+ try:
109
+ fe = db.query(FaceEncoding).filter(FaceEncoding.user_id == student_id).first()
110
+ assert fe is not None
111
+ assert fe.photo is not None and not fe.photo.startswith("data:")
112
+ finally:
113
+ _cleanup(db, org)
114
+ db.close()
115
+
116
+
117
+ def test_non_admin_role_forbidden(client, fake_storage):
118
+ org = "PhotoUpload_NonAdmin"
119
+ db = SessionLocal()
120
+ try:
121
+ _cleanup(db, org)
122
+ plan = db.query(Plan).first()
123
+ if not plan:
124
+ plan = Plan(name="basic", features=[], price=0)
125
+ db.add(plan); db.commit(); db.refresh(plan)
126
+ acc = Account(organization_name=org, plan_id=plan.id, category="school")
127
+ db.add(acc); db.commit(); db.refresh(acc)
128
+ teacher = User(
129
+ account_id=acc.id, name="T", lastname="T",
130
+ email="ph_teacher@talos.com", password_hash=hash_password("x"),
131
+ role="teacher", is_active="1",
132
+ )
133
+ student = User(
134
+ account_id=acc.id, name="S", lastname="S",
135
+ email="ph_student2@talos.com", password_hash=hash_password("x"),
136
+ role="student", is_active="1",
137
+ )
138
+ db.add_all([teacher, student]); db.commit()
139
+ db.refresh(teacher); db.refresh(student)
140
+ student_id = student.id
141
+ finally:
142
+ db.close()
143
+
144
+ token = _login(client, "ph_teacher@talos.com")
145
+ r = client.post(
146
+ f"/api/v1/users/{student_id}/photo",
147
+ headers={"Authorization": f"Bearer {token}"},
148
+ files={"file": ("a.png", _png_bytes(), "image/png")},
149
+ )
150
+ assert r.status_code in (401, 403)
151
+
152
+ db = SessionLocal()
153
+ try:
154
+ _cleanup(db, org)
155
+ finally:
156
+ db.close()
157
+
158
+
159
+ def test_rejects_gif_with_422(client, fake_storage):
160
+ org = "PhotoUpload_Gif"
161
+ db = SessionLocal()
162
+ try:
163
+ _cleanup(db, org)
164
+ _, admin, student = _seed(db, org, "ph_gif_admin@talos.com", "ph_gif_student@talos.com")
165
+ student_id = student.id
166
+ finally:
167
+ db.close()
168
+
169
+ token = _login(client, "ph_gif_admin@talos.com")
170
+ r = client.post(
171
+ f"/api/v1/users/{student_id}/photo",
172
+ headers={"Authorization": f"Bearer {token}"},
173
+ files={"file": ("a.gif", _gif_bytes(), "image/gif")},
174
+ )
175
+ assert r.status_code == 422
176
+
177
+ db = SessionLocal()
178
+ try:
179
+ _cleanup(db, org)
180
+ finally:
181
+ db.close()
182
+
183
+
184
+ def test_second_upload_deletes_previous_storage_file(client, fake_storage):
185
+ org = "PhotoUpload_Replace"
186
+ db = SessionLocal()
187
+ try:
188
+ _cleanup(db, org)
189
+ _, admin, student = _seed(db, org, "ph_rep_admin@talos.com", "ph_rep_student@talos.com")
190
+ student_id = student.id
191
+ finally:
192
+ db.close()
193
+
194
+ token = _login(client, "ph_rep_admin@talos.com")
195
+ h = {"Authorization": f"Bearer {token}"}
196
+ client.post(f"/api/v1/users/{student_id}/photo", headers=h, files={"file": ("a.png", _png_bytes(), "image/png")})
197
+ client.post(f"/api/v1/users/{student_id}/photo", headers=h, files={"file": ("b.png", _png_bytes(), "image/png")})
198
+
199
+ assert len(fake_storage.files) == 1 # only the second upload remains
200
+
201
+ db = SessionLocal()
202
+ try:
203
+ _cleanup(db, org)
204
+ finally:
205
+ db.close()
206
+
207
+
208
+ def test_cross_account_user_returns_404(client, fake_storage):
209
+ org_a = "PhotoUpload_AcctA"
210
+ org_b = "PhotoUpload_AcctB"
211
+ db = SessionLocal()
212
+ try:
213
+ _cleanup(db, org_a); _cleanup(db, org_b)
214
+ _, admin_a, _ = _seed(db, org_a, "ph_xa_admin@talos.com", "ph_xa_s@talos.com")
215
+ _, _, student_b = _seed(db, org_b, "ph_xb_admin@talos.com", "ph_xb_s@talos.com")
216
+ target_id = student_b.id # belongs to org B
217
+ finally:
218
+ db.close()
219
+
220
+ token = _login(client, "ph_xa_admin@talos.com")
221
+ r = client.post(
222
+ f"/api/v1/users/{target_id}/photo",
223
+ headers={"Authorization": f"Bearer {token}"},
224
+ files={"file": ("a.png", _png_bytes(), "image/png")},
225
+ )
226
+ assert r.status_code == 404
227
+
228
+ db = SessionLocal()
229
+ try:
230
+ _cleanup(db, org_a); _cleanup(db, org_b)
231
+ finally:
232
+ db.close()
docker-compose.yml CHANGED
@@ -38,10 +38,17 @@ services:
38
  JWT_SECRET_KEY: ${JWT_SECRET_KEY:-dev-only-change-me}
39
  SEED_DEMO: "1"
40
  CORS_ORIGINS: '["*"]'
 
 
 
 
 
 
41
  ports:
42
  - "8000:8000"
43
  volumes:
44
  - ./backend:/app
 
45
 
46
  frontend:
47
  build:
@@ -57,3 +64,4 @@ services:
57
 
58
  volumes:
59
  talos_pg_data:
 
 
38
  JWT_SECRET_KEY: ${JWT_SECRET_KEY:-dev-only-change-me}
39
  SEED_DEMO: "1"
40
  CORS_ORIGINS: '["*"]'
41
+ PHOTO_STORAGE_BACKEND: ${PHOTO_STORAGE_BACKEND:-local}
42
+ LOCAL_PHOTO_ROOT: /data/photos
43
+ LOCAL_PHOTO_URL_PREFIX: /api/v1/photos
44
+ SUPABASE_URL: ${SUPABASE_URL:-}
45
+ SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_KEY:-}
46
+ SUPABASE_PHOTO_BUCKET: ${SUPABASE_PHOTO_BUCKET:-user-photos}
47
  ports:
48
  - "8000:8000"
49
  volumes:
50
  - ./backend:/app
51
+ - photo_data:/data/photos
52
 
53
  frontend:
54
  build:
 
64
 
65
  volumes:
66
  talos_pg_data:
67
+ photo_data:
docs/sprints/2026-06-05_TA-01.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Optimización y Carga de Fotografías de Usuarios
2
+ * **Situación Actual:** Actualmente, las fotos de los usuarios se están guardando directamente en la base de datos como cadenas en Base64 (lo cual está afectando el rendimiento y el almacenamiento).
3
+
4
+ * **Nuevo Requerimiento:** * Además de capturar la foto en línea (cámara), el administrador debe poder subir archivos en formatos `png`, `jpg`, `jpeg` y `webp`.
5
+ * Antes de guardarse, la imagen debe pasar por un proceso de compresión eficiente (buscando reducir el almacenamiento en disco pero manteniendo una calidad visual óptima, "lossless" o compresión controlada).
6
+ * La imagen ya no se guardará en Base64 en la BD; ahora se subirá a un Storage y en la base de datos solo se almacenará la ruta/URL de acceso.
7
+ * *Nota de contexto:* Más adelante te proporcionaré las credenciales y accesos al bucket de Supabase Storage que utilizaremos para esto. Por ahora, diseña la lógica de forma agnóstica o preparada para Supabase.
8
+
9
+ ### 2. Módulo de Asistencia Administrativa (Casos de Contingencia)
10
+ * **Requerimiento:** Crear una nueva vista/interfaz dedicada para que los administradores del sistema puedan tomar asistencia directamente en el aula.
11
+
12
+ * **Caso de Uso:** Un profesor se enfermó o no asistió a clases, por lo que un administrador debe ir físicamente al aula a pasar lista a los alumnos de esa sección.
13
+
14
+ ### 3. Flexibilidad en las Reglas de Negocio de Asistencia (Check-in General vs. Asistencia de Aula)
15
+ * **Requerimiento:** El proceso de Check-in/Check-out del plantel (entrada/salida general) NO debe ser restrictivo para la asistencia en el aula. Un alumno puede ser marcado como "Asistente" en su clase/materia, incluso si no registra entrada en el acceso principal del plantel.
16
+
17
+ * **Caso de Uso:** Fallas tecnológicas (falla en el sistema de reconocimiento con OpenCV, corte de electricidad, o pérdida de internet en el equipo del kiosco de entrada). Los alumnos no pudieron hacer Check-in al entrar al plantel, pero el docente (o el administrador) debe poder registrar la asistencia de forma singular en su respectiva materia sin que el sistema bloquee la acción.
18
+
19
+ ---
20
+
21
+ ### Lo que espero de tu respuesta:
22
+ 1. **Diseño de Base de Datos:** Qué cambios o nuevas columnas/tablas sugieres (ej. cambiar el tipo de dato de la foto, campos para los estados de asistencia).
23
+ 2. **Estrategia de Procesamiento de Imágenes:** Qué librerías o enfoque recomiendas para la compresión en el backend antes de subir al storage.
24
+ 3. **Arquitectura del Flujo de Asistencia:** Cómo estructurar la lógica para que convivan el Check-in general (OpenCV/Kiosco) y la asistencia manual por aula sin depender estrictamente el uno del otro.
docs/superpowers/plans/2026-06-05-ta01-storage-and-attendance.md ADDED
@@ -0,0 +1,2247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TA-01 Implementation Plan — Storage de fotos + asistencia administrativa + flexibilidad gate
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Migrar fotos de usuarios de Base64 en BD a Supabase Storage (con disco local en dev), agregar una vista admin para tomar asistencia por contingencia, y desacoplar la asistencia de aula del check-in en gate.
6
+
7
+ **Architecture:** Tres bloques entregados en una sola unidad. Bloque A introduce una capa `PhotoStorage` con adapters intercambiables y un pipeline de compresión WebP. Bloque B extrae un servicio `services/attendance.py` reutilizado por nuevos endpoints `/admin/attendance/*` y agrega trazabilidad (`marked_by_role`, `marked_by_user_id`). Bloque C es un cambio quirúrgico: remover el filtro `entrance_logged_ids` del servicio compartido.
8
+
9
+ **Tech Stack:** FastAPI, SQLAlchemy, Alembic, PostgreSQL, Pillow, python-magic, pytest. Frontend: React + TypeScript + Recharts (no usado en este sprint pero ya instalado).
10
+
11
+ **Spec:** [`docs/superpowers/specs/2026-06-05-ta01-storage-and-attendance-design.md`](../specs/2026-06-05-ta01-storage-and-attendance-design.md)
12
+
13
+ ---
14
+
15
+ ## Phase 0 — Foundation (DB migration + models)
16
+
17
+ ### Task 1: Crear migración Alembic 028
18
+
19
+ **Files:**
20
+ - Create: `backend/migrations/versions/028_ta01_storage_and_attendance_attribution.py`
21
+
22
+ - [ ] **Step 1: Identificar revisión previa**
23
+
24
+ Run: `ls backend/migrations/versions/ | sort | tail -3`
25
+ Tomar el `down_revision` del archivo más reciente (debe ser `027_create_maria_antonia_valero_account`).
26
+
27
+ - [ ] **Step 2: Escribir la migración**
28
+
29
+ ```python
30
+ """TA-01: storage paths and attendance attribution
31
+
32
+ Revision ID: 028_ta01_storage_attribution
33
+ Revises: 027_create_maria_antonia_valero_account
34
+ Create Date: 2026-06-05
35
+ """
36
+ from alembic import op
37
+ import sqlalchemy as sa
38
+
39
+ revision = "028_ta01_storage_attribution"
40
+ down_revision = "027_create_maria_antonia_valero_account"
41
+ branch_labels = None
42
+ depends_on = None
43
+
44
+
45
+ def upgrade() -> None:
46
+ # Bloque A: face_encodings.photo de Text(base64) a VARCHAR(500) URL/path.
47
+ # Cleanup de filas existentes: vaciar photo (el admin re-sube) y permitir encoding NULL.
48
+ op.execute("UPDATE face_encodings SET photo = NULL")
49
+ op.alter_column(
50
+ "face_encodings", "photo",
51
+ existing_type=sa.Text(),
52
+ type_=sa.String(length=500),
53
+ existing_nullable=True,
54
+ )
55
+ op.alter_column(
56
+ "face_encodings", "encoding",
57
+ existing_type=sa.Text(),
58
+ nullable=True,
59
+ )
60
+
61
+ # Bloque B: trazabilidad de origen de la marca.
62
+ op.add_column(
63
+ "attendances",
64
+ sa.Column("marked_by_role", sa.String(length=20), nullable=True),
65
+ )
66
+ op.add_column(
67
+ "attendances",
68
+ sa.Column("marked_by_user_id", sa.BigInteger(), nullable=True),
69
+ )
70
+ op.create_foreign_key(
71
+ "fk_attendances_marked_by_user",
72
+ "attendances", "users",
73
+ ["marked_by_user_id"], ["id"],
74
+ )
75
+ op.create_index(
76
+ "ix_attendances_marked_by_user_id",
77
+ "attendances", ["marked_by_user_id"],
78
+ )
79
+
80
+
81
+ def downgrade() -> None:
82
+ op.drop_index("ix_attendances_marked_by_user_id", table_name="attendances")
83
+ op.drop_constraint("fk_attendances_marked_by_user", "attendances", type_="foreignkey")
84
+ op.drop_column("attendances", "marked_by_user_id")
85
+ op.drop_column("attendances", "marked_by_role")
86
+ op.alter_column(
87
+ "face_encodings", "encoding",
88
+ existing_type=sa.Text(),
89
+ nullable=False,
90
+ )
91
+ op.alter_column(
92
+ "face_encodings", "photo",
93
+ existing_type=sa.String(length=500),
94
+ type_=sa.Text(),
95
+ existing_nullable=True,
96
+ )
97
+ ```
98
+
99
+ - [ ] **Step 3: Aplicar localmente y verificar**
100
+
101
+ Run: `docker compose exec backend alembic upgrade head`
102
+ Expected: `Running upgrade 027_... -> 028_ta01_storage_attribution`
103
+
104
+ Run: `docker compose exec backend python -c "from sqlalchemy import inspect; from app.core.database import engine; i = inspect(engine); cols = [c['name'] for c in i.get_columns('attendances')]; print(cols)"`
105
+ Expected: incluye `marked_by_role` y `marked_by_user_id`.
106
+
107
+ - [ ] **Step 4: Probar roundtrip downgrade/upgrade**
108
+
109
+ Run: `docker compose exec backend alembic downgrade -1 && docker compose exec backend alembic upgrade head`
110
+ Expected: ambos exitosos.
111
+
112
+ - [ ] **Step 5: Commit**
113
+
114
+ ```bash
115
+ git add backend/migrations/versions/028_ta01_storage_and_attendance_attribution.py
116
+ git commit -m "feat(ta-01): migration for photo URL column + attendance attribution"
117
+ ```
118
+
119
+ ---
120
+
121
+ ### Task 2: Actualizar modelos SQLAlchemy
122
+
123
+ **Files:**
124
+ - Modify: `backend/app/models/face_encoding.py`
125
+ - Modify: `backend/app/models/attendance.py`
126
+
127
+ - [ ] **Step 1: Modificar `face_encoding.py`**
128
+
129
+ Reemplazar el cuerpo de la clase:
130
+
131
+ ```python
132
+ from sqlalchemy import Column, BigInteger, Text, String, DateTime, ForeignKey
133
+ from sqlalchemy import func
134
+ from app.core.database import Base
135
+
136
+
137
+ class FaceEncoding(Base):
138
+ __tablename__ = "face_encodings"
139
+
140
+ id = Column(BigInteger, primary_key=True, autoincrement=True)
141
+ user_id = Column(BigInteger, ForeignKey("users.id"), nullable=False)
142
+ account_id = Column(BigInteger, ForeignKey("accounts.id"), nullable=False)
143
+ encoding = Column(Text, nullable=True)
144
+ photo = Column(String(500), nullable=True)
145
+ created_at = Column(DateTime, server_default=func.now())
146
+ ```
147
+
148
+ - [ ] **Step 2: Modificar `attendance.py`**
149
+
150
+ Reemplazar el cuerpo de la clase:
151
+
152
+ ```python
153
+ from sqlalchemy import Column, BigInteger, String, DateTime, JSON, ForeignKey
154
+ from sqlalchemy import func
155
+ from app.core.database import Base
156
+
157
+
158
+ class Attendance(Base):
159
+ __tablename__ = "attendances"
160
+
161
+ id = Column(BigInteger, primary_key=True, autoincrement=True)
162
+ account_id = Column(BigInteger, ForeignKey("accounts.id"), nullable=False)
163
+ user_id = Column(BigInteger, ForeignKey("users.id"), nullable=False)
164
+ section_id = Column(BigInteger, ForeignKey("sections.id"), nullable=True)
165
+ time_log = Column(DateTime(timezone=True), server_default=func.now())
166
+ checkout_time = Column(DateTime(timezone=True), nullable=True)
167
+ coordinates = Column(JSON)
168
+ note = Column(String(255))
169
+ action = Column(String(10), nullable=True, comment="in or out")
170
+ marked_by_role = Column(String(20), nullable=True)
171
+ marked_by_user_id = Column(BigInteger, ForeignKey("users.id"), nullable=True)
172
+ ```
173
+
174
+ - [ ] **Step 3: Verificar que el backend importa sin errores**
175
+
176
+ Run: `docker compose exec backend python -c "from app.models.attendance import Attendance; from app.models.face_encoding import FaceEncoding; print(Attendance.__table__.columns.keys()); print(FaceEncoding.__table__.columns.keys())"`
177
+ Expected: lista con `marked_by_role` y `marked_by_user_id` para attendance; `photo` para face_encoding.
178
+
179
+ - [ ] **Step 4: Commit**
180
+
181
+ ```bash
182
+ git add backend/app/models/face_encoding.py backend/app/models/attendance.py
183
+ git commit -m "feat(ta-01): update FaceEncoding and Attendance models for new columns"
184
+ ```
185
+
186
+ ---
187
+
188
+ ## Phase 1 — Block A storage abstraction
189
+
190
+ ### Task 3: Definir el Protocol `PhotoStorage`
191
+
192
+ **Files:**
193
+ - Create: `backend/app/storage/__init__.py`
194
+ - Create: `backend/app/storage/base.py`
195
+
196
+ - [ ] **Step 1: Crear `backend/app/storage/__init__.py` con la factory**
197
+
198
+ ```python
199
+ import os
200
+ from app.storage.base import PhotoStorage
201
+
202
+
203
+ def get_storage() -> PhotoStorage:
204
+ backend = os.getenv("PHOTO_STORAGE_BACKEND", "local").lower()
205
+ if backend == "local":
206
+ from app.storage.local_disk import LocalDiskStorage
207
+ return LocalDiskStorage(
208
+ root=os.getenv("LOCAL_PHOTO_ROOT", "/data/photos"),
209
+ url_prefix=os.getenv("LOCAL_PHOTO_URL_PREFIX", "/api/v1/photos"),
210
+ )
211
+ if backend == "supabase":
212
+ from app.storage.supabase import SupabaseStorage
213
+ return SupabaseStorage(
214
+ url=os.getenv("SUPABASE_URL", ""),
215
+ key=os.getenv("SUPABASE_SERVICE_KEY", ""),
216
+ bucket=os.getenv("SUPABASE_PHOTO_BUCKET", "user-photos"),
217
+ )
218
+ raise ValueError(f"Unknown PHOTO_STORAGE_BACKEND: {backend}")
219
+ ```
220
+
221
+ - [ ] **Step 2: Crear `backend/app/storage/base.py`**
222
+
223
+ ```python
224
+ from typing import Protocol
225
+
226
+
227
+ class PhotoStorage(Protocol):
228
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
229
+ """Persiste el archivo y devuelve la ruta/identificador canónico que se guarda en BD."""
230
+ ...
231
+
232
+ def delete(self, path_or_url: str) -> None:
233
+ """Borra el archivo. Best-effort, no levanta si no existe."""
234
+ ...
235
+
236
+ def get_url(self, path_or_url: str) -> str:
237
+ """Devuelve la URL pública/firmada que el frontend usa para mostrar la foto."""
238
+ ...
239
+ ```
240
+
241
+ - [ ] **Step 3: Commit**
242
+
243
+ ```bash
244
+ git add backend/app/storage/__init__.py backend/app/storage/base.py
245
+ git commit -m "feat(ta-01): add PhotoStorage Protocol and get_storage factory"
246
+ ```
247
+
248
+ ---
249
+
250
+ ### Task 4: Implementar `InMemoryStorage` con tests (TDD)
251
+
252
+ **Files:**
253
+ - Create: `backend/tests/storage/__init__.py`
254
+ - Create: `backend/tests/storage/test_in_memory.py`
255
+ - Create: `backend/app/storage/in_memory.py`
256
+
257
+ - [ ] **Step 1: Crear test fallando**
258
+
259
+ `backend/tests/storage/test_in_memory.py`:
260
+
261
+ ```python
262
+ import pytest
263
+ from app.storage.in_memory import InMemoryStorage
264
+
265
+
266
+ def test_upload_returns_unique_path():
267
+ storage = InMemoryStorage()
268
+ p1 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp")
269
+ p2 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp")
270
+ assert p1 != p2
271
+ assert p1.startswith("mem://1/10/") and p1.endswith(".webp")
272
+
273
+
274
+ def test_get_url_returns_canonical_form():
275
+ storage = InMemoryStorage()
276
+ path = storage.upload(1, 10, b"x", "webp")
277
+ assert storage.get_url(path) == path
278
+
279
+
280
+ def test_delete_is_idempotent():
281
+ storage = InMemoryStorage()
282
+ path = storage.upload(1, 10, b"x", "webp")
283
+ storage.delete(path)
284
+ storage.delete(path)
285
+ storage.delete("mem://does/not/exist.webp")
286
+
287
+
288
+ def test_files_attribute_exposes_content_for_assertions():
289
+ storage = InMemoryStorage()
290
+ path = storage.upload(1, 10, b"hello", "webp")
291
+ assert storage.files[path] == b"hello"
292
+ ```
293
+
294
+ Run: `docker compose exec backend pytest backend/tests/storage/test_in_memory.py -v`
295
+ Expected: FAIL (`ModuleNotFoundError`).
296
+
297
+ - [ ] **Step 2: Implementar el adapter**
298
+
299
+ `backend/app/storage/in_memory.py`:
300
+
301
+ ```python
302
+ import uuid
303
+
304
+
305
+ class InMemoryStorage:
306
+ def __init__(self) -> None:
307
+ self.files: dict[str, bytes] = {}
308
+
309
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
310
+ path = f"mem://{account_id}/{user_id}/{uuid.uuid4()}.{ext}"
311
+ self.files[path] = content
312
+ return path
313
+
314
+ def delete(self, path_or_url: str) -> None:
315
+ self.files.pop(path_or_url, None)
316
+
317
+ def get_url(self, path_or_url: str) -> str:
318
+ return path_or_url
319
+ ```
320
+
321
+ - [ ] **Step 3: Tests pasan**
322
+
323
+ Run: `docker compose exec backend pytest backend/tests/storage/test_in_memory.py -v`
324
+ Expected: 4 passed.
325
+
326
+ - [ ] **Step 4: Commit**
327
+
328
+ ```bash
329
+ git add backend/app/storage/in_memory.py backend/tests/storage/
330
+ git commit -m "feat(ta-01): add InMemoryStorage adapter for tests"
331
+ ```
332
+
333
+ ---
334
+
335
+ ### Task 5: Implementar `LocalDiskStorage` con tests (TDD)
336
+
337
+ **Files:**
338
+ - Create: `backend/tests/storage/test_local_disk.py`
339
+ - Create: `backend/app/storage/local_disk.py`
340
+
341
+ - [ ] **Step 1: Test fallando**
342
+
343
+ `backend/tests/storage/test_local_disk.py`:
344
+
345
+ ```python
346
+ from pathlib import Path
347
+ import pytest
348
+ from app.storage.local_disk import LocalDiskStorage
349
+
350
+
351
+ @pytest.fixture
352
+ def storage(tmp_path: Path) -> LocalDiskStorage:
353
+ return LocalDiskStorage(root=str(tmp_path), url_prefix="/api/v1/photos")
354
+
355
+
356
+ def test_upload_creates_file(storage: LocalDiskStorage, tmp_path: Path):
357
+ path = storage.upload(account_id=2, user_id=20, content=b"abc", ext="webp")
358
+ assert path.startswith("2/20/") and path.endswith(".webp")
359
+ full = tmp_path / path
360
+ assert full.read_bytes() == b"abc"
361
+
362
+
363
+ def test_upload_creates_parent_dirs(storage: LocalDiskStorage, tmp_path: Path):
364
+ path = storage.upload(99, 999, b"x", "webp")
365
+ assert (tmp_path / path).exists()
366
+
367
+
368
+ def test_get_url_prepends_prefix(storage: LocalDiskStorage):
369
+ path = storage.upload(1, 1, b"x", "webp")
370
+ assert storage.get_url(path) == f"/api/v1/photos/{path}"
371
+
372
+
373
+ def test_delete_removes_file(storage: LocalDiskStorage, tmp_path: Path):
374
+ path = storage.upload(1, 1, b"x", "webp")
375
+ storage.delete(path)
376
+ assert not (tmp_path / path).exists()
377
+
378
+
379
+ def test_delete_missing_file_does_not_raise(storage: LocalDiskStorage):
380
+ storage.delete("nope/nope.webp") # no raises
381
+ ```
382
+
383
+ Run: `docker compose exec backend pytest backend/tests/storage/test_local_disk.py -v`
384
+ Expected: FAIL.
385
+
386
+ - [ ] **Step 2: Implementar**
387
+
388
+ `backend/app/storage/local_disk.py`:
389
+
390
+ ```python
391
+ import os
392
+ import uuid
393
+ from pathlib import Path
394
+
395
+
396
+ class LocalDiskStorage:
397
+ def __init__(self, root: str, url_prefix: str = "/api/v1/photos") -> None:
398
+ self.root = Path(root)
399
+ self.url_prefix = url_prefix.rstrip("/")
400
+
401
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
402
+ rel = f"{account_id}/{user_id}/{uuid.uuid4()}.{ext}"
403
+ target = self.root / rel
404
+ target.parent.mkdir(parents=True, exist_ok=True)
405
+ target.write_bytes(content)
406
+ return rel
407
+
408
+ def delete(self, path_or_url: str) -> None:
409
+ # Acepta path relativo o URL completa
410
+ rel = path_or_url
411
+ if path_or_url.startswith(self.url_prefix + "/"):
412
+ rel = path_or_url[len(self.url_prefix) + 1:]
413
+ target = self.root / rel
414
+ try:
415
+ target.unlink()
416
+ except FileNotFoundError:
417
+ pass
418
+
419
+ def get_url(self, path_or_url: str) -> str:
420
+ if path_or_url.startswith("http://") or path_or_url.startswith("https://"):
421
+ return path_or_url
422
+ if path_or_url.startswith(self.url_prefix + "/"):
423
+ return path_or_url
424
+ return f"{self.url_prefix}/{path_or_url}"
425
+ ```
426
+
427
+ - [ ] **Step 3: Tests pasan**
428
+
429
+ Run: `docker compose exec backend pytest backend/tests/storage/test_local_disk.py -v`
430
+ Expected: 5 passed.
431
+
432
+ - [ ] **Step 4: Commit**
433
+
434
+ ```bash
435
+ git add backend/app/storage/local_disk.py backend/tests/storage/test_local_disk.py
436
+ git commit -m "feat(ta-01): add LocalDiskStorage adapter"
437
+ ```
438
+
439
+ ---
440
+
441
+ ### Task 6: Stub de `SupabaseStorage`
442
+
443
+ **Files:**
444
+ - Create: `backend/tests/storage/test_supabase.py`
445
+ - Create: `backend/app/storage/supabase.py`
446
+
447
+ - [ ] **Step 1: Test fallando**
448
+
449
+ `backend/tests/storage/test_supabase.py`:
450
+
451
+ ```python
452
+ import pytest
453
+ from app.storage.supabase import SupabaseStorage
454
+
455
+
456
+ def test_upload_raises_until_credentials_arrive():
457
+ storage = SupabaseStorage(url="", key="", bucket="user-photos")
458
+ with pytest.raises(NotImplementedError, match="Supabase"):
459
+ storage.upload(1, 1, b"x", "webp")
460
+
461
+
462
+ def test_constructor_stores_config_without_calling_network():
463
+ s = SupabaseStorage(url="https://example.supabase.co", key="k", bucket="b")
464
+ assert s.bucket == "b"
465
+ ```
466
+
467
+ Run: `docker compose exec backend pytest backend/tests/storage/test_supabase.py -v`
468
+ Expected: FAIL.
469
+
470
+ - [ ] **Step 2: Implementar el stub**
471
+
472
+ `backend/app/storage/supabase.py`:
473
+
474
+ ```python
475
+ class SupabaseStorage:
476
+ """Stub. Se implementa cuando lleguen credenciales de Supabase."""
477
+
478
+ def __init__(self, url: str, key: str, bucket: str) -> None:
479
+ self.url = url
480
+ self.key = key
481
+ self.bucket = bucket
482
+
483
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
484
+ raise NotImplementedError(
485
+ "SupabaseStorage upload todavía no implementado — usar PHOTO_STORAGE_BACKEND=local"
486
+ )
487
+
488
+ def delete(self, path_or_url: str) -> None:
489
+ raise NotImplementedError(
490
+ "SupabaseStorage delete todavía no implementado"
491
+ )
492
+
493
+ def get_url(self, path_or_url: str) -> str:
494
+ raise NotImplementedError(
495
+ "SupabaseStorage get_url todavía no implementado"
496
+ )
497
+ ```
498
+
499
+ - [ ] **Step 3: Tests pasan**
500
+
501
+ Run: `docker compose exec backend pytest backend/tests/storage/test_supabase.py -v`
502
+ Expected: 2 passed.
503
+
504
+ - [ ] **Step 4: Commit**
505
+
506
+ ```bash
507
+ git add backend/app/storage/supabase.py backend/tests/storage/test_supabase.py
508
+ git commit -m "feat(ta-01): add SupabaseStorage stub (pending credentials)"
509
+ ```
510
+
511
+ ---
512
+
513
+ ### Task 7: Test de la factory `get_storage`
514
+
515
+ **Files:**
516
+ - Create: `backend/tests/storage/test_factory.py`
517
+
518
+ - [ ] **Step 1: Test**
519
+
520
+ `backend/tests/storage/test_factory.py`:
521
+
522
+ ```python
523
+ import pytest
524
+ from app.storage import get_storage
525
+ from app.storage.local_disk import LocalDiskStorage
526
+ from app.storage.supabase import SupabaseStorage
527
+
528
+
529
+ def test_default_backend_is_local(monkeypatch):
530
+ monkeypatch.delenv("PHOTO_STORAGE_BACKEND", raising=False)
531
+ s = get_storage()
532
+ assert isinstance(s, LocalDiskStorage)
533
+
534
+
535
+ def test_supabase_backend(monkeypatch):
536
+ monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "supabase")
537
+ s = get_storage()
538
+ assert isinstance(s, SupabaseStorage)
539
+
540
+
541
+ def test_unknown_backend_raises(monkeypatch):
542
+ monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "azureblobs")
543
+ with pytest.raises(ValueError, match="Unknown PHOTO_STORAGE_BACKEND"):
544
+ get_storage()
545
+ ```
546
+
547
+ - [ ] **Step 2: Tests pasan**
548
+
549
+ Run: `docker compose exec backend pytest backend/tests/storage/test_factory.py -v`
550
+ Expected: 3 passed.
551
+
552
+ - [ ] **Step 3: Commit**
553
+
554
+ ```bash
555
+ git add backend/tests/storage/test_factory.py
556
+ git commit -m "test(ta-01): cover get_storage factory env-var switching"
557
+ ```
558
+
559
+ ---
560
+
561
+ ## Phase 2 — Block A photo pipeline + endpoint
562
+
563
+ ### Task 8: Agregar dependencias
564
+
565
+ **Files:**
566
+ - Modify: `backend/requirements.txt`
567
+
568
+ - [ ] **Step 1: Inspeccionar requirements actuales**
569
+
570
+ Run: `Grep "Pillow|python-magic" backend/requirements.txt`
571
+
572
+ - [ ] **Step 2: Asegurar líneas**
573
+
574
+ Agregar (si no están):
575
+
576
+ ```
577
+ Pillow>=10.0.0
578
+ python-magic>=0.4.27 ; sys_platform != "win32"
579
+ python-magic-bin>=0.4.14 ; sys_platform == "win32"
580
+ ```
581
+
582
+ - [ ] **Step 3: Rebuild backend image**
583
+
584
+ Run: `docker compose build backend && docker compose up -d backend`
585
+ Expected: build succeeds, container healthy.
586
+
587
+ - [ ] **Step 4: Verificar imports**
588
+
589
+ Run: `docker compose exec backend python -c "from PIL import Image, ImageOps; import magic; print('ok')"`
590
+ Expected: `ok`.
591
+
592
+ - [ ] **Step 5: Commit**
593
+
594
+ ```bash
595
+ git add backend/requirements.txt
596
+ git commit -m "chore(ta-01): add Pillow and python-magic deps for photo pipeline"
597
+ ```
598
+
599
+ ---
600
+
601
+ ### Task 9: Pipeline de procesamiento de imágenes (TDD)
602
+
603
+ **Files:**
604
+ - Create: `backend/tests/services/__init__.py`
605
+ - Create: `backend/tests/services/test_photo_pipeline.py`
606
+ - Create: `backend/app/services/__init__.py` (vacío)
607
+ - Create: `backend/app/services/photo_pipeline.py`
608
+
609
+ - [ ] **Step 1: Test fallando**
610
+
611
+ `backend/tests/services/test_photo_pipeline.py`:
612
+
613
+ ```python
614
+ from io import BytesIO
615
+ import pytest
616
+ from PIL import Image
617
+ from app.services.photo_pipeline import process_user_photo, MAX_INPUT_BYTES, TARGET_MAX_DIM
618
+
619
+
620
+ def _png(width: int, height: int) -> bytes:
621
+ img = Image.new("RGB", (width, height), color=(123, 45, 67))
622
+ buf = BytesIO()
623
+ img.save(buf, format="PNG")
624
+ return buf.getvalue()
625
+
626
+
627
+ def _jpeg(width: int, height: int) -> bytes:
628
+ img = Image.new("RGB", (width, height), color=(10, 20, 30))
629
+ buf = BytesIO()
630
+ img.save(buf, format="JPEG")
631
+ return buf.getvalue()
632
+
633
+
634
+ def test_accepts_png_and_returns_webp():
635
+ out = process_user_photo(_png(400, 300))
636
+ img = Image.open(BytesIO(out))
637
+ assert img.format == "WEBP"
638
+ assert img.size == (400, 300) # menor a 800, no resize
639
+
640
+
641
+ def test_accepts_jpeg_and_resizes_large_image():
642
+ out = process_user_photo(_jpeg(2000, 1000))
643
+ img = Image.open(BytesIO(out))
644
+ assert img.format == "WEBP"
645
+ assert max(img.size) == TARGET_MAX_DIM
646
+
647
+
648
+ def test_rejects_oversize_input():
649
+ big = _png(50, 50) + b"\x00" * (MAX_INPUT_BYTES + 1)
650
+ with pytest.raises(ValueError, match="exceeds"):
651
+ process_user_photo(big)
652
+
653
+
654
+ def test_rejects_gif():
655
+ img = Image.new("RGB", (10, 10))
656
+ buf = BytesIO()
657
+ img.save(buf, format="GIF")
658
+ with pytest.raises(ValueError, match="unsupported"):
659
+ process_user_photo(buf.getvalue())
660
+
661
+
662
+ def test_rejects_non_image_bytes():
663
+ with pytest.raises(ValueError, match="unsupported"):
664
+ process_user_photo(b"not-an-image" * 10)
665
+ ```
666
+
667
+ Run: `docker compose exec backend pytest backend/tests/services/test_photo_pipeline.py -v`
668
+ Expected: FAIL.
669
+
670
+ - [ ] **Step 2: Implementar**
671
+
672
+ `backend/app/services/__init__.py`: vacío.
673
+
674
+ `backend/app/services/photo_pipeline.py`:
675
+
676
+ ```python
677
+ from io import BytesIO
678
+ from PIL import Image, ImageOps
679
+ import magic
680
+
681
+ ALLOWED_MIME = {"image/png", "image/jpeg", "image/webp"}
682
+ MAX_INPUT_BYTES = 5 * 1024 * 1024
683
+ TARGET_MAX_DIM = 800
684
+ WEBP_QUALITY = 85
685
+
686
+
687
+ def process_user_photo(raw: bytes) -> bytes:
688
+ if len(raw) > MAX_INPUT_BYTES:
689
+ raise ValueError(f"photo exceeds {MAX_INPUT_BYTES} bytes")
690
+ mime = magic.from_buffer(raw, mime=True)
691
+ if mime not in ALLOWED_MIME:
692
+ raise ValueError(f"unsupported mime: {mime}")
693
+ img = Image.open(BytesIO(raw))
694
+ img = ImageOps.exif_transpose(img)
695
+ img.thumbnail((TARGET_MAX_DIM, TARGET_MAX_DIM), Image.LANCZOS)
696
+ if img.mode in ("RGBA", "P", "LA"):
697
+ img = img.convert("RGB")
698
+ out = BytesIO()
699
+ img.save(out, format="WEBP", quality=WEBP_QUALITY, method=6)
700
+ return out.getvalue()
701
+ ```
702
+
703
+ - [ ] **Step 3: Tests pasan**
704
+
705
+ Run: `docker compose exec backend pytest backend/tests/services/test_photo_pipeline.py -v`
706
+ Expected: 5 passed.
707
+
708
+ - [ ] **Step 4: Commit**
709
+
710
+ ```bash
711
+ git add backend/app/services/__init__.py backend/app/services/photo_pipeline.py backend/tests/services/
712
+ git commit -m "feat(ta-01): add photo_pipeline with WebP compression and validation"
713
+ ```
714
+
715
+ ---
716
+
717
+ ### Task 10: Endpoint POST `/users/{user_id}/photo` (TDD)
718
+
719
+ **Files:**
720
+ - Create: `backend/tests/api/test_users_photo_upload.py`
721
+ - Modify: `backend/app/api/v1/endpoints/users.py`
722
+
723
+ - [ ] **Step 1: Inspeccionar utilidades de auth en tests existentes**
724
+
725
+ Read: `backend/tests/test_seed_demo_scoping.py` (líneas 1-40) — copiar el patrón de cliente autenticado y fixtures.
726
+
727
+ - [ ] **Step 2: Test fallando**
728
+
729
+ `backend/tests/api/test_users_photo_upload.py`:
730
+
731
+ ```python
732
+ from io import BytesIO
733
+ import pytest
734
+ from PIL import Image
735
+ from fastapi.testclient import TestClient
736
+ from app.main import app
737
+ from app.storage import get_storage # for monkeypatching in conftest
738
+
739
+
740
+ def _png_bytes() -> bytes:
741
+ buf = BytesIO()
742
+ Image.new("RGB", (50, 50), color=(1, 2, 3)).save(buf, format="PNG")
743
+ return buf.getvalue()
744
+
745
+
746
+ @pytest.fixture
747
+ def client(monkeypatch):
748
+ # Force in-memory storage during tests
749
+ from app.storage.in_memory import InMemoryStorage
750
+ fake = InMemoryStorage()
751
+ import app.api.v1.endpoints.users as users_mod
752
+ monkeypatch.setattr(users_mod, "get_storage", lambda: fake)
753
+ return TestClient(app), fake
754
+
755
+
756
+ def test_upload_requires_admin(client, admin_token, teacher_token, demo_student_id):
757
+ c, _ = client
758
+ r = c.post(
759
+ f"/api/v1/users/{demo_student_id}/photo",
760
+ headers={"Authorization": f"Bearer {teacher_token}"},
761
+ files={"file": ("a.png", _png_bytes(), "image/png")},
762
+ )
763
+ assert r.status_code in (401, 403)
764
+
765
+
766
+ def test_upload_stores_processed_photo_and_returns_url(
767
+ client, admin_token, demo_student_id
768
+ ):
769
+ c, fake = client
770
+ r = c.post(
771
+ f"/api/v1/users/{demo_student_id}/photo",
772
+ headers={"Authorization": f"Bearer {admin_token}"},
773
+ files={"file": ("a.png", _png_bytes(), "image/png")},
774
+ )
775
+ assert r.status_code == 200, r.text
776
+ body = r.json()
777
+ assert "photo_url" in body and body["photo_url"].endswith(".webp")
778
+ assert len(fake.files) == 1
779
+
780
+
781
+ def test_upload_rejects_gif(client, admin_token, demo_student_id):
782
+ c, _ = client
783
+ buf = BytesIO()
784
+ Image.new("RGB", (10, 10)).save(buf, format="GIF")
785
+ r = c.post(
786
+ f"/api/v1/users/{demo_student_id}/photo",
787
+ headers={"Authorization": f"Bearer {admin_token}"},
788
+ files={"file": ("a.gif", buf.getvalue(), "image/gif")},
789
+ )
790
+ assert r.status_code == 422
791
+
792
+
793
+ def test_second_upload_deletes_previous(client, admin_token, demo_student_id):
794
+ c, fake = client
795
+ h = {"Authorization": f"Bearer {admin_token}"}
796
+ c.post(f"/api/v1/users/{demo_student_id}/photo", headers=h, files={"file": ("a.png", _png_bytes(), "image/png")})
797
+ c.post(f"/api/v1/users/{demo_student_id}/photo", headers=h, files={"file": ("b.png", _png_bytes(), "image/png")})
798
+ assert len(fake.files) == 1
799
+ ```
800
+
801
+ > Si los fixtures `admin_token`, `teacher_token`, `demo_student_id` no existen, crearlos en `backend/tests/conftest.py` con un alembic upgrade + seed pequeño. Patrón a copiar: ver `test_seed_demo_scoping.py`.
802
+
803
+ - [ ] **Step 3: Implementar endpoint**
804
+
805
+ En `backend/app/api/v1/endpoints/users.py` agregar al final del archivo:
806
+
807
+ ```python
808
+ from fastapi import HTTPException
809
+ from app.storage import get_storage
810
+ from app.services.photo_pipeline import process_user_photo
811
+ from app.face_utils import extract_encoding # si existe; si no, usar None
812
+
813
+
814
+ @router.post("/{user_id}/photo")
815
+ def upload_user_photo(
816
+ user_id: int,
817
+ file: UploadFile = File(...),
818
+ current_user: User = Depends(RBAC(["admin"])),
819
+ db: Session = Depends(get_db),
820
+ ):
821
+ target = db.query(User).filter(
822
+ User.id == user_id,
823
+ User.account_id == current_user.account_id,
824
+ ).first()
825
+ if not target:
826
+ raise HTTPException(status_code=404, detail="user not found")
827
+
828
+ raw = file.file.read()
829
+ try:
830
+ processed = process_user_photo(raw)
831
+ except ValueError as e:
832
+ raise HTTPException(status_code=422, detail=str(e))
833
+
834
+ try:
835
+ encoding_str = extract_encoding(processed) # devuelve str o None
836
+ except Exception:
837
+ encoding_str = None
838
+
839
+ storage = get_storage()
840
+
841
+ # Borrar foto anterior best-effort
842
+ previous = (
843
+ db.query(FaceEncoding)
844
+ .filter(FaceEncoding.user_id == user_id, FaceEncoding.photo.isnot(None))
845
+ .order_by(FaceEncoding.id.desc())
846
+ .first()
847
+ )
848
+ if previous and previous.photo:
849
+ try:
850
+ storage.delete(previous.photo)
851
+ except Exception:
852
+ pass
853
+
854
+ new_path = storage.upload(target.account_id, user_id, processed, "webp")
855
+ fe = FaceEncoding(
856
+ user_id=user_id,
857
+ account_id=target.account_id,
858
+ encoding=encoding_str,
859
+ photo=new_path,
860
+ )
861
+ db.add(fe)
862
+ db.commit()
863
+
864
+ return {
865
+ "photo_url": storage.get_url(new_path),
866
+ "encoding_extracted": encoding_str is not None,
867
+ "warning": None if encoding_str else
868
+ "no se detectó rostro; el reconocimiento facial no funcionará hasta resubir una foto con rostro visible",
869
+ }
870
+ ```
871
+
872
+ > Si `app.face_utils.extract_encoding` no tiene la firma esperada (recibe `bytes`, devuelve `str|None`), adaptar el wrapper aquí: leer la API real de `face_utils.py` y, si solo acepta `PIL.Image` o un path, hacer la conversión inline; envolver excepciones para que `encoding_str = None`.
873
+
874
+ - [ ] **Step 4: Tests pasan**
875
+
876
+ Run: `docker compose exec backend pytest backend/tests/api/test_users_photo_upload.py -v`
877
+ Expected: 4 passed.
878
+
879
+ - [ ] **Step 5: Commit**
880
+
881
+ ```bash
882
+ git add backend/app/api/v1/endpoints/users.py backend/tests/api/test_users_photo_upload.py
883
+ git commit -m "feat(ta-01): photo upload endpoint with storage + encoding extraction"
884
+ ```
885
+
886
+ ---
887
+
888
+ ### Task 11: Endpoint GET `/photos/...` para servir archivos locales
889
+
890
+ **Files:**
891
+ - Create: `backend/app/api/v1/endpoints/photos.py`
892
+ - Modify: `backend/app/api/v1/router.py` (o donde se registren routers)
893
+
894
+ - [ ] **Step 1: Identificar el router principal**
895
+
896
+ Run: `Grep "include_router" backend/app/api/v1/ -r`
897
+
898
+ - [ ] **Step 2: Crear endpoint**
899
+
900
+ `backend/app/api/v1/endpoints/photos.py`:
901
+
902
+ ```python
903
+ import os
904
+ from pathlib import Path
905
+ from fastapi import APIRouter, Depends, HTTPException
906
+ from fastapi.responses import FileResponse
907
+ from app.dependencies.auth import get_current_user
908
+ from app.models.user import User
909
+
910
+ router = APIRouter(prefix="/photos", tags=["photos"])
911
+
912
+
913
+ @router.get("/{account_id}/{user_id}/{filename}")
914
+ def serve_photo(
915
+ account_id: int,
916
+ user_id: int,
917
+ filename: str,
918
+ current_user: User = Depends(get_current_user),
919
+ ):
920
+ if os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() != "local":
921
+ raise HTTPException(status_code=404, detail="not served locally")
922
+ if current_user.account_id != account_id:
923
+ raise HTTPException(status_code=404, detail="not found")
924
+ root = Path(os.getenv("LOCAL_PHOTO_ROOT", "/data/photos"))
925
+ target = root / str(account_id) / str(user_id) / filename
926
+ if not target.exists():
927
+ raise HTTPException(status_code=404, detail="not found")
928
+ return FileResponse(target, media_type="image/webp")
929
+ ```
930
+
931
+ - [ ] **Step 3: Registrar router**
932
+
933
+ En el router principal (probablemente `backend/app/api/v1/router.py` o `app/main.py`):
934
+
935
+ ```python
936
+ from app.api.v1.endpoints import photos
937
+ api_router.include_router(photos.router)
938
+ ```
939
+
940
+ - [ ] **Step 4: Smoke**
941
+
942
+ Run: `curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8000/api/v1/photos/1/1/nope.webp`
943
+ Expected: 404.
944
+
945
+ - [ ] **Step 5: Commit**
946
+
947
+ ```bash
948
+ git add backend/app/api/v1/endpoints/photos.py backend/app/api/v1/router.py
949
+ git commit -m "feat(ta-01): GET /photos endpoint for local storage backend"
950
+ ```
951
+
952
+ ---
953
+
954
+ ### Task 12: Mapear path → URL en respuestas de usuarios
955
+
956
+ **Files:**
957
+ - Modify: `backend/app/api/v1/endpoints/users.py` (líneas 70-99)
958
+
959
+ - [ ] **Step 1: Leer el bloque actual**
960
+
961
+ Read: `backend/app/api/v1/endpoints/users.py` líneas 60-105.
962
+
963
+ - [ ] **Step 2: Modificar el llenado de `ur.face_photo`**
964
+
965
+ Reemplazar el bloque (líneas ~93-99 del listado original):
966
+
967
+ ```python
968
+ storage = get_storage()
969
+ items = []
970
+ for u in users:
971
+ ur = UserResponse.model_validate(
972
+ {c.name: getattr(u, c.name) for c in u.__table__.columns},
973
+ )
974
+ raw_path = photos.get(u.id)
975
+ ur.face_photo = storage.get_url(raw_path) if raw_path else None
976
+ items.append(ur)
977
+ ```
978
+
979
+ (Importar `from app.storage import get_storage` al inicio del archivo si no está.)
980
+
981
+ - [ ] **Step 3: Verificar smoke**
982
+
983
+ Run: `docker compose exec backend pytest backend/tests/api/test_users_photo_upload.py -v`
984
+ Expected: 4 passed (regresión).
985
+
986
+ - [ ] **Step 4: Commit**
987
+
988
+ ```bash
989
+ git add backend/app/api/v1/endpoints/users.py
990
+ git commit -m "feat(ta-01): map face_encodings.photo path to URL in user responses"
991
+ ```
992
+
993
+ ---
994
+
995
+ ### Task 13: docker-compose y .env.example
996
+
997
+ **Files:**
998
+ - Modify: `docker-compose.yml`
999
+ - Modify: `.env.example`
1000
+
1001
+ - [ ] **Step 1: Agregar volumen y env al servicio backend**
1002
+
1003
+ En `docker-compose.yml`, dentro de `services.backend`:
1004
+
1005
+ ```yaml
1006
+ volumes:
1007
+ - photo_data:/data/photos
1008
+ # ... otros volúmenes existentes
1009
+ environment:
1010
+ PHOTO_STORAGE_BACKEND: ${PHOTO_STORAGE_BACKEND:-local}
1011
+ LOCAL_PHOTO_ROOT: /data/photos
1012
+ LOCAL_PHOTO_URL_PREFIX: /api/v1/photos
1013
+ SUPABASE_URL: ${SUPABASE_URL:-}
1014
+ SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_KEY:-}
1015
+ SUPABASE_PHOTO_BUCKET: ${SUPABASE_PHOTO_BUCKET:-user-photos}
1016
+ ```
1017
+
1018
+ Al final del archivo, en la sección `volumes:`:
1019
+
1020
+ ```yaml
1021
+ volumes:
1022
+ photo_data:
1023
+ ```
1024
+
1025
+ - [ ] **Step 2: Agregar a `.env.example`**
1026
+
1027
+ ```
1028
+ # Bloque A — Storage de fotos
1029
+ PHOTO_STORAGE_BACKEND=local
1030
+ LOCAL_PHOTO_ROOT=/data/photos
1031
+ LOCAL_PHOTO_URL_PREFIX=/api/v1/photos
1032
+ SUPABASE_URL=
1033
+ SUPABASE_SERVICE_KEY=
1034
+ SUPABASE_PHOTO_BUCKET=user-photos
1035
+ ```
1036
+
1037
+ - [ ] **Step 3: Smoke**
1038
+
1039
+ Run: `docker compose up -d backend && curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8000/api/v1/users?per_page=1 | jq '.items[0].face_photo'`
1040
+ Expected: `null` o una URL `/api/v1/photos/...`.
1041
+
1042
+ - [ ] **Step 4: Commit**
1043
+
1044
+ ```bash
1045
+ git add docker-compose.yml .env.example
1046
+ git commit -m "chore(ta-01): wire photo storage env vars and local volume"
1047
+ ```
1048
+
1049
+ ---
1050
+
1051
+ ## Phase 3 — Block B attendance service extraction
1052
+
1053
+ ### Task 14: `services/attendance.py` — `record_attendance` (TDD)
1054
+
1055
+ **Files:**
1056
+ - Create: `backend/tests/services/test_attendance_service.py`
1057
+ - Create: `backend/app/services/attendance.py`
1058
+
1059
+ - [ ] **Step 1: Test fallando**
1060
+
1061
+ `backend/tests/services/test_attendance_service.py`:
1062
+
1063
+ ```python
1064
+ from datetime import datetime, timezone, date
1065
+ import pytest
1066
+ from app.services.attendance import record_attendance
1067
+ from app.models.attendance import Attendance
1068
+
1069
+
1070
+ def test_record_attendance_persists_with_attribution(db_session, demo_account, demo_section, demo_student, demo_admin):
1071
+ att = record_attendance(
1072
+ db_session,
1073
+ account_id=demo_account.id,
1074
+ user_id=demo_student.id,
1075
+ section_id=demo_section.id,
1076
+ subject_id=None,
1077
+ action="in",
1078
+ marked_by_role="admin",
1079
+ marked_by_user_id=demo_admin.id,
1080
+ when=datetime.now(timezone.utc),
1081
+ note="Manual test",
1082
+ )
1083
+ assert att.id is not None
1084
+ assert att.marked_by_role == "admin"
1085
+ assert att.marked_by_user_id == demo_admin.id
1086
+ assert att.action == "in"
1087
+
1088
+
1089
+ def test_record_attendance_idempotent_same_day(db_session, demo_account, demo_section, demo_student, demo_admin):
1090
+ args = dict(
1091
+ account_id=demo_account.id,
1092
+ user_id=demo_student.id,
1093
+ section_id=demo_section.id,
1094
+ subject_id=None,
1095
+ action="in",
1096
+ marked_by_role="teacher",
1097
+ marked_by_user_id=demo_admin.id,
1098
+ when=datetime.now(timezone.utc),
1099
+ note=None,
1100
+ )
1101
+ record_attendance(db_session, **args)
1102
+ second = record_attendance(db_session, **args)
1103
+ rows = db_session.query(Attendance).filter(
1104
+ Attendance.user_id == demo_student.id,
1105
+ Attendance.section_id == demo_section.id,
1106
+ ).all()
1107
+ assert len(rows) == 1
1108
+ assert second.id == rows[0].id
1109
+ ```
1110
+
1111
+ > Fixtures `demo_account`, `demo_section`, `demo_student`, `demo_admin`, `db_session`: agregar a `conftest.py` si no existen. Patrón: `test_seed_demo_scoping.py`.
1112
+
1113
+ Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py -v`
1114
+ Expected: FAIL.
1115
+
1116
+ - [ ] **Step 2: Implementar**
1117
+
1118
+ `backend/app/services/attendance.py`:
1119
+
1120
+ ```python
1121
+ from datetime import datetime
1122
+ from typing import Optional
1123
+ from sqlalchemy.orm import Session
1124
+ from app.models.attendance import Attendance
1125
+
1126
+
1127
+ def record_attendance(
1128
+ db: Session,
1129
+ *,
1130
+ account_id: int,
1131
+ user_id: int,
1132
+ section_id: Optional[int],
1133
+ subject_id: Optional[int], # reservado para futuro per-subject tracking
1134
+ action: Optional[str],
1135
+ marked_by_role: str,
1136
+ marked_by_user_id: Optional[int],
1137
+ when: datetime,
1138
+ note: Optional[str] = None,
1139
+ ) -> Attendance:
1140
+ """
1141
+ Inserta una asistencia con atribución. Idempotente: si ya existe una marca
1142
+ 'in' para (user_id, section_id) en el mismo día, devuelve esa fila sin crear duplicado.
1143
+ """
1144
+ day = when.date()
1145
+ existing = (
1146
+ db.query(Attendance)
1147
+ .filter(
1148
+ Attendance.user_id == user_id,
1149
+ Attendance.account_id == account_id,
1150
+ Attendance.section_id == section_id,
1151
+ Attendance.time_log >= datetime.combine(day, datetime.min.time(), tzinfo=when.tzinfo),
1152
+ Attendance.time_log < datetime.combine(day, datetime.max.time(), tzinfo=when.tzinfo),
1153
+ )
1154
+ .order_by(Attendance.time_log.desc())
1155
+ .first()
1156
+ )
1157
+ if existing and (existing.action == action or (action == "in" and existing.action is None)):
1158
+ return existing
1159
+
1160
+ att = Attendance(
1161
+ account_id=account_id,
1162
+ user_id=user_id,
1163
+ section_id=section_id,
1164
+ time_log=when,
1165
+ action=action,
1166
+ note=note,
1167
+ marked_by_role=marked_by_role,
1168
+ marked_by_user_id=marked_by_user_id,
1169
+ )
1170
+ db.add(att)
1171
+ db.commit()
1172
+ db.refresh(att)
1173
+ return att
1174
+ ```
1175
+
1176
+ - [ ] **Step 3: Tests pasan**
1177
+
1178
+ Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py -v`
1179
+ Expected: 2 passed.
1180
+
1181
+ - [ ] **Step 4: Commit**
1182
+
1183
+ ```bash
1184
+ git add backend/app/services/attendance.py backend/tests/services/test_attendance_service.py
1185
+ git commit -m "feat(ta-01): add record_attendance service with attribution + idempotency"
1186
+ ```
1187
+
1188
+ ---
1189
+
1190
+ ### Task 15: `services/attendance.py` — `list_section_roster` (TDD)
1191
+
1192
+ **Files:**
1193
+ - Modify: `backend/app/services/attendance.py`
1194
+ - Modify: `backend/tests/services/test_attendance_service.py`
1195
+
1196
+ - [ ] **Step 1: Test fallando**
1197
+
1198
+ Agregar a `test_attendance_service.py`:
1199
+
1200
+ ```python
1201
+ from datetime import date
1202
+ from app.services.attendance import list_section_roster
1203
+
1204
+
1205
+ def test_list_section_roster_returns_students_with_chips(
1206
+ db_session, demo_account, demo_section, demo_student
1207
+ ):
1208
+ items = list_section_roster(
1209
+ db_session,
1210
+ account_id=demo_account.id,
1211
+ section_id=demo_section.id,
1212
+ on_date=date.today(),
1213
+ )
1214
+ assert any(it.id == demo_student.id for it in items)
1215
+ item = next(it for it in items if it.id == demo_student.id)
1216
+ assert hasattr(item, "already_checked_in")
1217
+ assert hasattr(item, "entrance_logged")
1218
+ ```
1219
+
1220
+ Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py::test_list_section_roster_returns_students_with_chips -v`
1221
+ Expected: FAIL.
1222
+
1223
+ - [ ] **Step 2: Implementar**
1224
+
1225
+ Agregar a `backend/app/services/attendance.py`:
1226
+
1227
+ ```python
1228
+ from dataclasses import dataclass
1229
+ from typing import List
1230
+ from datetime import date as date_type
1231
+ from app.models.user import User
1232
+ from app.models.enrollment import Enrollment
1233
+ from app.models.entrance_log import EntranceLog
1234
+
1235
+
1236
+ @dataclass
1237
+ class RosterItem:
1238
+ id: int
1239
+ name: str
1240
+ lastname: str
1241
+ card_id: Optional[str]
1242
+ phone_number: Optional[str]
1243
+ already_checked_in: bool
1244
+ entrance_logged: bool
1245
+
1246
+
1247
+ def list_section_roster(
1248
+ db: Session,
1249
+ *,
1250
+ account_id: int,
1251
+ section_id: int,
1252
+ on_date: date_type,
1253
+ ) -> List[RosterItem]:
1254
+ students = (
1255
+ db.query(User)
1256
+ .join(Enrollment, Enrollment.student_id == User.id)
1257
+ .filter(
1258
+ User.account_id == account_id,
1259
+ User.role == "student",
1260
+ User.is_active == "1",
1261
+ Enrollment.section_id == section_id,
1262
+ Enrollment.account_id == account_id,
1263
+ )
1264
+ .all()
1265
+ )
1266
+ if not students:
1267
+ return []
1268
+ student_ids = [s.id for s in students]
1269
+
1270
+ today_att = (
1271
+ db.query(Attendance.user_id, Attendance.action, Attendance.checkout_time)
1272
+ .filter(
1273
+ Attendance.user_id.in_(student_ids),
1274
+ Attendance.account_id == account_id,
1275
+ Attendance.time_log >= on_date,
1276
+ )
1277
+ .all()
1278
+ )
1279
+ checked_in_ids: set[int] = set()
1280
+ for user_id, action, checkout_time in today_att:
1281
+ if action == "in":
1282
+ checked_in_ids.add(user_id)
1283
+ elif action is None and checkout_time is None:
1284
+ checked_in_ids.add(user_id)
1285
+
1286
+ entrance_logs = (
1287
+ db.query(EntranceLog.user_id)
1288
+ .filter(
1289
+ EntranceLog.user_id.in_(student_ids),
1290
+ EntranceLog.account_id == account_id,
1291
+ EntranceLog.date == on_date,
1292
+ )
1293
+ .distinct()
1294
+ .all()
1295
+ )
1296
+ entrance_logged_ids = {el.user_id for el in entrance_logs}
1297
+
1298
+ return [
1299
+ RosterItem(
1300
+ id=s.id,
1301
+ name=s.name,
1302
+ lastname=s.lastname,
1303
+ card_id=s.card_id,
1304
+ phone_number=s.phone_number,
1305
+ already_checked_in=s.id in checked_in_ids,
1306
+ entrance_logged=s.id in entrance_logged_ids,
1307
+ )
1308
+ for s in students
1309
+ ]
1310
+ ```
1311
+
1312
+ - [ ] **Step 3: Tests pasan**
1313
+
1314
+ Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py -v`
1315
+ Expected: 3 passed.
1316
+
1317
+ - [ ] **Step 4: Commit**
1318
+
1319
+ ```bash
1320
+ git add backend/app/services/attendance.py backend/tests/services/test_attendance_service.py
1321
+ git commit -m "feat(ta-01): add list_section_roster service"
1322
+ ```
1323
+
1324
+ ---
1325
+
1326
+ ### Task 16: Refactor `teacher.py` para usar el servicio
1327
+
1328
+ **Files:**
1329
+ - Modify: `backend/app/api/v1/endpoints/teacher.py` (líneas ~456-541 `submit_swipe`, líneas ~567+ `batch_toggle`, líneas ~712+ `toggle_attendance`)
1330
+
1331
+ - [ ] **Step 1: Reemplazar el cuerpo de `submit_swipe`**
1332
+
1333
+ Mantener: validaciones de holiday, `_ensure_teacher_section`, schema, log_for y construcción de `present_today`. Reemplazar el bloque de iteración por:
1334
+
1335
+ ```python
1336
+ from app.services.attendance import record_attendance
1337
+
1338
+ # ... dentro de submit_swipe, después de validaciones ...
1339
+ created = 0
1340
+ for rec in payload.records:
1341
+ if not rec.present:
1342
+ continue
1343
+ att = record_attendance(
1344
+ db,
1345
+ account_id=current_user.account_id,
1346
+ user_id=rec.student_id,
1347
+ section_id=payload.section_id,
1348
+ subject_id=payload.subject_id,
1349
+ action="in",
1350
+ marked_by_role="teacher",
1351
+ marked_by_user_id=current_user.id,
1352
+ when=datetime.now(timezone.utc),
1353
+ note="Swipe: present",
1354
+ )
1355
+ if att.time_log >= now.replace(microsecond=0) - timedelta(seconds=2):
1356
+ created += 1
1357
+ ```
1358
+
1359
+ > `skipped` queda en `[]` siempre tras eliminar el gate filter en la próxima fase. Por ahora, mantenerlo construido con la misma lógica para no romper la respuesta — la Task 19 limpia esto.
1360
+
1361
+ - [ ] **Step 2: Hacer el mismo refactor en `batch_toggle`**
1362
+
1363
+ Reemplazar el bloque interno de iteración por llamadas a `record_attendance(... marked_by_role="teacher", marked_by_user_id=current_user.id, when=record_time, ...)`.
1364
+
1365
+ - [ ] **Step 3: `toggle_attendance` (single record)**
1366
+
1367
+ Idem.
1368
+
1369
+ - [ ] **Step 4: Reemplazar el cómputo del roster en endpoints de listado**
1370
+
1371
+ Donde se construye `entrance_logged_ids` + `StudentCardResponse` (líneas ~423-453 y ~689-707), reemplazar por:
1372
+
1373
+ ```python
1374
+ from app.services.attendance import list_section_roster
1375
+
1376
+ roster = list_section_roster(
1377
+ db,
1378
+ account_id=current_user.account_id,
1379
+ section_id=section_id,
1380
+ on_date=today,
1381
+ )
1382
+ return [StudentCardResponse(**r.__dict__) for r in roster]
1383
+ ```
1384
+
1385
+ - [ ] **Step 5: Correr la suite de teacher.py para no regresar**
1386
+
1387
+ Run: `docker compose exec backend pytest backend/tests/test_teacher_present_summary.py -v`
1388
+ Expected: PASS.
1389
+
1390
+ - [ ] **Step 6: Commit**
1391
+
1392
+ ```bash
1393
+ git add backend/app/api/v1/endpoints/teacher.py
1394
+ git commit -m "refactor(ta-01): route teacher attendance through services/attendance"
1395
+ ```
1396
+
1397
+ ---
1398
+
1399
+ ### Task 17: `facial.py` — marcar como `marked_by_role='kiosco'`
1400
+
1401
+ **Files:**
1402
+ - Modify: `backend/app/api/v1/endpoints/facial.py`
1403
+
1404
+ - [ ] **Step 1: Localizar inserciones de `Attendance`**
1405
+
1406
+ Run: `Grep "Attendance\(|Attendance \(" backend/app/api/v1/endpoints/facial.py`
1407
+
1408
+ - [ ] **Step 2: Agregar atribución a cada constructor `Attendance(...)`**
1409
+
1410
+ Para cada lugar donde se crea una `Attendance` en `facial.py`, agregar:
1411
+
1412
+ ```python
1413
+ marked_by_role="kiosco",
1414
+ marked_by_user_id=None,
1415
+ ```
1416
+
1417
+ > Si no hay ningún `Attendance(...)` en `facial.py` (el Grep arriba devolvió 0 matches), buscar dónde el kiosco escribe asistencia (probablemente `EntranceLog` solamente). En ese caso, este Task se cierra como no-op y se anota en el commit.
1418
+
1419
+ - [ ] **Step 3: Commit**
1420
+
1421
+ ```bash
1422
+ git add backend/app/api/v1/endpoints/facial.py
1423
+ git commit -m "feat(ta-01): tag kiosco attendance inserts with marked_by_role"
1424
+ ```
1425
+
1426
+ (O si fue no-op: `chore(ta-01): verify kiosco does not insert Attendance directly (no-op)`.)
1427
+
1428
+ ---
1429
+
1430
+ ## Phase 4 — Block C gate decouple
1431
+
1432
+ ### Task 18: Test de regresión — estudiante sin gate puede marcarse presente
1433
+
1434
+ **Files:**
1435
+ - Create: `backend/tests/api/test_teacher_attendance_gate_decouple.py`
1436
+
1437
+ - [ ] **Step 1: Test que ahora **debe fallar** porque la lógica aún bloquea**
1438
+
1439
+ `backend/tests/api/test_teacher_attendance_gate_decouple.py`:
1440
+
1441
+ ```python
1442
+ import pytest
1443
+ from fastapi.testclient import TestClient
1444
+ from app.main import app
1445
+
1446
+
1447
+ def test_swipe_marks_student_without_entrance_log_as_present(
1448
+ teacher_token, demo_section_id, demo_student_without_entrance_log
1449
+ ):
1450
+ c = TestClient(app)
1451
+ r = c.post(
1452
+ "/api/v1/teacher/attendance/swipe",
1453
+ headers={"Authorization": f"Bearer {teacher_token}"},
1454
+ json={
1455
+ "section_id": demo_section_id,
1456
+ "records": [{"student_id": demo_student_without_entrance_log, "present": True}],
1457
+ },
1458
+ )
1459
+ assert r.status_code == 201, r.text
1460
+ body = r.json()
1461
+ # Antes: este estudiante terminaba en `skipped`. Ahora: en `created`.
1462
+ assert body["created"] == 1
1463
+ assert body["skipped"] == []
1464
+
1465
+
1466
+ def test_batch_toggle_marks_student_without_entrance_log(
1467
+ teacher_token, demo_section_id, demo_student_without_entrance_log
1468
+ ):
1469
+ c = TestClient(app)
1470
+ r = c.post(
1471
+ "/api/v1/teacher/attendance/batch-toggle",
1472
+ headers={"Authorization": f"Bearer {teacher_token}"},
1473
+ json={
1474
+ "section_id": demo_section_id,
1475
+ "records": [{"student_id": demo_student_without_entrance_log, "present": True}],
1476
+ },
1477
+ )
1478
+ assert r.status_code == 200, r.text
1479
+ assert r.json().get("skipped") in ([], None)
1480
+
1481
+
1482
+ def test_roster_still_reports_entrance_logged_false(
1483
+ teacher_token, demo_section_id, demo_student_without_entrance_log
1484
+ ):
1485
+ c = TestClient(app)
1486
+ r = c.get(
1487
+ f"/api/v1/teacher/sections/{demo_section_id}/students",
1488
+ headers={"Authorization": f"Bearer {teacher_token}"},
1489
+ )
1490
+ assert r.status_code == 200
1491
+ items = r.json()
1492
+ target = next(it for it in items if it["id"] == demo_student_without_entrance_log)
1493
+ assert target["entrance_logged"] is False # info se conserva
1494
+ ```
1495
+
1496
+ > Fixtures `demo_student_without_entrance_log` (alumno enrolado en sección, SIN `EntranceLog` hoy): agregar a `conftest.py`.
1497
+
1498
+ Run: `docker compose exec backend pytest backend/tests/api/test_teacher_attendance_gate_decouple.py -v`
1499
+ Expected: FAIL en los dos primeros tests (el estudiante termina en `skipped`).
1500
+
1501
+ - [ ] **Step 2: NO commit todavía — Task 19 hace el cambio que vuelve verde.**
1502
+
1503
+ ---
1504
+
1505
+ ### Task 19: Remover el filtro `entrance_logged_ids`
1506
+
1507
+ **Files:**
1508
+ - Modify: `backend/app/api/v1/endpoints/teacher.py`
1509
+
1510
+ - [ ] **Step 1: Grep para inventario actualizado**
1511
+
1512
+ Run: `Grep -n "entrance_logged_ids" backend/app/api/v1/endpoints/teacher.py`
1513
+ Esperado: 6-8 ubicaciones (algunas ya removidas por Task 16 refactor).
1514
+
1515
+ - [ ] **Step 2: En `submit_swipe`**
1516
+
1517
+ Eliminar las líneas que construyen `entrance_logged_ids` Y las líneas `if rec.student_id not in entrance_logged_ids: skipped_ids.append(...); continue`. Eliminar también la sección que arma `skipped` con nombres si ya no hay `skipped_ids`. La respuesta debe pasar a `{"created": ..., "total": ..., "skipped": [], "present_today": ...}`.
1518
+
1519
+ - [ ] **Step 3: En `batch_toggle`**
1520
+
1521
+ Idem.
1522
+
1523
+ - [ ] **Step 4: En `toggle_attendance` (single record)**
1524
+
1525
+ Si tiene un check 409 derivado de `entrance_logged_ids`, removerlo. Mantener la validación de `_check_not_before_class` (time gate, intencional).
1526
+
1527
+ - [ ] **Step 5: NO tocar el roster**
1528
+
1529
+ `get_students` / `list_section_students` deben seguir devolviendo `entrance_logged: bool` calculado normalmente — el filtro era el bloqueo, el cálculo informativo permanece.
1530
+
1531
+ - [ ] **Step 6: Grep final**
1532
+
1533
+ Run: `Grep -n "entrance_logged_ids" backend/app/api/v1/endpoints/teacher.py`
1534
+ Esperado: solo apariciones en cómputo de roster informativo (las que devuelven el flag al frontend). NINGUNA debe usarse como filtro.
1535
+
1536
+ - [ ] **Step 7: Tests verdes**
1537
+
1538
+ Run: `docker compose exec backend pytest backend/tests/api/test_teacher_attendance_gate_decouple.py -v`
1539
+ Expected: 3 passed.
1540
+
1541
+ Run: `docker compose exec backend pytest backend/tests/ -v`
1542
+ Expected: toda la suite verde (sin regresiones).
1543
+
1544
+ - [ ] **Step 8: Commit**
1545
+
1546
+ ```bash
1547
+ git add backend/app/api/v1/endpoints/teacher.py backend/tests/api/test_teacher_attendance_gate_decouple.py
1548
+ git commit -m "feat(ta-01): decouple classroom attendance from gate entrance log"
1549
+ ```
1550
+
1551
+ ---
1552
+
1553
+ ## Phase 5 — Block B admin endpoints
1554
+
1555
+ ### Task 20: `GET /admin/sections` (TDD)
1556
+
1557
+ **Files:**
1558
+ - Create: `backend/tests/api/test_admin_attendance.py`
1559
+ - Create: `backend/app/api/v1/endpoints/admin_attendance.py`
1560
+ - Modify: router principal para registrar el nuevo router
1561
+
1562
+ - [ ] **Step 1: Test fallando**
1563
+
1564
+ `backend/tests/api/test_admin_attendance.py`:
1565
+
1566
+ ```python
1567
+ from fastapi.testclient import TestClient
1568
+ from app.main import app
1569
+
1570
+
1571
+ def test_admin_lists_all_sections_of_account(admin_token, demo_section_id):
1572
+ c = TestClient(app)
1573
+ r = c.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {admin_token}"})
1574
+ assert r.status_code == 200, r.text
1575
+ ids = [s["id"] for s in r.json()]
1576
+ assert demo_section_id in ids
1577
+
1578
+
1579
+ def test_admin_cannot_list_sections_of_other_account(other_account_admin_token, demo_section_id):
1580
+ c = TestClient(app)
1581
+ r = c.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {other_account_admin_token}"})
1582
+ assert r.status_code == 200
1583
+ ids = [s["id"] for s in r.json()]
1584
+ assert demo_section_id not in ids
1585
+
1586
+
1587
+ def test_teacher_role_forbidden(teacher_token):
1588
+ c = TestClient(app)
1589
+ r = c.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {teacher_token}"})
1590
+ assert r.status_code in (401, 403)
1591
+ ```
1592
+
1593
+ Run: FAIL (router no existe).
1594
+
1595
+ - [ ] **Step 2: Implementar**
1596
+
1597
+ `backend/app/api/v1/endpoints/admin_attendance.py`:
1598
+
1599
+ ```python
1600
+ from fastapi import APIRouter, Depends
1601
+ from sqlalchemy.orm import Session
1602
+ from app.core.database import get_db
1603
+ from app.middleware.rbac import RBAC
1604
+ from app.models.user import User
1605
+ from app.models.section import Section
1606
+
1607
+ router = APIRouter(prefix="/admin", tags=["admin-attendance"])
1608
+
1609
+
1610
+ @router.get("/sections")
1611
+ def admin_list_sections(
1612
+ current_user: User = Depends(RBAC(["admin"])),
1613
+ db: Session = Depends(get_db),
1614
+ ):
1615
+ rows = (
1616
+ db.query(Section)
1617
+ .filter(Section.account_id == current_user.account_id)
1618
+ .order_by(Section.name)
1619
+ .all()
1620
+ )
1621
+ return [{"id": s.id, "name": s.name} for s in rows]
1622
+ ```
1623
+
1624
+ Registrar el router en el archivo principal:
1625
+
1626
+ ```python
1627
+ from app.api.v1.endpoints import admin_attendance
1628
+ api_router.include_router(admin_attendance.router)
1629
+ ```
1630
+
1631
+ - [ ] **Step 3: Tests pasan**
1632
+
1633
+ Run: `docker compose exec backend pytest backend/tests/api/test_admin_attendance.py::test_admin_lists_all_sections_of_account backend/tests/api/test_admin_attendance.py::test_admin_cannot_list_sections_of_other_account backend/tests/api/test_admin_attendance.py::test_teacher_role_forbidden -v`
1634
+ Expected: 3 passed.
1635
+
1636
+ - [ ] **Step 4: Commit**
1637
+
1638
+ ```bash
1639
+ git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py backend/app/api/v1/router.py
1640
+ git commit -m "feat(ta-01): GET /admin/sections endpoint"
1641
+ ```
1642
+
1643
+ ---
1644
+
1645
+ ### Task 21: `GET /admin/sections/{id}/roster` (TDD)
1646
+
1647
+ **Files:**
1648
+ - Modify: `backend/app/api/v1/endpoints/admin_attendance.py`
1649
+ - Modify: `backend/tests/api/test_admin_attendance.py`
1650
+
1651
+ - [ ] **Step 1: Test fallando**
1652
+
1653
+ Agregar a `test_admin_attendance.py`:
1654
+
1655
+ ```python
1656
+ def test_admin_roster_returns_students_with_chips(admin_token, demo_section_id, demo_student_id):
1657
+ c = TestClient(app)
1658
+ r = c.get(
1659
+ f"/api/v1/admin/sections/{demo_section_id}/roster",
1660
+ headers={"Authorization": f"Bearer {admin_token}"},
1661
+ )
1662
+ assert r.status_code == 200
1663
+ items = r.json()
1664
+ assert any(it["id"] == demo_student_id for it in items)
1665
+ item = next(it for it in items if it["id"] == demo_student_id)
1666
+ assert "already_checked_in" in item
1667
+ assert "entrance_logged" in item
1668
+
1669
+
1670
+ def test_admin_roster_404_for_foreign_section(admin_token, foreign_section_id):
1671
+ c = TestClient(app)
1672
+ r = c.get(
1673
+ f"/api/v1/admin/sections/{foreign_section_id}/roster",
1674
+ headers={"Authorization": f"Bearer {admin_token}"},
1675
+ )
1676
+ assert r.status_code == 404
1677
+ ```
1678
+
1679
+ - [ ] **Step 2: Implementar**
1680
+
1681
+ Agregar a `admin_attendance.py`:
1682
+
1683
+ ```python
1684
+ from datetime import date, datetime
1685
+ from fastapi import HTTPException, Query
1686
+ from app.services.attendance import list_section_roster
1687
+
1688
+
1689
+ @router.get("/sections/{section_id}/roster")
1690
+ def admin_section_roster(
1691
+ section_id: int,
1692
+ on_date: str | None = Query(None, alias="date"),
1693
+ current_user: User = Depends(RBAC(["admin"])),
1694
+ db: Session = Depends(get_db),
1695
+ ):
1696
+ section = db.query(Section).filter(
1697
+ Section.id == section_id,
1698
+ Section.account_id == current_user.account_id,
1699
+ ).first()
1700
+ if not section:
1701
+ raise HTTPException(status_code=404, detail="section not found")
1702
+
1703
+ day = datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date.today()
1704
+ items = list_section_roster(
1705
+ db,
1706
+ account_id=current_user.account_id,
1707
+ section_id=section_id,
1708
+ on_date=day,
1709
+ )
1710
+ return [it.__dict__ for it in items]
1711
+ ```
1712
+
1713
+ - [ ] **Step 3: Tests pasan**
1714
+
1715
+ Run: `docker compose exec backend pytest backend/tests/api/test_admin_attendance.py -v`
1716
+ Expected: 5 passed.
1717
+
1718
+ - [ ] **Step 4: Commit**
1719
+
1720
+ ```bash
1721
+ git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py
1722
+ git commit -m "feat(ta-01): GET /admin/sections/{id}/roster"
1723
+ ```
1724
+
1725
+ ---
1726
+
1727
+ ### Task 22: `POST /admin/attendance/swipe` (TDD)
1728
+
1729
+ **Files:**
1730
+ - Modify: `backend/app/api/v1/endpoints/admin_attendance.py`
1731
+ - Modify: `backend/tests/api/test_admin_attendance.py`
1732
+
1733
+ - [ ] **Step 1: Test**
1734
+
1735
+ ```python
1736
+ def test_admin_swipe_marks_with_admin_attribution(
1737
+ admin_token, admin_user_id, demo_section_id, demo_student_id, db_session
1738
+ ):
1739
+ c = TestClient(app)
1740
+ r = c.post(
1741
+ "/api/v1/admin/attendance/swipe",
1742
+ headers={"Authorization": f"Bearer {admin_token}"},
1743
+ json={
1744
+ "section_id": demo_section_id,
1745
+ "records": [{"student_id": demo_student_id, "present": True}],
1746
+ },
1747
+ )
1748
+ assert r.status_code == 201, r.text
1749
+ assert r.json()["created"] == 1
1750
+ from app.models.attendance import Attendance
1751
+ row = db_session.query(Attendance).filter(
1752
+ Attendance.user_id == demo_student_id,
1753
+ Attendance.section_id == demo_section_id,
1754
+ ).order_by(Attendance.id.desc()).first()
1755
+ assert row.marked_by_role == "admin"
1756
+ assert row.marked_by_user_id == admin_user_id
1757
+
1758
+
1759
+ def test_admin_swipe_works_for_student_without_entrance_log(
1760
+ admin_token, demo_section_id, demo_student_without_entrance_log
1761
+ ):
1762
+ c = TestClient(app)
1763
+ r = c.post(
1764
+ "/api/v1/admin/attendance/swipe",
1765
+ headers={"Authorization": f"Bearer {admin_token}"},
1766
+ json={
1767
+ "section_id": demo_section_id,
1768
+ "records": [{"student_id": demo_student_without_entrance_log, "present": True}],
1769
+ },
1770
+ )
1771
+ assert r.status_code == 201
1772
+ assert r.json()["created"] == 1
1773
+ ```
1774
+
1775
+ - [ ] **Step 2: Implementar**
1776
+
1777
+ ```python
1778
+ from datetime import timezone
1779
+ from pydantic import BaseModel
1780
+ from app.services.attendance import record_attendance
1781
+
1782
+
1783
+ class AdminSwipeRecord(BaseModel):
1784
+ student_id: int
1785
+ present: bool
1786
+
1787
+
1788
+ class AdminSwipeRequest(BaseModel):
1789
+ section_id: int
1790
+ subject_id: int | None = None
1791
+ records: list[AdminSwipeRecord]
1792
+
1793
+
1794
+ @router.post("/attendance/swipe", status_code=201)
1795
+ def admin_attendance_swipe(
1796
+ payload: AdminSwipeRequest,
1797
+ current_user: User = Depends(RBAC(["admin"])),
1798
+ db: Session = Depends(get_db),
1799
+ ):
1800
+ section = db.query(Section).filter(
1801
+ Section.id == payload.section_id,
1802
+ Section.account_id == current_user.account_id,
1803
+ ).first()
1804
+ if not section:
1805
+ raise HTTPException(status_code=404, detail="section not found")
1806
+ created = 0
1807
+ now = datetime.now(timezone.utc)
1808
+ for rec in payload.records:
1809
+ if not rec.present:
1810
+ continue
1811
+ record_attendance(
1812
+ db,
1813
+ account_id=current_user.account_id,
1814
+ user_id=rec.student_id,
1815
+ section_id=payload.section_id,
1816
+ subject_id=payload.subject_id,
1817
+ action="in",
1818
+ marked_by_role="admin",
1819
+ marked_by_user_id=current_user.id,
1820
+ when=now,
1821
+ note="Admin: contingencia",
1822
+ )
1823
+ created += 1
1824
+ return {"created": created, "total": len(payload.records), "skipped": []}
1825
+ ```
1826
+
1827
+ - [ ] **Step 3: Tests pasan**
1828
+
1829
+ Run: `docker compose exec backend pytest backend/tests/api/test_admin_attendance.py -v`
1830
+ Expected: 7 passed.
1831
+
1832
+ - [ ] **Step 4: Commit**
1833
+
1834
+ ```bash
1835
+ git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py
1836
+ git commit -m "feat(ta-01): POST /admin/attendance/swipe with admin attribution"
1837
+ ```
1838
+
1839
+ ---
1840
+
1841
+ ### Task 23: `POST /admin/attendance/batch-toggle` (TDD)
1842
+
1843
+ **Files:**
1844
+ - Modify: `backend/app/api/v1/endpoints/admin_attendance.py`
1845
+ - Modify: `backend/tests/api/test_admin_attendance.py`
1846
+
1847
+ - [ ] **Step 1: Test**
1848
+
1849
+ ```python
1850
+ def test_admin_batch_toggle_for_past_date(
1851
+ admin_token, demo_section_id, demo_student_id, db_session
1852
+ ):
1853
+ c = TestClient(app)
1854
+ r = c.post(
1855
+ "/api/v1/admin/attendance/batch-toggle?date=2026-06-01",
1856
+ headers={"Authorization": f"Bearer {admin_token}"},
1857
+ json={
1858
+ "section_id": demo_section_id,
1859
+ "records": [{"student_id": demo_student_id, "present": True}],
1860
+ },
1861
+ )
1862
+ assert r.status_code == 200, r.text
1863
+ from app.models.attendance import Attendance
1864
+ row = db_session.query(Attendance).filter(
1865
+ Attendance.user_id == demo_student_id,
1866
+ Attendance.section_id == demo_section_id,
1867
+ ).order_by(Attendance.id.desc()).first()
1868
+ assert row.marked_by_role == "admin"
1869
+ assert row.time_log.date().isoformat() == "2026-06-01"
1870
+ ```
1871
+
1872
+ - [ ] **Step 2: Implementar**
1873
+
1874
+ ```python
1875
+ from datetime import time as time_type
1876
+
1877
+
1878
+ @router.post("/attendance/batch-toggle")
1879
+ def admin_batch_toggle(
1880
+ payload: AdminSwipeRequest,
1881
+ on_date: str | None = Query(None, alias="date"),
1882
+ current_user: User = Depends(RBAC(["admin"])),
1883
+ db: Session = Depends(get_db),
1884
+ ):
1885
+ section = db.query(Section).filter(
1886
+ Section.id == payload.section_id,
1887
+ Section.account_id == current_user.account_id,
1888
+ ).first()
1889
+ if not section:
1890
+ raise HTTPException(status_code=404, detail="section not found")
1891
+ day = datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date.today()
1892
+ when = (
1893
+ datetime.now(timezone.utc)
1894
+ if day == date.today()
1895
+ else datetime.combine(day, time_type(12, 0), tzinfo=timezone.utc)
1896
+ )
1897
+ created = 0
1898
+ for rec in payload.records:
1899
+ if not rec.present:
1900
+ continue
1901
+ record_attendance(
1902
+ db,
1903
+ account_id=current_user.account_id,
1904
+ user_id=rec.student_id,
1905
+ section_id=payload.section_id,
1906
+ subject_id=payload.subject_id,
1907
+ action="in",
1908
+ marked_by_role="admin",
1909
+ marked_by_user_id=current_user.id,
1910
+ when=when,
1911
+ note="Admin batch: contingencia",
1912
+ )
1913
+ created += 1
1914
+ return {"created": created, "total": len(payload.records), "skipped": []}
1915
+ ```
1916
+
1917
+ - [ ] **Step 3: Tests pasan**
1918
+
1919
+ Run: `docker compose exec backend pytest backend/tests/api/test_admin_attendance.py -v`
1920
+ Expected: 8 passed.
1921
+
1922
+ - [ ] **Step 4: Commit**
1923
+
1924
+ ```bash
1925
+ git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py
1926
+ git commit -m "feat(ta-01): POST /admin/attendance/batch-toggle with date support"
1927
+ ```
1928
+
1929
+ ---
1930
+
1931
+ ## Phase 6 — Frontend
1932
+
1933
+ ### Task 24: Extraer `AttendanceTable` y `StudentRow`
1934
+
1935
+ **Files:**
1936
+ - Create: `frontend/src/components/attendance/AttendanceTable.tsx`
1937
+ - Create: `frontend/src/components/attendance/StudentRow.tsx`
1938
+ - Create: `frontend/src/components/attendance/AttendanceSummaryChips.tsx`
1939
+ - Modify: `frontend/src/pages/teacher/TeacherAttendancePage.tsx`
1940
+
1941
+ - [ ] **Step 1: Leer la página actual**
1942
+
1943
+ Read: `frontend/src/pages/teacher/TeacherAttendancePage.tsx` completo. Identificar:
1944
+ - El JSX que renderiza la tabla de estudiantes.
1945
+ - El componente fila (chip presente/ausente + entrance chip).
1946
+ - Los contadores de presente/ausente.
1947
+
1948
+ - [ ] **Step 2: Crear `StudentRow.tsx`**
1949
+
1950
+ Copiar el JSX del row a `StudentRow.tsx`. Definir `interface StudentRowProps` con las props mínimas: `student`, `onToggle`, `pending`, `disabled`. Importar tipos comunes desde `services/teacherService.ts`.
1951
+
1952
+ - [ ] **Step 3: Crear `AttendanceTable.tsx`**
1953
+
1954
+ Componente que recibe `students: RosterItem[]`, `pendingToggles`, `onToggle`, `loading` y renderiza el header + map de `<StudentRow />`.
1955
+
1956
+ - [ ] **Step 4: Crear `AttendanceSummaryChips.tsx`**
1957
+
1958
+ Componente con los contadores presente/ausente y, si aplica, el desglose por sexo.
1959
+
1960
+ - [ ] **Step 5: Cambiar el styling del chip `entrance_logged` a gris/info**
1961
+
1962
+ En `StudentRow.tsx`, donde el chip muestra el estado de gate, usar un tono gris (no rojo) y tooltip "Sin check-in en gate. Podés marcar igualmente."
1963
+
1964
+ - [ ] **Step 6: Actualizar `TeacherAttendancePage.tsx` para usar los nuevos componentes**
1965
+
1966
+ Reemplazar el JSX duplicado por `<AttendanceTable students={...} ... />` y `<AttendanceSummaryChips ... />`.
1967
+
1968
+ - [ ] **Step 7: Verificar build y página**
1969
+
1970
+ Run: `docker compose exec frontend npm run typecheck` o equivalente.
1971
+ Expected: sin errores.
1972
+
1973
+ Browser smoke: Login como teacher, abrir `/teacher/attendance`, verificar que la tabla, el toggle y los chips funcionan igual que antes. Verificar que el chip de gate es gris/info y NO bloquea el toggle.
1974
+
1975
+ - [ ] **Step 8: Commit**
1976
+
1977
+ ```bash
1978
+ git add frontend/src/components/attendance/ frontend/src/pages/teacher/TeacherAttendancePage.tsx
1979
+ git commit -m "refactor(ta-01): extract AttendanceTable/StudentRow components from teacher page"
1980
+ ```
1981
+
1982
+ ---
1983
+
1984
+ ### Task 25: Servicio `adminAttendanceService.ts`
1985
+
1986
+ **Files:**
1987
+ - Create: `frontend/src/services/adminAttendanceService.ts`
1988
+
1989
+ - [ ] **Step 1: Espejar `teacherService.ts`**
1990
+
1991
+ Read: `frontend/src/services/teacherService.ts` (líneas 1-80).
1992
+
1993
+ Crear `adminAttendanceService.ts` con:
1994
+
1995
+ ```ts
1996
+ import { api } from "./api"; // o el cliente axios/fetch que use el proyecto
1997
+
1998
+ export interface AdminSection { id: number; name: string }
1999
+ export interface AdminRosterItem {
2000
+ id: number; name: string; lastname: string;
2001
+ card_id: string | null; phone_number: string | null;
2002
+ already_checked_in: boolean; entrance_logged: boolean;
2003
+ }
2004
+ export interface AdminSwipeRecord { student_id: number; present: boolean }
2005
+
2006
+ export const adminAttendanceService = {
2007
+ async listSections(): Promise<AdminSection[]> {
2008
+ const { data } = await api.get("/admin/sections");
2009
+ return data;
2010
+ },
2011
+ async getRoster(sectionId: number, date?: string): Promise<AdminRosterItem[]> {
2012
+ const { data } = await api.get(`/admin/sections/${sectionId}/roster`, { params: { date } });
2013
+ return data;
2014
+ },
2015
+ async swipe(sectionId: number, records: AdminSwipeRecord[]) {
2016
+ const { data } = await api.post("/admin/attendance/swipe", { section_id: sectionId, records });
2017
+ return data;
2018
+ },
2019
+ async batchToggle(sectionId: number, records: AdminSwipeRecord[], date?: string) {
2020
+ const { data } = await api.post(`/admin/attendance/batch-toggle`, { section_id: sectionId, records }, { params: { date } });
2021
+ return data;
2022
+ },
2023
+ };
2024
+ ```
2025
+
2026
+ - [ ] **Step 2: Commit**
2027
+
2028
+ ```bash
2029
+ git add frontend/src/services/adminAttendanceService.ts
2030
+ git commit -m "feat(ta-01): add adminAttendanceService client"
2031
+ ```
2032
+
2033
+ ---
2034
+
2035
+ ### Task 26: `AdminAttendancePage.tsx`
2036
+
2037
+ **Files:**
2038
+ - Create: `frontend/src/pages/admin/AdminAttendancePage.tsx`
2039
+
2040
+ - [ ] **Step 1: Implementación**
2041
+
2042
+ ```tsx
2043
+ import { useEffect, useState } from "react";
2044
+ import { AttendanceTable } from "@/components/attendance/AttendanceTable";
2045
+ import { AttendanceSummaryChips } from "@/components/attendance/AttendanceSummaryChips";
2046
+ import {
2047
+ adminAttendanceService,
2048
+ AdminSection,
2049
+ AdminRosterItem,
2050
+ } from "@/services/adminAttendanceService";
2051
+
2052
+ export default function AdminAttendancePage() {
2053
+ const [sections, setSections] = useState<AdminSection[]>([]);
2054
+ const [sectionId, setSectionId] = useState<number | null>(null);
2055
+ const [date, setDate] = useState<string>(() => new Date().toISOString().slice(0, 10));
2056
+ const [roster, setRoster] = useState<AdminRosterItem[]>([]);
2057
+ const [pending, setPending] = useState<Set<number>>(new Set());
2058
+ const [saving, setSaving] = useState(false);
2059
+
2060
+ useEffect(() => {
2061
+ adminAttendanceService.listSections().then(setSections);
2062
+ }, []);
2063
+
2064
+ useEffect(() => {
2065
+ if (sectionId == null) return;
2066
+ adminAttendanceService.getRoster(sectionId, date).then(setRoster);
2067
+ }, [sectionId, date]);
2068
+
2069
+ const togglePending = (id: number) => {
2070
+ setPending((s) => {
2071
+ const next = new Set(s);
2072
+ if (next.has(id)) next.delete(id); else next.add(id);
2073
+ return next;
2074
+ });
2075
+ };
2076
+
2077
+ const save = async () => {
2078
+ if (sectionId == null || pending.size === 0) return;
2079
+ setSaving(true);
2080
+ try {
2081
+ const records = roster
2082
+ .filter((r) => pending.has(r.id))
2083
+ .map((r) => ({ student_id: r.id, present: !r.already_checked_in }));
2084
+ await adminAttendanceService.batchToggle(sectionId, records, date);
2085
+ setPending(new Set());
2086
+ const fresh = await adminAttendanceService.getRoster(sectionId, date);
2087
+ setRoster(fresh);
2088
+ } finally {
2089
+ setSaving(false);
2090
+ }
2091
+ };
2092
+
2093
+ return (
2094
+ <div className="p-6 space-y-4">
2095
+ <header>
2096
+ <h1 className="text-xl font-semibold">Asistencia por contingencia</h1>
2097
+ <p className="text-sm text-gray-600">
2098
+ Usá esta vista cuando un docente está ausente y necesitás pasar lista en su aula.
2099
+ </p>
2100
+ </header>
2101
+ <div className="flex gap-3">
2102
+ <select
2103
+ value={sectionId ?? ""}
2104
+ onChange={(e) => setSectionId(e.target.value ? Number(e.target.value) : null)}
2105
+ className="border rounded px-3 py-2"
2106
+ >
2107
+ <option value="">Elegí una sección…</option>
2108
+ {sections.map((s) => (
2109
+ <option key={s.id} value={s.id}>{s.name}</option>
2110
+ ))}
2111
+ </select>
2112
+ <input
2113
+ type="date"
2114
+ value={date}
2115
+ onChange={(e) => setDate(e.target.value)}
2116
+ className="border rounded px-3 py-2"
2117
+ />
2118
+ </div>
2119
+ {sectionId != null && (
2120
+ <>
2121
+ <AttendanceSummaryChips students={roster} />
2122
+ <AttendanceTable
2123
+ students={roster}
2124
+ pendingToggles={pending}
2125
+ onToggle={togglePending}
2126
+ loading={false}
2127
+ />
2128
+ <button
2129
+ disabled={saving || pending.size === 0}
2130
+ onClick={save}
2131
+ className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
2132
+ >
2133
+ {saving ? "Guardando…" : `Guardar (${pending.size})`}
2134
+ </button>
2135
+ </>
2136
+ )}
2137
+ </div>
2138
+ );
2139
+ }
2140
+ ```
2141
+
2142
+ > Ajustar imports al alias real del proyecto (`@/` vs `src/`). Ajustar el shape de props de `AttendanceTable`/`AttendanceSummaryChips` a la API real de los componentes extraídos en Task 24.
2143
+
2144
+ - [ ] **Step 2: Verificar typecheck**
2145
+
2146
+ Run: `docker compose exec frontend npm run typecheck`
2147
+ Expected: sin errores.
2148
+
2149
+ - [ ] **Step 3: Commit**
2150
+
2151
+ ```bash
2152
+ git add frontend/src/pages/admin/AdminAttendancePage.tsx
2153
+ git commit -m "feat(ta-01): add AdminAttendancePage for contingency attendance"
2154
+ ```
2155
+
2156
+ ---
2157
+
2158
+ ### Task 27: Ruta y sidebar admin
2159
+
2160
+ **Files:**
2161
+ - Modify: archivo de rutas (probablemente `frontend/src/routes.tsx` o `frontend/src/App.tsx`)
2162
+ - Modify: sidebar admin (probablemente `frontend/src/components/admin/Sidebar.tsx`)
2163
+
2164
+ - [ ] **Step 1: Identificar archivos**
2165
+
2166
+ Run: `Glob "frontend/src/**/Sidebar*.tsx"` y `Glob "frontend/src/**/routes*.tsx"`.
2167
+
2168
+ - [ ] **Step 2: Agregar la ruta**
2169
+
2170
+ ```tsx
2171
+ import AdminAttendancePage from "@/pages/admin/AdminAttendancePage";
2172
+
2173
+ // ... dentro de las rutas admin
2174
+ <Route path="/admin/attendance" element={<AdminAttendancePage />} />
2175
+ ```
2176
+
2177
+ - [ ] **Step 3: Agregar item al sidebar admin**
2178
+
2179
+ ```tsx
2180
+ { to: "/admin/attendance", label: "Asistencia por contingencia", icon: <ClipboardIcon /> },
2181
+ ```
2182
+
2183
+ - [ ] **Step 4: Smoke browser**
2184
+
2185
+ Login admin → click "Asistencia por contingencia" → elegir sección → marcar uno → guardar. Verificar que la marca persiste (re-abrir la sección y ver el chip "presente").
2186
+
2187
+ - [ ] **Step 5: Commit**
2188
+
2189
+ ```bash
2190
+ git add frontend/src/routes.tsx frontend/src/components/admin/
2191
+ git commit -m "feat(ta-01): wire /admin/attendance route and sidebar item"
2192
+ ```
2193
+
2194
+ ---
2195
+
2196
+ ## Phase 7 — Verificación final
2197
+
2198
+ ### Task 28: Suite completa + smoke manual
2199
+
2200
+ - [ ] **Step 1: Suite backend**
2201
+
2202
+ Run: `docker compose exec backend pytest backend/tests/ -v`
2203
+ Expected: TODA la suite verde, incluyendo:
2204
+ - `backend/tests/storage/`
2205
+ - `backend/tests/services/`
2206
+ - `backend/tests/api/test_admin_attendance.py`
2207
+ - `backend/tests/api/test_users_photo_upload.py`
2208
+ - `backend/tests/api/test_teacher_attendance_gate_decouple.py`
2209
+ - Las suites preexistentes (sex aggregations, present summary, etc).
2210
+
2211
+ - [ ] **Step 2: Smoke manual**
2212
+
2213
+ Levantar todo: `docker compose up -d`.
2214
+
2215
+ Checklist en navegador:
2216
+ - [ ] Login admin → ir a un usuario → subir una foto JPG grande (>1MB). Verificar que la foto se muestra (URL nueva, no Base64) y el archivo en `/data/photos/...` existe (`docker compose exec backend ls /data/photos`).
2217
+ - [ ] Subir un GIF. Verificar 422 con mensaje claro.
2218
+ - [ ] Subir una foto sin rostro. Verificar que se guarda igual y el warning aparece.
2219
+ - [ ] Login admin → "Asistencia por contingencia" → elegir sección → marcar a un estudiante que NO hizo check-in en gate → guardar → verificar que la marca quedó (re-fetch).
2220
+ - [ ] Login teacher → marcar a un estudiante sin gate check-in → verificar que SÍ se marca presente y el chip de gate es gris/info.
2221
+ - [ ] DB: `docker compose exec db psql -U postgres -d talos -c "SELECT id, user_id, marked_by_role, marked_by_user_id FROM attendances ORDER BY id DESC LIMIT 5;"` — debe mostrar valores de admin/teacher según corresponda.
2222
+
2223
+ - [ ] **Step 3: Reporte al usuario**
2224
+
2225
+ > Sprint TA-01 implementado y verificado localmente. Tests verdes, smoke OK.
2226
+ > Pendiente: vos pushea cuando confirmes. Para el bloque A en prod hace falta que pongas `PHOTO_STORAGE_BACKEND=supabase` y las 3 vars de Supabase como Secrets en HF cuando tengas las credenciales.
2227
+
2228
+ ---
2229
+
2230
+ ## Notas para quien implemente
2231
+
2232
+ - **Convenciones del proyecto:**
2233
+ - `datetime.now(timezone.utc)` SIEMPRE en escrituras a columnas timezone-aware (TZ del container = `America/Caracas`).
2234
+ - Tests directos con pytest, NO tocar `init.sh`.
2235
+ - Commits locales OK, NO `git push` automático.
2236
+ - Postgres en dev y prod, no mezclar motores.
2237
+
2238
+ - **Fixtures requeridos (agregar a `backend/tests/conftest.py` si no existen):**
2239
+ - `admin_token`, `teacher_token`, `other_account_admin_token`
2240
+ - `admin_user_id`, `demo_student_id`, `demo_section_id`
2241
+ - `demo_student_without_entrance_log`, `foreign_section_id`
2242
+ - `db_session`, `demo_account`, `demo_section`, `demo_student`, `demo_admin`
2243
+ - Patrón a copiar: `backend/tests/test_seed_demo_scoping.py`.
2244
+
2245
+ - **Si surge ambigüedad sobre `app/face_utils.py`:** leer el archivo y adaptar la llamada en Task 10 a la firma real. El objetivo es: `(processed_bytes) → str | None`. Si la utilidad existente solo trabaja con paths o `PIL.Image`, hacer la conversión inline en el endpoint.
2246
+
2247
+ - **Si el router principal usa un patrón distinto:** Task 11 y Task 20 dan instrucciones genéricas (registrar `include_router`); ajustar al archivo real (probablemente `backend/app/api/v1/router.py` o `backend/app/main.py`).
docs/superpowers/specs/2026-06-05-ta01-storage-and-attendance-design.md ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TA-01 — Storage de fotos + asistencia administrativa + flexibilidad gate
2
+
3
+ **Fecha:** 2026-06-05
4
+ **Sprint:** TA-01
5
+ **Estado:** Diseño aprobado, pendiente plan de implementación
6
+ **Fuente requisitos:** `docs/sprints/2026-06-05_TA-01.md`
7
+
8
+ ## Resumen
9
+
10
+ Sprint con tres bloques independientes pero entregados como una sola unidad:
11
+
12
+ - **Bloque A — Fotos:** migrar fotos de usuarios de Base64 en BD a archivos comprimidos (WebP) en un storage externo (Supabase Storage en prod, disco local en dev), detrás de una interfaz `PhotoStorage` con adapters intercambiables.
13
+ - **Bloque B — Asistencia administrativa:** nueva vista y endpoints para que los administradores pasen lista por aula cuando un docente está ausente, con trazabilidad de quién marcó cada asistencia.
14
+ - **Bloque C — Flexibilidad gate ↔ aula:** desacoplar la asistencia de aula del registro de entrada al plantel para tolerar fallas técnicas del kiosco (OpenCV, electricidad, internet).
15
+
16
+ ## Motivación
17
+
18
+ 1. Las fotos en Base64 dentro de la columna `face_encodings.photo` están afectando rendimiento y crecimiento de la BD; el patrón estándar es guardar archivos en un storage y solo la ruta en la BD.
19
+ 2. Cuando un docente falta, hoy no existe forma de que un administrador pase lista por aula desde el sistema — debe hacerse manualmente o quedar sin registrar.
20
+ 3. El acoplamiento actual (un estudiante no puede ser marcado presente en clase si no hizo check-in en el gate) era intencional como invariante de negocio, pero la operación real tiene cortes de electricidad / internet / fallas de cámara que dejan al docente sin poder marcar asistencia legítima. La contingencia técnica gana prioridad sobre la invariante.
21
+
22
+ **Reversión consciente:** este sprint revierte la guía previa de mantener acoplados `EntranceLog` y asistencia de aula. La motivación es contingencia técnica documentada arriba.
23
+
24
+ ## Decisiones de diseño tomadas
25
+
26
+ | # | Pregunta | Decisión |
27
+ |---|----------|----------|
28
+ | 1 | Alcance del sprint | Un único spec con los 3 bloques. |
29
+ | 2 | Abstracción de storage | Interfaz `PhotoStorage` con adapters `LocalDiskStorage` (dev) y `SupabaseStorage` (prod). Switch por env var. |
30
+ | 3 | Ubicación de la URL/path de foto en BD | Cambiar el tipo de `face_encodings.photo` de `Text` a `VARCHAR(500)`. No agregar columna nueva en `users`. |
31
+ | 4 | Migración de datos existentes | No automática. El admin re-sube manualmente las pocas fotos existentes. La migración Alembic solo cambia el tipo. |
32
+ | 5 | Perfil de compresión | WebP lossy q=85, máximo 800×800 px manteniendo aspect ratio. |
33
+ | 6 | Scope del admin en asistencia | Cualquier sección de su cuenta. Sin tabla de asignación admin-sección. |
34
+ | 7 | Trazabilidad de quién marcó | Agregar `attendances.marked_by_role` y `attendances.marked_by_user_id`. También se popula en marcas hechas por docente y por kiosco. |
35
+ | 8 | Grado de desacople gate | Desacople total: nunca bloquear. El chip `entrance_logged` se sigue calculando como información en la UI. |
36
+ | 9 | Ubicación de la UI admin | Página nueva `/admin/attendance` reutilizando componentes extraídos de `TeacherAttendancePage`. |
37
+
38
+ ## Cambios de base de datos
39
+
40
+ Migración Alembic: `backend/migrations/versions/028_ta01_storage_and_attendance_attribution.py`
41
+
42
+ ```sql
43
+ -- Bloque A: foto pasa de Base64 a URL/path corto + permitir encoding NULL
44
+ ALTER TABLE face_encodings
45
+ ALTER COLUMN photo TYPE VARCHAR(500) USING NULL, -- vacía las filas viejas; admin re-sube
46
+ ALTER COLUMN encoding DROP NOT NULL; -- permite foto sin rostro detectado
47
+
48
+ -- Bloque B: trazabilidad de origen de la marca
49
+ ALTER TABLE attendances
50
+ ADD COLUMN marked_by_role VARCHAR(20), -- 'teacher' | 'admin' | 'kiosco'
51
+ ADD COLUMN marked_by_user_id BIGINT NULL,
52
+ ADD CONSTRAINT fk_attendances_marked_by_user
53
+ FOREIGN KEY (marked_by_user_id) REFERENCES users(id);
54
+
55
+ CREATE INDEX ix_attendances_marked_by_user_id ON attendances(marked_by_user_id);
56
+ ```
57
+
58
+ **Justificación de `encoding NULL`:** el endpoint de upload de Bloque A intenta extraer encoding facial vía `face_utils`. Si la foto no tiene rostro detectable (ej. foto carnet con lente o ángulo), guardamos la foto igualmente con `encoding=NULL` para no perder la foto de identidad del usuario. El kiosco facial filtra `WHERE encoding IS NOT NULL` al hacer matching.
59
+
60
+ **Downgrade:**
61
+
62
+ ```sql
63
+ DROP INDEX ix_attendances_marked_by_user_id;
64
+ ALTER TABLE attendances
65
+ DROP CONSTRAINT fk_attendances_marked_by_user,
66
+ DROP COLUMN marked_by_user_id,
67
+ DROP COLUMN marked_by_role;
68
+ ALTER TABLE face_encodings
69
+ ALTER COLUMN photo TYPE TEXT;
70
+ ```
71
+
72
+ **Modelos SQLAlchemy:**
73
+
74
+ - `app/models/face_encoding.py` → `photo = Column(String(500), nullable=True)`
75
+ - `app/models/attendance.py` → agregar `marked_by_role = Column(String(20), nullable=True)` y `marked_by_user_id = Column(BigInteger, ForeignKey("users.id"), nullable=True)`
76
+
77
+ ## Bloque A — Storage de fotos
78
+
79
+ ### 1. Capa de abstracción (`backend/app/storage/`)
80
+
81
+ Estructura nueva del paquete:
82
+
83
+ ```
84
+ backend/app/storage/
85
+ __init__.py # factory: get_storage() lee env var
86
+ base.py # Protocol PhotoStorage
87
+ local_disk.py # LocalDiskStorage
88
+ supabase.py # SupabaseStorage (stub inicial)
89
+ in_memory.py # InMemoryStorage (solo tests)
90
+ ```
91
+
92
+ `base.py`:
93
+
94
+ ```python
95
+ from typing import Protocol
96
+
97
+ class PhotoStorage(Protocol):
98
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
99
+ """Persiste el archivo y devuelve la ruta/URL canónica que se guarda en BD."""
100
+ def delete(self, path_or_url: str) -> None:
101
+ """Borra el archivo. Best-effort, no levanta si no existe."""
102
+ def get_url(self, path_or_url: str) -> str:
103
+ """Devuelve la URL pública o firmada con la que el frontend lo consume."""
104
+ ```
105
+
106
+ `__init__.py`:
107
+
108
+ ```python
109
+ def get_storage() -> PhotoStorage:
110
+ backend = os.getenv("PHOTO_STORAGE_BACKEND", "local").lower()
111
+ if backend == "local":
112
+ return LocalDiskStorage(root=os.getenv("LOCAL_PHOTO_ROOT", "/data/photos"))
113
+ if backend == "supabase":
114
+ return SupabaseStorage(
115
+ url=os.getenv("SUPABASE_URL"),
116
+ key=os.getenv("SUPABASE_SERVICE_KEY"),
117
+ bucket=os.getenv("SUPABASE_PHOTO_BUCKET", "user-photos"),
118
+ )
119
+ raise ValueError(f"Unknown PHOTO_STORAGE_BACKEND: {backend}")
120
+ ```
121
+
122
+ `LocalDiskStorage`:
123
+
124
+ - Path en disco: `{root}/{account_id}/{user_id}/{uuid4}.{ext}`
125
+ - `get_url` devuelve `/api/v1/photos/{path}` (endpoint sirve el archivo con `FileResponse`)
126
+ - `delete` ignora `FileNotFoundError`
127
+
128
+ `SupabaseStorage` (inicial: stub que tira `NotImplementedError` con mensaje claro hasta que lleguen credenciales; las firmas y tests fakeados ya quedan listos).
129
+
130
+ ### 2. Pipeline de procesamiento de imágenes (`backend/app/services/photo_pipeline.py`)
131
+
132
+ ```python
133
+ from io import BytesIO
134
+ from PIL import Image, ImageOps
135
+ import magic
136
+
137
+ ALLOWED_MIME = {"image/png", "image/jpeg", "image/webp"}
138
+ MAX_INPUT_BYTES = 5 * 1024 * 1024 # 5 MB
139
+ TARGET_MAX_DIM = 800
140
+ WEBP_QUALITY = 85
141
+
142
+ def process_user_photo(raw: bytes) -> bytes:
143
+ if len(raw) > MAX_INPUT_BYTES:
144
+ raise ValueError("photo exceeds 5 MB")
145
+ mime = magic.from_buffer(raw, mime=True)
146
+ if mime not in ALLOWED_MIME:
147
+ raise ValueError(f"unsupported mime: {mime}")
148
+ img = Image.open(BytesIO(raw))
149
+ img = ImageOps.exif_transpose(img) # corrige rotación
150
+ img.thumbnail((TARGET_MAX_DIM, TARGET_MAX_DIM), Image.LANCZOS)
151
+ if img.mode in ("RGBA", "P"):
152
+ img = img.convert("RGB")
153
+ out = BytesIO()
154
+ img.save(out, format="WEBP", quality=WEBP_QUALITY, method=6)
155
+ return out.getvalue()
156
+ ```
157
+
158
+ Librerías nuevas en `backend/requirements.txt`: `Pillow` (verificar versión actual), `python-magic`. En Windows dev, `python-magic-bin`.
159
+
160
+ ### 3. Endpoint de upload
161
+
162
+ `POST /api/v1/users/{user_id}/photo` (admin-only):
163
+
164
+ ```
165
+ 1. multipart/form-data con campo `file` (max 5 MB; png|jpg|jpeg|webp)
166
+ 2. processed = process_user_photo(raw) # WebP 800×800 q=85
167
+ 3. Intentar extract_encoding(processed) vía face_utils:
168
+ - éxito → encoding_str
169
+ - sin rostro detectable → encoding_str = None, warning_flag = True
170
+ 4. storage = get_storage()
171
+ 5. Buscar último face_encoding del user; si existe y tiene photo:
172
+ storage.delete(old.photo) # best-effort
173
+ 6. new_path = storage.upload(account_id, user_id, processed, "webp")
174
+ 7. INSERT face_encodings (user_id, account_id, encoding=encoding_str, photo=new_path)
175
+ 8. Respuesta:
176
+ 200 { "photo_url": storage.get_url(new_path),
177
+ "encoding_extracted": bool,
178
+ "warning": "no se detectó rostro; el reconocimiento facial no
179
+ funcionará hasta resubir una foto con rostro visible"
180
+ if not encoding_extracted else None }
181
+ ```
182
+
183
+ **Mapeo en responses de usuarios:** En `users.py:72-99` (y cualquier otro lugar que devuelva `face_photo`), la columna `face_encodings.photo` ahora contiene un path/URL. Antes de devolverlo al frontend, pasa por `storage.get_url(path)` para que el frontend reciba siempre una URL servible (sea local `/api/v1/photos/...` o Supabase firmada). El campo `face_photo` en `UserResponse` schema mantiene su nombre y tipo `Optional[str]`.
184
+
185
+ ### 4. Endpoint para servir foto local
186
+
187
+ `GET /api/v1/photos/{account_id}/{user_id}/{filename}` con `FileResponse` y verificación de pertenencia a cuenta (auth + scope). Solo activo cuando `PHOTO_STORAGE_BACKEND=local`.
188
+
189
+ ## Bloque B — Asistencia administrativa
190
+
191
+ ### 1. Refactor previo (extracción de servicio)
192
+
193
+ Mover la lógica de marca de asistencia desde `app/api/v1/endpoints/teacher.py` a `app/services/attendance.py`:
194
+
195
+ ```python
196
+ def record_attendance(
197
+ db, *, account_id, user_id, section_id, subject_id, action,
198
+ marked_by_role: str, marked_by_user_id: int, when: datetime,
199
+ ) -> Attendance: ...
200
+
201
+ def list_section_roster(
202
+ db, *, account_id, section_id, on_date,
203
+ ) -> list[StudentRosterItem]: ...
204
+ ```
205
+
206
+ `teacher.py` y los nuevos endpoints admin pasan a llamar al servicio. Esto elimina duplicación y deja el cambio del Bloque C en un solo lugar.
207
+
208
+ ### 2. Endpoints admin (`app/api/v1/endpoints/admin_attendance.py`)
209
+
210
+ ```
211
+ GET /api/v1/admin/sections
212
+ GET /api/v1/admin/sections/{section_id}/subjects?on_date=YYYY-MM-DD
213
+ GET /api/v1/admin/sections/{section_id}/roster?subject_id=&on_date=YYYY-MM-DD
214
+ POST /api/v1/admin/attendance/swipe
215
+ POST /api/v1/admin/attendance/batch-toggle
216
+ ```
217
+
218
+ Schemas: mismos de `teacher` con renombre cosmético. Auth: `require_role("admin")`. Scope: filtrado por `current_user.account_id` en todas las queries.
219
+
220
+ ### 3. Frontend
221
+
222
+ Componentes nuevos / reusados:
223
+
224
+ - Extraer de `frontend/src/pages/teacher/TeacherAttendancePage.tsx` los componentes presentacionales: `AttendanceTable`, `StudentRow`, `AttendanceSummaryChips`. Mover a `frontend/src/components/attendance/`.
225
+ - Nueva página: `frontend/src/pages/admin/AdminAttendancePage.tsx`
226
+ - Header: selector `Section` → `Subject` → `Date` (default hoy).
227
+ - Body: `<AttendanceTable />` con datos del endpoint admin.
228
+ - Footer: contadores presente/ausente y botón "Guardar".
229
+ - Nuevo servicio: `frontend/src/services/adminAttendanceService.ts` espejo de `teacherService.ts`.
230
+ - Ruta: `/admin/attendance` agregada al router y al sidebar admin con el item "Asistencia por contingencia".
231
+
232
+ ## Bloque C — Desacople gate ↔ aula
233
+
234
+ ### Cambios
235
+
236
+ En `app/api/v1/endpoints/teacher.py` (y, después del refactor del Bloque B, en `app/services/attendance.py`):
237
+
238
+ - Eliminar el cálculo de `entrance_logged_ids` como **filtro** en `submit_swipe` (`teacher.py:470-496`) y en `batch-toggle` (`teacher.py:580-…`).
239
+ - Eliminar las acumulaciones de `skipped_ids` derivadas del check de gate.
240
+ - Eliminar las ramas `if rec.student_id not in entrance_logged_ids: skipped_ids.append(...)`.
241
+ - Grep adicional antes de implementar: `entrance_logged_ids` en todo el backend para asegurar que no quedó otro punto bloqueante (también revisar `services/attendance.py` post-refactor del Bloque B).
242
+
243
+ El `entrance_logged` que se devuelve en el roster (`GET /students` y similares) sigue calculándose; solo cambia su rol: ya no es bloqueante.
244
+
245
+ **Marcas desde el kiosco:** en `app/api/v1/endpoints/facial.py`, donde se inserta una `Attendance` desde reconocimiento facial, agregar `marked_by_role='kiosco'` y `marked_by_user_id=None`. Es un cambio de una línea para preservar consistencia del Bloque B.
246
+
247
+ ### Documentación de UI
248
+
249
+ En `TeacherAttendancePage` y `AdminAttendancePage`: el chip `entrance_logged` cambia de tono de "advertencia bloqueante" a "informativo" (gris). Tooltip: "Este estudiante no registró entrada en el gate hoy. Podés marcar asistencia igualmente."
250
+
251
+ ## Arquitectura de archivos (cambios)
252
+
253
+ ```
254
+ backend/
255
+ app/
256
+ models/
257
+ attendance.py [edit: +marked_by_role, +marked_by_user_id]
258
+ face_encoding.py [edit: photo = String(500)]
259
+ storage/ [NEW]
260
+ __init__.py
261
+ base.py
262
+ local_disk.py
263
+ supabase.py
264
+ in_memory.py
265
+ services/ [NEW or grow]
266
+ attendance.py [NEW: record_attendance, list_section_roster]
267
+ photo_pipeline.py [NEW]
268
+ api/v1/endpoints/
269
+ teacher.py [edit: usa services/attendance + quita gate filter]
270
+ admin_attendance.py [NEW]
271
+ users.py [edit: photo endpoint + mapea path → URL en responses]
272
+ photos.py [NEW: GET local file]
273
+ migrations/versions/
274
+ 028_ta01_storage_and_attendance_attribution.py [NEW]
275
+ tests/
276
+ storage/ [NEW: test_local_disk, test_supabase, test_in_memory]
277
+ services/ [NEW: test_photo_pipeline, test_attendance_service]
278
+ api/
279
+ test_admin_attendance.py [NEW]
280
+ test_teacher_attendance_gate_decouple.py [NEW: regresión Bloque C]
281
+ test_users_photo_upload.py [NEW]
282
+
283
+ frontend/
284
+ src/
285
+ components/attendance/ [NEW: extracción]
286
+ AttendanceTable.tsx
287
+ StudentRow.tsx
288
+ AttendanceSummaryChips.tsx
289
+ pages/
290
+ teacher/TeacherAttendancePage.tsx [edit: usa componentes extraídos]
291
+ admin/AdminAttendancePage.tsx [NEW]
292
+ services/
293
+ adminAttendanceService.ts [NEW]
294
+ routes.tsx [edit: +/admin/attendance]
295
+ ```
296
+
297
+ ## Variables de entorno nuevas
298
+
299
+ ```
300
+ PHOTO_STORAGE_BACKEND=local # local | supabase
301
+ LOCAL_PHOTO_ROOT=/data/photos # solo si backend=local
302
+ SUPABASE_URL= # solo si backend=supabase
303
+ SUPABASE_SERVICE_KEY= # solo si backend=supabase
304
+ SUPABASE_PHOTO_BUCKET=user-photos # opcional, default mostrado
305
+ ```
306
+
307
+ En `docker-compose.yml` montar volumen `/data/photos` para el backend (dev). En `.env.example` agregar las cinco variables con valores de dev.
308
+
309
+ ## Plan de testing
310
+
311
+ - **Storage**
312
+ - `LocalDiskStorage`: upload escribe archivo, delete lo borra (y es idempotente), get_url devuelve el path correcto.
313
+ - `InMemoryStorage`: smoke en memoria para tests rápidos del pipeline.
314
+ - `SupabaseStorage`: stub levanta `NotImplementedError` con mensaje claro hasta integración real.
315
+ - **Photo pipeline**
316
+ - Rechaza tamaños > 5 MB.
317
+ - Rechaza mime no permitido (probar gif).
318
+ - Acepta png, jpeg, webp.
319
+ - Output siempre es WebP de ≤ 800×800.
320
+ - EXIF rotation se aplica (foto verticalmente girada queda derecha).
321
+ - **Endpoint upload**
322
+ - Admin de otra cuenta no puede subir foto de un user.
323
+ - Sube foto, llamada GET la devuelve.
324
+ - Subir segunda foto borra la anterior del storage.
325
+ - **Servicio de asistencia**
326
+ - `record_attendance` setea `marked_by_role` y `marked_by_user_id` correctamente.
327
+ - Idempotencia: misma marca dos veces no duplica.
328
+ - **Endpoints admin**
329
+ - Admin puede listar todas las secciones de su cuenta.
330
+ - Admin de otra cuenta recibe 404 al pedir una sección ajena.
331
+ - `swipe` y `batch-toggle` se comportan como los de teacher pero con `marked_by_role='admin'`.
332
+ - **Regresión Bloque C**
333
+ - Estudiante sin `EntranceLog` del día ahora SÍ se marca presente en `teacher/attendance/swipe` y en `teacher/attendance/batch-toggle`.
334
+ - El roster sigue devolviendo `entrance_logged: false` para ese estudiante (información preservada).
335
+
336
+ ## Out of scope
337
+
338
+ - Migración automática de fotos Base64 existentes (admin re-sube manualmente).
339
+ - UI para que el admin "confirme ausencia de docente" o se asigne a una sección (admin tiene scope completo).
340
+ - Reportes diferenciados por `marked_by_role` (la columna queda lista pero los reports no la consumen en este sprint).
341
+ - Soporte para Supabase Storage real funcionando — el adapter queda con stub. La integración efectiva se hará cuando lleguen credenciales (sprint posterior).
342
+
343
+ ## Riesgos y mitigaciones
344
+
345
+ | Riesgo | Mitigación |
346
+ |--------|------------|
347
+ | Volumen local `/data/photos` en dev no persiste entre `docker compose down -v` | Documentar; el admin re-sube en dev. |
348
+ | `python-magic` requiere libmagic; en Windows usar `python-magic-bin` | Documentar en `requirements.txt` y `README` con condición de OS. |
349
+ | Reverter el filtro del gate podría permitir marcar a un estudiante que ni siquiera vino al colegio | Aceptado por requisito de contingencia. Trazabilidad retroactiva queda en `attendances.marked_by_user_id` (quién marcó) + flag `entrance_logged=false` ya almacenado, suficiente para auditar después. |
350
+ | Extraer componentes del frontend puede romper la UI de docente | Test manual de TeacherAttendancePage post-refactor antes de mergear. |
351
+
352
+ ## Convenciones del proyecto a respetar
353
+
354
+ - TZ: usar `datetime.now(timezone.utc)` para escrituras a columnas timezone-aware. El contenedor está en `America/Caracas`.
355
+ - Tests: pytest directo, **no** tocar `init.sh`.
356
+ - Commits locales OK durante el sprint, **NO** push automático a producción.
357
+ - Un mismo motor de BD en dev y prod (PostgreSQL).
frontend/src/App.tsx CHANGED
@@ -9,6 +9,7 @@ import EnrollmentsPage from './pages/EnrollmentsPage'
9
  import AttendanceReportsPage from './pages/AttendanceReportsPage'
10
  import SettingsPage from './pages/SettingsPage'
11
  import TeacherAttendancePage from './pages/TeacherAttendancePage'
 
12
  import TeacherSubjectsPage from './pages/TeacherSubjectsPage'
13
  import TeacherSectionsPage from './pages/TeacherSectionsPage'
14
  import PublicCheckInPage from './pages/PublicCheckInPage'
@@ -48,6 +49,7 @@ export default function App() {
48
  <Route path="attendance" element={<AttendanceReportsPage />} />
49
  <Route path="settings" element={<SettingsPage />} />
50
  <Route path="teacher-attendance" element={<TeacherAttendancePage />} />
 
51
  <Route path="public-checkin" element={<PublicCheckInPage />} />
52
  <Route path="developer" element={<DeveloperPage />} />
53
  <Route path="card-templates" element={<CardTemplatesPage />} />
 
9
  import AttendanceReportsPage from './pages/AttendanceReportsPage'
10
  import SettingsPage from './pages/SettingsPage'
11
  import TeacherAttendancePage from './pages/TeacherAttendancePage'
12
+ import AdminAttendancePage from './pages/AdminAttendancePage'
13
  import TeacherSubjectsPage from './pages/TeacherSubjectsPage'
14
  import TeacherSectionsPage from './pages/TeacherSectionsPage'
15
  import PublicCheckInPage from './pages/PublicCheckInPage'
 
49
  <Route path="attendance" element={<AttendanceReportsPage />} />
50
  <Route path="settings" element={<SettingsPage />} />
51
  <Route path="teacher-attendance" element={<TeacherAttendancePage />} />
52
+ <Route path="admin-attendance" element={<AdminAttendancePage />} />
53
  <Route path="public-checkin" element={<PublicCheckInPage />} />
54
  <Route path="developer" element={<DeveloperPage />} />
55
  <Route path="card-templates" element={<CardTemplatesPage />} />
frontend/src/components/AuthImage.tsx ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState, type ImgHTMLAttributes, type ReactNode } from 'react';
2
+ import { Loader2 } from 'lucide-react';
3
+ import api from '../services/api';
4
+
5
+ interface AuthImageProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
6
+ src: string | null | undefined;
7
+ fallback?: ReactNode;
8
+ }
9
+
10
+ /**
11
+ * Renders an authenticated image. The `<img src>` tag cannot send our JWT
12
+ * Authorization header, so a direct URL to a protected endpoint (e.g.
13
+ * `/api/v1/photos/...`) returns 401 and shows broken in the browser.
14
+ * AuthImage fetches the bytes through the axios instance (which injects
15
+ * the auth header), converts the response to a blob URL, and renders that.
16
+ *
17
+ * For dataURLs and blob URLs we render directly without fetching.
18
+ */
19
+ export default function AuthImage({ src, fallback = null, ...imgProps }: AuthImageProps) {
20
+ const [blobUrl, setBlobUrl] = useState<string | null>(null);
21
+ const [error, setError] = useState(false);
22
+
23
+ useEffect(() => {
24
+ if (!src) {
25
+ setBlobUrl(null);
26
+ setError(false);
27
+ return;
28
+ }
29
+
30
+ // Pass-through for data: and blob: URLs.
31
+ if (src.startsWith('data:') || src.startsWith('blob:')) {
32
+ setBlobUrl(src);
33
+ setError(false);
34
+ return;
35
+ }
36
+
37
+ let cancelled = false;
38
+ let createdUrl: string | null = null;
39
+ setError(false);
40
+
41
+ // Strip our axios baseURL prefix so the path doesn't double up.
42
+ const relative = src.replace(/^\/api\/v1/, '');
43
+
44
+ api
45
+ .get(relative, { responseType: 'blob' })
46
+ .then((res) => {
47
+ if (cancelled) return;
48
+ createdUrl = URL.createObjectURL(res.data);
49
+ setBlobUrl(createdUrl);
50
+ })
51
+ .catch(() => {
52
+ if (!cancelled) setError(true);
53
+ });
54
+
55
+ return () => {
56
+ cancelled = true;
57
+ if (createdUrl) URL.revokeObjectURL(createdUrl);
58
+ };
59
+ }, [src]);
60
+
61
+ if (error || !src) return <>{fallback}</>;
62
+ if (!blobUrl) {
63
+ const { className = '', ...rest } = imgProps;
64
+ return (
65
+ <div
66
+ {...(rest as React.HTMLAttributes<HTMLDivElement>)}
67
+ className={`${className} flex items-center justify-center bg-gray-100`}
68
+ aria-busy="true"
69
+ aria-label="Cargando imagen"
70
+ >
71
+ <Loader2 size={16} className="animate-spin text-gray-400" />
72
+ </div>
73
+ );
74
+ }
75
+ return <img src={blobUrl} {...imgProps} />;
76
+ }
frontend/src/components/CameraCapture.tsx CHANGED
@@ -1,5 +1,5 @@
1
  import { useState, useRef, useEffect, useCallback } from 'react';
2
- import { Camera, Check, RotateCcw } from 'lucide-react';
3
 
4
  interface CameraCaptureProps {
5
  isOpen: boolean;
@@ -18,11 +18,14 @@ export default function CameraCapture({ isOpen, onCapture, onClose }: CameraCapt
18
  const [cameraError, setCameraError] = useState(false);
19
  const [captured, setCaptured] = useState<string | null>(null);
20
  const [hasFaceDetector, setHasFaceDetector] = useState(false);
 
21
 
22
  const startCamera = useCallback(async () => {
23
  try {
24
  stopCamera();
25
- const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480, facingMode: 'user' } });
 
 
26
  streamRef.current = stream;
27
  if (videoRef.current) videoRef.current.srcObject = stream;
28
  setCameraReady(true);
@@ -30,6 +33,10 @@ export default function CameraCapture({ isOpen, onCapture, onClose }: CameraCapt
30
  } catch {
31
  setCameraError(true);
32
  }
 
 
 
 
33
  }, []);
34
 
35
  const stopCamera = useCallback(() => {
@@ -209,10 +216,20 @@ export default function CameraCapture({ isOpen, onCapture, onClose }: CameraCapt
209
  {hasFaceDetector && (
210
  <p className="text-xs text-center text-green-600">Detección facial activa</p>
211
  )}
212
- <button onClick={handleCapture} disabled={!cameraReady}
213
- className="w-full bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-sm inline-flex items-center justify-center gap-2 disabled:opacity-50">
214
- <Camera size={16} /> Tomar Foto
215
- </button>
 
 
 
 
 
 
 
 
 
 
216
  </div>
217
  )}
218
  </div>
 
1
  import { useState, useRef, useEffect, useCallback } from 'react';
2
+ import { Camera, Check, RotateCcw, SwitchCamera } from 'lucide-react';
3
 
4
  interface CameraCaptureProps {
5
  isOpen: boolean;
 
18
  const [cameraError, setCameraError] = useState(false);
19
  const [captured, setCaptured] = useState<string | null>(null);
20
  const [hasFaceDetector, setHasFaceDetector] = useState(false);
21
+ const [facingMode, setFacingMode] = useState<'user' | 'environment'>('user');
22
 
23
  const startCamera = useCallback(async () => {
24
  try {
25
  stopCamera();
26
+ const stream = await navigator.mediaDevices.getUserMedia({
27
+ video: { width: 640, height: 480, facingMode },
28
+ });
29
  streamRef.current = stream;
30
  if (videoRef.current) videoRef.current.srcObject = stream;
31
  setCameraReady(true);
 
33
  } catch {
34
  setCameraError(true);
35
  }
36
+ }, [facingMode]);
37
+
38
+ const toggleFacing = useCallback(() => {
39
+ setFacingMode((m) => (m === 'user' ? 'environment' : 'user'));
40
  }, []);
41
 
42
  const stopCamera = useCallback(() => {
 
216
  {hasFaceDetector && (
217
  <p className="text-xs text-center text-green-600">Detección facial activa</p>
218
  )}
219
+ <div className="flex gap-2">
220
+ <button onClick={handleCapture} disabled={!cameraReady}
221
+ className="flex-1 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-sm inline-flex items-center justify-center gap-2 disabled:opacity-50">
222
+ <Camera size={16} /> Tomar foto
223
+ </button>
224
+ <button onClick={toggleFacing} type="button"
225
+ title={facingMode === 'user' ? 'Cambiar a cámara trasera' : 'Cambiar a cámara frontal'}
226
+ className="bg-gray-100 text-gray-700 px-3 py-2 rounded-lg hover:bg-gray-200 transition text-sm inline-flex items-center justify-center gap-1.5">
227
+ <SwitchCamera size={16} />
228
+ <span className="hidden sm:inline">
229
+ {facingMode === 'user' ? 'Trasera' : 'Frontal'}
230
+ </span>
231
+ </button>
232
+ </div>
233
  </div>
234
  )}
235
  </div>
frontend/src/components/Layout.tsx CHANGED
@@ -1,10 +1,40 @@
1
- import { Outlet } from 'react-router-dom';
 
 
2
  import Sidebar from './Sidebar';
3
 
4
  export default function Layout() {
 
 
 
 
 
 
 
 
5
  return (
6
  <div className="app-layout">
7
- <Sidebar />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  <main className="main-content">
9
  <Outlet />
10
  </main>
 
1
+ import { Outlet, useLocation } from 'react-router-dom';
2
+ import { useState, useEffect } from 'react';
3
+ import { Menu } from 'lucide-react';
4
  import Sidebar from './Sidebar';
5
 
6
  export default function Layout() {
7
+ const [mobileOpen, setMobileOpen] = useState(false);
8
+ const location = useLocation();
9
+
10
+ // Close drawer whenever the route changes.
11
+ useEffect(() => {
12
+ setMobileOpen(false);
13
+ }, [location.pathname]);
14
+
15
  return (
16
  <div className="app-layout">
17
+ {/* Floating hamburger (mobile only, no full topbar) */}
18
+ <button
19
+ type="button"
20
+ onClick={() => setMobileOpen(true)}
21
+ aria-label="Abrir menú"
22
+ className="mobile-menu-fab md:hidden"
23
+ >
24
+ <Menu size={20} />
25
+ </button>
26
+
27
+ {/* Backdrop for mobile drawer */}
28
+ {mobileOpen && (
29
+ <div
30
+ className="fixed inset-0 bg-black/50 z-30 md:hidden"
31
+ onClick={() => setMobileOpen(false)}
32
+ aria-hidden="true"
33
+ />
34
+ )}
35
+
36
+ <Sidebar mobileOpen={mobileOpen} onClose={() => setMobileOpen(false)} />
37
+
38
  <main className="main-content">
39
  <Outlet />
40
  </main>
frontend/src/components/Sidebar.tsx CHANGED
@@ -1,7 +1,12 @@
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'] },
@@ -14,6 +19,7 @@ const navItems = [
14
  { to: '/dashboard/mis-hijos', label: 'Mis Hijos', icon: Heart, roles: ['representative'] },
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'] },
@@ -28,7 +34,7 @@ function hasAdminAccess(user: { role: string; permissions: string[] } | null): b
28
  return user?.role === 'admin' || user?.role === 'developer' || (user?.permissions ?? []).includes('admin.full');
29
  }
30
 
31
- export default function Sidebar() {
32
  const user = useAuthStore((s) => s.user);
33
  const clearAuth = useAuthStore((s) => s.clearAuth);
34
  const isAdmin = hasAdminAccess(user);
@@ -45,14 +51,32 @@ export default function Sidebar() {
45
  });
46
 
47
  return (
48
- <aside className="sidebar">
49
  <div className="sidebar-header">
50
- <span className="text-xl font-bold">Talos Access</span>
51
- <span className="sidebar-role">{translateRole(user?.role)}</span>
 
 
 
 
 
 
 
 
 
 
 
 
52
  </div>
53
  <nav className="sidebar-nav">
54
  {visible.map((item) => (
55
- <NavLink key={item.to} to={item.to} end={item.to === '/dashboard'} className={({ isActive }) => `nav-item${isActive ? ' active' : ''}`}>
 
 
 
 
 
 
56
  <item.icon size={18} />
57
  <span>{item.label}</span>
58
  </NavLink>
 
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, X } from 'lucide-react';
5
+
6
+ interface SidebarProps {
7
+ mobileOpen?: boolean;
8
+ onClose?: () => void;
9
+ }
10
 
11
  const navItems = [
12
  { to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] },
 
19
  { to: '/dashboard/mis-hijos', label: 'Mis Hijos', icon: Heart, roles: ['representative'] },
20
  { to: '/dashboard/public-checkin', label: 'Mi Asistencia', icon: Clock, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] },
21
  { to: '/dashboard/teacher-attendance', label: 'Asistencia', icon: CreditCard, roles: ['teacher'] },
22
+ { to: '/dashboard/admin-attendance', label: 'Asistencia (contingencia)', icon: ClipboardCheck, roles: ['admin'] },
23
  { to: '/dashboard/attendance', label: 'Reportes', icon: BarChart3, roles: ['admin', 'administrativo'] },
24
  { to: '/dashboard/student-report', label: 'Rep. Estudiantes', icon: FileText, roles: ['admin', 'administrativo'] },
25
  { to: '/dashboard/late-arrivals', label: 'Tardanzas', icon: Clock, roles: ['admin', 'administrativo', 'teacher'] },
 
34
  return user?.role === 'admin' || user?.role === 'developer' || (user?.permissions ?? []).includes('admin.full');
35
  }
36
 
37
+ export default function Sidebar({ mobileOpen = false, onClose }: SidebarProps) {
38
  const user = useAuthStore((s) => s.user);
39
  const clearAuth = useAuthStore((s) => s.clearAuth);
40
  const isAdmin = hasAdminAccess(user);
 
51
  });
52
 
53
  return (
54
+ <aside className={`sidebar${mobileOpen ? ' sidebar-open' : ''}`}>
55
  <div className="sidebar-header">
56
+ <div className="flex flex-col">
57
+ <span className="text-xl font-bold">Talos Access</span>
58
+ <span className="sidebar-role">{translateRole(user?.role)}</span>
59
+ </div>
60
+ {onClose && (
61
+ <button
62
+ type="button"
63
+ onClick={onClose}
64
+ aria-label="Cerrar menú"
65
+ className="md:hidden p-1.5 rounded-lg hover:bg-gray-800 text-gray-300"
66
+ >
67
+ <X size={18} />
68
+ </button>
69
+ )}
70
  </div>
71
  <nav className="sidebar-nav">
72
  {visible.map((item) => (
73
+ <NavLink
74
+ key={item.to}
75
+ to={item.to}
76
+ end={item.to === '/dashboard'}
77
+ onClick={onClose}
78
+ className={({ isActive }) => `nav-item${isActive ? ' active' : ''}`}
79
+ >
80
  <item.icon size={18} />
81
  <span>{item.label}</span>
82
  </NavLink>
frontend/src/pages/AdminAttendancePage.tsx ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from 'react';
2
+ import { Loader2, Save, ClipboardList } from 'lucide-react';
3
+ import {
4
+ adminAttendanceService,
5
+ type AdminSection,
6
+ type AdminRosterItem,
7
+ type AdminAttendanceRecord,
8
+ } from '../services/adminAttendanceService';
9
+ import DateInput from '../components/DateInput';
10
+
11
+ export default function AdminAttendancePage() {
12
+ const [sections, setSections] = useState<AdminSection[]>([]);
13
+ const [sectionId, setSectionId] = useState<number | ''>('');
14
+ const [date, setDate] = useState<string>(() => new Date().toISOString().slice(0, 10));
15
+ const [roster, setRoster] = useState<AdminRosterItem[]>([]);
16
+ const [rosterLoading, setRosterLoading] = useState(false);
17
+ // pending: student_id → desired new present value
18
+ const [pendingToggles, setPendingToggles] = useState<Map<number, boolean>>(new Map());
19
+ const [saving, setSaving] = useState(false);
20
+ const [error, setError] = useState<string | null>(null);
21
+ const [toast, setToast] = useState<{ text: string; type: 'error' | 'success' } | null>(null);
22
+
23
+ // Auto-dismiss toast
24
+ useEffect(() => {
25
+ if (!toast) return;
26
+ const t = setTimeout(() => setToast(null), 4000);
27
+ return () => clearTimeout(t);
28
+ }, [toast]);
29
+
30
+ // Load sections on mount
31
+ useEffect(() => {
32
+ adminAttendanceService
33
+ .listSections()
34
+ .then(setSections)
35
+ .catch((e) => setError(String(e?.message ?? e)));
36
+ }, []);
37
+
38
+ // Load roster when section or date changes
39
+ useEffect(() => {
40
+ if (sectionId === '') return;
41
+ setRosterLoading(true);
42
+ setError(null);
43
+ setPendingToggles(new Map());
44
+ adminAttendanceService
45
+ .getRoster(Number(sectionId), date)
46
+ .then((r) => { setRoster(r); setRosterLoading(false); })
47
+ .catch((e) => { setError(String(e?.message ?? e)); setRosterLoading(false); });
48
+ }, [sectionId, date]);
49
+
50
+ const getEffective = (r: AdminRosterItem): { present: boolean; pending: boolean } => {
51
+ if (pendingToggles.has(r.id)) {
52
+ return { present: pendingToggles.get(r.id)!, pending: true };
53
+ }
54
+ return { present: r.already_checked_in, pending: false };
55
+ };
56
+
57
+ const toggleStudent = (r: AdminRosterItem) => {
58
+ const currentEffective = pendingToggles.has(r.id)
59
+ ? pendingToggles.get(r.id)!
60
+ : r.already_checked_in;
61
+ setPendingToggles((prev) => {
62
+ const next = new Map(prev);
63
+ next.set(r.id, !currentEffective);
64
+ return next;
65
+ });
66
+ };
67
+
68
+ const save = async () => {
69
+ if (sectionId === '' || pendingToggles.size === 0) return;
70
+ setSaving(true);
71
+ setError(null);
72
+ try {
73
+ const records: AdminAttendanceRecord[] = Array.from(pendingToggles.entries()).map(
74
+ ([student_id, present]) => ({ student_id, present }),
75
+ );
76
+ const res = await adminAttendanceService.batchToggle(Number(sectionId), records, date);
77
+ setPendingToggles(new Map());
78
+ const skippedCount = res.skipped?.length ?? 0;
79
+ if (skippedCount > 0) {
80
+ setToast({ text: `${res.created} marcados. ${skippedCount} no se pudieron marcar (sin check-in en gate).`, type: 'error' });
81
+ } else {
82
+ setToast({ text: `Asistencia guardada correctamente (${res.created} registros).`, type: 'success' });
83
+ }
84
+ // Refresh roster to show updated state
85
+ const fresh = await adminAttendanceService.getRoster(Number(sectionId), date);
86
+ setRoster(fresh);
87
+ } catch (e: any) {
88
+ setError(String(e?.response?.data?.detail ?? e?.message ?? e));
89
+ } finally {
90
+ setSaving(false);
91
+ }
92
+ };
93
+
94
+ const sortedRoster = [...roster].sort((a, b) => {
95
+ const aEff = getEffective(a);
96
+ const bEff = getEffective(b);
97
+ if (aEff.present === bEff.present) return 0;
98
+ return aEff.present ? 1 : -1; // absent first
99
+ });
100
+
101
+ const presentRoster = roster.filter((r) => getEffective(r).present);
102
+ const presentCount = presentRoster.length;
103
+ const presentM = presentRoster.filter((r) => r.sex === 'M').length;
104
+ const presentF = presentRoster.filter((r) => r.sex === 'F').length;
105
+ const absentCount = roster.length - presentCount;
106
+
107
+ return (
108
+ <div className="max-w-4xl mx-auto space-y-6">
109
+ {toast && (
110
+ <div
111
+ className={`fixed top-6 left-1/2 -translate-x-1/2 z-[100] px-6 py-3 rounded-xl shadow-lg text-sm font-medium transition-all duration-300 animate-fade-in ${toast.type === 'error' ? 'bg-red-600 text-white' : 'bg-emerald-600 text-white'}`}
112
+ onClick={() => setToast(null)}
113
+ style={{ cursor: 'pointer' }}
114
+ >
115
+ {toast.text}
116
+ </div>
117
+ )}
118
+
119
+ <div>
120
+ <h1>Asistencia por contingencia</h1>
121
+ <p className="text-sm text-gray-500 mt-1">
122
+ Use esta vista cuando un docente esté ausente y necesite pasar lista en su aula.
123
+ </p>
124
+ </div>
125
+
126
+ {error && (
127
+ <div className="rounded-lg bg-red-50 border border-red-200 text-red-700 px-4 py-2 text-sm">
128
+ {error}
129
+ </div>
130
+ )}
131
+
132
+ <div className="flex gap-3 items-end flex-wrap">
133
+ <div>
134
+ <label className="block text-xs text-gray-500 mb-1">Sección</label>
135
+ <select
136
+ value={sectionId}
137
+ onChange={(e) => setSectionId(e.target.value ? Number(e.target.value) : '')}
138
+ className="border border-gray-300 rounded-lg px-3 py-2"
139
+ style={{ minWidth: 220 }}
140
+ >
141
+ <option value="">Seleccione una sección…</option>
142
+ {sections.map((s) => (
143
+ <option key={s.id} value={s.id}>{s.name}</option>
144
+ ))}
145
+ </select>
146
+ </div>
147
+ <div>
148
+ <label className="block text-xs text-gray-500 mb-1">Fecha</label>
149
+ <DateInput
150
+ value={date}
151
+ onChange={(v) => setDate(v)}
152
+ className="border border-gray-300 rounded-lg px-3 py-2"
153
+ />
154
+ </div>
155
+ </div>
156
+
157
+ {sectionId === '' ? (
158
+ <div className="rounded-xl border border-dashed border-gray-300 bg-gray-50/60 py-12 px-6 text-center">
159
+ <ClipboardList size={32} className="mx-auto text-gray-400 mb-3" />
160
+ <p className="text-sm font-medium text-gray-700">
161
+ Seleccione una sección para comenzar
162
+ </p>
163
+ <p className="text-xs text-gray-500 mt-1">
164
+ La lista de alumnos aparecerá aquí una vez que seleccione una sección de la cuenta.
165
+ </p>
166
+ </div>
167
+ ) : (
168
+ <>
169
+ {rosterLoading ? (
170
+ <div className="flex items-center justify-center py-12">
171
+ <Loader2 size={24} className="animate-spin text-gray-400" />
172
+ </div>
173
+ ) : (
174
+ <>
175
+ {roster.length > 0 && (
176
+ <div className="rounded-lg bg-emerald-50 border border-emerald-200 px-4 py-2 text-sm font-medium text-emerald-900 inline-flex items-center gap-3 flex-wrap">
177
+ <span>Presentes: {presentCount}</span>
178
+ <span className="text-emerald-700 text-xs">
179
+ (Masculinos: {presentM} · Femeninos: {presentF})
180
+ </span>
181
+ <span className="border-l border-emerald-300 pl-3">Ausentes: {absentCount}</span>
182
+ </div>
183
+ )}
184
+
185
+ <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
186
+ <div className="overflow-x-auto">
187
+ <table className="w-full text-sm min-w-[560px] lg:min-w-0">
188
+ <thead>
189
+ <tr className="border-b border-gray-200 text-left text-gray-500">
190
+ <th className="pb-2 font-medium pl-3 pr-2 pt-2">Estudiante</th>
191
+ <th className="pb-2 font-medium pr-2 pt-2">Cédula</th>
192
+ <th className="pb-2 font-medium pr-2 pt-2">Estado</th>
193
+ <th className="pb-2 font-medium pr-2 pt-2">Entrada al plantel</th>
194
+ <th className="pb-2 font-medium pt-2 pr-3 text-right">Acción</th>
195
+ </tr>
196
+ </thead>
197
+ <tbody>
198
+ {sortedRoster.length === 0 ? (
199
+ <tr>
200
+ <td colSpan={5} className="text-gray-400 text-sm text-center py-8">
201
+ Sin estudiantes en esta sección
202
+ </td>
203
+ </tr>
204
+ ) : (
205
+ sortedRoster.map((r) => {
206
+ const eff = getEffective(r);
207
+ return (
208
+ <tr
209
+ key={r.id}
210
+ className={`border-b border-gray-100 ${eff.pending ? 'bg-amber-50/50' : ''}`}
211
+ >
212
+ <td className="py-2 font-medium pl-3 pr-2">
213
+ {r.lastname}, {r.name}
214
+ </td>
215
+ <td className="py-2 text-gray-500 text-xs font-mono pr-2">
216
+ {r.card_id || '-'}
217
+ </td>
218
+ <td className="py-2 pr-2">
219
+ <span
220
+ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
221
+ eff.present
222
+ ? 'bg-green-100 text-green-700'
223
+ : 'bg-red-100 text-red-700'
224
+ }`}
225
+ >
226
+ {eff.present ? 'Presente' : 'Ausente'}
227
+ </span>
228
+ </td>
229
+ <td className="py-2 pr-2">
230
+ <span
231
+ className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500"
232
+ title={
233
+ r.entrance_logged
234
+ ? 'El alumno registró su entrada al plantel hoy.'
235
+ : 'El alumno no registró entrada al plantel hoy. Puede marcar asistencia igualmente.'
236
+ }
237
+ >
238
+ {r.entrance_logged ? 'Registrada' : 'Sin registro'}
239
+ </span>
240
+ </td>
241
+ <td className="py-2 pr-3 text-right">
242
+ <button
243
+ type="button"
244
+ onClick={() => toggleStudent(r)}
245
+ className={`px-3 py-1 rounded-lg text-xs transition-colors ${
246
+ eff.pending
247
+ ? 'bg-amber-100 text-amber-700 border border-amber-300 hover:bg-amber-200'
248
+ : 'bg-gray-50 border border-gray-200 text-gray-600 hover:bg-blue-50 hover:border-blue-300'
249
+ }`}
250
+ >
251
+ {eff.pending
252
+ ? eff.present ? 'Marcar presente ↩' : 'Marcar ausente ↩'
253
+ : eff.present ? 'Marcar ausente' : 'Marcar presente'}
254
+ </button>
255
+ </td>
256
+ </tr>
257
+ );
258
+ })
259
+ )}
260
+ </tbody>
261
+ </table>
262
+ </div>
263
+
264
+ {pendingToggles.size > 0 && (
265
+ <div className="border-t border-gray-200 p-4 flex items-center justify-between bg-amber-50/30">
266
+ <span className="text-sm text-amber-700 font-medium">
267
+ {pendingToggles.size} cambio{pendingToggles.size !== 1 ? 's' : ''} pendiente{pendingToggles.size !== 1 ? 's' : ''}
268
+ </span>
269
+ <button
270
+ type="button"
271
+ onClick={save}
272
+ disabled={saving}
273
+ className="inline-flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 text-sm"
274
+ >
275
+ {saving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
276
+ {saving ? 'Guardando…' : 'Guardar Cambios'}
277
+ </button>
278
+ </div>
279
+ )}
280
+ </div>
281
+ </>
282
+ )}
283
+ </>
284
+ )}
285
+ </div>
286
+ );
287
+ }
288
+
frontend/src/pages/SectionsPage.tsx CHANGED
@@ -126,8 +126,24 @@ export default function SectionsPage() {
126
  <div className="flex items-center justify-between">
127
  <h1>Secciones</h1>
128
  <div className="flex gap-2">
129
- <button className="bg-white text-blue-600 border border-blue-300 px-4 py-2 rounded-lg hover:bg-blue-50 transition text-sm inline-flex items-center justify-center gap-2" onClick={() => setShowBulkUpload(true)}><Upload size={16} /> Carga Masiva</button>
130
- <button className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-sm inline-flex items-center justify-center gap-2" onClick={openCreate}><Plus size={16} /> Nueva Sección</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  </div>
132
  </div>
133
  <div className="flex gap-3 items-end flex-wrap">
 
126
  <div className="flex items-center justify-between">
127
  <h1>Secciones</h1>
128
  <div className="flex gap-2">
129
+ <button
130
+ aria-label="Carga Masiva"
131
+ title="Carga Masiva"
132
+ className="bg-white text-blue-600 border border-blue-300 p-2 sm:px-4 sm:py-2 rounded-lg hover:bg-blue-50 transition text-sm inline-flex items-center justify-center gap-2"
133
+ onClick={() => setShowBulkUpload(true)}
134
+ >
135
+ <Upload size={16} />
136
+ <span className="hidden sm:inline">Carga Masiva</span>
137
+ </button>
138
+ <button
139
+ aria-label="Nueva Sección"
140
+ title="Nueva Sección"
141
+ className="bg-blue-600 text-white p-2 sm:px-4 sm:py-2 rounded-lg hover:bg-blue-700 transition text-sm inline-flex items-center justify-center gap-2"
142
+ onClick={openCreate}
143
+ >
144
+ <Plus size={16} />
145
+ <span className="hidden sm:inline">Nueva Sección</span>
146
+ </button>
147
  </div>
148
  </div>
149
  <div className="flex gap-3 items-end flex-wrap">