from datetime import date, timedelta from flask import current_app from models import TempSpec from utils import send_email, process_recipients def check_expiring_specs(app): """Scheduled task: notify when specs will expire in 3 or 7 days.""" with app.app_context(): current_app.logger.info("Running scheduled task: Checking for expiring specs...") today = date.today() targets = {3, 7} expiring_soon = TempSpec.query.filter( TempSpec.status == "active" ).all() if not expiring_soon: current_app.logger.info("No active specs found for expiry check.") return configured_defaults = app.config.get("DEFAULT_NOTIFICATION_EMAILS", "") default_recipients = process_recipients(configured_defaults) if configured_defaults else [] for spec in expiring_soon: if not spec.end_date: continue remaining_days = (spec.end_date - today).days if remaining_days not in targets: continue recipients_source = spec.notification_emails or configured_defaults recipients = process_recipients(recipients_source) if recipients_source else default_recipients if not recipients: current_app.logger.warning( "Skip expiry reminder for %s - no recipients.", spec.spec_code ) continue subject = f"[TempSpec Reminder] '{spec.spec_code}' expires in {remaining_days} day(s)" body = f"""
Hello,
This is an automated reminder.
Temp spec {spec.spec_code} - {spec.title} will expire on {spec.end_date.strftime('%Y-%m-%d')}.
Days remaining: {remaining_days}
Applicant: {spec.applicant}
Please sign in to the system if an extension is required.
This message was sent automatically. Please do not reply.
""" send_email(recipients, subject, body) current_app.logger.info( "Sent expiry reminder for spec %s to %d recipients.", spec.spec_code, len(recipients), )