|
1 | 1 | # email_sender.py
|
2 | 2 | # Path: appointment/email_sender/email_sender.py
|
3 | 3 | import os
|
| 4 | +from datetime import datetime, timedelta |
| 5 | +from typing import Any, Optional, Tuple |
4 | 6 |
|
5 | 7 | from django.conf import settings
|
6 | 8 | from django.core.mail import send_mail
|
7 | 9 | from django.template import loader
|
| 10 | +from django.utils import timezone |
8 | 11 |
|
9 | 12 | from appointment.logger_config import get_logger
|
10 | 13 | from appointment.settings import APP_DEFAULT_FROM_EMAIL, check_q_cluster
|
11 | 14 |
|
12 | 15 | logger = get_logger(__name__)
|
13 | 16 |
|
14 | 17 | try:
|
15 |
| - from django_q.tasks import async_task |
| 18 | + from django_q.tasks import async_task, schedule |
| 19 | + from django_q.models import Schedule |
| 20 | + |
16 | 21 |
|
17 | 22 | DJANGO_Q_AVAILABLE = True
|
18 | 23 | except ImportError:
|
19 | 24 | async_task = None
|
| 25 | + schedule = None |
| 26 | + Schedule = None |
| 27 | + |
20 | 28 | DJANGO_Q_AVAILABLE = False
|
21 | 29 | logger.warning("django-q is not installed. Email will be sent synchronously.")
|
22 | 30 |
|
@@ -87,6 +95,146 @@ def send_email(recipient_list, subject: str, template_url: str = None, context:
|
87 | 95 | logger.error(f"Error sending email: {e}")
|
88 | 96 |
|
89 | 97 |
|
| 98 | +def validate_required_fields(recipient_list: list, subject: str) -> Tuple[bool, str]: |
| 99 | + if not recipient_list or not subject: |
| 100 | + return False, "Recipient list and subject are required." |
| 101 | + return True, "" |
| 102 | + |
| 103 | + |
| 104 | +def validate_and_process_datetime(dt: Optional[datetime], field_name: str) -> Tuple[bool, str, Optional[datetime]]: |
| 105 | + if not dt: |
| 106 | + return True, "", None |
| 107 | + |
| 108 | + if not isinstance(dt, datetime): |
| 109 | + try: |
| 110 | + dt = datetime.fromisoformat(dt) |
| 111 | + except ValueError: |
| 112 | + return False, f"Invalid {field_name} format. Use ISO format or datetime object.", None |
| 113 | + |
| 114 | + if dt.tzinfo is None: |
| 115 | + dt = timezone.make_aware(dt) |
| 116 | + |
| 117 | + return True, "", dt |
| 118 | + |
| 119 | + |
| 120 | +def validate_send_at(send_at: Optional[datetime]) -> tuple[bool, str, None] | tuple[ |
| 121 | + bool, str, datetime | None | timedelta | Any]: |
| 122 | + success, message, processed_send_at = validate_and_process_datetime(send_at, "send_at") |
| 123 | + if not success: |
| 124 | + return success, message, None |
| 125 | + |
| 126 | + if processed_send_at and processed_send_at <= timezone.now(): |
| 127 | + return False, "send_at must be in the future.", None |
| 128 | + |
| 129 | + return True, "", processed_send_at or (timezone.now() + timedelta(minutes=1)) |
| 130 | + |
| 131 | + |
| 132 | +def validate_repeat_until(repeat_until: Optional[datetime], send_at: datetime) -> Tuple[bool, str, Optional[datetime]]: |
| 133 | + success, message, processed_repeat_until = validate_and_process_datetime(repeat_until, "repeat_until") |
| 134 | + if not success: |
| 135 | + return success, message, None |
| 136 | + |
| 137 | + if processed_repeat_until and processed_repeat_until <= send_at: |
| 138 | + return False, "repeat_until must be after send_at.", None |
| 139 | + |
| 140 | + return True, "", processed_repeat_until |
| 141 | + |
| 142 | + |
| 143 | +def validate_repeat_option(repeat: Optional[str]) -> Tuple[bool, str, Optional[str]]: |
| 144 | + valid_options = ['HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY', 'QUARTERLY', 'YEARLY'] |
| 145 | + if repeat and repeat not in valid_options: |
| 146 | + return False, f"Invalid repeat option. Choose from {', '.join(valid_options)}.", None |
| 147 | + return True, "", repeat |
| 148 | + |
| 149 | + |
| 150 | +def schedule_email_task( |
| 151 | + recipient_list: list, |
| 152 | + subject: str, |
| 153 | + html_message: str, |
| 154 | + from_email: str, |
| 155 | + attachments: Optional[list], |
| 156 | + schedule_type: str, |
| 157 | + send_at: datetime, |
| 158 | + name: Optional[str], |
| 159 | + repeat_until: Optional[datetime] |
| 160 | +) -> Tuple[bool, str]: |
| 161 | + try: |
| 162 | + schedule( |
| 163 | + 'appointment.tasks.send_email_task', |
| 164 | + recipient_list=recipient_list, |
| 165 | + subject=subject, |
| 166 | + message=None, |
| 167 | + html_message=html_message, |
| 168 | + from_email=from_email, |
| 169 | + attachments=attachments, |
| 170 | + schedule_type=schedule_type, |
| 171 | + next_run=send_at, |
| 172 | + name=name, |
| 173 | + repeats=-1 if schedule_type != Schedule.ONCE and not repeat_until else None, |
| 174 | + end_date=repeat_until |
| 175 | + ) |
| 176 | + return True, "Email scheduled successfully." |
| 177 | + except Exception as e: |
| 178 | + logger.error(f"Error scheduling email: {e}") |
| 179 | + return False, f"Error scheduling email: {str(e)}" |
| 180 | + |
| 181 | + |
| 182 | +def schedule_email_sending( |
| 183 | + recipient_list: list, |
| 184 | + subject: str, |
| 185 | + template_url: Optional[str] = None, |
| 186 | + context: Optional[dict] = None, |
| 187 | + from_email: Optional[str] = None, |
| 188 | + attachments: Optional[list] = None, |
| 189 | + send_at: Optional[datetime] = None, |
| 190 | + name: Optional[str] = None, |
| 191 | + repeat: Optional[str] = None, |
| 192 | + repeat_until: Optional[datetime] = None |
| 193 | +) -> Tuple[bool, str]: |
| 194 | + if not has_required_email_settings(): |
| 195 | + return False, "Email settings are not configured." |
| 196 | + |
| 197 | + if not check_q_cluster() or not DJANGO_Q_AVAILABLE: |
| 198 | + return False, "Django-Q is not available." |
| 199 | + |
| 200 | + # Validate required fields |
| 201 | + success, message = validate_required_fields(recipient_list, subject) |
| 202 | + if not success: |
| 203 | + return success, message |
| 204 | + |
| 205 | + # Validate and process send_at |
| 206 | + success, message, processed_send_at = validate_send_at(send_at) |
| 207 | + if not success: |
| 208 | + return success, message |
| 209 | + |
| 210 | + # Validate repeat option |
| 211 | + success, message, validated_repeat = validate_repeat_option(repeat) |
| 212 | + if not success: |
| 213 | + return success, message |
| 214 | + |
| 215 | + # Validate repeat_until |
| 216 | + success, message, processed_repeat_until = validate_repeat_until(repeat_until, processed_send_at) |
| 217 | + if not success: |
| 218 | + return success, message |
| 219 | + |
| 220 | + from_email = from_email or APP_DEFAULT_FROM_EMAIL |
| 221 | + html_message = render_email_template(template_url, context) |
| 222 | + |
| 223 | + schedule_type = getattr(Schedule, validated_repeat or 'ONCE') |
| 224 | + |
| 225 | + return schedule_email_task( |
| 226 | + recipient_list, |
| 227 | + subject, |
| 228 | + html_message, |
| 229 | + from_email, |
| 230 | + attachments, |
| 231 | + schedule_type, |
| 232 | + processed_send_at, |
| 233 | + name, |
| 234 | + processed_repeat_until |
| 235 | + ) |
| 236 | + |
| 237 | + |
90 | 238 | def notify_admin(subject: str, template_url: str = None, context: dict = None, message: str = None,
|
91 | 239 | recipient_email: str = None, attachments=None):
|
92 | 240 | if not has_required_email_settings():
|
|
0 commit comments