"""Email log viewer and test-email endpoint.""" from typing import Optional from fastapi import APIRouter, Depends, Query from pydantic import BaseModel, EmailStr from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, func, desc from app.auth.dependencies import require_super_admin from app.database import get_db from app.models.user import HubUser from app.models.email_log import EmailLog, EmailType, EmailStatus router = APIRouter(prefix="/api/email", tags=["email"]) @router.get("/logs") async def list_email_logs( email_type: Optional[EmailType] = Query(None), status: Optional[EmailStatus] = Query(None), school_id: Optional[str] = Query(None), page: int = Query(1, ge=1), per_page: int = Query(50, ge=1, le=200), _admin: HubUser = Depends(require_super_admin), db: AsyncSession = Depends(get_db), ): """Paginated email delivery history — super admin only.""" stmt = select(EmailLog).order_by(desc(EmailLog.created_at)) if email_type: stmt = stmt.where(EmailLog.email_type == email_type) if status: stmt = stmt.where(EmailLog.status == status) if school_id: stmt = stmt.where(EmailLog.school_id == school_id) total = (await db.execute(select(func.count()).select_from(stmt.subquery()))).scalar_one() logs = (await db.execute(stmt.offset((page - 1) * per_page).limit(per_page))).scalars().all() return { "items": [ { "id": log.id, "school_id": log.school_id, "to_email": log.to_email, "subject": log.subject, "email_type": log.email_type.value, "status": log.status.value, "error_message": log.error_message, "sent_at": log.sent_at.isoformat() if log.sent_at else None, "created_at": log.created_at.isoformat(), } for log in logs ], "total": total, "page": page, "per_page": per_page, } class TestEmailBody(BaseModel): to: EmailStr @router.post("/test") async def send_test_email( body: TestEmailBody, _admin: HubUser = Depends(require_super_admin), ): """Send a test email to verify SMTP configuration.""" from app.services.email import send_email success = send_email( to=body.to, subject="TapTrack Hub — SMTP Test Email", body=( "This is a test email from TapTrack Hub.\n\n" "If you received this, your SMTP configuration is working correctly.\n\n" "TapTrack Hub Team" ), html=( "
This is a test email from TapTrack Hub.
" "If you received this, your SMTP configuration is working correctly.
" "TapTrack Hub Team
" "