63 lines
2.3 KiB
Python
63 lines
2.3 KiB
Python
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"""
|
|
<html>
|
|
<body>
|
|
<p>Hello,</p>
|
|
<p>This is an automated reminder.</p>
|
|
<p>Temp spec <b>{spec.spec_code} - {spec.title}</b> will expire on {spec.end_date.strftime('%Y-%m-%d')}.</p>
|
|
<p><b>Days remaining: {remaining_days}</b></p>
|
|
<p>Applicant: {spec.applicant}</p>
|
|
<p>Please sign in to the system if an extension is required.</p>
|
|
<p>This message was sent automatically. Please do not reply.</p>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
send_email(recipients, subject, body)
|
|
current_app.logger.info(
|
|
"Sent expiry reminder for spec %s to %d recipients.",
|
|
spec.spec_code,
|
|
len(recipients),
|
|
)
|
|
|