from datetime import date, timedelta from models import TempSpec from utils import send_email from ldap_utils import get_ldap_group_members def check_expiring_specs(app): """ 每日執行的排程任務:檢查即將到期的暫規並發送提醒郵件。 """ with app.app_context(): print("Running scheduled task: Checking for expiring specs...") today = date.today() seven_days_later = today + timedelta(days=7) three_days_later = today + timedelta(days=3) # 找出 7 天後 和 3 天後到期的暫規 expiring_soon = TempSpec.query.filter( TempSpec.status == 'active', TempSpec.end_date.in_([seven_days_later, three_days_later]) ).all() if not expiring_soon: print("No specs expiring in 3 or 7 days.") return # 定義預設的通知對象 # 可以根據需要修改群組名稱 default_recipients = get_ldap_group_members('TempSpec_Admins') if not default_recipients: print("Warning: Could not find default recipients in AD group 'TempSpec_Admins'.") # 如果找不到預設群組,可以設定備用收件人 default_recipients = ['admin@example.com'] # 請根據實際情況修改 for spec in expiring_soon: remaining_days = (spec.end_date - today).days # 組合通知郵件 subject = f"[暫規到期提醒] 規範 '{spec.spec_code}' 將於 {remaining_days} 天後到期" body = f"""

您好,

此為自動提醒郵件。

暫時規範 {spec.spec_code} - {spec.title} 即將到期。

結束日期: {spec.end_date.strftime('%Y-%m-%d')} (剩餘 {remaining_days} 天)

申請人: {spec.applicant}

請及時處理,如需展延請登入系統操作。

此為系統自動發送的通知郵件,請勿直接回覆。

""" # 發送郵件給預設群組 send_email(default_recipients, subject, body) print(f"Sent expiry reminder for spec {spec.spec_code} to {len(default_recipients)} recipients.")