|
| 1 | +import logging |
| 2 | +import uuid |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +from django.contrib.auth.models import User |
| 6 | +from django.db.models import Count |
| 7 | +from django.template.loader import render_to_string |
| 8 | +from django.utils import timezone |
| 9 | + |
| 10 | +from alert_system.models import AlertEmailLog, AlertEmailThread, LoadItem |
| 11 | +from alert_system.utils import get_alert_email_context, get_alert_subscriptions |
| 12 | +from notifications.models import AlertSubscription |
| 13 | +from notifications.notification import send_notification |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +DEFAULT_ALERT_PER_DAY = 100 |
| 18 | + |
| 19 | + |
| 20 | +def send_alert_email_notification( |
| 21 | + load_item: LoadItem, |
| 22 | + user: User, |
| 23 | + subscription: AlertSubscription, |
| 24 | + thread: Optional[AlertEmailThread], |
| 25 | + is_reply: bool = False, |
| 26 | +) -> None: |
| 27 | + """Helper function to send email and create log entry""" |
| 28 | + message_id: str = str(uuid.uuid4()) |
| 29 | + |
| 30 | + email_log = AlertEmailLog.objects.create( |
| 31 | + user=user, |
| 32 | + subscription=subscription, |
| 33 | + item=load_item, |
| 34 | + status=AlertEmailLog.Status.PROCESSING, |
| 35 | + message_id=message_id, |
| 36 | + thread=thread, |
| 37 | + ) |
| 38 | + |
| 39 | + try: |
| 40 | + if is_reply: |
| 41 | + subject = f"Re: Hazard Alert: {load_item.event_title}" |
| 42 | + template = "email/alert_system/alert_notification_reply.html" |
| 43 | + email_type = "Alert Email Notification Reply" |
| 44 | + in_reply_to = thread.root_email_message_id |
| 45 | + else: |
| 46 | + subject = f"New Hazard Alert: {load_item.event_title}" |
| 47 | + template = "email/alert_system/alert_notification.html" |
| 48 | + email_type = "Alert Email Notification" |
| 49 | + in_reply_to = None |
| 50 | + |
| 51 | + email_context = get_alert_email_context(load_item, user) |
| 52 | + email_body = render_to_string(template, email_context) |
| 53 | + send_notification( |
| 54 | + subject=subject, |
| 55 | + recipients=[user.email], |
| 56 | + message_id=message_id, |
| 57 | + in_reply_to=in_reply_to, |
| 58 | + html=email_body, |
| 59 | + mailtype=email_type, |
| 60 | + ) |
| 61 | + # Create thread for initial emails |
| 62 | + email_log.status = AlertEmailLog.Status.SENT |
| 63 | + email_log.email_sent_at = timezone.now() |
| 64 | + |
| 65 | + if not is_reply: |
| 66 | + thread, created = AlertEmailThread.objects.get_or_create( |
| 67 | + user=user, |
| 68 | + parent_event_id=load_item.parent_event_id, |
| 69 | + defaults={ |
| 70 | + "root_email_message_id": message_id, |
| 71 | + "root_message_sent_at": timezone.now(), |
| 72 | + }, |
| 73 | + ) |
| 74 | + email_log.thread = thread |
| 75 | + email_log.save(update_fields=["status", "email_sent_at", "thread"]) |
| 76 | + |
| 77 | + if created: |
| 78 | + logger.info( |
| 79 | + f"Alert Email thread created for user [{user.get_full_name()}] " |
| 80 | + f"with parent event [{load_item.parent_event_id}]" |
| 81 | + ) |
| 82 | + else: |
| 83 | + logger.info( |
| 84 | + f"Existing thread found for user [{user.get_full_name()}] " f"with parent event [{load_item.parent_event_id}]" |
| 85 | + ) |
| 86 | + else: |
| 87 | + email_log.save(update_fields=["status", "email_sent_at"]) |
| 88 | + logger.info(f"Alert email sent to [{user.get_full_name()}] for LoadItem ID [{load_item.id}]") |
| 89 | + |
| 90 | + except Exception: |
| 91 | + email_log.status = AlertEmailLog.Status.FAILED |
| 92 | + email_log.save(update_fields=["status"]) |
| 93 | + logger.warning(f"Alert email failed for [{user.get_full_name()}] LoadItem ID [{load_item.id}]", exc_info=True) |
| 94 | + |
| 95 | + |
| 96 | +def process_email_alert(load_item_id: int) -> None: |
| 97 | + load_item = LoadItem.objects.select_related("connector", "connector__dtype").filter(id=load_item_id).first() |
| 98 | + |
| 99 | + if not load_item: |
| 100 | + logger.warning(f"LoadItem with ID [{load_item_id}] not found") |
| 101 | + return |
| 102 | + |
| 103 | + subscriptions = list(get_alert_subscriptions(load_item)) |
| 104 | + if not subscriptions: |
| 105 | + logger.info(f"No alert subscriptions matched for LoadItem ID [{load_item_id}]") |
| 106 | + return |
| 107 | + |
| 108 | + today = timezone.now().date() |
| 109 | + user_ids = [sub.user_id for sub in subscriptions] |
| 110 | + subscription_ids = [sub.id for sub in subscriptions] |
| 111 | + |
| 112 | + # Daily email counts per user |
| 113 | + daily_counts = ( |
| 114 | + AlertEmailLog.objects.filter( |
| 115 | + user_id__in=user_ids, |
| 116 | + subscription_id__in=subscription_ids, |
| 117 | + status=AlertEmailLog.Status.SENT, |
| 118 | + email_sent_at__date=today, |
| 119 | + ) |
| 120 | + .values("user_id", "subscription_id") |
| 121 | + .annotate(sent_count=Count("id")) |
| 122 | + ) |
| 123 | + daily_count_map = {(item["user_id"], item["subscription_id"]): item["sent_count"] for item in daily_counts} |
| 124 | + |
| 125 | + # Emails already sent for this item (per user) |
| 126 | + already_sent = set( |
| 127 | + AlertEmailLog.objects.filter( |
| 128 | + user_id__in=user_ids, |
| 129 | + subscription_id__in=subscription_ids, |
| 130 | + item_id=load_item_id, |
| 131 | + status=AlertEmailLog.Status.SENT, |
| 132 | + ).values_list("user_id", "subscription_id") |
| 133 | + ) |
| 134 | + |
| 135 | + # Existing threads for this correlation_id |
| 136 | + existing_threads = { |
| 137 | + thread.user_id: thread |
| 138 | + for thread in AlertEmailThread.objects.filter( |
| 139 | + parent_event_id=load_item.parent_event_id, |
| 140 | + user_id__in=user_ids, |
| 141 | + ) |
| 142 | + } |
| 143 | + |
| 144 | + for subscription in subscriptions: |
| 145 | + user = subscription.user |
| 146 | + user_id: int = user.id |
| 147 | + subscription_id: int = subscription.id |
| 148 | + |
| 149 | + # Reply if this specific user has an existing thread |
| 150 | + thread = existing_threads.get(user_id) |
| 151 | + is_reply: bool = thread is not None |
| 152 | + |
| 153 | + # Skip duplicate emails for same item |
| 154 | + if (user_id, subscription_id) in already_sent: |
| 155 | + logger.info(f"Duplicate alert skipped for user [{user.get_full_name()}] " f"with LoadItem ID [{load_item_id}]") |
| 156 | + continue |
| 157 | + |
| 158 | + # Skip if daily alert limit reached |
| 159 | + sent_today: int = daily_count_map.get((user_id, subscription_id), 0) |
| 160 | + effective_limit = subscription.alert_per_day or DEFAULT_ALERT_PER_DAY |
| 161 | + if sent_today >= effective_limit: |
| 162 | + logger.info(f"Daily alert limit reached for user [{user.get_full_name()}]") |
| 163 | + continue |
| 164 | + |
| 165 | + send_alert_email_notification(load_item=load_item, user=user, subscription=subscription, thread=thread, is_reply=is_reply) |
0 commit comments