diff --git a/.opencode/ARCHITECTURE.md b/.opencode/ARCHITECTURE.md deleted file mode 100644 index e1261f843d8609cb2aab52c95e2fa8faaeda95ec..0000000000000000000000000000000000000000 --- a/.opencode/ARCHITECTURE.md +++ /dev/null @@ -1,63 +0,0 @@ -# Prompt de Desarrollo: Sistema SaaS de Control de Asistencias (MVP) - -### Nombre del proyecto: Talos - Access - -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). - -Diseña la arquitectura, el modelo de datos modular y los endpoints necesarios basándote en los siguientes requerimientos estrictos: - ---- - -## 1. Stack Tecnológico & Arquitectura -- **Backend:** FastAPI (Python), implementando arquitectura limpia por capas o basada en routers/features. -- **Frontend:** React + Vite + Tailwind CSS (Estructura empresarial modular, no SPA plana). -- **Base de Datos:** MySQL (Relacional, optimizada con índices para consultas de alta concurrencia en horas pico de entrada/salida). -- **Caché y Mensajería:** Redis (Para gestionar colas de procesamiento de imágenes de OpenCV, sesiones activas y limitación de peticiones/Rate Limiting). -- **Visión Artificial:** OpenCV (Procesamiento de streams de video/imágenes para reconocimiento facial). - ---- - -## 2. Lógica de Negocio y Niveles de Suscripción (SaaS) -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: - -- **Plan Basic (Manual):** Entrada/Salida mediante teclado introduciendo el documento de identidad (DNI). -- **Plan Premium (Hardware):** Entrada/Salida automatizada mediante la lectura de códigos de barras/QR impresos en los carnets escolares. -- **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). - ---- - -## 3. Matriz de Permisología y Control de Acceso (RBAC / ABAC) -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: - -- **Rol: Admin (Administrador del Plantel)** - - Acceso total al sistema (CRUD completo de usuarios, alumnos, docentes y planes). - - 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). - - Acceso a reportes globales consolidados. - -- **Rol: Usuario (Docentes / Profesores)** - - 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. - -- **Rol: Representante (Padres / Tutores)** - - Acceso exclusivo a un perfil de consulta externa para verificar el historial de asistencia, retrasos y reportes **únicamente de sus representados (hijos)**. - -*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. - ---- - -## 4. Requerimientos de Frontend, Visualización y Datos -Para el frontend en React, el sistema requiere dos componentes de alta complejidad de datos: - -- **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). -- **Filtrabilidad Avanzada (Backend Driven):** Todos los módulos de reportes deben incluir un panel de filtros especiales y combinables: - - Rango de fechas dinámico. - - Estado de asistencia (A tiempo, Retraso, Falta Justificada, Falta Injustificada). - - Sección / Aula / Grado. - - Filtro por docente o alumno específico. - - Los datos deben paginarse desde el backend para evitar problemas de rendimiento. - ---- - -## ¿Qué necesito que generes primero? -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. -2. La estructura de endpoints esenciales en FastAPI para el flujo de Check-In/Check-Out considerando los 3 planes. -3. La configuración del middleware de seguridad para validar el acceso cruzado de profesores y representantes. \ No newline at end of file diff --git a/.opencode/skills/boilerpalette/SKILLS.md b/.opencode/skills/boilerpalette/SKILLS.md deleted file mode 100644 index 70dccdc88e5e2e24df79e9ba492986ced6ef1554..0000000000000000000000000000000000000000 --- a/.opencode/skills/boilerpalette/SKILLS.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -name: fastapi-opencv-boilerplate -description: Scaffolds a professional FastAPI project integrated with OpenCV and MySQL using architectural best practices. -license: MIT -compatibility: opencode -metadata: - audience: developers - workflow: project-initialization ---- - -## What I do - -- **Generate a structured FastAPI boilerplate** following the official template guidelines (Clean Architecture / Router-based separation). -- **Configure MySQL integration** via SQLAlchemy ORM (async/sync ready) including base models and session management. -- **Inject basic OpenCV utility modules** for processing images or video streams within background tasks or endpoints. -- **Create environmental setups** including a `.env.example`, `requirements.txt`, and a `Dockerfile`. - -## When to use me - -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. - ---- - -### Suggested Project Structure - -```text -my_fastapi_app/ -│ -├── app/ -│ ├── __init__.py -│ ├── main.py # Application entrypoint -│ ├── core/ -│ │ ├── config.py # Pydantic environment settings -│ │ └── security.py -│ │ -│ ├── database/ -│ │ ├── session.py # MySQL engine and sessionmaker -│ │ └── base_class.py # Declarative base for SQLAlchemy -│ │ -│ ├── models/ # SQLAlchemy ORM models -│ │ └── __init__.py -│ │ -│ ├── schemas/ # Pydantic data validation schemas -│ │ └── __init__.py -│ │ -│ ├── api/ # API Endpoints (V1) -│ │ ├── router.py # Main APIRouter orchestrator -│ │ └── endpoints/ -│ │ ├── vision.py # OpenCV processing routes -│ │ └── auth.py -│ │ -│ └── services/ # Core business logic / Vision pipelines -│ └── vision_service.py # OpenCV image manipulation logic -│ -├── .env.example -├── Dockerfile -├── README.md -└── requirements.txt \ No newline at end of file diff --git a/.opencode/skills/containerization/SKILLS.md b/.opencode/skills/containerization/SKILLS.md deleted file mode 100644 index 1affef1c6137ac64af3a5dfd23ef9116a54e0e46..0000000000000000000000000000000000000000 --- a/.opencode/skills/containerization/SKILLS.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -name: dockerize-fastapi-react-mysql -description: Provisions production-ready Docker and Docker Compose configurations for orchestrating a complex FastAPI (OpenCV) backend, React frontend, and MySQL database. -license: MIT -compatibility: opencode -metadata: - audience: devops-and-developers - workflow: containerization ---- - -## What I do - -- **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). -- **Orchestrate a unified multi-container system** via `docker-compose.yml` including internal networking, configuration overrides, structural data volumes, and healthcheck sequencing. -- **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. - -## When to use me - -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. - ---- - -### Suggested Containerization Setup - -```text -my_project_root/ -│ -├── backend/ # (Your structured FastAPI codebase) -│ ├── app/ -│ ├── Dockerfile -│ └── requirements.txt -│ -├── frontend/ # (Your enterprise React codebase) -│ ├── src/ -│ ├── Dockerfile -│ └── nginx.conf # Nginx config for handling React SPA routes internally -│ -├── docker-compose.yml # Central orchestration manifest -└── .env # Global environment configurations \ No newline at end of file diff --git a/.opencode/skills/frontend/SKILLS.md b/.opencode/skills/frontend/SKILLS.md deleted file mode 100644 index be0859f42c952ec38041de3b747e1af96dd4f88c..0000000000000000000000000000000000000000 --- a/.opencode/skills/frontend/SKILLS.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -name: react-enterprise-fastapi-bridge -description: Scaffolds a production-ready, highly modular React frontend using Vite and Tailwind CSS, architected for large-scale enterprise systems connecting to FastAPI backends. -license: MIT -compatibility: opencode -metadata: - audience: architects-and-developers - workflow: enterprise-frontend-initialization ---- - -## What I do - -- **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. -- **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. -- **Configure Advanced Tailwind Utilities** utilizing `tailwind-merge` and `clsx` to construct production-ready, dynamic, and highly reusable design-system components. -- **Inject Enterprise API Routing and Layering** providing strict abstraction layers between the HTTP transport layer (Axios), domain-specific services, and global layout managers. - -## When to use me - -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. - ---- - -### Suggested Enterprise Project Structure - -```text -my_enterprise_app/ -│ -├── src/ -│ ├── assets/ # Global assets (images, logos, fonts) -│ ├── components/ # Base Design System / Atomic UI (Unbound to domain) -│ │ ├── ui/ # Button, Input, Modal, Table, Dropdown -│ │ └── feedback/ # Skeletons, Spinners, Toast notifications -│ │ -│ ├── config/ # Core configurations and Axios transport layers -│ │ └── axios.instance.js # Interceptors for Auth, Refresh Tokens, and Logging -│ │ -│ ├── features/ # Domain-Driven Modules (Self-contained boundaries) -│ │ ├── auth/ # Components, hooks, types, and api endpoints for Auth -│ │ ├── dashboard/ # Layouts and widgets for general entry metrics -│ │ └── vision-pipelines/ # Enterprise module for OpenCV stream/batch management -│ │ ├── api/ # Localized api calls: getPipeline(), processBatch() -│ │ ├── components/ # CanvasViewer, LiveStreamPlayer, MetricsTable -│ │ ├── hooks/ # usePipelineMutation, useStreamMetrics -│ │ └── pages/ # Full views: PipelineConfigPage, LiveMonitorPage -│ │ -│ ├── layouts/ # Structural Shells (AdminLayout, PublicLayout) -│ │ └── RootLayout.jsx -│ │ -│ ├── routes/ # Advanced Router definition with lazy-loading & guards -│ │ ├── AppRoutes.jsx # Route tree orchestration -│ │ └── GuardedRoute.jsx # Role-based access control (RBAC) handling -│ │ -│ ├── store/ # Client-side State (Zustand / Redux Toolkit) -│ │ └── useUIStore.js # Global UI behaviors (sidebars, persistent preferences) -│ │ -│ ├── App.jsx # Global Providers (QueryClientProvider, Theme, Router) -│ ├── main.jsx # DOM Mount point -│ └── index.css # Design-system design variables and Tailwind directives -│ -├── tailwind.config.js # Design-system extended schema definitions -├── vite.config.js # Advanced aliases mapping (@/features, @/components) -└── package.json \ No newline at end of file diff --git a/.opencode/skills/ui-ux/SKILLS.md b/.opencode/skills/ui-ux/SKILLS.md deleted file mode 100644 index 83c2f4561ec18b6ef7ac46f9b3c8bea126b8423d..0000000000000000000000000000000000000000 --- a/.opencode/skills/ui-ux/SKILLS.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: ui-ux-soft-ui-master -description: Enforces high-fidelity UI/UX principles, modern design systems, and Soft UI design trends using Tailwind CSS. -license: MIT -compatibility: opencode -metadata: - audience: frontend-developers - workflow: UI-refactoring-and-styling ---- - -## What I do - -- **Transform raw/ugly HTML/React components** into visually stunning, premium interfaces using **Soft UI / Modern Neumorphism** aesthetics. -- **Enforce UX best practices:** Visual hierarchy, optimal cognitive load, accessible contrast ratios (WCAG), interactive states (`hover`, `focus`, `active`), and smooth micro-interactions. -- **Construct cohesive design systems:** Implement unified spacing scales, precise border-radii, consistent shadow structures, and semantic color palettes. -- **Refactor layout patterns:** Optimize mobile-first responsiveness, grid systems, and dashboard information density. - -## When to use me - -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. \ No newline at end of file diff --git a/backend/.env.example b/backend/.env.example index be6b2ea870e59b765108b49055b105d64c6787a2..fef01db1020c1e2596705135599b7eba434779ab 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -24,3 +24,11 @@ APP_NAME=Talos Access DEBUG=true API_V1_PREFIX=/api/v1 CORS_ORIGINS=["http://localhost:5173"] + +# Bloque A — Storage de fotos +PHOTO_STORAGE_BACKEND=local +LOCAL_PHOTO_ROOT=/data/photos +LOCAL_PHOTO_URL_PREFIX=/api/v1/photos +SUPABASE_URL= +SUPABASE_SERVICE_KEY= +SUPABASE_PHOTO_BUCKET=user-photos diff --git a/backend/Dockerfile b/backend/Dockerfile index 4fb814e8b799a3db3bcc00f37c2f979195a4faf1..3d0a7f5f74125873be90ba14a1373e3785f6d91a 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -7,6 +7,7 @@ RUN apt-get update && apt-get install -y \ cmake \ build-essential \ tzdata \ + libmagic1 \ && rm -rf /var/lib/apt/lists/* WORKDIR /app diff --git a/backend/alembic/versions/028_ta01_storage_and_attendance_attribution.py b/backend/alembic/versions/028_ta01_storage_and_attendance_attribution.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcaa228cf8899eb532b42cbeddcfbf54533a18b --- /dev/null +++ b/backend/alembic/versions/028_ta01_storage_and_attendance_attribution.py @@ -0,0 +1,79 @@ +"""TA-01: storage paths and attendance attribution + +WARNING: Upgrade deletes all existing face_encodings.photo data +(was base64; now URL/path). Admins must re-upload after deployment. +Downgrade does NOT restore the deleted photos. + +Bloque A: face_encodings.photo Text(base64) → VARCHAR(500) URL/path; + face_encodings.encoding allowed to be NULL. +Bloque B: attendances gets marked_by_role + marked_by_user_id for + attribution traceability (teacher | admin | kiosco). + +Revision ID: 028 +Revises: 027 +Create Date: 2026-06-05 +""" + +from alembic import op +import sqlalchemy as sa + +revision = "028" +down_revision = "027" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Bloque A: face_encodings.photo de Text(base64) a VARCHAR(500) URL/path. + # Cleanup de filas existentes: vaciar photo (el admin re-sube) y permitir encoding NULL. + op.execute("UPDATE face_encodings SET photo = NULL") + op.alter_column( + "face_encodings", "photo", + existing_type=sa.Text(), + type_=sa.String(length=500), + existing_nullable=True, + ) + op.alter_column( + "face_encodings", "encoding", + existing_type=sa.Text(), + nullable=True, + ) + + # Bloque B: trazabilidad de origen de la marca. + op.add_column( + "attendances", + sa.Column("marked_by_role", sa.String(length=20), nullable=True), + ) + op.add_column( + "attendances", + sa.Column("marked_by_user_id", sa.BigInteger(), nullable=True), + ) + op.create_foreign_key( + "fk_attendances_marked_by_user", + "attendances", "users", + ["marked_by_user_id"], ["id"], + ondelete="SET NULL", + ) + op.create_index( + "ix_attendances_marked_by_user_id", + "attendances", ["marked_by_user_id"], + ) + + +def downgrade() -> None: + # NOTE: Photo data deleted in upgrade is NOT restored here. + op.drop_index("ix_attendances_marked_by_user_id", table_name="attendances") + op.drop_constraint("fk_attendances_marked_by_user", "attendances", type_="foreignkey") + op.drop_column("attendances", "marked_by_user_id") + op.drop_column("attendances", "marked_by_role") + op.alter_column( + "face_encodings", "encoding", + existing_type=sa.Text(), + nullable=False, + ) + op.alter_column( + "face_encodings", "photo", + existing_type=sa.String(length=500), + type_=sa.Text(), + existing_nullable=True, + ) diff --git a/backend/app/api/v1/endpoints/admin_attendance.py b/backend/app/api/v1/endpoints/admin_attendance.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3d8ad87bcb525b23d615dde41a94d5c591ab0c --- /dev/null +++ b/backend/app/api/v1/endpoints/admin_attendance.py @@ -0,0 +1,147 @@ +from datetime import datetime, date as date_type, time, timezone +from typing import Optional, List + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.core.database import get_db +from app.middleware.rbac import RBAC +from app.models.user import User +from app.models.section import Section +from app.services.attendance import record_attendance, list_section_roster + +router = APIRouter(prefix="/admin", tags=["admin-attendance"]) + + +@router.get("/sections") +def admin_list_sections( + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + rows = ( + db.query(Section) + .filter(Section.account_id == current_user.account_id) + .order_by(Section.name) + .all() + ) + return [{"id": s.id, "name": s.name} for s in rows] + + +@router.get("/sections/{section_id}/roster") +def admin_section_roster( + section_id: int, + on_date: Optional[str] = Query(None, alias="date"), + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + section = ( + db.query(Section) + .filter( + Section.id == section_id, + Section.account_id == current_user.account_id, + ) + .first() + ) + if not section: + raise HTTPException(status_code=404, detail="section not found") + + day = ( + datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date_type.today() + ) + items = list_section_roster( + db, + account_id=current_user.account_id, + section_id=section_id, + on_date=day, + ) + return [it.__dict__ for it in items] + + +class AdminSwipeRecord(BaseModel): + student_id: int + present: bool + + +class AdminSwipeRequest(BaseModel): + section_id: int + subject_id: Optional[int] = None + records: List[AdminSwipeRecord] + + +def _ensure_admin_section(payload_section_id: int, account_id: int, db: Session) -> Section: + section = ( + db.query(Section) + .filter( + Section.id == payload_section_id, + Section.account_id == account_id, + ) + .first() + ) + if not section: + raise HTTPException(status_code=404, detail="section not found") + return section + + +@router.post("/attendance/swipe", status_code=201) +def admin_attendance_swipe( + payload: AdminSwipeRequest, + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + _ensure_admin_section(payload.section_id, current_user.account_id, db) + when = datetime.now(timezone.utc) + created = 0 + for rec in payload.records: + if not rec.present: + continue + record_attendance( + db, + account_id=current_user.account_id, + user_id=rec.student_id, + section_id=payload.section_id, + subject_id=payload.subject_id, + action="in", + marked_by_role="admin", + marked_by_user_id=current_user.id, + when=when, + note="Admin: contingencia", + ) + created += 1 + return {"created": created, "total": len(payload.records), "skipped": []} + + +@router.post("/attendance/batch-toggle") +def admin_batch_toggle( + payload: AdminSwipeRequest, + on_date: Optional[str] = Query(None, alias="date"), + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + _ensure_admin_section(payload.section_id, current_user.account_id, db) + day = ( + datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date_type.today() + ) + when = ( + datetime.now(timezone.utc) + if day == date_type.today() + else datetime.combine(day, time(12, 0), tzinfo=timezone.utc) + ) + created = 0 + for rec in payload.records: + if not rec.present: + continue + record_attendance( + db, + account_id=current_user.account_id, + user_id=rec.student_id, + section_id=payload.section_id, + subject_id=payload.subject_id, + action="in", + marked_by_role="admin", + marked_by_user_id=current_user.id, + when=when, + note="Admin batch: contingencia", + ) + created += 1 + return {"created": created, "total": len(payload.records), "skipped": []} diff --git a/backend/app/api/v1/endpoints/dashboard.py b/backend/app/api/v1/endpoints/dashboard.py index 376f71902af089106eeeac88f60fa152e8399213..b22dcd5ebe1f4cabc0df1a738d519c8effd95a7c 100644 --- a/backend/app/api/v1/endpoints/dashboard.py +++ b/backend/app/api/v1/endpoints/dashboard.py @@ -29,6 +29,137 @@ def _teacher_section_ids(current_user: User, db: Session): return [r.section_id for r in rows] +def _presence_user_ids_in_range( + db: Session, + *, + account_id: int, + date_from: date, + date_to: date, + section_ids: Optional[list[int]] = None, +) -> set[int]: + """User IDs with ANY presence event in [date_from, date_to]. + + Presence = EntranceLog (gate / kiosk) OR Attendance.action == "in" (class). + Sources are deduped — a student with both counts once. Per TA-01, + classroom marks are valid even when the gate is down (contingency). + + If `section_ids` is given, scope to students whose presence event ties + to one of those sections (Attendance.section_id directly; EntranceLog + has no section, so we join Enrollment). + """ + gate_q = db.query(EntranceLog.user_id).filter( + EntranceLog.account_id == account_id, + EntranceLog.date >= date_from, + EntranceLog.date <= date_to, + ) + if section_ids is not None: + gate_q = ( + gate_q.join(Enrollment, Enrollment.student_id == EntranceLog.user_id) + .filter( + Enrollment.section_id.in_(section_ids), + Enrollment.account_id == account_id, + ) + ) + gate_ids = {row[0] for row in gate_q.distinct().all()} + + class_q = db.query(Attendance.user_id).filter( + Attendance.account_id == account_id, + Attendance.action == "in", + cast(Attendance.time_log, Date) >= date_from, + cast(Attendance.time_log, Date) <= date_to, + ) + if section_ids is not None: + class_q = class_q.filter(Attendance.section_id.in_(section_ids)) + class_ids = {row[0] for row in class_q.distinct().all()} + + return gate_ids | class_ids + + +def _exit_user_ids_in_range( + db: Session, + *, + account_id: int, + date_from: date, + date_to: date, + section_ids: Optional[list[int]] = None, +) -> set[int]: + """User IDs with an exit event in [date_from, date_to]. + + Exit = EntranceLog.checkout_time set OR Attendance.action == "out". + Same union/dedup logic as presence. + """ + gate_q = db.query(EntranceLog.user_id).filter( + EntranceLog.account_id == account_id, + EntranceLog.date >= date_from, + EntranceLog.date <= date_to, + EntranceLog.checkout_time.isnot(None), + ) + if section_ids is not None: + gate_q = ( + gate_q.join(Enrollment, Enrollment.student_id == EntranceLog.user_id) + .filter( + Enrollment.section_id.in_(section_ids), + Enrollment.account_id == account_id, + ) + ) + gate_ids = {row[0] for row in gate_q.distinct().all()} + + class_q = db.query(Attendance.user_id).filter( + Attendance.account_id == account_id, + Attendance.action == "out", + cast(Attendance.time_log, Date) >= date_from, + cast(Attendance.time_log, Date) <= date_to, + ) + if section_ids is not None: + class_q = class_q.filter(Attendance.section_id.in_(section_ids)) + class_ids = {row[0] for row in class_q.distinct().all()} + + return gate_ids | class_ids + + +def _presence_user_ids_by_day( + db: Session, + *, + account_id: int, + start_date: date, + end_date: date, + section_ids: Optional[list[int]] = None, +) -> dict[date, set[int]]: + """Per-day union of presence user IDs (EntranceLog + Attendance 'in').""" + gate_q = db.query(EntranceLog.date, EntranceLog.user_id).filter( + EntranceLog.account_id == account_id, + EntranceLog.date >= start_date, + EntranceLog.date <= end_date, + ) + if section_ids is not None: + gate_q = ( + gate_q.join(Enrollment, Enrollment.student_id == EntranceLog.user_id) + .filter( + Enrollment.section_id.in_(section_ids), + Enrollment.account_id == account_id, + ) + ) + + class_q = db.query( + cast(Attendance.time_log, Date).label("log_date"), + Attendance.user_id, + ).filter( + Attendance.account_id == account_id, + Attendance.action == "in", + cast(Attendance.time_log, Date) >= start_date, + cast(Attendance.time_log, Date) <= end_date, + ) + if section_ids is not None: + class_q = class_q.filter(Attendance.section_id.in_(section_ids)) + + by_day: dict[date, set[int]] = {} + for d, uid in gate_q.all(): + by_day.setdefault(d, set()).add(uid) + for d, uid in class_q.all(): + by_day.setdefault(d, set()).add(uid) + return by_day + + @router.get("/stats") def dashboard_stats( db: Session = Depends(get_db), @@ -53,36 +184,15 @@ def dashboard_stats( ).scalar() or 0 today = date.today() - today_checkins = db.query(func.count(func.distinct(Attendance.user_id))).filter( - Attendance.section_id.in_(sec_ids), - Attendance.account_id == account_id, - cast(Attendance.time_log, Date) == today, - ).scalar() or 0 - - users_out_today = db.query(func.distinct(Attendance.user_id)).filter( - Attendance.section_id.in_(sec_ids), - Attendance.account_id == account_id, - cast(Attendance.time_log, Date) == today, - Attendance.action == "out", - ).subquery() - - currently_on_campus = db.query(func.count(func.distinct(Attendance.user_id))).filter( - Attendance.section_id.in_(sec_ids), - Attendance.account_id == account_id, - cast(Attendance.time_log, Date) == today, - Attendance.checkout_time.is_(None), - ~Attendance.user_id.in_(users_out_today), - ).scalar() or 0 - - today_checkouts = db.query(func.count(func.distinct(Attendance.user_id))).filter( - Attendance.section_id.in_(sec_ids), - Attendance.account_id == account_id, - cast(Attendance.time_log, Date) == today, - or_( - Attendance.checkout_time.isnot(None), - Attendance.action == "out", - ), - ).scalar() or 0 + present_today = _presence_user_ids_in_range( + db, account_id=account_id, date_from=today, date_to=today, section_ids=sec_ids, + ) + exited_today = _exit_user_ids_in_range( + db, account_id=account_id, date_from=today, date_to=today, section_ids=sec_ids, + ) + today_checkins = len(present_today) + today_checkouts = len(exited_today) + currently_on_campus = len(present_today - exited_today) return { "total_students": total_students, @@ -115,24 +225,18 @@ def dashboard_stats( Subject.account_id == account_id, ).scalar() or 0 - # Check-in/out real proviene de EntranceLog (kiosko / facial), no de Attendance. + # Asistencia = unión deduplicada de EntranceLog (gate) + Attendance "in" (aula). + # Per TA-01, una marca de aula es válida aun sin gate (contingencia). today = date.today() - today_checkins = db.query(func.count(func.distinct(EntranceLog.user_id))).filter( - EntranceLog.account_id == account_id, - EntranceLog.date == today, - ).scalar() or 0 - - currently_on_campus = db.query(func.count(EntranceLog.id)).filter( - EntranceLog.account_id == account_id, - EntranceLog.date == today, - EntranceLog.checkout_time.is_(None), - ).scalar() or 0 - - today_checkouts = db.query(func.count(EntranceLog.id)).filter( - EntranceLog.account_id == account_id, - EntranceLog.date == today, - EntranceLog.checkout_time.isnot(None), - ).scalar() or 0 + present_today = _presence_user_ids_in_range( + db, account_id=account_id, date_from=today, date_to=today, + ) + exited_today = _exit_user_ids_in_range( + db, account_id=account_id, date_from=today, date_to=today, + ) + today_checkins = len(present_today) + today_checkouts = len(exited_today) + currently_on_campus = len(present_today - exited_today) return { "total_students": total_students, @@ -156,39 +260,15 @@ def attendance_trend( today_ref = date.today() start_date = today_ref - timedelta(days=days - 1) - if sec_ids is not None: - # Docente: asistencia de clase por sección (Attendance) - rows = ( - db.query( - cast(Attendance.time_log, Date).label("log_date"), - func.count(func.distinct(Attendance.user_id)).label("cnt"), - ) - .filter( - Attendance.account_id == account_id, - Attendance.section_id.in_(sec_ids), - cast(Attendance.time_log, Date) >= start_date, - cast(Attendance.time_log, Date) <= today_ref, - ) - .group_by(cast(Attendance.time_log, Date)) - .all() - ) - trend_map = {row.log_date: row.cnt for row in rows} - else: - # Admin: check-ins reales (EntranceLog) por día - rows = ( - db.query( - EntranceLog.date.label("log_date"), - func.count(func.distinct(EntranceLog.user_id)).label("cnt"), - ) - .filter( - EntranceLog.account_id == account_id, - EntranceLog.date >= start_date, - EntranceLog.date <= today_ref, - ) - .group_by(EntranceLog.date) - .all() - ) - trend_map = {row.log_date: row.cnt for row in rows} + # Asistencia por día = unión deduplicada de EntranceLog + Attendance "in". + by_day = _presence_user_ids_by_day( + db, + account_id=account_id, + start_date=start_date, + end_date=today_ref, + section_ids=sec_ids, + ) + trend_map = {d: len(uids) for d, uids in by_day.items()} result = [] for i in range(days): @@ -347,8 +427,13 @@ def sex_by_section( "totals": {"masculino": 0, "femenino": 0, "sin_especificar": 0, "total": 0}, } - # Students attended in range, grouped by section - rows = ( + # Students attended in range, grouped by section. + # A student counts as "asistente" if EITHER: + # (a) gate kiosk / facial check-in (EntranceLog), OR + # (b) teacher/admin classroom mark (Attendance.action == "in"), + # which are intentionally decoupled per TA-01: a class mark is valid + # even without a gate log when there's a contingency (power, kiosk). + gate_rows = ( db.query(Section.id, Enrollment.student_id) .join(Enrollment, Enrollment.section_id == Section.id) .join(EntranceLog, EntranceLog.user_id == Enrollment.student_id) @@ -362,10 +447,25 @@ def sex_by_section( .distinct() .all() ) - by_section: dict[int, list[int]] = {sid: [] for sid in sec_ids_in_scope} + class_rows = ( + db.query(Section.id, Enrollment.student_id) + .join(Enrollment, Enrollment.section_id == Section.id) + .join(Attendance, Attendance.user_id == Enrollment.student_id) + .filter( + Section.id.in_(sec_ids_in_scope), + Enrollment.account_id == account_id, + Attendance.account_id == account_id, + Attendance.action == "in", + cast(Attendance.time_log, Date) >= df, + cast(Attendance.time_log, Date) <= dt, + ) + .distinct() + .all() + ) + by_section: dict[int, set[int]] = {sid: set() for sid in sec_ids_in_scope} all_student_ids: set[int] = set() - for sec_id, stu_id in rows: - by_section[sec_id].append(stu_id) + for sec_id, stu_id in (*gate_rows, *class_rows): + by_section[sec_id].add(stu_id) all_student_ids.add(stu_id) out_sections = [] diff --git a/backend/app/api/v1/endpoints/facial.py b/backend/app/api/v1/endpoints/facial.py index a0e65c901d605a2bed7f48bd13a8d3aeeff2d9ec..0116409ea8de8bb717088d484ff316dfb6abbe8f 100644 --- a/backend/app/api/v1/endpoints/facial.py +++ b/backend/app/api/v1/endpoints/facial.py @@ -1,3 +1,12 @@ +"""Facial recognition kiosk endpoints. + +NOTE (TA-01): the kiosk path only writes `EntranceLog` rows (gate check-in). +It does NOT insert into `Attendance` directly — classroom attendance is +recorded by teachers (`teacher.py`) and admins (`admin_attendance.py`), +which tag rows with `marked_by_role` accordingly. If you ever add a kiosk +write to `Attendance`, set `marked_by_role='kiosco'` and +`marked_by_user_id=None` to preserve attribution. +""" from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from sqlalchemy import cast, Date @@ -85,11 +94,31 @@ def enroll_face( if encoding is None: raise HTTPException(status_code=400, detail="Could not extract face encoding") + # TA-01: photo goes through pipeline (WebP compression) + storage abstraction, + # never as base64 in BD (column is VARCHAR(500), too small for a dataURL). + photo_path: Optional[str] = None + try: + import base64 as _b64 + from app.services.photo_pipeline import process_user_photo + from app.storage import get_storage + + raw = payload.image + if "," in raw: + raw = raw.split(",")[1] + processed = process_user_photo(_b64.b64decode(raw)) + photo_path = get_storage().upload( + current_user.account_id, target.id, processed, "webp", + ) + except Exception: + # Photo compression/upload is best-effort. If it fails, we still + # save the encoding so facial recognition keeps working. + photo_path = None + fe = FaceEncoding( user_id=target.id, account_id=current_user.account_id, encoding=json.dumps(encoding), - photo=payload.image, + photo=photo_path, ) db.add(fe) db.commit() diff --git a/backend/app/api/v1/endpoints/photos.py b/backend/app/api/v1/endpoints/photos.py new file mode 100644 index 0000000000000000000000000000000000000000..535c7188efe39c44cfa05a211bc7914d6dfba82e --- /dev/null +++ b/backend/app/api/v1/endpoints/photos.py @@ -0,0 +1,29 @@ +import os +from pathlib import Path +from fastapi import APIRouter, Depends, HTTPException +from fastapi.responses import FileResponse +from app.dependencies.auth import get_current_user +from app.models.user import User + +router = APIRouter(prefix="/photos", tags=["photos"]) + + +@router.get("/{account_id}/{user_id}/{filename}") +def serve_photo( + account_id: int, + user_id: int, + filename: str, + current_user: User = Depends(get_current_user), +): + if os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() != "local": + raise HTTPException(status_code=404, detail="not served locally") + if current_user.account_id != account_id: + raise HTTPException(status_code=404, detail="not found") + root = Path(os.getenv("LOCAL_PHOTO_ROOT", "/data/photos")).resolve() + target = (root / str(account_id) / str(user_id) / filename).resolve() + # Block path traversal (filename = "../../../etc/passwd" etc.) + if not target.is_relative_to(root): + raise HTTPException(status_code=400, detail="invalid path") + if not target.exists(): + raise HTTPException(status_code=404, detail="not found") + return FileResponse(target, media_type="image/webp") diff --git a/backend/app/api/v1/endpoints/teacher.py b/backend/app/api/v1/endpoints/teacher.py index c9538412279841b72daf1c86616a7dc9684ce021..f716c4ae568ae1f02caa437ada824ad79e14f9e0 100644 --- a/backend/app/api/v1/endpoints/teacher.py +++ b/backend/app/api/v1/endpoints/teacher.py @@ -26,6 +26,7 @@ from app.models.section_schedule import SectionSchedule from app.utils.holiday_check import is_holiday from app.utils.sex_counts import count_by_sex from app.utils.audit import log_for +from app.services.attendance import record_attendance, list_section_roster router = APIRouter(prefix="/teacher", tags=["teacher"]) @@ -414,43 +415,25 @@ def section_students( db: Session = Depends(get_db), ): _ensure_teacher_section(section_id, current_user.id, current_user.account_id, db) - enrollments = db.query(Enrollment).filter(Enrollment.section_id == section_id, Enrollment.account_id == current_user.account_id).all() - student_ids = [e.student_id for e in enrollments] - students = db.query(User).filter(User.id.in_(student_ids), User.is_active == "1").all() - today = date.today() - checked_in_ids = set() - entrance_logged_ids = set() - if students: - student_id_list = [s.id for s in students] - today_att = db.query( - Attendance.user_id, - Attendance.action, - Attendance.checkout_time, - ).filter( - Attendance.user_id.in_(student_id_list), - Attendance.account_id == current_user.account_id, - Attendance.time_log >= today, - ).order_by(Attendance.time_log.desc()).all() - seen = set() - for user_id, action, checkout_time in today_att: - if user_id in seen: - continue - seen.add(user_id) - if action == "out": - continue - if action == "in": - checked_in_ids.add(user_id) - elif action is None and checkout_time is None: - checked_in_ids.add(user_id) - entrance_logs = db.query(EntranceLog.user_id).filter( - EntranceLog.user_id.in_(student_id_list), - EntranceLog.account_id == current_user.account_id, - EntranceLog.date == today, - ).distinct().all() - entrance_logged_ids = {el.user_id for el in entrance_logs} - - 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] + roster = list_section_roster( + db, + account_id=current_user.account_id, + section_id=section_id, + on_date=today, + ) + return [ + StudentCardResponse( + id=r.id, + name=r.name, + lastname=r.lastname, + card_id=r.card_id, + phone_number=r.phone_number, + already_checked_in=r.already_checked_in, + entrance_logged=r.entrance_logged, + ) + for r in roster + ] @router.post("/attendance/swipe", status_code=status.HTTP_201_CREATED) @@ -466,17 +449,6 @@ def submit_swipe( today = now.date() created = 0 - student_ids = [rec.student_id for rec in payload.records] - entrance_logged_ids = set() - if student_ids: - els = db.query(EntranceLog.user_id).filter( - EntranceLog.user_id.in_(student_ids), - EntranceLog.account_id == current_user.account_id, - EntranceLog.date == today, - ).distinct().all() - entrance_logged_ids = {el.user_id for el in els} - - skipped_ids: list[int] = [] for rec in payload.records: if not rec.present: continue @@ -490,24 +462,23 @@ def submit_swipe( already_in = existing and existing.action is None and existing.checkout_time is None if already_in: continue - if rec.student_id not in entrance_logged_ids: - # student hasn't done their daily entrance at the campus gate, can't be - # marked present in class. Report back to the teacher so they know why. - skipped_ids.append(rec.student_id) - continue - 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")) + record_attendance( + db, + account_id=current_user.account_id, + user_id=rec.student_id, + section_id=payload.section_id, + subject_id=payload.subject_id, + action="in", + marked_by_role="teacher", + marked_by_user_id=current_user.id, + when=datetime.now(timezone.utc), + note="Swipe: present", + ) created += 1 db.commit() - # Resolve skipped students to {student_id, name} for the frontend toast. + # `skipped` is always empty after gate decouple (TA-01). Response shape preserved. skipped: list[dict] = [] - if skipped_ids: - rows = db.query(User).filter( - User.id.in_(skipped_ids), - User.account_id == current_user.account_id, - ).all() - name_map = {u.id: f"{u.name} {u.lastname}" for u in rows} - skipped = [{"student_id": sid, "name": name_map.get(sid, "")} for sid in skipped_ids] section = db.query(Section).filter(Section.id == payload.section_id).first() subject = db.query(Subject).filter(Subject.id == payload.subject_id).first() if payload.subject_id else None @@ -577,17 +548,6 @@ def batch_toggle( _ensure_teacher_section(payload.section_id, current_user.id, current_user.account_id, db) record_time = datetime.now(timezone.utc) if day == date.today() else datetime.combine(day, time(12, 0), tzinfo=timezone.utc) - student_ids = [rec.student_id for rec in payload.records] - entrance_logged_ids = set() - if student_ids: - els = db.query(EntranceLog.user_id).filter( - EntranceLog.user_id.in_(student_ids), - EntranceLog.account_id == current_user.account_id, - EntranceLog.date == day, - ).distinct().all() - entrance_logged_ids = {el.user_id for el in els} - - skipped_ids = [] for rec in payload.records: existing = db.query(Attendance).filter( Attendance.user_id == rec.student_id, @@ -601,23 +561,25 @@ def batch_toggle( ).first() already_present = existing is not None if rec.present: - if rec.student_id not in entrance_logged_ids: - skipped_ids.append(rec.student_id) - continue if not already_present: - 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")) + record_attendance( + db, + account_id=current_user.account_id, + user_id=rec.student_id, + section_id=payload.section_id, + subject_id=payload.subject_id, + action="in", + marked_by_role="teacher", + marked_by_user_id=current_user.id, + when=record_time, + note="Toggle: present", + ) elif already_present: db.delete(existing) db.commit() - skipped = [] - if skipped_ids: - rows = db.query(User).filter( - User.id.in_(skipped_ids), - User.account_id == current_user.account_id, - ).all() - name_map = {u.id: f"{u.name} {u.lastname}" for u in rows} - skipped = [{"student_id": sid, "name": name_map.get(sid, "")} for sid in skipped_ids] + # `skipped` is always empty after gate decouple (TA-01). Response shape preserved. + skipped: list[dict] = [] now_local = datetime.now() section = db.query(Section).filter(Section.id == payload.section_id).first() @@ -758,16 +720,18 @@ def toggle_attendance( db.commit() return {"present": False, "attendance_id": None} else: - has_entrance = db.query(EntranceLog).filter( - EntranceLog.user_id == student_id, - EntranceLog.account_id == current_user.account_id, - EntranceLog.date == day, - ).first() - if not has_entrance: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="El estudiante no tiene ingreso registrado hoy") - 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") - db.add(att) - db.commit() + att = record_attendance( + db, + account_id=current_user.account_id, + user_id=student_id, + section_id=section_id, + subject_id=subject_id, + action="in", + marked_by_role="teacher", + marked_by_user_id=current_user.id, + when=datetime.now(timezone.utc), + note="Swipe: present", + ) log_for( db, current_user, "Marcar asistencia", "asistencias", details={ diff --git a/backend/app/api/v1/endpoints/users.py b/backend/app/api/v1/endpoints/users.py index a13f0024b022b4df2f14ea71205a80d2f05c04f9..85aece301de12ce3be93fe2ec116a774bcc3aff4 100644 --- a/backend/app/api/v1/endpoints/users.py +++ b/backend/app/api/v1/endpoints/users.py @@ -2,6 +2,9 @@ from fastapi import APIRouter, Depends, HTTPException, status, Query, Request from sqlalchemy.orm import Session from sqlalchemy import or_, func from typing import Optional +import json +import numpy as np +import cv2 from app.utils.audit import log_for @@ -20,6 +23,9 @@ from app.models.teacher_section import TeacherSection from app.models.enrollment import Enrollment from app.models.face_encoding import FaceEncoding from app.utils.csv_import import generate_csv_template, parse_csv_upload, process_csv_rows +from app.storage import get_storage +from app.services.photo_pipeline import process_user_photo +from app.face_utils import detect_face, encode_face router = APIRouter(prefix="/users", tags=["users"]) @@ -90,12 +96,14 @@ def list_users( ) photos = {r.user_id: r.photo for r in rows} + storage = get_storage() items = [] for u in users: ur = UserResponse.model_validate( {c.name: getattr(u, c.name) for c in u.__table__.columns}, ) - ur.face_photo = photos.get(u.id) + raw_path = photos.get(u.id) + ur.face_photo = storage.get_url(raw_path) if raw_path else None items.append(ur) return PaginatedResponse( @@ -323,3 +331,70 @@ def deactivate_user( log_for(db, current_user, "Desactivar usuario", "usuarios", details={"user_id": user.id, "nombre": f"{user.name} {user.lastname}"}, request=request) + + +@router.post("/{user_id}/photo") +def upload_user_photo( + user_id: int, + file: UploadFile = File(...), + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + target = db.query(User).filter( + User.id == user_id, + User.account_id == current_user.account_id, + ).first() + if not target: + raise HTTPException(status_code=404, detail="user not found") + + raw = file.file.read() + try: + processed = process_user_photo(raw) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) + + # Best-effort face encoding extraction. + encoding_str = None + try: + arr = np.frombuffer(processed, np.uint8) + img = cv2.imdecode(arr, cv2.IMREAD_COLOR) + if img is not None: + face = detect_face(img) + if face is not None: + vec = encode_face(face) + if vec is not None: + encoding_str = json.dumps(vec) + except Exception: + encoding_str = None + + storage = get_storage() + + # Delete previous photo from storage (best-effort) + previous = ( + db.query(FaceEncoding) + .filter(FaceEncoding.user_id == user_id, FaceEncoding.photo.isnot(None)) + .order_by(FaceEncoding.id.desc()) + .first() + ) + if previous and previous.photo: + try: + storage.delete(previous.photo) + except Exception: + pass + + new_path = storage.upload(target.account_id, user_id, processed, "webp") + fe = FaceEncoding( + user_id=user_id, + account_id=target.account_id, + encoding=encoding_str, + photo=new_path, + ) + db.add(fe) + db.commit() + + return { + "photo_url": storage.get_url(new_path), + "encoding_extracted": encoding_str is not None, + "warning": None if encoding_str else + "no se detectó rostro; el reconocimiento facial no funcionará hasta resubir una foto con rostro visible", + } diff --git a/backend/app/api/v1/router.py b/backend/app/api/v1/router.py index 177280f79a61106ad37b9dabc023c477e2dcac80..4fcea9a8b90db2496dceec0457c6a889c48e3415 100644 --- a/backend/app/api/v1/router.py +++ b/backend/app/api/v1/router.py @@ -1,6 +1,6 @@ from fastapi import APIRouter -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 +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 router = APIRouter(prefix="/api/v1") router.include_router(auth.router) @@ -23,3 +23,5 @@ router.include_router(representative.router) router.include_router(audit_logs.router) router.include_router(reports.router) router.include_router(holidays.router) +router.include_router(photos.router) +router.include_router(admin_attendance.router) diff --git a/backend/app/models/attendance.py b/backend/app/models/attendance.py index 1fae65fda048b6ddf7ccb595810f29dd24f7fd14..467ee8bfb38126b6a0e199941cb76d8fc27aa110 100644 --- a/backend/app/models/attendance.py +++ b/backend/app/models/attendance.py @@ -15,3 +15,5 @@ class Attendance(Base): coordinates = Column(JSON) note = Column(String(255)) action = Column(String(10), nullable=True, comment="in or out") + marked_by_role = Column(String(20), nullable=True) + marked_by_user_id = Column(BigInteger, ForeignKey("users.id"), nullable=True) diff --git a/backend/app/models/face_encoding.py b/backend/app/models/face_encoding.py index 2ca48b4de488f91bedef40c3e532d858ce3406a4..cc7a121db715808cfd23b620d7fcac514353cd37 100644 --- a/backend/app/models/face_encoding.py +++ b/backend/app/models/face_encoding.py @@ -1,4 +1,4 @@ -from sqlalchemy import Column, BigInteger, Text, DateTime, ForeignKey +from sqlalchemy import Column, BigInteger, Text, String, DateTime, ForeignKey from sqlalchemy import func from app.core.database import Base @@ -9,6 +9,6 @@ class FaceEncoding(Base): id = Column(BigInteger, primary_key=True, autoincrement=True) user_id = Column(BigInteger, ForeignKey("users.id"), nullable=False) account_id = Column(BigInteger, ForeignKey("accounts.id"), nullable=False) - encoding = Column(Text, nullable=False) - photo = Column(Text, nullable=True) + encoding = Column(Text, nullable=True) + photo = Column(String(500), nullable=True) created_at = Column(DateTime, server_default=func.now()) diff --git a/.opencode/ARCHITECTURE.txt b/backend/app/services/__init__.py similarity index 100% rename from .opencode/ARCHITECTURE.txt rename to backend/app/services/__init__.py diff --git a/backend/app/services/attendance.py b/backend/app/services/attendance.py new file mode 100644 index 0000000000000000000000000000000000000000..d280ac68f203f6f271f65caf131ee670cc5c0d0d --- /dev/null +++ b/backend/app/services/attendance.py @@ -0,0 +1,160 @@ +"""Attendance service: shared logic for teacher + admin attendance endpoints. + +Centralizes the insert of `Attendance` rows (with attribution) and the +construction of a section roster with the gate/check-in chips. Both teacher +and admin endpoints route through here so that attribution columns and +roster shape stay consistent. +""" +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, date as date_type +from typing import List, Optional + +from sqlalchemy.orm import Session + +from app.models.attendance import Attendance +from app.models.user import User +from app.models.enrollment import Enrollment +from app.models.entrance_log import EntranceLog + + +@dataclass +class RosterItem: + id: int + name: str + lastname: str + card_id: Optional[str] + phone_number: Optional[str] + sex: Optional[str] + already_checked_in: bool + entrance_logged: bool + + +def record_attendance( + db: Session, + *, + account_id: int, + user_id: int, + section_id: Optional[int], + subject_id: Optional[int], + action: Optional[str], + marked_by_role: str, + marked_by_user_id: Optional[int], + when: datetime, + note: Optional[str] = None, +) -> Attendance: + """Insert an Attendance row with attribution. + + Idempotent within the same calendar day for the same (user_id, section_id): + if there's already a row for that combination with matching action, it + returns the existing row. + """ + day = when.date() + day_start = datetime.combine(day, datetime.min.time(), tzinfo=when.tzinfo) + day_end = datetime.combine(day, datetime.max.time(), tzinfo=when.tzinfo) + + existing = ( + db.query(Attendance) + .filter( + Attendance.user_id == user_id, + Attendance.account_id == account_id, + Attendance.section_id == section_id, + Attendance.time_log >= day_start, + Attendance.time_log < day_end, + ) + .order_by(Attendance.time_log.desc()) + .first() + ) + if existing and ( + existing.action == action + or (action == "in" and existing.action is None) + ): + return existing + + att = Attendance( + account_id=account_id, + user_id=user_id, + section_id=section_id, + time_log=when, + action=action, + note=note, + marked_by_role=marked_by_role, + marked_by_user_id=marked_by_user_id, + ) + db.add(att) + db.commit() + db.refresh(att) + return att + + +def list_section_roster( + db: Session, + *, + account_id: int, + section_id: int, + on_date: date_type, +) -> List[RosterItem]: + """List active students enrolled in the section, with check-in chips. + + The `entrance_logged` flag is informational — gate ↔ classroom attendance + are intentionally decoupled (TA-01). Consumers should NOT use this to + block marking attendance. + """ + students = ( + db.query(User) + .join(Enrollment, Enrollment.student_id == User.id) + .filter( + User.account_id == account_id, + User.role == "student", + User.is_active == "1", + Enrollment.section_id == section_id, + Enrollment.account_id == account_id, + ) + .all() + ) + if not students: + return [] + student_ids = [s.id for s in students] + + today_att = ( + db.query(Attendance.user_id, Attendance.action, Attendance.checkout_time) + .filter( + Attendance.user_id.in_(student_ids), + Attendance.account_id == account_id, + Attendance.time_log >= on_date, + ) + .all() + ) + checked_in_ids: set[int] = set() + for user_id, action, checkout_time in today_att: + if action == "in": + checked_in_ids.add(user_id) + elif action is None and checkout_time is None: + checked_in_ids.add(user_id) + + entrance_logs = ( + db.query(EntranceLog.user_id) + .filter( + EntranceLog.user_id.in_(student_ids), + EntranceLog.account_id == account_id, + EntranceLog.date == on_date, + ) + .distinct() + .all() + ) + entrance_logged_ids = {el.user_id for el in entrance_logs} + + return [ + RosterItem( + id=s.id, + name=s.name, + lastname=s.lastname, + card_id=s.card_id, + phone_number=s.phone_number, + sex=s.sex, + already_checked_in=s.id in checked_in_ids, + entrance_logged=s.id in entrance_logged_ids, + ) + for s in students + ] diff --git a/backend/app/services/photo_pipeline.py b/backend/app/services/photo_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..a11cd16633b57ffab47d1c26d5e126220d22b2ab --- /dev/null +++ b/backend/app/services/photo_pipeline.py @@ -0,0 +1,24 @@ +from io import BytesIO +from PIL import Image, ImageOps +import magic + +ALLOWED_MIME = {"image/png", "image/jpeg", "image/webp"} +MAX_INPUT_BYTES = 5 * 1024 * 1024 +TARGET_MAX_DIM = 800 +WEBP_QUALITY = 85 + + +def process_user_photo(raw: bytes) -> bytes: + if len(raw) > MAX_INPUT_BYTES: + raise ValueError(f"photo exceeds {MAX_INPUT_BYTES} bytes") + mime = magic.from_buffer(raw, mime=True) + if mime not in ALLOWED_MIME: + raise ValueError(f"unsupported mime: {mime}") + img = Image.open(BytesIO(raw)) + img = ImageOps.exif_transpose(img) + img.thumbnail((TARGET_MAX_DIM, TARGET_MAX_DIM), Image.LANCZOS) + if img.mode in ("RGBA", "P", "LA"): + img = img.convert("RGB") + out = BytesIO() + img.save(out, format="WEBP", quality=WEBP_QUALITY, method=6) + return out.getvalue() diff --git a/backend/app/storage/__init__.py b/backend/app/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a65d0d12989fff1d75394d70388412108fbfcea4 --- /dev/null +++ b/backend/app/storage/__init__.py @@ -0,0 +1,20 @@ +import os +from app.storage.base import PhotoStorage + + +def get_storage() -> PhotoStorage: + backend = os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() + if backend == "local": + from app.storage.local_disk import LocalDiskStorage + return LocalDiskStorage( + root=os.getenv("LOCAL_PHOTO_ROOT", "/data/photos"), + url_prefix=os.getenv("LOCAL_PHOTO_URL_PREFIX", "/api/v1/photos"), + ) + if backend == "supabase": + from app.storage.supabase import SupabaseStorage + return SupabaseStorage( + url=os.getenv("SUPABASE_URL", ""), + key=os.getenv("SUPABASE_SERVICE_KEY", ""), + bucket=os.getenv("SUPABASE_PHOTO_BUCKET", "user-photos"), + ) + raise ValueError(f"Unknown PHOTO_STORAGE_BACKEND: {backend}") diff --git a/backend/app/storage/base.py b/backend/app/storage/base.py new file mode 100644 index 0000000000000000000000000000000000000000..3330a8f32448776b1b117b890191b67e0b96245d --- /dev/null +++ b/backend/app/storage/base.py @@ -0,0 +1,15 @@ +from typing import Protocol + + +class PhotoStorage(Protocol): + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + """Persiste el archivo y devuelve la ruta/identificador canónico que se guarda en BD.""" + ... + + def delete(self, path_or_url: str) -> None: + """Borra el archivo. Best-effort, no levanta si no existe.""" + ... + + def get_url(self, path_or_url: str) -> str: + """Devuelve la URL pública/firmada que el frontend usa para mostrar la foto.""" + ... diff --git a/backend/app/storage/in_memory.py b/backend/app/storage/in_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..7d19b371eedd2c5c9749053a3286401e2182bd59 --- /dev/null +++ b/backend/app/storage/in_memory.py @@ -0,0 +1,17 @@ +import uuid + + +class InMemoryStorage: + def __init__(self) -> None: + self.files: dict[str, bytes] = {} + + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + path = f"mem://{account_id}/{user_id}/{uuid.uuid4()}.{ext}" + self.files[path] = content + return path + + def delete(self, path_or_url: str) -> None: + self.files.pop(path_or_url, None) + + def get_url(self, path_or_url: str) -> str: + return path_or_url diff --git a/backend/app/storage/local_disk.py b/backend/app/storage/local_disk.py new file mode 100644 index 0000000000000000000000000000000000000000..86c400c718977e0af45db50f61619004f419a0ff --- /dev/null +++ b/backend/app/storage/local_disk.py @@ -0,0 +1,32 @@ +import uuid +from pathlib import Path + + +class LocalDiskStorage: + def __init__(self, root: str, url_prefix: str = "/api/v1/photos") -> None: + self.root = Path(root) + self.url_prefix = url_prefix.rstrip("/") + + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + rel = f"{account_id}/{user_id}/{uuid.uuid4()}.{ext}" + target = self.root / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + return rel + + def delete(self, path_or_url: str) -> None: + rel = path_or_url + if path_or_url.startswith(self.url_prefix + "/"): + rel = path_or_url[len(self.url_prefix) + 1:] + target = self.root / rel + try: + target.unlink() + except FileNotFoundError: + pass + + def get_url(self, path_or_url: str) -> str: + if path_or_url.startswith("http://") or path_or_url.startswith("https://"): + return path_or_url + if path_or_url.startswith(self.url_prefix + "/"): + return path_or_url + return f"{self.url_prefix}/{path_or_url}" diff --git a/backend/app/storage/supabase.py b/backend/app/storage/supabase.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd3cc09e1ea054edf716cbf43240ba4a96eeb72 --- /dev/null +++ b/backend/app/storage/supabase.py @@ -0,0 +1,22 @@ +class SupabaseStorage: + """Stub. Se implementa cuando lleguen credenciales de Supabase.""" + + def __init__(self, url: str, key: str, bucket: str) -> None: + self.url = url + self.key = key + self.bucket = bucket + + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + raise NotImplementedError( + "SupabaseStorage upload todavía no implementado — usar PHOTO_STORAGE_BACKEND=local" + ) + + def delete(self, path_or_url: str) -> None: + raise NotImplementedError( + "SupabaseStorage delete todavía no implementado" + ) + + def get_url(self, path_or_url: str) -> str: + raise NotImplementedError( + "SupabaseStorage get_url todavía no implementado" + ) diff --git a/backend/requirements.txt b/backend/requirements.txt index 09b842d5bac34bda94ad4749161704bdb33f3525..d5eda910bde65eb091ff2504d35f1eba443d34b4 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -17,3 +17,6 @@ alembic==1.14.0 httpx==0.28.1 tzdata==2026.2 openpyxl==3.1.5 +Pillow>=10.0.0 +python-magic>=0.4.27 +pytest>=9.0.0 diff --git a/backend/tests/services/__init__.py b/backend/tests/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/tests/services/test_photo_pipeline.py b/backend/tests/services/test_photo_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..acf266b119edfd3b50f26532943405e61b68cc63 --- /dev/null +++ b/backend/tests/services/test_photo_pipeline.py @@ -0,0 +1,51 @@ +from io import BytesIO +import pytest +from PIL import Image +from app.services.photo_pipeline import process_user_photo, MAX_INPUT_BYTES, TARGET_MAX_DIM + + +def _png(width: int, height: int) -> bytes: + img = Image.new("RGB", (width, height), color=(123, 45, 67)) + buf = BytesIO() + img.save(buf, format="PNG") + return buf.getvalue() + + +def _jpeg(width: int, height: int) -> bytes: + img = Image.new("RGB", (width, height), color=(10, 20, 30)) + buf = BytesIO() + img.save(buf, format="JPEG") + return buf.getvalue() + + +def test_accepts_png_and_returns_webp(): + out = process_user_photo(_png(400, 300)) + img = Image.open(BytesIO(out)) + assert img.format == "WEBP" + assert img.size == (400, 300) + + +def test_accepts_jpeg_and_resizes_large_image(): + out = process_user_photo(_jpeg(2000, 1000)) + img = Image.open(BytesIO(out)) + assert img.format == "WEBP" + assert max(img.size) == TARGET_MAX_DIM + + +def test_rejects_oversize_input(): + big = _png(50, 50) + b"\x00" * (MAX_INPUT_BYTES + 1) + with pytest.raises(ValueError, match="exceeds"): + process_user_photo(big) + + +def test_rejects_gif(): + img = Image.new("RGB", (10, 10)) + buf = BytesIO() + img.save(buf, format="GIF") + with pytest.raises(ValueError, match="unsupported"): + process_user_photo(buf.getvalue()) + + +def test_rejects_non_image_bytes(): + with pytest.raises(ValueError, match="unsupported"): + process_user_photo(b"not-an-image" * 10) diff --git a/backend/tests/storage/__init__.py b/backend/tests/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/tests/storage/test_factory.py b/backend/tests/storage/test_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..557ca68cb11667b19c4070b81c9bb562dace48b3 --- /dev/null +++ b/backend/tests/storage/test_factory.py @@ -0,0 +1,22 @@ +import pytest +from app.storage import get_storage +from app.storage.local_disk import LocalDiskStorage +from app.storage.supabase import SupabaseStorage + + +def test_default_backend_is_local(monkeypatch): + monkeypatch.delenv("PHOTO_STORAGE_BACKEND", raising=False) + s = get_storage() + assert isinstance(s, LocalDiskStorage) + + +def test_supabase_backend(monkeypatch): + monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "supabase") + s = get_storage() + assert isinstance(s, SupabaseStorage) + + +def test_unknown_backend_raises(monkeypatch): + monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "azureblobs") + with pytest.raises(ValueError, match="Unknown PHOTO_STORAGE_BACKEND"): + get_storage() diff --git a/backend/tests/storage/test_in_memory.py b/backend/tests/storage/test_in_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..c919393858c6c03ab2c884270852df70a402318d --- /dev/null +++ b/backend/tests/storage/test_in_memory.py @@ -0,0 +1,30 @@ +import pytest +from app.storage.in_memory import InMemoryStorage + + +def test_upload_returns_unique_path(): + storage = InMemoryStorage() + p1 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp") + p2 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp") + assert p1 != p2 + assert p1.startswith("mem://1/10/") and p1.endswith(".webp") + + +def test_get_url_returns_canonical_form(): + storage = InMemoryStorage() + path = storage.upload(1, 10, b"x", "webp") + assert storage.get_url(path) == path + + +def test_delete_is_idempotent(): + storage = InMemoryStorage() + path = storage.upload(1, 10, b"x", "webp") + storage.delete(path) + storage.delete(path) + storage.delete("mem://does/not/exist.webp") + + +def test_files_attribute_exposes_content_for_assertions(): + storage = InMemoryStorage() + path = storage.upload(1, 10, b"hello", "webp") + assert storage.files[path] == b"hello" diff --git a/backend/tests/storage/test_local_disk.py b/backend/tests/storage/test_local_disk.py new file mode 100644 index 0000000000000000000000000000000000000000..7059ba9655b79e1209c068c99871f7c8b2fa7df6 --- /dev/null +++ b/backend/tests/storage/test_local_disk.py @@ -0,0 +1,35 @@ +from pathlib import Path +import pytest +from app.storage.local_disk import LocalDiskStorage + + +@pytest.fixture +def storage(tmp_path: Path) -> LocalDiskStorage: + return LocalDiskStorage(root=str(tmp_path), url_prefix="/api/v1/photos") + + +def test_upload_creates_file(storage: LocalDiskStorage, tmp_path: Path): + path = storage.upload(account_id=2, user_id=20, content=b"abc", ext="webp") + assert path.startswith("2/20/") and path.endswith(".webp") + full = tmp_path / path + assert full.read_bytes() == b"abc" + + +def test_upload_creates_parent_dirs(storage: LocalDiskStorage, tmp_path: Path): + path = storage.upload(99, 999, b"x", "webp") + assert (tmp_path / path).exists() + + +def test_get_url_prepends_prefix(storage: LocalDiskStorage): + path = storage.upload(1, 1, b"x", "webp") + assert storage.get_url(path) == f"/api/v1/photos/{path}" + + +def test_delete_removes_file(storage: LocalDiskStorage, tmp_path: Path): + path = storage.upload(1, 1, b"x", "webp") + storage.delete(path) + assert not (tmp_path / path).exists() + + +def test_delete_missing_file_does_not_raise(storage: LocalDiskStorage): + storage.delete("nope/nope.webp") diff --git a/backend/tests/storage/test_supabase.py b/backend/tests/storage/test_supabase.py new file mode 100644 index 0000000000000000000000000000000000000000..4112feb2a4fd7a477105f1438298222a43550598 --- /dev/null +++ b/backend/tests/storage/test_supabase.py @@ -0,0 +1,13 @@ +import pytest +from app.storage.supabase import SupabaseStorage + + +def test_upload_raises_until_credentials_arrive(): + storage = SupabaseStorage(url="", key="", bucket="user-photos") + with pytest.raises(NotImplementedError, match="Supabase"): + storage.upload(1, 1, b"x", "webp") + + +def test_constructor_stores_config_without_calling_network(): + s = SupabaseStorage(url="https://example.supabase.co", key="k", bucket="b") + assert s.bucket == "b" diff --git a/backend/tests/test_admin_attendance.py b/backend/tests/test_admin_attendance.py new file mode 100644 index 0000000000000000000000000000000000000000..58d653f60ebad535adf1130d54f2405e0a3a900f --- /dev/null +++ b/backend/tests/test_admin_attendance.py @@ -0,0 +1,353 @@ +from datetime import date +import pytest +from fastapi.testclient import TestClient + +from app.main import app +from app.core.database import SessionLocal, Base, engine +from app.models.plan import Plan +from app.models.account import Account +from app.models.user import User +from app.models.section import Section +from app.models.subject import Subject +from app.models.enrollment import Enrollment +from app.models.attendance import Attendance +from app.models.entrance_log import EntranceLog +from app.core.security import hash_password + + +@pytest.fixture(scope="module") +def client(): + Base.metadata.create_all(bind=engine) + yield TestClient(app) + + +def _cleanup(db, org_name): + accs = db.query(Account).filter(Account.organization_name == org_name).all() + for acc in accs: + try: + from app.models.audit_log import AuditLog + db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete() + except Exception: + pass + db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete() + db.query(Attendance).filter(Attendance.account_id == acc.id).delete() + db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete() + db.query(Section).filter(Section.account_id == acc.id).delete() + db.query(Subject).filter(Subject.account_id == acc.id).delete() + db.query(User).filter(User.account_id == acc.id).update({"parent_id": None}) + db.query(User).filter(User.account_id == acc.id).delete() + db.query(Account).filter(Account.id == acc.id).delete() + db.commit() + + +def _seed(db, org_name, admin_email, student_email, teacher_email=None): + plan = db.query(Plan).first() + if not plan: + plan = Plan(name="basic", features=[], price=0) + db.add(plan); db.commit(); db.refresh(plan) + acc = Account(organization_name=org_name, plan_id=plan.id, category="school") + db.add(acc); db.commit(); db.refresh(acc) + admin = User(account_id=acc.id, name="A", lastname="A", + email=admin_email, password_hash=hash_password("x"), + role="admin", is_active="1") + student = User(account_id=acc.id, name="S", lastname="S", + email=student_email, password_hash=hash_password("x"), + role="student", is_active="1", sex="M") + users = [admin, student] + teacher = None + if teacher_email: + teacher = User(account_id=acc.id, name="T", lastname="T", + email=teacher_email, password_hash=hash_password("x"), + role="teacher", is_active="1") + users.append(teacher) + db.add_all(users); db.commit() + for u in users: db.refresh(u) + sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40) + subj = Subject(account_id=acc.id, name="Mate") + db.add_all([sec, subj]); db.commit(); db.refresh(sec); db.refresh(subj) + db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=student.id)) + db.commit() + return acc, admin, student, sec, subj, teacher + + +def _login(client, email): + r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"}) + return r.json()["access_token"] + + +# Task 20: GET /admin/sections + +def test_admin_lists_all_sections_of_their_account(client): + org = "AdminAtt_ListSections" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, _, sec, _, _ = _seed(db, org, "ad_ls_admin@talos.com", "ad_ls_s@talos.com") + section_id = sec.id + finally: + db.close() + + token = _login(client, "ad_ls_admin@talos.com") + r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200, r.text + ids = [s["id"] for s in r.json()] + assert section_id in ids + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_admin_cannot_see_sections_of_other_account(client): + org_a = "AdminAtt_CrossA"; org_b = "AdminAtt_CrossB" + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + _, admin_a, _, _, _, _ = _seed(db, org_a, "ad_xa_admin@talos.com", "ad_xa_s@talos.com") + _, _, _, sec_b, _, _ = _seed(db, org_b, "ad_xb_admin@talos.com", "ad_xb_s@talos.com") + sec_b_id = sec_b.id + finally: + db.close() + + token = _login(client, "ad_xa_admin@talos.com") + r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200 + ids = [s["id"] for s in r.json()] + assert sec_b_id not in ids + + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + finally: + db.close() + + +def test_teacher_role_is_forbidden_on_admin_sections(client): + org = "AdminAtt_TeacherForbid" + db = SessionLocal() + try: + _cleanup(db, org) + _seed(db, org, "ad_tf_admin@talos.com", "ad_tf_s@talos.com", "ad_tf_teacher@talos.com") + finally: + db.close() + + token = _login(client, "ad_tf_teacher@talos.com") + r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"}) + assert r.status_code in (401, 403) + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +# Task 21: GET /admin/sections/{id}/roster + +def test_admin_roster_returns_enrolled_students(client): + org = "AdminAtt_Roster" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, student, sec, _, _ = _seed(db, org, "ad_r_admin@talos.com", "ad_r_s@talos.com") + sec_id, student_id = sec.id, student.id + finally: + db.close() + + token = _login(client, "ad_r_admin@talos.com") + r = client.get( + f"/api/v1/admin/sections/{sec_id}/roster", + headers={"Authorization": f"Bearer {token}"}, + ) + assert r.status_code == 200, r.text + items = r.json() + assert any(it["id"] == student_id for it in items) + item = next(it for it in items if it["id"] == student_id) + assert "already_checked_in" in item + assert "entrance_logged" in item + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_admin_roster_404_for_foreign_section(client): + org_a = "AdminAtt_RostA"; org_b = "AdminAtt_RostB" + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + _, _, _, _, _, _ = _seed(db, org_a, "ad_rxa_admin@talos.com", "ad_rxa_s@talos.com") + _, _, _, sec_b, _, _ = _seed(db, org_b, "ad_rxb_admin@talos.com", "ad_rxb_s@talos.com") + sec_b_id = sec_b.id + finally: + db.close() + + token = _login(client, "ad_rxa_admin@talos.com") + r = client.get( + f"/api/v1/admin/sections/{sec_b_id}/roster", + headers={"Authorization": f"Bearer {token}"}, + ) + assert r.status_code == 404 + + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + finally: + db.close() + + +# Task 22: POST /admin/attendance/swipe + +def test_admin_swipe_marks_with_admin_attribution(client): + org = "AdminAtt_SwipeAttrib" + db = SessionLocal() + try: + _cleanup(db, org) + _, admin, student, sec, subj, _ = _seed( + db, org, "ad_sw_admin@talos.com", "ad_sw_s@talos.com" + ) + admin_id, sec_id, subj_id, student_id = admin.id, sec.id, subj.id, student.id + finally: + db.close() + + token = _login(client, "ad_sw_admin@talos.com") + r = client.post( + "/api/v1/admin/attendance/swipe", + headers={"Authorization": f"Bearer {token}"}, + json={ + "section_id": sec_id, + "subject_id": subj_id, + "records": [{"student_id": student_id, "present": True}], + }, + ) + assert r.status_code == 201, r.text + assert r.json()["created"] == 1 + + db = SessionLocal() + try: + row = ( + db.query(Attendance) + .filter( + Attendance.user_id == student_id, + Attendance.section_id == sec_id, + ) + .order_by(Attendance.id.desc()) + .first() + ) + assert row is not None + assert row.marked_by_role == "admin" + assert row.marked_by_user_id == admin_id + finally: + _cleanup(db, org) + db.close() + + +def test_admin_swipe_works_without_entrance_log(client): + """Admin marks should never block on gate, ever.""" + org = "AdminAtt_SwipeNoGate" + db = SessionLocal() + try: + _cleanup(db, org) + _, _, student, sec, subj, _ = _seed(db, org, "ad_swng_admin@talos.com", "ad_swng_s@talos.com") + sec_id, subj_id, student_id = sec.id, subj.id, student.id + finally: + db.close() + + token = _login(client, "ad_swng_admin@talos.com") + r = client.post( + "/api/v1/admin/attendance/swipe", + headers={"Authorization": f"Bearer {token}"}, + json={ + "section_id": sec_id, + "subject_id": subj_id, + "records": [{"student_id": student_id, "present": True}], + }, + ) + assert r.status_code == 201 + assert r.json()["created"] == 1 + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_admin_swipe_404_for_foreign_section(client): + org_a = "AdminAtt_SwipeXA"; org_b = "AdminAtt_SwipeXB" + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + _, _, _, _, _, _ = _seed(db, org_a, "ad_sxa_admin@talos.com", "ad_sxa_s@talos.com") + _, _, student_b, sec_b, subj_b, _ = _seed( + db, org_b, "ad_sxb_admin@talos.com", "ad_sxb_s@talos.com" + ) + sec_b_id, subj_b_id, student_b_id = sec_b.id, subj_b.id, student_b.id + finally: + db.close() + + token = _login(client, "ad_sxa_admin@talos.com") + r = client.post( + "/api/v1/admin/attendance/swipe", + headers={"Authorization": f"Bearer {token}"}, + json={ + "section_id": sec_b_id, + "subject_id": subj_b_id, + "records": [{"student_id": student_b_id, "present": True}], + }, + ) + assert r.status_code == 404 + + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + finally: + db.close() + + +# Task 23: POST /admin/attendance/batch-toggle + +def test_admin_batch_toggle_for_past_date(client): + org = "AdminAtt_BatchPastDate" + db = SessionLocal() + try: + _cleanup(db, org) + _, admin, student, sec, subj, _ = _seed(db, org, "ad_b_admin@talos.com", "ad_b_s@talos.com") + sec_id, subj_id, student_id, admin_id = sec.id, subj.id, student.id, admin.id + finally: + db.close() + + token = _login(client, "ad_b_admin@talos.com") + r = client.post( + "/api/v1/admin/attendance/batch-toggle?date=2026-06-01", + headers={"Authorization": f"Bearer {token}"}, + json={ + "section_id": sec_id, + "subject_id": subj_id, + "records": [{"student_id": student_id, "present": True}], + }, + ) + assert r.status_code == 200, r.text + + db = SessionLocal() + try: + row = ( + db.query(Attendance) + .filter( + Attendance.user_id == student_id, + Attendance.section_id == sec_id, + ) + .order_by(Attendance.id.desc()) + .first() + ) + assert row is not None + assert row.marked_by_role == "admin" + assert row.marked_by_user_id == admin_id + assert row.time_log.date().isoformat() == "2026-06-01" + finally: + _cleanup(db, org) + db.close() diff --git a/backend/tests/test_attendance_service.py b/backend/tests/test_attendance_service.py new file mode 100644 index 0000000000000000000000000000000000000000..6ab1664f1f374a4f1a1ca7fd116f336b44df8a6d --- /dev/null +++ b/backend/tests/test_attendance_service.py @@ -0,0 +1,209 @@ +from datetime import date, datetime, timezone +import pytest + +from app.core.database import SessionLocal, Base, engine +from app.models.plan import Plan +from app.models.account import Account +from app.models.user import User +from app.models.section import Section +from app.models.subject import Subject +from app.models.enrollment import Enrollment +from app.models.entrance_log import EntranceLog +from app.models.attendance import Attendance +from app.core.security import hash_password + + +@pytest.fixture(scope="module") +def setup_db(): + Base.metadata.create_all(bind=engine) + + +def _cleanup(db, org_name): + accs = db.query(Account).filter(Account.organization_name == org_name).all() + for acc in accs: + try: + from app.models.audit_log import AuditLog + db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete() + except Exception: + pass + db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete() + db.query(Attendance).filter(Attendance.account_id == acc.id).delete() + db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete() + db.query(Section).filter(Section.account_id == acc.id).delete() + db.query(Subject).filter(Subject.account_id == acc.id).delete() + db.query(User).filter(User.account_id == acc.id).update({"parent_id": None}) + db.query(User).filter(User.account_id == acc.id).delete() + db.query(Account).filter(Account.id == acc.id).delete() + db.commit() + + +def _seed_basic(db, org_name): + plan = db.query(Plan).first() + if not plan: + plan = Plan(name="basic", features=[], price=0) + db.add(plan); db.commit(); db.refresh(plan) + acc = Account(organization_name=org_name, plan_id=plan.id, category="school") + db.add(acc); db.commit(); db.refresh(acc) + admin = User(account_id=acc.id, name="A", lastname="A", + email=f"{org_name}_admin@talos.com", password_hash=hash_password("x"), + role="admin", is_active="1") + student = User(account_id=acc.id, name="S", lastname="S", + email=f"{org_name}_student@talos.com", password_hash=hash_password("x"), + role="student", is_active="1", sex="M") + db.add_all([admin, student]); db.commit() + db.refresh(admin); db.refresh(student) + sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40) + db.add(sec); db.commit(); db.refresh(sec) + db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=student.id)) + db.commit() + return acc, admin, student, sec + + +# Task 14 tests: record_attendance + +def test_record_attendance_persists_with_attribution(setup_db): + from app.services.attendance import record_attendance + + org = "AttSvc_Record_Persists" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, student, sec = _seed_basic(db, org) + att = record_attendance( + db, + account_id=acc.id, + user_id=student.id, + section_id=sec.id, + subject_id=None, + action="in", + marked_by_role="admin", + marked_by_user_id=admin.id, + when=datetime.now(timezone.utc), + note="Manual test", + ) + assert att.id is not None + assert att.marked_by_role == "admin" + assert att.marked_by_user_id == admin.id + assert att.action == "in" + assert att.note == "Manual test" + finally: + _cleanup(db, org) + db.close() + + +def test_record_attendance_idempotent_same_day_same_section(setup_db): + from app.services.attendance import record_attendance + + org = "AttSvc_Record_Idempotent" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, student, sec = _seed_basic(db, org) + args = dict( + account_id=acc.id, + user_id=student.id, + section_id=sec.id, + subject_id=None, + action="in", + marked_by_role="teacher", + marked_by_user_id=admin.id, + when=datetime.now(timezone.utc), + note=None, + ) + first = record_attendance(db, **args) + second = record_attendance(db, **args) + rows = db.query(Attendance).filter( + Attendance.user_id == student.id, + Attendance.section_id == sec.id, + ).all() + assert len(rows) == 1 + assert second.id == first.id == rows[0].id + finally: + _cleanup(db, org) + db.close() + + +# Task 15 tests: list_section_roster + +def test_list_section_roster_returns_students_with_chips(setup_db): + from app.services.attendance import list_section_roster + + org = "AttSvc_Roster_Basic" + db = SessionLocal() + try: + _cleanup(db, org) + acc, _, student, sec = _seed_basic(db, org) + items = list_section_roster( + db, + account_id=acc.id, + section_id=sec.id, + on_date=date.today(), + ) + assert any(it.id == student.id for it in items) + item = next(it for it in items if it.id == student.id) + assert hasattr(item, "already_checked_in") + assert hasattr(item, "entrance_logged") + # No attendance and no entrance log seeded → both False + assert item.already_checked_in is False + assert item.entrance_logged is False + finally: + _cleanup(db, org) + db.close() + + +def test_list_section_roster_reflects_attendance_and_entrance_log(setup_db): + from app.services.attendance import list_section_roster + + org = "AttSvc_Roster_WithChips" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, student, sec = _seed_basic(db, org) + today = date.today() + # Seed entrance log + db.add(EntranceLog(account_id=acc.id, user_id=student.id, date=today, + method="manual", checkin_time=datetime.now(timezone.utc))) + # Seed an "in" attendance + db.add(Attendance( + account_id=acc.id, user_id=student.id, section_id=sec.id, + action="in", + marked_by_role="teacher", marked_by_user_id=admin.id, + )) + db.commit() + + items = list_section_roster( + db, + account_id=acc.id, + section_id=sec.id, + on_date=today, + ) + item = next(it for it in items if it.id == student.id) + assert item.already_checked_in is True + assert item.entrance_logged is True + finally: + _cleanup(db, org) + db.close() + + +def test_list_section_roster_excludes_inactive_students(setup_db): + from app.services.attendance import list_section_roster + + org = "AttSvc_Roster_InactiveExcluded" + db = SessionLocal() + try: + _cleanup(db, org) + acc, _, student, sec = _seed_basic(db, org) + # Mark student inactive + student.is_active = "0" + db.commit() + + items = list_section_roster( + db, + account_id=acc.id, + section_id=sec.id, + on_date=date.today(), + ) + assert not any(it.id == student.id for it in items) + finally: + _cleanup(db, org) + db.close() diff --git a/backend/tests/test_dashboard_sex_by_section.py b/backend/tests/test_dashboard_sex_by_section.py index b2a2b75275b704d580dc06b54760561466ebe324..8e06bf24881319caef74ea6703e47191a1ec0a67 100644 --- a/backend/tests/test_dashboard_sex_by_section.py +++ b/backend/tests/test_dashboard_sex_by_section.py @@ -11,6 +11,7 @@ from app.models.section import Section from app.models.enrollment import Enrollment from app.models.teacher_section import TeacherSection from app.models.entrance_log import EntranceLog +from app.models.attendance import Attendance from app.core.security import hash_password @@ -23,6 +24,7 @@ def client(): def _cleanup(db, acc_id): """Remove all seeded data for account acc_id in FK-safe order.""" db.query(EntranceLog).filter(EntranceLog.account_id == acc_id).delete() + db.query(Attendance).filter(Attendance.account_id == acc_id).delete() try: from app.models.audit_log import AuditLog 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): r2 = client.get("/api/v1/dashboard/sex-by-section?section_ids=abc", headers={"Authorization": f"Bearer {token}"}) assert r2.status_code == 400 + + +def test_sex_by_section_counts_classroom_attendance_without_gate_log(client): + """TA-01 regression: student marked present in class via Attendance.action='in' + must appear in the chart even with NO EntranceLog (gate-decoupled contingency). + """ + org_name = "SbsTest_ClassNoGate" + acc_id = None + db = SessionLocal() + try: + _cleanup_by_org_name(db, org_name) + plan = db.query(Plan).first() + acc = Account(organization_name=org_name, plan_id=plan.id, category="school") + db.add(acc); db.commit(); db.refresh(acc) + acc_id = acc.id + admin = User(account_id=acc.id, name="A", lastname="A", + email=f"sbs_cng_admin_{acc.id}@talos.com", + password_hash=hash_password("x"), + role="admin", is_active="1", sex="M") + db.add(admin); db.commit(); db.refresh(admin) + sec = Section(account_id=acc.id, name="Z", academic_period="2025-2026", max_students=40) + db.add(sec); db.commit(); db.refresh(sec) + # One M student, one F student. Both enrolled in sec. + # Only Attendance "in" rows — NO EntranceLog. Simulates gate-down contingency. + sm = User(account_id=acc.id, name="cng_m", lastname="X", role="student", is_active="1", + email=f"sbs_cng_m_{acc.id}@talos.com", password_hash=hash_password("x"), sex="M") + sf = User(account_id=acc.id, name="cng_f", lastname="X", role="student", is_active="1", + email=f"sbs_cng_f_{acc.id}@talos.com", password_hash=hash_password("x"), sex="F") + db.add_all([sm, sf]); db.commit(); db.refresh(sm); db.refresh(sf) + db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=sm.id)) + db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=sf.id)) + db.add(Attendance( + account_id=acc.id, user_id=sm.id, section_id=sec.id, + action="in", marked_by_role="admin", marked_by_user_id=admin.id, + )) + db.add(Attendance( + account_id=acc.id, user_id=sf.id, section_id=sec.id, + action="in", marked_by_role="teacher", marked_by_user_id=admin.id, + )) + db.commit() + admin_email = admin.email + finally: + db.close() + + try: + token = _login(client, admin_email) + r = client.get("/api/v1/dashboard/sex-by-section", + headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200 + body = r.json() + sec_z = next(s for s in body["sections"] if s["section_name"] == "Z") + assert sec_z["masculino"] == 1, f"expected 1 M, got {sec_z}" + assert sec_z["femenino"] == 1, f"expected 1 F, got {sec_z}" + assert sec_z["total"] == 2 + finally: + db = SessionLocal() + try: + if acc_id is not None: + _cleanup(db, acc_id) + finally: + db.close() diff --git a/backend/tests/test_dashboard_stats_union.py b/backend/tests/test_dashboard_stats_union.py new file mode 100644 index 0000000000000000000000000000000000000000..2052f88474356eea18ea92de721bbd4b9208fec7 --- /dev/null +++ b/backend/tests/test_dashboard_stats_union.py @@ -0,0 +1,240 @@ +"""TA-01 regression: dashboard /stats and /attendance-trend count attendance +as union of EntranceLog (gate) and Attendance "in" (classroom), deduped per +(user, day). A student marked present in class without gate check-in (per +the TA-01 contingency path) must still appear in the counts. +""" +from datetime import date, datetime, timezone + +import pytest +from fastapi.testclient import TestClient + +from app.main import app +from app.core.database import SessionLocal, Base, engine +from app.models.plan import Plan +from app.models.account import Account +from app.models.user import User +from app.models.section import Section +from app.models.enrollment import Enrollment +from app.models.attendance import Attendance +from app.models.entrance_log import EntranceLog +from app.core.security import hash_password + + +@pytest.fixture(scope="module") +def client(): + Base.metadata.create_all(bind=engine) + yield TestClient(app) + + +def _cleanup(db, org_name): + accs = db.query(Account).filter(Account.organization_name == org_name).all() + for acc in accs: + try: + from app.models.audit_log import AuditLog + db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete() + except Exception: + pass + db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete() + db.query(Attendance).filter(Attendance.account_id == acc.id).delete() + db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete() + db.query(Section).filter(Section.account_id == acc.id).delete() + db.query(User).filter(User.account_id == acc.id).update({"parent_id": None}) + db.query(User).filter(User.account_id == acc.id).delete() + db.query(Account).filter(Account.id == acc.id).delete() + db.commit() + + +def _seed_admin_section(db, org_name, n_students=3): + plan = db.query(Plan).first() + if not plan: + plan = Plan(name="basic", features=[], price=0) + db.add(plan); db.commit(); db.refresh(plan) + acc = Account(organization_name=org_name, plan_id=plan.id, category="school") + db.add(acc); db.commit(); db.refresh(acc) + admin = User( + account_id=acc.id, name="A", lastname="A", + email=f"sru_admin_{acc.id}@talos.com", password_hash=hash_password("x"), + role="admin", is_active="1", sex="M", + ) + db.add(admin); db.commit(); db.refresh(admin) + sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40) + db.add(sec); db.commit(); db.refresh(sec) + students = [] + for i in range(n_students): + s = User( + account_id=acc.id, name=f"s{i}", lastname="X", role="student", is_active="1", + email=f"sru_s{i}_{acc.id}@talos.com", password_hash=hash_password("x"), sex="M", + ) + db.add(s); db.commit(); db.refresh(s) + db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=s.id)) + students.append(s) + db.commit() + return acc, admin, sec, students + + +def _login(client, email): + r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"}) + return r.json()["access_token"] + + +def test_stats_today_checkins_includes_class_only_marks(client): + """A student marked present in class only (no EntranceLog) counts in today_checkins.""" + org = "DashStats_ClassOnly" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, sec, students = _seed_admin_section(db, org, n_students=2) + # Student[0]: only class mark, NO gate. + db.add(Attendance( + account_id=acc.id, user_id=students[0].id, section_id=sec.id, + action="in", marked_by_role="admin", marked_by_user_id=admin.id, + )) + # Student[1]: only gate. + db.add(EntranceLog( + account_id=acc.id, user_id=students[1].id, date=date.today(), + method="manual", checkin_time=datetime.now(timezone.utc), + )) + db.commit() + admin_email = admin.email + finally: + db.close() + + try: + token = _login(client, admin_email) + r = client.get("/api/v1/dashboard/stats", + headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200, r.text + body = r.json() + # Both students counted: 1 via class, 1 via gate. + assert body["today_checkins"] == 2, body + finally: + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_stats_today_checkins_dedupes_student_with_both_events(client): + """Student with EntranceLog AND Attendance 'in' counts ONCE.""" + org = "DashStats_Dedup" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, sec, students = _seed_admin_section(db, org, n_students=1) + # Same student: both gate + class. + db.add(EntranceLog( + account_id=acc.id, user_id=students[0].id, date=date.today(), + method="manual", checkin_time=datetime.now(timezone.utc), + )) + db.add(Attendance( + account_id=acc.id, user_id=students[0].id, section_id=sec.id, + action="in", marked_by_role="teacher", marked_by_user_id=admin.id, + )) + db.commit() + admin_email = admin.email + finally: + db.close() + + try: + token = _login(client, admin_email) + r = client.get("/api/v1/dashboard/stats", + headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200 + body = r.json() + assert body["today_checkins"] == 1, f"expected 1 (deduped), got {body['today_checkins']}" + finally: + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_stats_currently_on_campus_subtracts_exits(client): + """currently_on_campus = present_today - exited_today (union semantics).""" + org = "DashStats_OnCampus" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, sec, students = _seed_admin_section(db, org, n_students=3) + # s0: gate in + checked out → counted in checkouts, NOT in on-campus + db.add(EntranceLog( + account_id=acc.id, user_id=students[0].id, date=date.today(), + method="manual", checkin_time=datetime.now(timezone.utc), + checkout_time=datetime.now(timezone.utc), + )) + # s1: gate in, no exit → on campus + db.add(EntranceLog( + account_id=acc.id, user_id=students[1].id, date=date.today(), + method="manual", checkin_time=datetime.now(timezone.utc), + )) + # s2: class "in" only, no exit → on campus + db.add(Attendance( + account_id=acc.id, user_id=students[2].id, section_id=sec.id, + action="in", marked_by_role="admin", marked_by_user_id=admin.id, + )) + db.commit() + admin_email = admin.email + finally: + db.close() + + try: + token = _login(client, admin_email) + r = client.get("/api/v1/dashboard/stats", + headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200 + body = r.json() + assert body["today_checkins"] == 3, body + assert body["today_checkouts"] == 1, body # only s0 left + assert body["currently_on_campus"] == 2, body # s1 + s2 + finally: + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_attendance_trend_unions_and_dedupes_per_day(client): + """Per-day trend counts union of gate + class, deduped per (day, user).""" + org = "DashTrend_Union" + db = SessionLocal() + try: + _cleanup(db, org) + acc, admin, sec, students = _seed_admin_section(db, org, n_students=2) + today = date.today() + # s0: gate AND class today → 1 (deduped). + db.add(EntranceLog( + account_id=acc.id, user_id=students[0].id, date=today, + method="manual", checkin_time=datetime.now(timezone.utc), + )) + db.add(Attendance( + account_id=acc.id, user_id=students[0].id, section_id=sec.id, + action="in", marked_by_role="teacher", marked_by_user_id=admin.id, + )) + # s1: class only today → 1 (would have been zero pre-fix). + db.add(Attendance( + account_id=acc.id, user_id=students[1].id, section_id=sec.id, + action="in", marked_by_role="admin", marked_by_user_id=admin.id, + )) + db.commit() + admin_email = admin.email + finally: + db.close() + + try: + token = _login(client, admin_email) + r = client.get("/api/v1/dashboard/attendance-trend?days=1", + headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200, r.text + body = r.json() + # 1-day window → today only. + today_entry = next(p for p in body if p["date"] == today.isoformat()) + assert today_entry["count"] == 2, f"expected 2 (s0 deduped + s1 class-only), got {today_entry}" + finally: + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() diff --git a/backend/tests/test_teacher_attendance_gate_decouple.py b/backend/tests/test_teacher_attendance_gate_decouple.py new file mode 100644 index 0000000000000000000000000000000000000000..97b5723fa316252d8a88d8a9e4351784bf1cb23b --- /dev/null +++ b/backend/tests/test_teacher_attendance_gate_decouple.py @@ -0,0 +1,182 @@ +from datetime import date, datetime, timezone +import pytest +from fastapi.testclient import TestClient + +from app.main import app +from app.core.database import SessionLocal, Base, engine +from app.models.plan import Plan +from app.models.account import Account +from app.models.user import User +from app.models.section import Section +from app.models.subject import Subject +from app.models.enrollment import Enrollment +from app.models.teacher_section import TeacherSection +from app.models.attendance import Attendance +from app.models.entrance_log import EntranceLog +from app.core.security import hash_password + + +@pytest.fixture(scope="module") +def client(): + Base.metadata.create_all(bind=engine) + yield TestClient(app) + + +def _cleanup(db, org_name): + accs = db.query(Account).filter(Account.organization_name == org_name).all() + for acc in accs: + try: + from app.models.audit_log import AuditLog + db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete() + except Exception: + pass + db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete() + db.query(Attendance).filter(Attendance.account_id == acc.id).delete() + db.query(TeacherSection).filter(TeacherSection.account_id == acc.id).delete() + db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete() + db.query(Section).filter(Section.account_id == acc.id).delete() + db.query(Subject).filter(Subject.account_id == acc.id).delete() + db.query(User).filter(User.account_id == acc.id).update({"parent_id": None}) + db.query(User).filter(User.account_id == acc.id).delete() + db.query(Account).filter(Account.id == acc.id).delete() + db.commit() + + +def _seed(db, org_name, teacher_email, student_email): + plan = db.query(Plan).first() + if not plan: + plan = Plan(name="basic", features=[], price=0) + db.add(plan); db.commit(); db.refresh(plan) + acc = Account(organization_name=org_name, plan_id=plan.id, category="school") + db.add(acc); db.commit(); db.refresh(acc) + teacher = User( + account_id=acc.id, name="T", lastname="T", + email=teacher_email, password_hash=hash_password("x"), + role="teacher", is_active="1", + ) + student = User( + account_id=acc.id, name="S", lastname="S", + email=student_email, password_hash=hash_password("x"), + role="student", is_active="1", sex="M", + ) + db.add_all([teacher, student]); db.commit() + db.refresh(teacher); db.refresh(student) + sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40) + subj = Subject(account_id=acc.id, name="Mate") + db.add_all([sec, subj]); db.commit(); db.refresh(sec); db.refresh(subj) + db.add(TeacherSection(account_id=acc.id, section_id=sec.id, subject_id=subj.id, teacher_id=teacher.id)) + db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=student.id)) + db.commit() + return acc, teacher, sec, subj, student + + +def _login(client, email): + r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"}) + return r.json()["access_token"] + + +def test_swipe_marks_student_without_entrance_log_as_present(client): + org = "GateDecouple_Swipe" + db = SessionLocal() + try: + _cleanup(db, org) + acc, teacher, sec, subj, student = _seed( + db, org, "gd_swipe_t@talos.com", "gd_swipe_s@talos.com" + ) + section_id, subject_id, student_id = sec.id, subj.id, student.id + # NOTE: no EntranceLog seeded for this student + finally: + db.close() + + token = _login(client, "gd_swipe_t@talos.com") + r = client.post( + "/api/v1/teacher/attendance/swipe", + headers={"Authorization": f"Bearer {token}"}, + json={ + "section_id": section_id, + "subject_id": subject_id, + "records": [{"student_id": student_id, "present": True}], + }, + ) + assert r.status_code == 201, r.text + body = r.json() + # After Task 19: should be created=1, skipped=[] + assert body["created"] == 1, f"expected created=1, got body={body}" + assert body["skipped"] == [], f"expected skipped=[], got {body['skipped']}" + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_batch_toggle_marks_student_without_entrance_log(client): + org = "GateDecouple_Batch" + db = SessionLocal() + try: + _cleanup(db, org) + acc, teacher, sec, subj, student = _seed( + db, org, "gd_batch_t@talos.com", "gd_batch_s@talos.com" + ) + section_id, subject_id, student_id = sec.id, subj.id, student.id + finally: + db.close() + + token = _login(client, "gd_batch_t@talos.com") + r = client.post( + "/api/v1/teacher/attendance/batch-toggle", + headers={"Authorization": f"Bearer {token}"}, + json={ + "section_id": section_id, + "subject_id": subject_id, + "records": [{"student_id": student_id, "present": True}], + }, + ) + assert r.status_code in (200, 201), r.text + body = r.json() + # batch_toggle should not skip students due to gate + assert body.get("skipped", []) == [] + + # Verify a row was actually inserted + db = SessionLocal() + try: + row = db.query(Attendance).filter( + Attendance.user_id == student_id, + Attendance.section_id == section_id, + ).first() + assert row is not None, "expected attendance row inserted despite missing entrance log" + finally: + _cleanup(db, org) + db.close() + + +def test_roster_still_reports_entrance_logged_false(client): + """The flag is informational and must be preserved after gate decouple.""" + org = "GateDecouple_Roster" + db = SessionLocal() + try: + _cleanup(db, org) + acc, teacher, sec, _, student = _seed( + db, org, "gd_roster_t@talos.com", "gd_roster_s@talos.com" + ) + section_id, student_id = sec.id, student.id + finally: + db.close() + + token = _login(client, "gd_roster_t@talos.com") + r = client.get( + f"/api/v1/teacher/sections/{section_id}/students", + headers={"Authorization": f"Bearer {token}"}, + ) + assert r.status_code == 200, r.text + items = r.json() + target = next((it for it in items if it["id"] == student_id), None) + assert target is not None, "student missing from roster" + assert target["entrance_logged"] is False, "info flag must remain" + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() diff --git a/backend/tests/test_users_photo_upload.py b/backend/tests/test_users_photo_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..db868a6de626ad9eaac672c8406a796fd875d037 --- /dev/null +++ b/backend/tests/test_users_photo_upload.py @@ -0,0 +1,232 @@ +from io import BytesIO +import json +import pytest +from PIL import Image +from fastapi.testclient import TestClient + +from app.main import app +from app.core.database import SessionLocal, Base, engine +from app.models.account import Account +from app.models.user import User +from app.models.plan import Plan +from app.models.face_encoding import FaceEncoding +from app.core.security import hash_password +from app.storage.in_memory import InMemoryStorage +import app.api.v1.endpoints.users as users_mod + + +@pytest.fixture(scope="module") +def client(): + Base.metadata.create_all(bind=engine) + yield TestClient(app) + + +@pytest.fixture +def fake_storage(monkeypatch): + fake = InMemoryStorage() + monkeypatch.setattr(users_mod, "get_storage", lambda: fake) + return fake + + +def _cleanup(db, org_name): + accs = db.query(Account).filter(Account.organization_name == org_name).all() + for acc in accs: + db.query(FaceEncoding).filter(FaceEncoding.account_id == acc.id).delete() + try: + from app.models.audit_log import AuditLog + db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete() + except Exception: + pass + db.query(User).filter(User.account_id == acc.id).update({"parent_id": None}) + db.query(User).filter(User.account_id == acc.id).delete() + db.query(Account).filter(Account.id == acc.id).delete() + db.commit() + + +def _seed(db, org_name, admin_email, student_email): + plan = db.query(Plan).first() + if not plan: + plan = Plan(name="basic", features=[], price=0) + db.add(plan); db.commit(); db.refresh(plan) + acc = Account(organization_name=org_name, plan_id=plan.id, category="school") + db.add(acc); db.commit(); db.refresh(acc) + admin = User( + account_id=acc.id, name="A", lastname="A", + email=admin_email, password_hash=hash_password("x"), + role="admin", is_active="1", + ) + db.add(admin); db.commit(); db.refresh(admin) + student = User( + account_id=acc.id, name="S", lastname="S", + email=student_email, password_hash=hash_password("x"), + role="student", is_active="1", + ) + db.add(student); db.commit(); db.refresh(student) + return acc, admin, student + + +def _login(client, email): + r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"}) + return r.json()["access_token"] + + +def _png_bytes(w=50, h=50) -> bytes: + buf = BytesIO() + Image.new("RGB", (w, h), color=(1, 2, 3)).save(buf, format="PNG") + return buf.getvalue() + + +def _gif_bytes() -> bytes: + buf = BytesIO() + Image.new("RGB", (10, 10)).save(buf, format="GIF") + return buf.getvalue() + + +def test_admin_uploads_photo_returns_url_and_creates_face_encoding(client, fake_storage): + org = "PhotoUpload_Happy" + db = SessionLocal() + try: + _cleanup(db, org) + _, admin, student = _seed(db, org, "ph_admin@talos.com", "ph_student@talos.com") + admin_id, student_id, acc_id = admin.id, student.id, admin.account_id + finally: + db.close() + + token = _login(client, "ph_admin@talos.com") + r = client.post( + f"/api/v1/users/{student_id}/photo", + headers={"Authorization": f"Bearer {token}"}, + files={"file": ("a.png", _png_bytes(), "image/png")}, + ) + assert r.status_code == 200, r.text + body = r.json() + assert "photo_url" in body + assert "encoding_extracted" in body + assert len(fake_storage.files) == 1 + + db = SessionLocal() + try: + fe = db.query(FaceEncoding).filter(FaceEncoding.user_id == student_id).first() + assert fe is not None + assert fe.photo is not None and not fe.photo.startswith("data:") + finally: + _cleanup(db, org) + db.close() + + +def test_non_admin_role_forbidden(client, fake_storage): + org = "PhotoUpload_NonAdmin" + db = SessionLocal() + try: + _cleanup(db, org) + plan = db.query(Plan).first() + if not plan: + plan = Plan(name="basic", features=[], price=0) + db.add(plan); db.commit(); db.refresh(plan) + acc = Account(organization_name=org, plan_id=plan.id, category="school") + db.add(acc); db.commit(); db.refresh(acc) + teacher = User( + account_id=acc.id, name="T", lastname="T", + email="ph_teacher@talos.com", password_hash=hash_password("x"), + role="teacher", is_active="1", + ) + student = User( + account_id=acc.id, name="S", lastname="S", + email="ph_student2@talos.com", password_hash=hash_password("x"), + role="student", is_active="1", + ) + db.add_all([teacher, student]); db.commit() + db.refresh(teacher); db.refresh(student) + student_id = student.id + finally: + db.close() + + token = _login(client, "ph_teacher@talos.com") + r = client.post( + f"/api/v1/users/{student_id}/photo", + headers={"Authorization": f"Bearer {token}"}, + files={"file": ("a.png", _png_bytes(), "image/png")}, + ) + assert r.status_code in (401, 403) + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_rejects_gif_with_422(client, fake_storage): + org = "PhotoUpload_Gif" + db = SessionLocal() + try: + _cleanup(db, org) + _, admin, student = _seed(db, org, "ph_gif_admin@talos.com", "ph_gif_student@talos.com") + student_id = student.id + finally: + db.close() + + token = _login(client, "ph_gif_admin@talos.com") + r = client.post( + f"/api/v1/users/{student_id}/photo", + headers={"Authorization": f"Bearer {token}"}, + files={"file": ("a.gif", _gif_bytes(), "image/gif")}, + ) + assert r.status_code == 422 + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_second_upload_deletes_previous_storage_file(client, fake_storage): + org = "PhotoUpload_Replace" + db = SessionLocal() + try: + _cleanup(db, org) + _, admin, student = _seed(db, org, "ph_rep_admin@talos.com", "ph_rep_student@talos.com") + student_id = student.id + finally: + db.close() + + token = _login(client, "ph_rep_admin@talos.com") + h = {"Authorization": f"Bearer {token}"} + client.post(f"/api/v1/users/{student_id}/photo", headers=h, files={"file": ("a.png", _png_bytes(), "image/png")}) + client.post(f"/api/v1/users/{student_id}/photo", headers=h, files={"file": ("b.png", _png_bytes(), "image/png")}) + + assert len(fake_storage.files) == 1 # only the second upload remains + + db = SessionLocal() + try: + _cleanup(db, org) + finally: + db.close() + + +def test_cross_account_user_returns_404(client, fake_storage): + org_a = "PhotoUpload_AcctA" + org_b = "PhotoUpload_AcctB" + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + _, admin_a, _ = _seed(db, org_a, "ph_xa_admin@talos.com", "ph_xa_s@talos.com") + _, _, student_b = _seed(db, org_b, "ph_xb_admin@talos.com", "ph_xb_s@talos.com") + target_id = student_b.id # belongs to org B + finally: + db.close() + + token = _login(client, "ph_xa_admin@talos.com") + r = client.post( + f"/api/v1/users/{target_id}/photo", + headers={"Authorization": f"Bearer {token}"}, + files={"file": ("a.png", _png_bytes(), "image/png")}, + ) + assert r.status_code == 404 + + db = SessionLocal() + try: + _cleanup(db, org_a); _cleanup(db, org_b) + finally: + db.close() diff --git a/docker-compose.yml b/docker-compose.yml index 5e12694720e006b2a6e781213769be042ed754f7..042f84e612b2ee0b5d16af0adbcbb5240532610f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,10 +38,17 @@ services: JWT_SECRET_KEY: ${JWT_SECRET_KEY:-dev-only-change-me} SEED_DEMO: "1" CORS_ORIGINS: '["*"]' + PHOTO_STORAGE_BACKEND: ${PHOTO_STORAGE_BACKEND:-local} + LOCAL_PHOTO_ROOT: /data/photos + LOCAL_PHOTO_URL_PREFIX: /api/v1/photos + SUPABASE_URL: ${SUPABASE_URL:-} + SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_KEY:-} + SUPABASE_PHOTO_BUCKET: ${SUPABASE_PHOTO_BUCKET:-user-photos} ports: - "8000:8000" volumes: - ./backend:/app + - photo_data:/data/photos frontend: build: @@ -57,3 +64,4 @@ services: volumes: talos_pg_data: + photo_data: diff --git a/docs/sprints/2026-06-05_TA-01.md b/docs/sprints/2026-06-05_TA-01.md new file mode 100644 index 0000000000000000000000000000000000000000..89311cf96842ea50d4fc2657ee154671d3b73076 --- /dev/null +++ b/docs/sprints/2026-06-05_TA-01.md @@ -0,0 +1,24 @@ +### 1. Optimización y Carga de Fotografías de Usuarios +* **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). + +* **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`. + * 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). + * 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. + * *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. + +### 2. Módulo de Asistencia Administrativa (Casos de Contingencia) +* **Requerimiento:** Crear una nueva vista/interfaz dedicada para que los administradores del sistema puedan tomar asistencia directamente en el aula. + +* **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. + +### 3. Flexibilidad en las Reglas de Negocio de Asistencia (Check-in General vs. Asistencia de Aula) +* **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. + +* **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. + +--- + +### Lo que espero de tu respuesta: +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). +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. +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. \ No newline at end of file diff --git a/docs/superpowers/plans/2026-06-05-ta01-storage-and-attendance.md b/docs/superpowers/plans/2026-06-05-ta01-storage-and-attendance.md new file mode 100644 index 0000000000000000000000000000000000000000..c73a60f136062d24a20fd231d158ad6092804957 --- /dev/null +++ b/docs/superpowers/plans/2026-06-05-ta01-storage-and-attendance.md @@ -0,0 +1,2247 @@ +# TA-01 Implementation Plan — Storage de fotos + asistencia administrativa + flexibilidad gate + +> **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. + +**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. + +**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. + +**Tech Stack:** FastAPI, SQLAlchemy, Alembic, PostgreSQL, Pillow, python-magic, pytest. Frontend: React + TypeScript + Recharts (no usado en este sprint pero ya instalado). + +**Spec:** [`docs/superpowers/specs/2026-06-05-ta01-storage-and-attendance-design.md`](../specs/2026-06-05-ta01-storage-and-attendance-design.md) + +--- + +## Phase 0 — Foundation (DB migration + models) + +### Task 1: Crear migración Alembic 028 + +**Files:** +- Create: `backend/migrations/versions/028_ta01_storage_and_attendance_attribution.py` + +- [ ] **Step 1: Identificar revisión previa** + +Run: `ls backend/migrations/versions/ | sort | tail -3` +Tomar el `down_revision` del archivo más reciente (debe ser `027_create_maria_antonia_valero_account`). + +- [ ] **Step 2: Escribir la migración** + +```python +"""TA-01: storage paths and attendance attribution + +Revision ID: 028_ta01_storage_attribution +Revises: 027_create_maria_antonia_valero_account +Create Date: 2026-06-05 +""" +from alembic import op +import sqlalchemy as sa + +revision = "028_ta01_storage_attribution" +down_revision = "027_create_maria_antonia_valero_account" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Bloque A: face_encodings.photo de Text(base64) a VARCHAR(500) URL/path. + # Cleanup de filas existentes: vaciar photo (el admin re-sube) y permitir encoding NULL. + op.execute("UPDATE face_encodings SET photo = NULL") + op.alter_column( + "face_encodings", "photo", + existing_type=sa.Text(), + type_=sa.String(length=500), + existing_nullable=True, + ) + op.alter_column( + "face_encodings", "encoding", + existing_type=sa.Text(), + nullable=True, + ) + + # Bloque B: trazabilidad de origen de la marca. + op.add_column( + "attendances", + sa.Column("marked_by_role", sa.String(length=20), nullable=True), + ) + op.add_column( + "attendances", + sa.Column("marked_by_user_id", sa.BigInteger(), nullable=True), + ) + op.create_foreign_key( + "fk_attendances_marked_by_user", + "attendances", "users", + ["marked_by_user_id"], ["id"], + ) + op.create_index( + "ix_attendances_marked_by_user_id", + "attendances", ["marked_by_user_id"], + ) + + +def downgrade() -> None: + op.drop_index("ix_attendances_marked_by_user_id", table_name="attendances") + op.drop_constraint("fk_attendances_marked_by_user", "attendances", type_="foreignkey") + op.drop_column("attendances", "marked_by_user_id") + op.drop_column("attendances", "marked_by_role") + op.alter_column( + "face_encodings", "encoding", + existing_type=sa.Text(), + nullable=False, + ) + op.alter_column( + "face_encodings", "photo", + existing_type=sa.String(length=500), + type_=sa.Text(), + existing_nullable=True, + ) +``` + +- [ ] **Step 3: Aplicar localmente y verificar** + +Run: `docker compose exec backend alembic upgrade head` +Expected: `Running upgrade 027_... -> 028_ta01_storage_attribution` + +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)"` +Expected: incluye `marked_by_role` y `marked_by_user_id`. + +- [ ] **Step 4: Probar roundtrip downgrade/upgrade** + +Run: `docker compose exec backend alembic downgrade -1 && docker compose exec backend alembic upgrade head` +Expected: ambos exitosos. + +- [ ] **Step 5: Commit** + +```bash +git add backend/migrations/versions/028_ta01_storage_and_attendance_attribution.py +git commit -m "feat(ta-01): migration for photo URL column + attendance attribution" +``` + +--- + +### Task 2: Actualizar modelos SQLAlchemy + +**Files:** +- Modify: `backend/app/models/face_encoding.py` +- Modify: `backend/app/models/attendance.py` + +- [ ] **Step 1: Modificar `face_encoding.py`** + +Reemplazar el cuerpo de la clase: + +```python +from sqlalchemy import Column, BigInteger, Text, String, DateTime, ForeignKey +from sqlalchemy import func +from app.core.database import Base + + +class FaceEncoding(Base): + __tablename__ = "face_encodings" + + id = Column(BigInteger, primary_key=True, autoincrement=True) + user_id = Column(BigInteger, ForeignKey("users.id"), nullable=False) + account_id = Column(BigInteger, ForeignKey("accounts.id"), nullable=False) + encoding = Column(Text, nullable=True) + photo = Column(String(500), nullable=True) + created_at = Column(DateTime, server_default=func.now()) +``` + +- [ ] **Step 2: Modificar `attendance.py`** + +Reemplazar el cuerpo de la clase: + +```python +from sqlalchemy import Column, BigInteger, String, DateTime, JSON, ForeignKey +from sqlalchemy import func +from app.core.database import Base + + +class Attendance(Base): + __tablename__ = "attendances" + + id = Column(BigInteger, primary_key=True, autoincrement=True) + account_id = Column(BigInteger, ForeignKey("accounts.id"), nullable=False) + user_id = Column(BigInteger, ForeignKey("users.id"), nullable=False) + section_id = Column(BigInteger, ForeignKey("sections.id"), nullable=True) + time_log = Column(DateTime(timezone=True), server_default=func.now()) + checkout_time = Column(DateTime(timezone=True), nullable=True) + coordinates = Column(JSON) + note = Column(String(255)) + action = Column(String(10), nullable=True, comment="in or out") + marked_by_role = Column(String(20), nullable=True) + marked_by_user_id = Column(BigInteger, ForeignKey("users.id"), nullable=True) +``` + +- [ ] **Step 3: Verificar que el backend importa sin errores** + +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())"` +Expected: lista con `marked_by_role` y `marked_by_user_id` para attendance; `photo` para face_encoding. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/models/face_encoding.py backend/app/models/attendance.py +git commit -m "feat(ta-01): update FaceEncoding and Attendance models for new columns" +``` + +--- + +## Phase 1 — Block A storage abstraction + +### Task 3: Definir el Protocol `PhotoStorage` + +**Files:** +- Create: `backend/app/storage/__init__.py` +- Create: `backend/app/storage/base.py` + +- [ ] **Step 1: Crear `backend/app/storage/__init__.py` con la factory** + +```python +import os +from app.storage.base import PhotoStorage + + +def get_storage() -> PhotoStorage: + backend = os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() + if backend == "local": + from app.storage.local_disk import LocalDiskStorage + return LocalDiskStorage( + root=os.getenv("LOCAL_PHOTO_ROOT", "/data/photos"), + url_prefix=os.getenv("LOCAL_PHOTO_URL_PREFIX", "/api/v1/photos"), + ) + if backend == "supabase": + from app.storage.supabase import SupabaseStorage + return SupabaseStorage( + url=os.getenv("SUPABASE_URL", ""), + key=os.getenv("SUPABASE_SERVICE_KEY", ""), + bucket=os.getenv("SUPABASE_PHOTO_BUCKET", "user-photos"), + ) + raise ValueError(f"Unknown PHOTO_STORAGE_BACKEND: {backend}") +``` + +- [ ] **Step 2: Crear `backend/app/storage/base.py`** + +```python +from typing import Protocol + + +class PhotoStorage(Protocol): + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + """Persiste el archivo y devuelve la ruta/identificador canónico que se guarda en BD.""" + ... + + def delete(self, path_or_url: str) -> None: + """Borra el archivo. Best-effort, no levanta si no existe.""" + ... + + def get_url(self, path_or_url: str) -> str: + """Devuelve la URL pública/firmada que el frontend usa para mostrar la foto.""" + ... +``` + +- [ ] **Step 3: Commit** + +```bash +git add backend/app/storage/__init__.py backend/app/storage/base.py +git commit -m "feat(ta-01): add PhotoStorage Protocol and get_storage factory" +``` + +--- + +### Task 4: Implementar `InMemoryStorage` con tests (TDD) + +**Files:** +- Create: `backend/tests/storage/__init__.py` +- Create: `backend/tests/storage/test_in_memory.py` +- Create: `backend/app/storage/in_memory.py` + +- [ ] **Step 1: Crear test fallando** + +`backend/tests/storage/test_in_memory.py`: + +```python +import pytest +from app.storage.in_memory import InMemoryStorage + + +def test_upload_returns_unique_path(): + storage = InMemoryStorage() + p1 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp") + p2 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp") + assert p1 != p2 + assert p1.startswith("mem://1/10/") and p1.endswith(".webp") + + +def test_get_url_returns_canonical_form(): + storage = InMemoryStorage() + path = storage.upload(1, 10, b"x", "webp") + assert storage.get_url(path) == path + + +def test_delete_is_idempotent(): + storage = InMemoryStorage() + path = storage.upload(1, 10, b"x", "webp") + storage.delete(path) + storage.delete(path) + storage.delete("mem://does/not/exist.webp") + + +def test_files_attribute_exposes_content_for_assertions(): + storage = InMemoryStorage() + path = storage.upload(1, 10, b"hello", "webp") + assert storage.files[path] == b"hello" +``` + +Run: `docker compose exec backend pytest backend/tests/storage/test_in_memory.py -v` +Expected: FAIL (`ModuleNotFoundError`). + +- [ ] **Step 2: Implementar el adapter** + +`backend/app/storage/in_memory.py`: + +```python +import uuid + + +class InMemoryStorage: + def __init__(self) -> None: + self.files: dict[str, bytes] = {} + + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + path = f"mem://{account_id}/{user_id}/{uuid.uuid4()}.{ext}" + self.files[path] = content + return path + + def delete(self, path_or_url: str) -> None: + self.files.pop(path_or_url, None) + + def get_url(self, path_or_url: str) -> str: + return path_or_url +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/storage/test_in_memory.py -v` +Expected: 4 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/storage/in_memory.py backend/tests/storage/ +git commit -m "feat(ta-01): add InMemoryStorage adapter for tests" +``` + +--- + +### Task 5: Implementar `LocalDiskStorage` con tests (TDD) + +**Files:** +- Create: `backend/tests/storage/test_local_disk.py` +- Create: `backend/app/storage/local_disk.py` + +- [ ] **Step 1: Test fallando** + +`backend/tests/storage/test_local_disk.py`: + +```python +from pathlib import Path +import pytest +from app.storage.local_disk import LocalDiskStorage + + +@pytest.fixture +def storage(tmp_path: Path) -> LocalDiskStorage: + return LocalDiskStorage(root=str(tmp_path), url_prefix="/api/v1/photos") + + +def test_upload_creates_file(storage: LocalDiskStorage, tmp_path: Path): + path = storage.upload(account_id=2, user_id=20, content=b"abc", ext="webp") + assert path.startswith("2/20/") and path.endswith(".webp") + full = tmp_path / path + assert full.read_bytes() == b"abc" + + +def test_upload_creates_parent_dirs(storage: LocalDiskStorage, tmp_path: Path): + path = storage.upload(99, 999, b"x", "webp") + assert (tmp_path / path).exists() + + +def test_get_url_prepends_prefix(storage: LocalDiskStorage): + path = storage.upload(1, 1, b"x", "webp") + assert storage.get_url(path) == f"/api/v1/photos/{path}" + + +def test_delete_removes_file(storage: LocalDiskStorage, tmp_path: Path): + path = storage.upload(1, 1, b"x", "webp") + storage.delete(path) + assert not (tmp_path / path).exists() + + +def test_delete_missing_file_does_not_raise(storage: LocalDiskStorage): + storage.delete("nope/nope.webp") # no raises +``` + +Run: `docker compose exec backend pytest backend/tests/storage/test_local_disk.py -v` +Expected: FAIL. + +- [ ] **Step 2: Implementar** + +`backend/app/storage/local_disk.py`: + +```python +import os +import uuid +from pathlib import Path + + +class LocalDiskStorage: + def __init__(self, root: str, url_prefix: str = "/api/v1/photos") -> None: + self.root = Path(root) + self.url_prefix = url_prefix.rstrip("/") + + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + rel = f"{account_id}/{user_id}/{uuid.uuid4()}.{ext}" + target = self.root / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + return rel + + def delete(self, path_or_url: str) -> None: + # Acepta path relativo o URL completa + rel = path_or_url + if path_or_url.startswith(self.url_prefix + "/"): + rel = path_or_url[len(self.url_prefix) + 1:] + target = self.root / rel + try: + target.unlink() + except FileNotFoundError: + pass + + def get_url(self, path_or_url: str) -> str: + if path_or_url.startswith("http://") or path_or_url.startswith("https://"): + return path_or_url + if path_or_url.startswith(self.url_prefix + "/"): + return path_or_url + return f"{self.url_prefix}/{path_or_url}" +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/storage/test_local_disk.py -v` +Expected: 5 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/storage/local_disk.py backend/tests/storage/test_local_disk.py +git commit -m "feat(ta-01): add LocalDiskStorage adapter" +``` + +--- + +### Task 6: Stub de `SupabaseStorage` + +**Files:** +- Create: `backend/tests/storage/test_supabase.py` +- Create: `backend/app/storage/supabase.py` + +- [ ] **Step 1: Test fallando** + +`backend/tests/storage/test_supabase.py`: + +```python +import pytest +from app.storage.supabase import SupabaseStorage + + +def test_upload_raises_until_credentials_arrive(): + storage = SupabaseStorage(url="", key="", bucket="user-photos") + with pytest.raises(NotImplementedError, match="Supabase"): + storage.upload(1, 1, b"x", "webp") + + +def test_constructor_stores_config_without_calling_network(): + s = SupabaseStorage(url="https://example.supabase.co", key="k", bucket="b") + assert s.bucket == "b" +``` + +Run: `docker compose exec backend pytest backend/tests/storage/test_supabase.py -v` +Expected: FAIL. + +- [ ] **Step 2: Implementar el stub** + +`backend/app/storage/supabase.py`: + +```python +class SupabaseStorage: + """Stub. Se implementa cuando lleguen credenciales de Supabase.""" + + def __init__(self, url: str, key: str, bucket: str) -> None: + self.url = url + self.key = key + self.bucket = bucket + + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + raise NotImplementedError( + "SupabaseStorage upload todavía no implementado — usar PHOTO_STORAGE_BACKEND=local" + ) + + def delete(self, path_or_url: str) -> None: + raise NotImplementedError( + "SupabaseStorage delete todavía no implementado" + ) + + def get_url(self, path_or_url: str) -> str: + raise NotImplementedError( + "SupabaseStorage get_url todavía no implementado" + ) +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/storage/test_supabase.py -v` +Expected: 2 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/storage/supabase.py backend/tests/storage/test_supabase.py +git commit -m "feat(ta-01): add SupabaseStorage stub (pending credentials)" +``` + +--- + +### Task 7: Test de la factory `get_storage` + +**Files:** +- Create: `backend/tests/storage/test_factory.py` + +- [ ] **Step 1: Test** + +`backend/tests/storage/test_factory.py`: + +```python +import pytest +from app.storage import get_storage +from app.storage.local_disk import LocalDiskStorage +from app.storage.supabase import SupabaseStorage + + +def test_default_backend_is_local(monkeypatch): + monkeypatch.delenv("PHOTO_STORAGE_BACKEND", raising=False) + s = get_storage() + assert isinstance(s, LocalDiskStorage) + + +def test_supabase_backend(monkeypatch): + monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "supabase") + s = get_storage() + assert isinstance(s, SupabaseStorage) + + +def test_unknown_backend_raises(monkeypatch): + monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "azureblobs") + with pytest.raises(ValueError, match="Unknown PHOTO_STORAGE_BACKEND"): + get_storage() +``` + +- [ ] **Step 2: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/storage/test_factory.py -v` +Expected: 3 passed. + +- [ ] **Step 3: Commit** + +```bash +git add backend/tests/storage/test_factory.py +git commit -m "test(ta-01): cover get_storage factory env-var switching" +``` + +--- + +## Phase 2 — Block A photo pipeline + endpoint + +### Task 8: Agregar dependencias + +**Files:** +- Modify: `backend/requirements.txt` + +- [ ] **Step 1: Inspeccionar requirements actuales** + +Run: `Grep "Pillow|python-magic" backend/requirements.txt` + +- [ ] **Step 2: Asegurar líneas** + +Agregar (si no están): + +``` +Pillow>=10.0.0 +python-magic>=0.4.27 ; sys_platform != "win32" +python-magic-bin>=0.4.14 ; sys_platform == "win32" +``` + +- [ ] **Step 3: Rebuild backend image** + +Run: `docker compose build backend && docker compose up -d backend` +Expected: build succeeds, container healthy. + +- [ ] **Step 4: Verificar imports** + +Run: `docker compose exec backend python -c "from PIL import Image, ImageOps; import magic; print('ok')"` +Expected: `ok`. + +- [ ] **Step 5: Commit** + +```bash +git add backend/requirements.txt +git commit -m "chore(ta-01): add Pillow and python-magic deps for photo pipeline" +``` + +--- + +### Task 9: Pipeline de procesamiento de imágenes (TDD) + +**Files:** +- Create: `backend/tests/services/__init__.py` +- Create: `backend/tests/services/test_photo_pipeline.py` +- Create: `backend/app/services/__init__.py` (vacío) +- Create: `backend/app/services/photo_pipeline.py` + +- [ ] **Step 1: Test fallando** + +`backend/tests/services/test_photo_pipeline.py`: + +```python +from io import BytesIO +import pytest +from PIL import Image +from app.services.photo_pipeline import process_user_photo, MAX_INPUT_BYTES, TARGET_MAX_DIM + + +def _png(width: int, height: int) -> bytes: + img = Image.new("RGB", (width, height), color=(123, 45, 67)) + buf = BytesIO() + img.save(buf, format="PNG") + return buf.getvalue() + + +def _jpeg(width: int, height: int) -> bytes: + img = Image.new("RGB", (width, height), color=(10, 20, 30)) + buf = BytesIO() + img.save(buf, format="JPEG") + return buf.getvalue() + + +def test_accepts_png_and_returns_webp(): + out = process_user_photo(_png(400, 300)) + img = Image.open(BytesIO(out)) + assert img.format == "WEBP" + assert img.size == (400, 300) # menor a 800, no resize + + +def test_accepts_jpeg_and_resizes_large_image(): + out = process_user_photo(_jpeg(2000, 1000)) + img = Image.open(BytesIO(out)) + assert img.format == "WEBP" + assert max(img.size) == TARGET_MAX_DIM + + +def test_rejects_oversize_input(): + big = _png(50, 50) + b"\x00" * (MAX_INPUT_BYTES + 1) + with pytest.raises(ValueError, match="exceeds"): + process_user_photo(big) + + +def test_rejects_gif(): + img = Image.new("RGB", (10, 10)) + buf = BytesIO() + img.save(buf, format="GIF") + with pytest.raises(ValueError, match="unsupported"): + process_user_photo(buf.getvalue()) + + +def test_rejects_non_image_bytes(): + with pytest.raises(ValueError, match="unsupported"): + process_user_photo(b"not-an-image" * 10) +``` + +Run: `docker compose exec backend pytest backend/tests/services/test_photo_pipeline.py -v` +Expected: FAIL. + +- [ ] **Step 2: Implementar** + +`backend/app/services/__init__.py`: vacío. + +`backend/app/services/photo_pipeline.py`: + +```python +from io import BytesIO +from PIL import Image, ImageOps +import magic + +ALLOWED_MIME = {"image/png", "image/jpeg", "image/webp"} +MAX_INPUT_BYTES = 5 * 1024 * 1024 +TARGET_MAX_DIM = 800 +WEBP_QUALITY = 85 + + +def process_user_photo(raw: bytes) -> bytes: + if len(raw) > MAX_INPUT_BYTES: + raise ValueError(f"photo exceeds {MAX_INPUT_BYTES} bytes") + mime = magic.from_buffer(raw, mime=True) + if mime not in ALLOWED_MIME: + raise ValueError(f"unsupported mime: {mime}") + img = Image.open(BytesIO(raw)) + img = ImageOps.exif_transpose(img) + img.thumbnail((TARGET_MAX_DIM, TARGET_MAX_DIM), Image.LANCZOS) + if img.mode in ("RGBA", "P", "LA"): + img = img.convert("RGB") + out = BytesIO() + img.save(out, format="WEBP", quality=WEBP_QUALITY, method=6) + return out.getvalue() +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/services/test_photo_pipeline.py -v` +Expected: 5 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/services/__init__.py backend/app/services/photo_pipeline.py backend/tests/services/ +git commit -m "feat(ta-01): add photo_pipeline with WebP compression and validation" +``` + +--- + +### Task 10: Endpoint POST `/users/{user_id}/photo` (TDD) + +**Files:** +- Create: `backend/tests/api/test_users_photo_upload.py` +- Modify: `backend/app/api/v1/endpoints/users.py` + +- [ ] **Step 1: Inspeccionar utilidades de auth en tests existentes** + +Read: `backend/tests/test_seed_demo_scoping.py` (líneas 1-40) — copiar el patrón de cliente autenticado y fixtures. + +- [ ] **Step 2: Test fallando** + +`backend/tests/api/test_users_photo_upload.py`: + +```python +from io import BytesIO +import pytest +from PIL import Image +from fastapi.testclient import TestClient +from app.main import app +from app.storage import get_storage # for monkeypatching in conftest + + +def _png_bytes() -> bytes: + buf = BytesIO() + Image.new("RGB", (50, 50), color=(1, 2, 3)).save(buf, format="PNG") + return buf.getvalue() + + +@pytest.fixture +def client(monkeypatch): + # Force in-memory storage during tests + from app.storage.in_memory import InMemoryStorage + fake = InMemoryStorage() + import app.api.v1.endpoints.users as users_mod + monkeypatch.setattr(users_mod, "get_storage", lambda: fake) + return TestClient(app), fake + + +def test_upload_requires_admin(client, admin_token, teacher_token, demo_student_id): + c, _ = client + r = c.post( + f"/api/v1/users/{demo_student_id}/photo", + headers={"Authorization": f"Bearer {teacher_token}"}, + files={"file": ("a.png", _png_bytes(), "image/png")}, + ) + assert r.status_code in (401, 403) + + +def test_upload_stores_processed_photo_and_returns_url( + client, admin_token, demo_student_id +): + c, fake = client + r = c.post( + f"/api/v1/users/{demo_student_id}/photo", + headers={"Authorization": f"Bearer {admin_token}"}, + files={"file": ("a.png", _png_bytes(), "image/png")}, + ) + assert r.status_code == 200, r.text + body = r.json() + assert "photo_url" in body and body["photo_url"].endswith(".webp") + assert len(fake.files) == 1 + + +def test_upload_rejects_gif(client, admin_token, demo_student_id): + c, _ = client + buf = BytesIO() + Image.new("RGB", (10, 10)).save(buf, format="GIF") + r = c.post( + f"/api/v1/users/{demo_student_id}/photo", + headers={"Authorization": f"Bearer {admin_token}"}, + files={"file": ("a.gif", buf.getvalue(), "image/gif")}, + ) + assert r.status_code == 422 + + +def test_second_upload_deletes_previous(client, admin_token, demo_student_id): + c, fake = client + h = {"Authorization": f"Bearer {admin_token}"} + c.post(f"/api/v1/users/{demo_student_id}/photo", headers=h, files={"file": ("a.png", _png_bytes(), "image/png")}) + c.post(f"/api/v1/users/{demo_student_id}/photo", headers=h, files={"file": ("b.png", _png_bytes(), "image/png")}) + assert len(fake.files) == 1 +``` + +> 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`. + +- [ ] **Step 3: Implementar endpoint** + +En `backend/app/api/v1/endpoints/users.py` agregar al final del archivo: + +```python +from fastapi import HTTPException +from app.storage import get_storage +from app.services.photo_pipeline import process_user_photo +from app.face_utils import extract_encoding # si existe; si no, usar None + + +@router.post("/{user_id}/photo") +def upload_user_photo( + user_id: int, + file: UploadFile = File(...), + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + target = db.query(User).filter( + User.id == user_id, + User.account_id == current_user.account_id, + ).first() + if not target: + raise HTTPException(status_code=404, detail="user not found") + + raw = file.file.read() + try: + processed = process_user_photo(raw) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) + + try: + encoding_str = extract_encoding(processed) # devuelve str o None + except Exception: + encoding_str = None + + storage = get_storage() + + # Borrar foto anterior best-effort + previous = ( + db.query(FaceEncoding) + .filter(FaceEncoding.user_id == user_id, FaceEncoding.photo.isnot(None)) + .order_by(FaceEncoding.id.desc()) + .first() + ) + if previous and previous.photo: + try: + storage.delete(previous.photo) + except Exception: + pass + + new_path = storage.upload(target.account_id, user_id, processed, "webp") + fe = FaceEncoding( + user_id=user_id, + account_id=target.account_id, + encoding=encoding_str, + photo=new_path, + ) + db.add(fe) + db.commit() + + return { + "photo_url": storage.get_url(new_path), + "encoding_extracted": encoding_str is not None, + "warning": None if encoding_str else + "no se detectó rostro; el reconocimiento facial no funcionará hasta resubir una foto con rostro visible", + } +``` + +> 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`. + +- [ ] **Step 4: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/api/test_users_photo_upload.py -v` +Expected: 4 passed. + +- [ ] **Step 5: Commit** + +```bash +git add backend/app/api/v1/endpoints/users.py backend/tests/api/test_users_photo_upload.py +git commit -m "feat(ta-01): photo upload endpoint with storage + encoding extraction" +``` + +--- + +### Task 11: Endpoint GET `/photos/...` para servir archivos locales + +**Files:** +- Create: `backend/app/api/v1/endpoints/photos.py` +- Modify: `backend/app/api/v1/router.py` (o donde se registren routers) + +- [ ] **Step 1: Identificar el router principal** + +Run: `Grep "include_router" backend/app/api/v1/ -r` + +- [ ] **Step 2: Crear endpoint** + +`backend/app/api/v1/endpoints/photos.py`: + +```python +import os +from pathlib import Path +from fastapi import APIRouter, Depends, HTTPException +from fastapi.responses import FileResponse +from app.dependencies.auth import get_current_user +from app.models.user import User + +router = APIRouter(prefix="/photos", tags=["photos"]) + + +@router.get("/{account_id}/{user_id}/{filename}") +def serve_photo( + account_id: int, + user_id: int, + filename: str, + current_user: User = Depends(get_current_user), +): + if os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() != "local": + raise HTTPException(status_code=404, detail="not served locally") + if current_user.account_id != account_id: + raise HTTPException(status_code=404, detail="not found") + root = Path(os.getenv("LOCAL_PHOTO_ROOT", "/data/photos")) + target = root / str(account_id) / str(user_id) / filename + if not target.exists(): + raise HTTPException(status_code=404, detail="not found") + return FileResponse(target, media_type="image/webp") +``` + +- [ ] **Step 3: Registrar router** + +En el router principal (probablemente `backend/app/api/v1/router.py` o `app/main.py`): + +```python +from app.api.v1.endpoints import photos +api_router.include_router(photos.router) +``` + +- [ ] **Step 4: Smoke** + +Run: `curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8000/api/v1/photos/1/1/nope.webp` +Expected: 404. + +- [ ] **Step 5: Commit** + +```bash +git add backend/app/api/v1/endpoints/photos.py backend/app/api/v1/router.py +git commit -m "feat(ta-01): GET /photos endpoint for local storage backend" +``` + +--- + +### Task 12: Mapear path → URL en respuestas de usuarios + +**Files:** +- Modify: `backend/app/api/v1/endpoints/users.py` (líneas 70-99) + +- [ ] **Step 1: Leer el bloque actual** + +Read: `backend/app/api/v1/endpoints/users.py` líneas 60-105. + +- [ ] **Step 2: Modificar el llenado de `ur.face_photo`** + +Reemplazar el bloque (líneas ~93-99 del listado original): + +```python +storage = get_storage() +items = [] +for u in users: + ur = UserResponse.model_validate( + {c.name: getattr(u, c.name) for c in u.__table__.columns}, + ) + raw_path = photos.get(u.id) + ur.face_photo = storage.get_url(raw_path) if raw_path else None + items.append(ur) +``` + +(Importar `from app.storage import get_storage` al inicio del archivo si no está.) + +- [ ] **Step 3: Verificar smoke** + +Run: `docker compose exec backend pytest backend/tests/api/test_users_photo_upload.py -v` +Expected: 4 passed (regresión). + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/api/v1/endpoints/users.py +git commit -m "feat(ta-01): map face_encodings.photo path to URL in user responses" +``` + +--- + +### Task 13: docker-compose y .env.example + +**Files:** +- Modify: `docker-compose.yml` +- Modify: `.env.example` + +- [ ] **Step 1: Agregar volumen y env al servicio backend** + +En `docker-compose.yml`, dentro de `services.backend`: + +```yaml + volumes: + - photo_data:/data/photos + # ... otros volúmenes existentes + environment: + PHOTO_STORAGE_BACKEND: ${PHOTO_STORAGE_BACKEND:-local} + LOCAL_PHOTO_ROOT: /data/photos + LOCAL_PHOTO_URL_PREFIX: /api/v1/photos + SUPABASE_URL: ${SUPABASE_URL:-} + SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_KEY:-} + SUPABASE_PHOTO_BUCKET: ${SUPABASE_PHOTO_BUCKET:-user-photos} +``` + +Al final del archivo, en la sección `volumes:`: + +```yaml +volumes: + photo_data: +``` + +- [ ] **Step 2: Agregar a `.env.example`** + +``` +# Bloque A — Storage de fotos +PHOTO_STORAGE_BACKEND=local +LOCAL_PHOTO_ROOT=/data/photos +LOCAL_PHOTO_URL_PREFIX=/api/v1/photos +SUPABASE_URL= +SUPABASE_SERVICE_KEY= +SUPABASE_PHOTO_BUCKET=user-photos +``` + +- [ ] **Step 3: Smoke** + +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'` +Expected: `null` o una URL `/api/v1/photos/...`. + +- [ ] **Step 4: Commit** + +```bash +git add docker-compose.yml .env.example +git commit -m "chore(ta-01): wire photo storage env vars and local volume" +``` + +--- + +## Phase 3 — Block B attendance service extraction + +### Task 14: `services/attendance.py` — `record_attendance` (TDD) + +**Files:** +- Create: `backend/tests/services/test_attendance_service.py` +- Create: `backend/app/services/attendance.py` + +- [ ] **Step 1: Test fallando** + +`backend/tests/services/test_attendance_service.py`: + +```python +from datetime import datetime, timezone, date +import pytest +from app.services.attendance import record_attendance +from app.models.attendance import Attendance + + +def test_record_attendance_persists_with_attribution(db_session, demo_account, demo_section, demo_student, demo_admin): + att = record_attendance( + db_session, + account_id=demo_account.id, + user_id=demo_student.id, + section_id=demo_section.id, + subject_id=None, + action="in", + marked_by_role="admin", + marked_by_user_id=demo_admin.id, + when=datetime.now(timezone.utc), + note="Manual test", + ) + assert att.id is not None + assert att.marked_by_role == "admin" + assert att.marked_by_user_id == demo_admin.id + assert att.action == "in" + + +def test_record_attendance_idempotent_same_day(db_session, demo_account, demo_section, demo_student, demo_admin): + args = dict( + account_id=demo_account.id, + user_id=demo_student.id, + section_id=demo_section.id, + subject_id=None, + action="in", + marked_by_role="teacher", + marked_by_user_id=demo_admin.id, + when=datetime.now(timezone.utc), + note=None, + ) + record_attendance(db_session, **args) + second = record_attendance(db_session, **args) + rows = db_session.query(Attendance).filter( + Attendance.user_id == demo_student.id, + Attendance.section_id == demo_section.id, + ).all() + assert len(rows) == 1 + assert second.id == rows[0].id +``` + +> 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`. + +Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py -v` +Expected: FAIL. + +- [ ] **Step 2: Implementar** + +`backend/app/services/attendance.py`: + +```python +from datetime import datetime +from typing import Optional +from sqlalchemy.orm import Session +from app.models.attendance import Attendance + + +def record_attendance( + db: Session, + *, + account_id: int, + user_id: int, + section_id: Optional[int], + subject_id: Optional[int], # reservado para futuro per-subject tracking + action: Optional[str], + marked_by_role: str, + marked_by_user_id: Optional[int], + when: datetime, + note: Optional[str] = None, +) -> Attendance: + """ + Inserta una asistencia con atribución. Idempotente: si ya existe una marca + 'in' para (user_id, section_id) en el mismo día, devuelve esa fila sin crear duplicado. + """ + day = when.date() + existing = ( + db.query(Attendance) + .filter( + Attendance.user_id == user_id, + Attendance.account_id == account_id, + Attendance.section_id == section_id, + Attendance.time_log >= datetime.combine(day, datetime.min.time(), tzinfo=when.tzinfo), + Attendance.time_log < datetime.combine(day, datetime.max.time(), tzinfo=when.tzinfo), + ) + .order_by(Attendance.time_log.desc()) + .first() + ) + if existing and (existing.action == action or (action == "in" and existing.action is None)): + return existing + + att = Attendance( + account_id=account_id, + user_id=user_id, + section_id=section_id, + time_log=when, + action=action, + note=note, + marked_by_role=marked_by_role, + marked_by_user_id=marked_by_user_id, + ) + db.add(att) + db.commit() + db.refresh(att) + return att +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py -v` +Expected: 2 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/services/attendance.py backend/tests/services/test_attendance_service.py +git commit -m "feat(ta-01): add record_attendance service with attribution + idempotency" +``` + +--- + +### Task 15: `services/attendance.py` — `list_section_roster` (TDD) + +**Files:** +- Modify: `backend/app/services/attendance.py` +- Modify: `backend/tests/services/test_attendance_service.py` + +- [ ] **Step 1: Test fallando** + +Agregar a `test_attendance_service.py`: + +```python +from datetime import date +from app.services.attendance import list_section_roster + + +def test_list_section_roster_returns_students_with_chips( + db_session, demo_account, demo_section, demo_student +): + items = list_section_roster( + db_session, + account_id=demo_account.id, + section_id=demo_section.id, + on_date=date.today(), + ) + assert any(it.id == demo_student.id for it in items) + item = next(it for it in items if it.id == demo_student.id) + assert hasattr(item, "already_checked_in") + assert hasattr(item, "entrance_logged") +``` + +Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py::test_list_section_roster_returns_students_with_chips -v` +Expected: FAIL. + +- [ ] **Step 2: Implementar** + +Agregar a `backend/app/services/attendance.py`: + +```python +from dataclasses import dataclass +from typing import List +from datetime import date as date_type +from app.models.user import User +from app.models.enrollment import Enrollment +from app.models.entrance_log import EntranceLog + + +@dataclass +class RosterItem: + id: int + name: str + lastname: str + card_id: Optional[str] + phone_number: Optional[str] + already_checked_in: bool + entrance_logged: bool + + +def list_section_roster( + db: Session, + *, + account_id: int, + section_id: int, + on_date: date_type, +) -> List[RosterItem]: + students = ( + db.query(User) + .join(Enrollment, Enrollment.student_id == User.id) + .filter( + User.account_id == account_id, + User.role == "student", + User.is_active == "1", + Enrollment.section_id == section_id, + Enrollment.account_id == account_id, + ) + .all() + ) + if not students: + return [] + student_ids = [s.id for s in students] + + today_att = ( + db.query(Attendance.user_id, Attendance.action, Attendance.checkout_time) + .filter( + Attendance.user_id.in_(student_ids), + Attendance.account_id == account_id, + Attendance.time_log >= on_date, + ) + .all() + ) + checked_in_ids: set[int] = set() + for user_id, action, checkout_time in today_att: + if action == "in": + checked_in_ids.add(user_id) + elif action is None and checkout_time is None: + checked_in_ids.add(user_id) + + entrance_logs = ( + db.query(EntranceLog.user_id) + .filter( + EntranceLog.user_id.in_(student_ids), + EntranceLog.account_id == account_id, + EntranceLog.date == on_date, + ) + .distinct() + .all() + ) + entrance_logged_ids = {el.user_id for el in entrance_logs} + + return [ + RosterItem( + 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 + ] +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/services/test_attendance_service.py -v` +Expected: 3 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/services/attendance.py backend/tests/services/test_attendance_service.py +git commit -m "feat(ta-01): add list_section_roster service" +``` + +--- + +### Task 16: Refactor `teacher.py` para usar el servicio + +**Files:** +- Modify: `backend/app/api/v1/endpoints/teacher.py` (líneas ~456-541 `submit_swipe`, líneas ~567+ `batch_toggle`, líneas ~712+ `toggle_attendance`) + +- [ ] **Step 1: Reemplazar el cuerpo de `submit_swipe`** + +Mantener: validaciones de holiday, `_ensure_teacher_section`, schema, log_for y construcción de `present_today`. Reemplazar el bloque de iteración por: + +```python +from app.services.attendance import record_attendance + +# ... dentro de submit_swipe, después de validaciones ... +created = 0 +for rec in payload.records: + if not rec.present: + continue + att = record_attendance( + db, + account_id=current_user.account_id, + user_id=rec.student_id, + section_id=payload.section_id, + subject_id=payload.subject_id, + action="in", + marked_by_role="teacher", + marked_by_user_id=current_user.id, + when=datetime.now(timezone.utc), + note="Swipe: present", + ) + if att.time_log >= now.replace(microsecond=0) - timedelta(seconds=2): + created += 1 +``` + +> `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. + +- [ ] **Step 2: Hacer el mismo refactor en `batch_toggle`** + +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, ...)`. + +- [ ] **Step 3: `toggle_attendance` (single record)** + +Idem. + +- [ ] **Step 4: Reemplazar el cómputo del roster en endpoints de listado** + +Donde se construye `entrance_logged_ids` + `StudentCardResponse` (líneas ~423-453 y ~689-707), reemplazar por: + +```python +from app.services.attendance import list_section_roster + +roster = list_section_roster( + db, + account_id=current_user.account_id, + section_id=section_id, + on_date=today, +) +return [StudentCardResponse(**r.__dict__) for r in roster] +``` + +- [ ] **Step 5: Correr la suite de teacher.py para no regresar** + +Run: `docker compose exec backend pytest backend/tests/test_teacher_present_summary.py -v` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add backend/app/api/v1/endpoints/teacher.py +git commit -m "refactor(ta-01): route teacher attendance through services/attendance" +``` + +--- + +### Task 17: `facial.py` — marcar como `marked_by_role='kiosco'` + +**Files:** +- Modify: `backend/app/api/v1/endpoints/facial.py` + +- [ ] **Step 1: Localizar inserciones de `Attendance`** + +Run: `Grep "Attendance\(|Attendance \(" backend/app/api/v1/endpoints/facial.py` + +- [ ] **Step 2: Agregar atribución a cada constructor `Attendance(...)`** + +Para cada lugar donde se crea una `Attendance` en `facial.py`, agregar: + +```python +marked_by_role="kiosco", +marked_by_user_id=None, +``` + +> 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. + +- [ ] **Step 3: Commit** + +```bash +git add backend/app/api/v1/endpoints/facial.py +git commit -m "feat(ta-01): tag kiosco attendance inserts with marked_by_role" +``` + +(O si fue no-op: `chore(ta-01): verify kiosco does not insert Attendance directly (no-op)`.) + +--- + +## Phase 4 — Block C gate decouple + +### Task 18: Test de regresión — estudiante sin gate puede marcarse presente + +**Files:** +- Create: `backend/tests/api/test_teacher_attendance_gate_decouple.py` + +- [ ] **Step 1: Test que ahora **debe fallar** porque la lógica aún bloquea** + +`backend/tests/api/test_teacher_attendance_gate_decouple.py`: + +```python +import pytest +from fastapi.testclient import TestClient +from app.main import app + + +def test_swipe_marks_student_without_entrance_log_as_present( + teacher_token, demo_section_id, demo_student_without_entrance_log +): + c = TestClient(app) + r = c.post( + "/api/v1/teacher/attendance/swipe", + headers={"Authorization": f"Bearer {teacher_token}"}, + json={ + "section_id": demo_section_id, + "records": [{"student_id": demo_student_without_entrance_log, "present": True}], + }, + ) + assert r.status_code == 201, r.text + body = r.json() + # Antes: este estudiante terminaba en `skipped`. Ahora: en `created`. + assert body["created"] == 1 + assert body["skipped"] == [] + + +def test_batch_toggle_marks_student_without_entrance_log( + teacher_token, demo_section_id, demo_student_without_entrance_log +): + c = TestClient(app) + r = c.post( + "/api/v1/teacher/attendance/batch-toggle", + headers={"Authorization": f"Bearer {teacher_token}"}, + json={ + "section_id": demo_section_id, + "records": [{"student_id": demo_student_without_entrance_log, "present": True}], + }, + ) + assert r.status_code == 200, r.text + assert r.json().get("skipped") in ([], None) + + +def test_roster_still_reports_entrance_logged_false( + teacher_token, demo_section_id, demo_student_without_entrance_log +): + c = TestClient(app) + r = c.get( + f"/api/v1/teacher/sections/{demo_section_id}/students", + headers={"Authorization": f"Bearer {teacher_token}"}, + ) + assert r.status_code == 200 + items = r.json() + target = next(it for it in items if it["id"] == demo_student_without_entrance_log) + assert target["entrance_logged"] is False # info se conserva +``` + +> Fixtures `demo_student_without_entrance_log` (alumno enrolado en sección, SIN `EntranceLog` hoy): agregar a `conftest.py`. + +Run: `docker compose exec backend pytest backend/tests/api/test_teacher_attendance_gate_decouple.py -v` +Expected: FAIL en los dos primeros tests (el estudiante termina en `skipped`). + +- [ ] **Step 2: NO commit todavía — Task 19 hace el cambio que vuelve verde.** + +--- + +### Task 19: Remover el filtro `entrance_logged_ids` + +**Files:** +- Modify: `backend/app/api/v1/endpoints/teacher.py` + +- [ ] **Step 1: Grep para inventario actualizado** + +Run: `Grep -n "entrance_logged_ids" backend/app/api/v1/endpoints/teacher.py` +Esperado: 6-8 ubicaciones (algunas ya removidas por Task 16 refactor). + +- [ ] **Step 2: En `submit_swipe`** + +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": ...}`. + +- [ ] **Step 3: En `batch_toggle`** + +Idem. + +- [ ] **Step 4: En `toggle_attendance` (single record)** + +Si tiene un check 409 derivado de `entrance_logged_ids`, removerlo. Mantener la validación de `_check_not_before_class` (time gate, intencional). + +- [ ] **Step 5: NO tocar el roster** + +`get_students` / `list_section_students` deben seguir devolviendo `entrance_logged: bool` calculado normalmente — el filtro era el bloqueo, el cálculo informativo permanece. + +- [ ] **Step 6: Grep final** + +Run: `Grep -n "entrance_logged_ids" backend/app/api/v1/endpoints/teacher.py` +Esperado: solo apariciones en cómputo de roster informativo (las que devuelven el flag al frontend). NINGUNA debe usarse como filtro. + +- [ ] **Step 7: Tests verdes** + +Run: `docker compose exec backend pytest backend/tests/api/test_teacher_attendance_gate_decouple.py -v` +Expected: 3 passed. + +Run: `docker compose exec backend pytest backend/tests/ -v` +Expected: toda la suite verde (sin regresiones). + +- [ ] **Step 8: Commit** + +```bash +git add backend/app/api/v1/endpoints/teacher.py backend/tests/api/test_teacher_attendance_gate_decouple.py +git commit -m "feat(ta-01): decouple classroom attendance from gate entrance log" +``` + +--- + +## Phase 5 — Block B admin endpoints + +### Task 20: `GET /admin/sections` (TDD) + +**Files:** +- Create: `backend/tests/api/test_admin_attendance.py` +- Create: `backend/app/api/v1/endpoints/admin_attendance.py` +- Modify: router principal para registrar el nuevo router + +- [ ] **Step 1: Test fallando** + +`backend/tests/api/test_admin_attendance.py`: + +```python +from fastapi.testclient import TestClient +from app.main import app + + +def test_admin_lists_all_sections_of_account(admin_token, demo_section_id): + c = TestClient(app) + r = c.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {admin_token}"}) + assert r.status_code == 200, r.text + ids = [s["id"] for s in r.json()] + assert demo_section_id in ids + + +def test_admin_cannot_list_sections_of_other_account(other_account_admin_token, demo_section_id): + c = TestClient(app) + r = c.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {other_account_admin_token}"}) + assert r.status_code == 200 + ids = [s["id"] for s in r.json()] + assert demo_section_id not in ids + + +def test_teacher_role_forbidden(teacher_token): + c = TestClient(app) + r = c.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {teacher_token}"}) + assert r.status_code in (401, 403) +``` + +Run: FAIL (router no existe). + +- [ ] **Step 2: Implementar** + +`backend/app/api/v1/endpoints/admin_attendance.py`: + +```python +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from app.core.database import get_db +from app.middleware.rbac import RBAC +from app.models.user import User +from app.models.section import Section + +router = APIRouter(prefix="/admin", tags=["admin-attendance"]) + + +@router.get("/sections") +def admin_list_sections( + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + rows = ( + db.query(Section) + .filter(Section.account_id == current_user.account_id) + .order_by(Section.name) + .all() + ) + return [{"id": s.id, "name": s.name} for s in rows] +``` + +Registrar el router en el archivo principal: + +```python +from app.api.v1.endpoints import admin_attendance +api_router.include_router(admin_attendance.router) +``` + +- [ ] **Step 3: Tests pasan** + +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` +Expected: 3 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py backend/app/api/v1/router.py +git commit -m "feat(ta-01): GET /admin/sections endpoint" +``` + +--- + +### Task 21: `GET /admin/sections/{id}/roster` (TDD) + +**Files:** +- Modify: `backend/app/api/v1/endpoints/admin_attendance.py` +- Modify: `backend/tests/api/test_admin_attendance.py` + +- [ ] **Step 1: Test fallando** + +Agregar a `test_admin_attendance.py`: + +```python +def test_admin_roster_returns_students_with_chips(admin_token, demo_section_id, demo_student_id): + c = TestClient(app) + r = c.get( + f"/api/v1/admin/sections/{demo_section_id}/roster", + headers={"Authorization": f"Bearer {admin_token}"}, + ) + assert r.status_code == 200 + items = r.json() + assert any(it["id"] == demo_student_id for it in items) + item = next(it for it in items if it["id"] == demo_student_id) + assert "already_checked_in" in item + assert "entrance_logged" in item + + +def test_admin_roster_404_for_foreign_section(admin_token, foreign_section_id): + c = TestClient(app) + r = c.get( + f"/api/v1/admin/sections/{foreign_section_id}/roster", + headers={"Authorization": f"Bearer {admin_token}"}, + ) + assert r.status_code == 404 +``` + +- [ ] **Step 2: Implementar** + +Agregar a `admin_attendance.py`: + +```python +from datetime import date, datetime +from fastapi import HTTPException, Query +from app.services.attendance import list_section_roster + + +@router.get("/sections/{section_id}/roster") +def admin_section_roster( + section_id: int, + on_date: str | None = Query(None, alias="date"), + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + section = db.query(Section).filter( + Section.id == section_id, + Section.account_id == current_user.account_id, + ).first() + if not section: + raise HTTPException(status_code=404, detail="section not found") + + day = datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date.today() + items = list_section_roster( + db, + account_id=current_user.account_id, + section_id=section_id, + on_date=day, + ) + return [it.__dict__ for it in items] +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/api/test_admin_attendance.py -v` +Expected: 5 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py +git commit -m "feat(ta-01): GET /admin/sections/{id}/roster" +``` + +--- + +### Task 22: `POST /admin/attendance/swipe` (TDD) + +**Files:** +- Modify: `backend/app/api/v1/endpoints/admin_attendance.py` +- Modify: `backend/tests/api/test_admin_attendance.py` + +- [ ] **Step 1: Test** + +```python +def test_admin_swipe_marks_with_admin_attribution( + admin_token, admin_user_id, demo_section_id, demo_student_id, db_session +): + c = TestClient(app) + r = c.post( + "/api/v1/admin/attendance/swipe", + headers={"Authorization": f"Bearer {admin_token}"}, + json={ + "section_id": demo_section_id, + "records": [{"student_id": demo_student_id, "present": True}], + }, + ) + assert r.status_code == 201, r.text + assert r.json()["created"] == 1 + from app.models.attendance import Attendance + row = db_session.query(Attendance).filter( + Attendance.user_id == demo_student_id, + Attendance.section_id == demo_section_id, + ).order_by(Attendance.id.desc()).first() + assert row.marked_by_role == "admin" + assert row.marked_by_user_id == admin_user_id + + +def test_admin_swipe_works_for_student_without_entrance_log( + admin_token, demo_section_id, demo_student_without_entrance_log +): + c = TestClient(app) + r = c.post( + "/api/v1/admin/attendance/swipe", + headers={"Authorization": f"Bearer {admin_token}"}, + json={ + "section_id": demo_section_id, + "records": [{"student_id": demo_student_without_entrance_log, "present": True}], + }, + ) + assert r.status_code == 201 + assert r.json()["created"] == 1 +``` + +- [ ] **Step 2: Implementar** + +```python +from datetime import timezone +from pydantic import BaseModel +from app.services.attendance import record_attendance + + +class AdminSwipeRecord(BaseModel): + student_id: int + present: bool + + +class AdminSwipeRequest(BaseModel): + section_id: int + subject_id: int | None = None + records: list[AdminSwipeRecord] + + +@router.post("/attendance/swipe", status_code=201) +def admin_attendance_swipe( + payload: AdminSwipeRequest, + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + section = db.query(Section).filter( + Section.id == payload.section_id, + Section.account_id == current_user.account_id, + ).first() + if not section: + raise HTTPException(status_code=404, detail="section not found") + created = 0 + now = datetime.now(timezone.utc) + for rec in payload.records: + if not rec.present: + continue + record_attendance( + db, + account_id=current_user.account_id, + user_id=rec.student_id, + section_id=payload.section_id, + subject_id=payload.subject_id, + action="in", + marked_by_role="admin", + marked_by_user_id=current_user.id, + when=now, + note="Admin: contingencia", + ) + created += 1 + return {"created": created, "total": len(payload.records), "skipped": []} +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/api/test_admin_attendance.py -v` +Expected: 7 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py +git commit -m "feat(ta-01): POST /admin/attendance/swipe with admin attribution" +``` + +--- + +### Task 23: `POST /admin/attendance/batch-toggle` (TDD) + +**Files:** +- Modify: `backend/app/api/v1/endpoints/admin_attendance.py` +- Modify: `backend/tests/api/test_admin_attendance.py` + +- [ ] **Step 1: Test** + +```python +def test_admin_batch_toggle_for_past_date( + admin_token, demo_section_id, demo_student_id, db_session +): + c = TestClient(app) + r = c.post( + "/api/v1/admin/attendance/batch-toggle?date=2026-06-01", + headers={"Authorization": f"Bearer {admin_token}"}, + json={ + "section_id": demo_section_id, + "records": [{"student_id": demo_student_id, "present": True}], + }, + ) + assert r.status_code == 200, r.text + from app.models.attendance import Attendance + row = db_session.query(Attendance).filter( + Attendance.user_id == demo_student_id, + Attendance.section_id == demo_section_id, + ).order_by(Attendance.id.desc()).first() + assert row.marked_by_role == "admin" + assert row.time_log.date().isoformat() == "2026-06-01" +``` + +- [ ] **Step 2: Implementar** + +```python +from datetime import time as time_type + + +@router.post("/attendance/batch-toggle") +def admin_batch_toggle( + payload: AdminSwipeRequest, + on_date: str | None = Query(None, alias="date"), + current_user: User = Depends(RBAC(["admin"])), + db: Session = Depends(get_db), +): + section = db.query(Section).filter( + Section.id == payload.section_id, + Section.account_id == current_user.account_id, + ).first() + if not section: + raise HTTPException(status_code=404, detail="section not found") + day = datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date.today() + when = ( + datetime.now(timezone.utc) + if day == date.today() + else datetime.combine(day, time_type(12, 0), tzinfo=timezone.utc) + ) + created = 0 + for rec in payload.records: + if not rec.present: + continue + record_attendance( + db, + account_id=current_user.account_id, + user_id=rec.student_id, + section_id=payload.section_id, + subject_id=payload.subject_id, + action="in", + marked_by_role="admin", + marked_by_user_id=current_user.id, + when=when, + note="Admin batch: contingencia", + ) + created += 1 + return {"created": created, "total": len(payload.records), "skipped": []} +``` + +- [ ] **Step 3: Tests pasan** + +Run: `docker compose exec backend pytest backend/tests/api/test_admin_attendance.py -v` +Expected: 8 passed. + +- [ ] **Step 4: Commit** + +```bash +git add backend/app/api/v1/endpoints/admin_attendance.py backend/tests/api/test_admin_attendance.py +git commit -m "feat(ta-01): POST /admin/attendance/batch-toggle with date support" +``` + +--- + +## Phase 6 — Frontend + +### Task 24: Extraer `AttendanceTable` y `StudentRow` + +**Files:** +- Create: `frontend/src/components/attendance/AttendanceTable.tsx` +- Create: `frontend/src/components/attendance/StudentRow.tsx` +- Create: `frontend/src/components/attendance/AttendanceSummaryChips.tsx` +- Modify: `frontend/src/pages/teacher/TeacherAttendancePage.tsx` + +- [ ] **Step 1: Leer la página actual** + +Read: `frontend/src/pages/teacher/TeacherAttendancePage.tsx` completo. Identificar: +- El JSX que renderiza la tabla de estudiantes. +- El componente fila (chip presente/ausente + entrance chip). +- Los contadores de presente/ausente. + +- [ ] **Step 2: Crear `StudentRow.tsx`** + +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`. + +- [ ] **Step 3: Crear `AttendanceTable.tsx`** + +Componente que recibe `students: RosterItem[]`, `pendingToggles`, `onToggle`, `loading` y renderiza el header + map de ``. + +- [ ] **Step 4: Crear `AttendanceSummaryChips.tsx`** + +Componente con los contadores presente/ausente y, si aplica, el desglose por sexo. + +- [ ] **Step 5: Cambiar el styling del chip `entrance_logged` a gris/info** + +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." + +- [ ] **Step 6: Actualizar `TeacherAttendancePage.tsx` para usar los nuevos componentes** + +Reemplazar el JSX duplicado por `` y ``. + +- [ ] **Step 7: Verificar build y página** + +Run: `docker compose exec frontend npm run typecheck` o equivalente. +Expected: sin errores. + +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. + +- [ ] **Step 8: Commit** + +```bash +git add frontend/src/components/attendance/ frontend/src/pages/teacher/TeacherAttendancePage.tsx +git commit -m "refactor(ta-01): extract AttendanceTable/StudentRow components from teacher page" +``` + +--- + +### Task 25: Servicio `adminAttendanceService.ts` + +**Files:** +- Create: `frontend/src/services/adminAttendanceService.ts` + +- [ ] **Step 1: Espejar `teacherService.ts`** + +Read: `frontend/src/services/teacherService.ts` (líneas 1-80). + +Crear `adminAttendanceService.ts` con: + +```ts +import { api } from "./api"; // o el cliente axios/fetch que use el proyecto + +export interface AdminSection { id: number; name: string } +export interface AdminRosterItem { + id: number; name: string; lastname: string; + card_id: string | null; phone_number: string | null; + already_checked_in: boolean; entrance_logged: boolean; +} +export interface AdminSwipeRecord { student_id: number; present: boolean } + +export const adminAttendanceService = { + async listSections(): Promise { + const { data } = await api.get("/admin/sections"); + return data; + }, + async getRoster(sectionId: number, date?: string): Promise { + const { data } = await api.get(`/admin/sections/${sectionId}/roster`, { params: { date } }); + return data; + }, + async swipe(sectionId: number, records: AdminSwipeRecord[]) { + const { data } = await api.post("/admin/attendance/swipe", { section_id: sectionId, records }); + return data; + }, + async batchToggle(sectionId: number, records: AdminSwipeRecord[], date?: string) { + const { data } = await api.post(`/admin/attendance/batch-toggle`, { section_id: sectionId, records }, { params: { date } }); + return data; + }, +}; +``` + +- [ ] **Step 2: Commit** + +```bash +git add frontend/src/services/adminAttendanceService.ts +git commit -m "feat(ta-01): add adminAttendanceService client" +``` + +--- + +### Task 26: `AdminAttendancePage.tsx` + +**Files:** +- Create: `frontend/src/pages/admin/AdminAttendancePage.tsx` + +- [ ] **Step 1: Implementación** + +```tsx +import { useEffect, useState } from "react"; +import { AttendanceTable } from "@/components/attendance/AttendanceTable"; +import { AttendanceSummaryChips } from "@/components/attendance/AttendanceSummaryChips"; +import { + adminAttendanceService, + AdminSection, + AdminRosterItem, +} from "@/services/adminAttendanceService"; + +export default function AdminAttendancePage() { + const [sections, setSections] = useState([]); + const [sectionId, setSectionId] = useState(null); + const [date, setDate] = useState(() => new Date().toISOString().slice(0, 10)); + const [roster, setRoster] = useState([]); + const [pending, setPending] = useState>(new Set()); + const [saving, setSaving] = useState(false); + + useEffect(() => { + adminAttendanceService.listSections().then(setSections); + }, []); + + useEffect(() => { + if (sectionId == null) return; + adminAttendanceService.getRoster(sectionId, date).then(setRoster); + }, [sectionId, date]); + + const togglePending = (id: number) => { + setPending((s) => { + const next = new Set(s); + if (next.has(id)) next.delete(id); else next.add(id); + return next; + }); + }; + + const save = async () => { + if (sectionId == null || pending.size === 0) return; + setSaving(true); + try { + const records = roster + .filter((r) => pending.has(r.id)) + .map((r) => ({ student_id: r.id, present: !r.already_checked_in })); + await adminAttendanceService.batchToggle(sectionId, records, date); + setPending(new Set()); + const fresh = await adminAttendanceService.getRoster(sectionId, date); + setRoster(fresh); + } finally { + setSaving(false); + } + }; + + return ( +
+
+

Asistencia por contingencia

+

+ Usá esta vista cuando un docente está ausente y necesitás pasar lista en su aula. +

+
+
+ + setDate(e.target.value)} + className="border rounded px-3 py-2" + /> +
+ {sectionId != null && ( + <> + + + + + )} +
+ ); +} +``` + +> 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. + +- [ ] **Step 2: Verificar typecheck** + +Run: `docker compose exec frontend npm run typecheck` +Expected: sin errores. + +- [ ] **Step 3: Commit** + +```bash +git add frontend/src/pages/admin/AdminAttendancePage.tsx +git commit -m "feat(ta-01): add AdminAttendancePage for contingency attendance" +``` + +--- + +### Task 27: Ruta y sidebar admin + +**Files:** +- Modify: archivo de rutas (probablemente `frontend/src/routes.tsx` o `frontend/src/App.tsx`) +- Modify: sidebar admin (probablemente `frontend/src/components/admin/Sidebar.tsx`) + +- [ ] **Step 1: Identificar archivos** + +Run: `Glob "frontend/src/**/Sidebar*.tsx"` y `Glob "frontend/src/**/routes*.tsx"`. + +- [ ] **Step 2: Agregar la ruta** + +```tsx +import AdminAttendancePage from "@/pages/admin/AdminAttendancePage"; + +// ... dentro de las rutas admin +} /> +``` + +- [ ] **Step 3: Agregar item al sidebar admin** + +```tsx +{ to: "/admin/attendance", label: "Asistencia por contingencia", icon: }, +``` + +- [ ] **Step 4: Smoke browser** + +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"). + +- [ ] **Step 5: Commit** + +```bash +git add frontend/src/routes.tsx frontend/src/components/admin/ +git commit -m "feat(ta-01): wire /admin/attendance route and sidebar item" +``` + +--- + +## Phase 7 — Verificación final + +### Task 28: Suite completa + smoke manual + +- [ ] **Step 1: Suite backend** + +Run: `docker compose exec backend pytest backend/tests/ -v` +Expected: TODA la suite verde, incluyendo: +- `backend/tests/storage/` +- `backend/tests/services/` +- `backend/tests/api/test_admin_attendance.py` +- `backend/tests/api/test_users_photo_upload.py` +- `backend/tests/api/test_teacher_attendance_gate_decouple.py` +- Las suites preexistentes (sex aggregations, present summary, etc). + +- [ ] **Step 2: Smoke manual** + +Levantar todo: `docker compose up -d`. + +Checklist en navegador: +- [ ] 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`). +- [ ] Subir un GIF. Verificar 422 con mensaje claro. +- [ ] Subir una foto sin rostro. Verificar que se guarda igual y el warning aparece. +- [ ] 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). +- [ ] Login teacher → marcar a un estudiante sin gate check-in → verificar que SÍ se marca presente y el chip de gate es gris/info. +- [ ] 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. + +- [ ] **Step 3: Reporte al usuario** + +> Sprint TA-01 implementado y verificado localmente. Tests verdes, smoke OK. +> 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. + +--- + +## Notas para quien implemente + +- **Convenciones del proyecto:** + - `datetime.now(timezone.utc)` SIEMPRE en escrituras a columnas timezone-aware (TZ del container = `America/Caracas`). + - Tests directos con pytest, NO tocar `init.sh`. + - Commits locales OK, NO `git push` automático. + - Postgres en dev y prod, no mezclar motores. + +- **Fixtures requeridos (agregar a `backend/tests/conftest.py` si no existen):** + - `admin_token`, `teacher_token`, `other_account_admin_token` + - `admin_user_id`, `demo_student_id`, `demo_section_id` + - `demo_student_without_entrance_log`, `foreign_section_id` + - `db_session`, `demo_account`, `demo_section`, `demo_student`, `demo_admin` + - Patrón a copiar: `backend/tests/test_seed_demo_scoping.py`. + +- **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. + +- **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`). diff --git a/docs/superpowers/specs/2026-06-05-ta01-storage-and-attendance-design.md b/docs/superpowers/specs/2026-06-05-ta01-storage-and-attendance-design.md new file mode 100644 index 0000000000000000000000000000000000000000..d64e47eb8c5f3281a177829c4709cf30f1a1aced --- /dev/null +++ b/docs/superpowers/specs/2026-06-05-ta01-storage-and-attendance-design.md @@ -0,0 +1,357 @@ +# TA-01 — Storage de fotos + asistencia administrativa + flexibilidad gate + +**Fecha:** 2026-06-05 +**Sprint:** TA-01 +**Estado:** Diseño aprobado, pendiente plan de implementación +**Fuente requisitos:** `docs/sprints/2026-06-05_TA-01.md` + +## Resumen + +Sprint con tres bloques independientes pero entregados como una sola unidad: + +- **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. +- **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. +- **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). + +## Motivación + +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. +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. +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. + +**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. + +## Decisiones de diseño tomadas + +| # | Pregunta | Decisión | +|---|----------|----------| +| 1 | Alcance del sprint | Un único spec con los 3 bloques. | +| 2 | Abstracción de storage | Interfaz `PhotoStorage` con adapters `LocalDiskStorage` (dev) y `SupabaseStorage` (prod). Switch por env var. | +| 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`. | +| 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. | +| 5 | Perfil de compresión | WebP lossy q=85, máximo 800×800 px manteniendo aspect ratio. | +| 6 | Scope del admin en asistencia | Cualquier sección de su cuenta. Sin tabla de asignación admin-sección. | +| 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. | +| 8 | Grado de desacople gate | Desacople total: nunca bloquear. El chip `entrance_logged` se sigue calculando como información en la UI. | +| 9 | Ubicación de la UI admin | Página nueva `/admin/attendance` reutilizando componentes extraídos de `TeacherAttendancePage`. | + +## Cambios de base de datos + +Migración Alembic: `backend/migrations/versions/028_ta01_storage_and_attendance_attribution.py` + +```sql +-- Bloque A: foto pasa de Base64 a URL/path corto + permitir encoding NULL +ALTER TABLE face_encodings + ALTER COLUMN photo TYPE VARCHAR(500) USING NULL, -- vacía las filas viejas; admin re-sube + ALTER COLUMN encoding DROP NOT NULL; -- permite foto sin rostro detectado + +-- Bloque B: trazabilidad de origen de la marca +ALTER TABLE attendances + ADD COLUMN marked_by_role VARCHAR(20), -- 'teacher' | 'admin' | 'kiosco' + ADD COLUMN marked_by_user_id BIGINT NULL, + ADD CONSTRAINT fk_attendances_marked_by_user + FOREIGN KEY (marked_by_user_id) REFERENCES users(id); + +CREATE INDEX ix_attendances_marked_by_user_id ON attendances(marked_by_user_id); +``` + +**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. + +**Downgrade:** + +```sql +DROP INDEX ix_attendances_marked_by_user_id; +ALTER TABLE attendances + DROP CONSTRAINT fk_attendances_marked_by_user, + DROP COLUMN marked_by_user_id, + DROP COLUMN marked_by_role; +ALTER TABLE face_encodings + ALTER COLUMN photo TYPE TEXT; +``` + +**Modelos SQLAlchemy:** + +- `app/models/face_encoding.py` → `photo = Column(String(500), nullable=True)` +- `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)` + +## Bloque A — Storage de fotos + +### 1. Capa de abstracción (`backend/app/storage/`) + +Estructura nueva del paquete: + +``` +backend/app/storage/ + __init__.py # factory: get_storage() lee env var + base.py # Protocol PhotoStorage + local_disk.py # LocalDiskStorage + supabase.py # SupabaseStorage (stub inicial) + in_memory.py # InMemoryStorage (solo tests) +``` + +`base.py`: + +```python +from typing import Protocol + +class PhotoStorage(Protocol): + def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str: + """Persiste el archivo y devuelve la ruta/URL canónica que se guarda en BD.""" + def delete(self, path_or_url: str) -> None: + """Borra el archivo. Best-effort, no levanta si no existe.""" + def get_url(self, path_or_url: str) -> str: + """Devuelve la URL pública o firmada con la que el frontend lo consume.""" +``` + +`__init__.py`: + +```python +def get_storage() -> PhotoStorage: + backend = os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() + if backend == "local": + return LocalDiskStorage(root=os.getenv("LOCAL_PHOTO_ROOT", "/data/photos")) + if backend == "supabase": + return SupabaseStorage( + url=os.getenv("SUPABASE_URL"), + key=os.getenv("SUPABASE_SERVICE_KEY"), + bucket=os.getenv("SUPABASE_PHOTO_BUCKET", "user-photos"), + ) + raise ValueError(f"Unknown PHOTO_STORAGE_BACKEND: {backend}") +``` + +`LocalDiskStorage`: + +- Path en disco: `{root}/{account_id}/{user_id}/{uuid4}.{ext}` +- `get_url` devuelve `/api/v1/photos/{path}` (endpoint sirve el archivo con `FileResponse`) +- `delete` ignora `FileNotFoundError` + +`SupabaseStorage` (inicial: stub que tira `NotImplementedError` con mensaje claro hasta que lleguen credenciales; las firmas y tests fakeados ya quedan listos). + +### 2. Pipeline de procesamiento de imágenes (`backend/app/services/photo_pipeline.py`) + +```python +from io import BytesIO +from PIL import Image, ImageOps +import magic + +ALLOWED_MIME = {"image/png", "image/jpeg", "image/webp"} +MAX_INPUT_BYTES = 5 * 1024 * 1024 # 5 MB +TARGET_MAX_DIM = 800 +WEBP_QUALITY = 85 + +def process_user_photo(raw: bytes) -> bytes: + if len(raw) > MAX_INPUT_BYTES: + raise ValueError("photo exceeds 5 MB") + mime = magic.from_buffer(raw, mime=True) + if mime not in ALLOWED_MIME: + raise ValueError(f"unsupported mime: {mime}") + img = Image.open(BytesIO(raw)) + img = ImageOps.exif_transpose(img) # corrige rotación + img.thumbnail((TARGET_MAX_DIM, TARGET_MAX_DIM), Image.LANCZOS) + if img.mode in ("RGBA", "P"): + img = img.convert("RGB") + out = BytesIO() + img.save(out, format="WEBP", quality=WEBP_QUALITY, method=6) + return out.getvalue() +``` + +Librerías nuevas en `backend/requirements.txt`: `Pillow` (verificar versión actual), `python-magic`. En Windows dev, `python-magic-bin`. + +### 3. Endpoint de upload + +`POST /api/v1/users/{user_id}/photo` (admin-only): + +``` +1. multipart/form-data con campo `file` (max 5 MB; png|jpg|jpeg|webp) +2. processed = process_user_photo(raw) # WebP 800×800 q=85 +3. Intentar extract_encoding(processed) vía face_utils: + - éxito → encoding_str + - sin rostro detectable → encoding_str = None, warning_flag = True +4. storage = get_storage() +5. Buscar último face_encoding del user; si existe y tiene photo: + storage.delete(old.photo) # best-effort +6. new_path = storage.upload(account_id, user_id, processed, "webp") +7. INSERT face_encodings (user_id, account_id, encoding=encoding_str, photo=new_path) +8. Respuesta: + 200 { "photo_url": storage.get_url(new_path), + "encoding_extracted": bool, + "warning": "no se detectó rostro; el reconocimiento facial no + funcionará hasta resubir una foto con rostro visible" + if not encoding_extracted else None } +``` + +**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]`. + +### 4. Endpoint para servir foto local + +`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`. + +## Bloque B — Asistencia administrativa + +### 1. Refactor previo (extracción de servicio) + +Mover la lógica de marca de asistencia desde `app/api/v1/endpoints/teacher.py` a `app/services/attendance.py`: + +```python +def record_attendance( + db, *, account_id, user_id, section_id, subject_id, action, + marked_by_role: str, marked_by_user_id: int, when: datetime, +) -> Attendance: ... + +def list_section_roster( + db, *, account_id, section_id, on_date, +) -> list[StudentRosterItem]: ... +``` + +`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. + +### 2. Endpoints admin (`app/api/v1/endpoints/admin_attendance.py`) + +``` +GET /api/v1/admin/sections +GET /api/v1/admin/sections/{section_id}/subjects?on_date=YYYY-MM-DD +GET /api/v1/admin/sections/{section_id}/roster?subject_id=&on_date=YYYY-MM-DD +POST /api/v1/admin/attendance/swipe +POST /api/v1/admin/attendance/batch-toggle +``` + +Schemas: mismos de `teacher` con renombre cosmético. Auth: `require_role("admin")`. Scope: filtrado por `current_user.account_id` en todas las queries. + +### 3. Frontend + +Componentes nuevos / reusados: + +- Extraer de `frontend/src/pages/teacher/TeacherAttendancePage.tsx` los componentes presentacionales: `AttendanceTable`, `StudentRow`, `AttendanceSummaryChips`. Mover a `frontend/src/components/attendance/`. +- Nueva página: `frontend/src/pages/admin/AdminAttendancePage.tsx` + - Header: selector `Section` → `Subject` → `Date` (default hoy). + - Body: `` con datos del endpoint admin. + - Footer: contadores presente/ausente y botón "Guardar". +- Nuevo servicio: `frontend/src/services/adminAttendanceService.ts` espejo de `teacherService.ts`. +- Ruta: `/admin/attendance` agregada al router y al sidebar admin con el item "Asistencia por contingencia". + +## Bloque C — Desacople gate ↔ aula + +### Cambios + +En `app/api/v1/endpoints/teacher.py` (y, después del refactor del Bloque B, en `app/services/attendance.py`): + +- Eliminar el cálculo de `entrance_logged_ids` como **filtro** en `submit_swipe` (`teacher.py:470-496`) y en `batch-toggle` (`teacher.py:580-…`). +- Eliminar las acumulaciones de `skipped_ids` derivadas del check de gate. +- Eliminar las ramas `if rec.student_id not in entrance_logged_ids: skipped_ids.append(...)`. +- 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). + +El `entrance_logged` que se devuelve en el roster (`GET /students` y similares) sigue calculándose; solo cambia su rol: ya no es bloqueante. + +**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. + +### Documentación de UI + +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." + +## Arquitectura de archivos (cambios) + +``` +backend/ + app/ + models/ + attendance.py [edit: +marked_by_role, +marked_by_user_id] + face_encoding.py [edit: photo = String(500)] + storage/ [NEW] + __init__.py + base.py + local_disk.py + supabase.py + in_memory.py + services/ [NEW or grow] + attendance.py [NEW: record_attendance, list_section_roster] + photo_pipeline.py [NEW] + api/v1/endpoints/ + teacher.py [edit: usa services/attendance + quita gate filter] + admin_attendance.py [NEW] + users.py [edit: photo endpoint + mapea path → URL en responses] + photos.py [NEW: GET local file] + migrations/versions/ + 028_ta01_storage_and_attendance_attribution.py [NEW] + tests/ + storage/ [NEW: test_local_disk, test_supabase, test_in_memory] + services/ [NEW: test_photo_pipeline, test_attendance_service] + api/ + test_admin_attendance.py [NEW] + test_teacher_attendance_gate_decouple.py [NEW: regresión Bloque C] + test_users_photo_upload.py [NEW] + +frontend/ + src/ + components/attendance/ [NEW: extracción] + AttendanceTable.tsx + StudentRow.tsx + AttendanceSummaryChips.tsx + pages/ + teacher/TeacherAttendancePage.tsx [edit: usa componentes extraídos] + admin/AdminAttendancePage.tsx [NEW] + services/ + adminAttendanceService.ts [NEW] + routes.tsx [edit: +/admin/attendance] +``` + +## Variables de entorno nuevas + +``` +PHOTO_STORAGE_BACKEND=local # local | supabase +LOCAL_PHOTO_ROOT=/data/photos # solo si backend=local +SUPABASE_URL= # solo si backend=supabase +SUPABASE_SERVICE_KEY= # solo si backend=supabase +SUPABASE_PHOTO_BUCKET=user-photos # opcional, default mostrado +``` + +En `docker-compose.yml` montar volumen `/data/photos` para el backend (dev). En `.env.example` agregar las cinco variables con valores de dev. + +## Plan de testing + +- **Storage** + - `LocalDiskStorage`: upload escribe archivo, delete lo borra (y es idempotente), get_url devuelve el path correcto. + - `InMemoryStorage`: smoke en memoria para tests rápidos del pipeline. + - `SupabaseStorage`: stub levanta `NotImplementedError` con mensaje claro hasta integración real. +- **Photo pipeline** + - Rechaza tamaños > 5 MB. + - Rechaza mime no permitido (probar gif). + - Acepta png, jpeg, webp. + - Output siempre es WebP de ≤ 800×800. + - EXIF rotation se aplica (foto verticalmente girada queda derecha). +- **Endpoint upload** + - Admin de otra cuenta no puede subir foto de un user. + - Sube foto, llamada GET la devuelve. + - Subir segunda foto borra la anterior del storage. +- **Servicio de asistencia** + - `record_attendance` setea `marked_by_role` y `marked_by_user_id` correctamente. + - Idempotencia: misma marca dos veces no duplica. +- **Endpoints admin** + - Admin puede listar todas las secciones de su cuenta. + - Admin de otra cuenta recibe 404 al pedir una sección ajena. + - `swipe` y `batch-toggle` se comportan como los de teacher pero con `marked_by_role='admin'`. +- **Regresión Bloque C** + - Estudiante sin `EntranceLog` del día ahora SÍ se marca presente en `teacher/attendance/swipe` y en `teacher/attendance/batch-toggle`. + - El roster sigue devolviendo `entrance_logged: false` para ese estudiante (información preservada). + +## Out of scope + +- Migración automática de fotos Base64 existentes (admin re-sube manualmente). +- UI para que el admin "confirme ausencia de docente" o se asigne a una sección (admin tiene scope completo). +- Reportes diferenciados por `marked_by_role` (la columna queda lista pero los reports no la consumen en este sprint). +- Soporte para Supabase Storage real funcionando — el adapter queda con stub. La integración efectiva se hará cuando lleguen credenciales (sprint posterior). + +## Riesgos y mitigaciones + +| Riesgo | Mitigación | +|--------|------------| +| Volumen local `/data/photos` en dev no persiste entre `docker compose down -v` | Documentar; el admin re-sube en dev. | +| `python-magic` requiere libmagic; en Windows usar `python-magic-bin` | Documentar en `requirements.txt` y `README` con condición de OS. | +| 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. | +| Extraer componentes del frontend puede romper la UI de docente | Test manual de TeacherAttendancePage post-refactor antes de mergear. | + +## Convenciones del proyecto a respetar + +- TZ: usar `datetime.now(timezone.utc)` para escrituras a columnas timezone-aware. El contenedor está en `America/Caracas`. +- Tests: pytest directo, **no** tocar `init.sh`. +- Commits locales OK durante el sprint, **NO** push automático a producción. +- Un mismo motor de BD en dev y prod (PostgreSQL). diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 516c3eabb491c75de3506eebb752188d55f29305..757fe38f5bcee32033b8c2ecba0ecf73045deda5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -9,6 +9,7 @@ import EnrollmentsPage from './pages/EnrollmentsPage' import AttendanceReportsPage from './pages/AttendanceReportsPage' import SettingsPage from './pages/SettingsPage' import TeacherAttendancePage from './pages/TeacherAttendancePage' +import AdminAttendancePage from './pages/AdminAttendancePage' import TeacherSubjectsPage from './pages/TeacherSubjectsPage' import TeacherSectionsPage from './pages/TeacherSectionsPage' import PublicCheckInPage from './pages/PublicCheckInPage' @@ -48,6 +49,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/frontend/src/components/AuthImage.tsx b/frontend/src/components/AuthImage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..71e4e1282e501cd638d1c600d58baf6133104ecd --- /dev/null +++ b/frontend/src/components/AuthImage.tsx @@ -0,0 +1,76 @@ +import { useEffect, useState, type ImgHTMLAttributes, type ReactNode } from 'react'; +import { Loader2 } from 'lucide-react'; +import api from '../services/api'; + +interface AuthImageProps extends Omit, 'src'> { + src: string | null | undefined; + fallback?: ReactNode; +} + +/** + * Renders an authenticated image. The `` tag cannot send our JWT + * Authorization header, so a direct URL to a protected endpoint (e.g. + * `/api/v1/photos/...`) returns 401 and shows broken in the browser. + * AuthImage fetches the bytes through the axios instance (which injects + * the auth header), converts the response to a blob URL, and renders that. + * + * For dataURLs and blob URLs we render directly without fetching. + */ +export default function AuthImage({ src, fallback = null, ...imgProps }: AuthImageProps) { + const [blobUrl, setBlobUrl] = useState(null); + const [error, setError] = useState(false); + + useEffect(() => { + if (!src) { + setBlobUrl(null); + setError(false); + return; + } + + // Pass-through for data: and blob: URLs. + if (src.startsWith('data:') || src.startsWith('blob:')) { + setBlobUrl(src); + setError(false); + return; + } + + let cancelled = false; + let createdUrl: string | null = null; + setError(false); + + // Strip our axios baseURL prefix so the path doesn't double up. + const relative = src.replace(/^\/api\/v1/, ''); + + api + .get(relative, { responseType: 'blob' }) + .then((res) => { + if (cancelled) return; + createdUrl = URL.createObjectURL(res.data); + setBlobUrl(createdUrl); + }) + .catch(() => { + if (!cancelled) setError(true); + }); + + return () => { + cancelled = true; + if (createdUrl) URL.revokeObjectURL(createdUrl); + }; + }, [src]); + + if (error || !src) return <>{fallback}; + if (!blobUrl) { + const { className = '', ...rest } = imgProps; + return ( +
)} + className={`${className} flex items-center justify-center bg-gray-100`} + aria-busy="true" + aria-label="Cargando imagen" + > + +
+ ); + } + return ; +} diff --git a/frontend/src/components/CameraCapture.tsx b/frontend/src/components/CameraCapture.tsx index 5843be367b00b70382c71e7ddf4c379ad3dd6e11..1607ec88012ef55982fe77cd490ebe0c262eaa02 100644 --- a/frontend/src/components/CameraCapture.tsx +++ b/frontend/src/components/CameraCapture.tsx @@ -1,5 +1,5 @@ import { useState, useRef, useEffect, useCallback } from 'react'; -import { Camera, Check, RotateCcw } from 'lucide-react'; +import { Camera, Check, RotateCcw, SwitchCamera } from 'lucide-react'; interface CameraCaptureProps { isOpen: boolean; @@ -18,11 +18,14 @@ export default function CameraCapture({ isOpen, onCapture, onClose }: CameraCapt const [cameraError, setCameraError] = useState(false); const [captured, setCaptured] = useState(null); const [hasFaceDetector, setHasFaceDetector] = useState(false); + const [facingMode, setFacingMode] = useState<'user' | 'environment'>('user'); const startCamera = useCallback(async () => { try { stopCamera(); - const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480, facingMode: 'user' } }); + const stream = await navigator.mediaDevices.getUserMedia({ + video: { width: 640, height: 480, facingMode }, + }); streamRef.current = stream; if (videoRef.current) videoRef.current.srcObject = stream; setCameraReady(true); @@ -30,6 +33,10 @@ export default function CameraCapture({ isOpen, onCapture, onClose }: CameraCapt } catch { setCameraError(true); } + }, [facingMode]); + + const toggleFacing = useCallback(() => { + setFacingMode((m) => (m === 'user' ? 'environment' : 'user')); }, []); const stopCamera = useCallback(() => { @@ -209,10 +216,20 @@ export default function CameraCapture({ isOpen, onCapture, onClose }: CameraCapt {hasFaceDetector && (

Detección facial activa

)} - +
+ + +
)} diff --git a/frontend/src/components/Layout.tsx b/frontend/src/components/Layout.tsx index cbf81bf90581eae14e69edfb9f05170f166d5918..159d4d79de190ad342fbd61ac0869885674c9f0c 100644 --- a/frontend/src/components/Layout.tsx +++ b/frontend/src/components/Layout.tsx @@ -1,10 +1,40 @@ -import { Outlet } from 'react-router-dom'; +import { Outlet, useLocation } from 'react-router-dom'; +import { useState, useEffect } from 'react'; +import { Menu } from 'lucide-react'; import Sidebar from './Sidebar'; export default function Layout() { + const [mobileOpen, setMobileOpen] = useState(false); + const location = useLocation(); + + // Close drawer whenever the route changes. + useEffect(() => { + setMobileOpen(false); + }, [location.pathname]); + return (
- + {/* Floating hamburger (mobile only, no full topbar) */} + + + {/* Backdrop for mobile drawer */} + {mobileOpen && ( +
setMobileOpen(false)} + aria-hidden="true" + /> + )} + + setMobileOpen(false)} /> +
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index c6badb28a4d6eac75f0fc6d115e97e44f73b3b40..b46b452a3786f37fd7da10272f63772a38d8662a 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -1,7 +1,12 @@ import { NavLink } from 'react-router-dom'; import { useAuthStore } from '../store/authStore'; import { translateRole } from '../utils/roles'; -import { Users, LayoutDashboard, BookOpen, ClipboardCheck, LogOut, GraduationCap, BarChart3, Settings, CreditCard, Clock, Code2, IdCard, Heart, Calendar, Search, FileText } from 'lucide-react'; +import { Users, LayoutDashboard, BookOpen, ClipboardCheck, LogOut, GraduationCap, BarChart3, Settings, CreditCard, Clock, Code2, IdCard, Heart, Calendar, Search, FileText, X } from 'lucide-react'; + +interface SidebarProps { + mobileOpen?: boolean; + onClose?: () => void; +} const navItems = [ { to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] }, @@ -14,6 +19,7 @@ const navItems = [ { to: '/dashboard/mis-hijos', label: 'Mis Hijos', icon: Heart, roles: ['representative'] }, { to: '/dashboard/public-checkin', label: 'Mi Asistencia', icon: Clock, roles: ['admin', 'teacher', 'representative', 'student', 'administrativo', 'obrero'] }, { to: '/dashboard/teacher-attendance', label: 'Asistencia', icon: CreditCard, roles: ['teacher'] }, + { to: '/dashboard/admin-attendance', label: 'Asistencia (contingencia)', icon: ClipboardCheck, roles: ['admin'] }, { to: '/dashboard/attendance', label: 'Reportes', icon: BarChart3, roles: ['admin', 'administrativo'] }, { to: '/dashboard/student-report', label: 'Rep. Estudiantes', icon: FileText, roles: ['admin', 'administrativo'] }, { 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 return user?.role === 'admin' || user?.role === 'developer' || (user?.permissions ?? []).includes('admin.full'); } -export default function Sidebar() { +export default function Sidebar({ mobileOpen = false, onClose }: SidebarProps) { const user = useAuthStore((s) => s.user); const clearAuth = useAuthStore((s) => s.clearAuth); const isAdmin = hasAdminAccess(user); @@ -45,14 +51,32 @@ export default function Sidebar() { }); return ( -