"""Celery task: send monthly reports to schools.""" import logging from app.worker import celery_app logger = logging.getLogger(__name__) @celery_app.task(name="reports.send_monthly_reports") def send_monthly_reports(): """Send monthly attendance and SMS report email to each active school.""" import os from datetime import date, timedelta from sqlalchemy import create_engine, select from sqlalchemy.orm import sessionmaker from app.models.school import School, SchoolStatus from app.services.email import send_email db_url = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@db:5432/taptrack_hub") engine = create_engine(db_url.replace("postgresql+asyncpg://", "postgresql://"), pool_pre_ping=True) db = sessionmaker(bind=engine)() try: today = date.today() prev_month_end = date(today.year, today.month, 1) - timedelta(days=1) prev_month_start = date(prev_month_end.year, prev_month_end.month, 1) schools = db.execute(select(School).where(School.status == SchoolStatus.active)).scalars().all() for school in schools: if not school.billing_email: continue send_email( to=school.billing_email, subject=f"Monthly Report — {school.name} — {prev_month_start.strftime('%B %Y')}", body=f"Dear {school.contact_name or school.name},\n\nPlease find your monthly summary for {prev_month_start.strftime('%B %Y')} in your TapTrack Hub portal.\n\nSMS Credits Remaining: {float(school.sms_credits):.0f}\n\nLog in to view full details.\n\nThank you,\nTapTrack Hub Team", ) logger.info(f"Sent monthly reports to {len(schools)} schools") finally: db.close()