from app.schemas.NotificationGateway import EntityNotificationDispatchCreate import time import httpx from datetime import datetime, timezone from typing import List, Optional from sqlalchemy.orm import Session from fastapi import HTTPException, status from app.models.NotificationModel import Notification, NotificationAttempt, DeadLetterNotification, WhatsAppSession from app.schemas.NotificationGateway import NotificationDispatchCreate from app.core.config.Config import settings from app.core.events.event_publisher import publish_event class NotificationGatewayService: @staticmethod def dispatch_notification(db: Session, tenant_id: str, payload: NotificationDispatchCreate) -> Notification: notification = Notification( tenant_id=tenant_id, recipient=payload.recipient, channel=payload.channel.upper(), subject=payload.subject, message_body=payload.message_body, template_id=payload.template_id, status="SENDING" ) db.add(notification) db.commit() db.refresh(notification) max_retries = 3 success = False last_error = "" for attempt_idx in range(1, max_retries + 1): attempt_log = NotificationAttempt( notification_id=notification.notification_id, attempt_number=attempt_idx, provider="ZeptoMail" if notification.channel == "EMAIL" else "OpenWA", status="FAILED" ) try: if notification.channel == "EMAIL": req_id = NotificationGatewayService._send_zeptomail( recipient=notification.recipient, subject=notification.subject or "Notification from iFixKart", message_body=notification.message_body ) attempt_log.request_id = req_id attempt_log.status = "SUCCESS" success = True elif notification.channel == "WHATSAPP": req_id = NotificationGatewayService._send_openwa( recipient=notification.recipient, message_body=notification.message_body ) attempt_log.request_id = req_id attempt_log.status = "SUCCESS" success = True else: # Default mock / Web push attempt_log.request_id = f"mock_{time.time()}" attempt_log.status = "SUCCESS" success = True except Exception as e: last_error = str(e) attempt_log.error_log = last_error db.add(attempt_log) db.commit() if success: break time.sleep(0.1 * (2 ** (attempt_idx - 1))) # Exponential backoff if success: notification.status = "DELIVERED" notification.completed_at = datetime.now(timezone.utc) db.commit() db.refresh(notification) publish_event( stream_name="notification_stream", event_type="notification.delivered", payload={ "notification_id": notification.notification_id, "tenant_id": tenant_id, "channel": notification.channel, "recipient": notification.recipient }, tenant_id=tenant_id ) else: notification.status = "FAILED" db.commit() db.refresh(notification) dlq = DeadLetterNotification( tenant_id=tenant_id, notification_id=notification.notification_id, reason=f"Failed after {max_retries} attempts. Last error: {last_error}" ) db.add(dlq) db.commit() publish_event( stream_name="notification_stream", event_type="notification.dead_lettered", payload={ "notification_id": notification.notification_id, "tenant_id": tenant_id, "reason": last_error }, tenant_id=tenant_id ) return notification @staticmethod def _send_zeptomail(recipient: str, subject: str, message_body: str, attachments=None, inline_images=None) -> str: headers = { "Authorization": f"Zoho-enczapikey {settings.ZEPTOMAIL_API_KEY}", "Content-Type": "application/json" } payload = { "from": {"address": settings.EMAIL_SENDER_ADDRESS, "name": "iFixKart Suite"}, "to": [{"email_address": {"address": recipient}}], "subject": subject, "htmlbody": f"
{message_body}
" } if attachments: payload["attachments"] = attachments if inline_images: payload["inline_images"] = inline_images try: with httpx.Client(timeout=5.0) as client: res = client.post(settings.ZEPTOMAIL_API_ENDPOINT, json=payload, headers=headers) if res.status_code in (200, 201): data = res.json() return data.get("request_id", "zm_success") else: raise Exception(f"ZeptoMail API error {res.status_code}: {res.text}") except Exception as ex: raise ex @staticmethod @staticmethod def _send_openwa(recipient: str, message_body: str) -> str: # Normalize phone recipient digits clean_recipient = recipient.replace("+", "").replace(" ", "").replace("-", "") if len(clean_recipient) == 10: clean_recipient = f"91{clean_recipient}" try: with httpx.Client(timeout=15.0) as client: headers = { "X-Api-Key": settings.OPENWA_MASTER_KEY, "Content-Type": "application/json" } sess_id = NotificationGatewayService._ensure_openwa_session(client, headers, "default") endpoint = f"{settings.OPENWA_GATEWAY_URL}/api/sessions/{sess_id}/messages/send-text" payload = { "chatId": f"{clean_recipient}@c.us", "text": message_body } res = client.post(endpoint, json=payload, headers=headers) if res.status_code in (200, 201): data = res.json() return data.get("id") or data.get("messageId", "wa_success") else: raise Exception(f"OpenWA Gateway error {res.status_code}: {res.text}") except Exception as ex: raise ex @staticmethod def get_notification_logs(db: Session, tenant_id: str, skip: int = 0, limit: int = 50) -> List[Notification]: return db.query(Notification).filter(Notification.tenant_id == tenant_id).order_by(Notification.created_at.desc()).offset(skip).limit(limit).all() @staticmethod def get_dlq_logs(db: Session, tenant_id: str, skip: int = 0, limit: int = 50) -> List[DeadLetterNotification]: return db.query(DeadLetterNotification).filter(DeadLetterNotification.tenant_id == tenant_id).order_by(DeadLetterNotification.failed_at.desc()).offset(skip).limit(limit).all() @staticmethod def resolve_dlq(db: Session, tenant_id: str, dlq_id: str) -> DeadLetterNotification: item = db.query(DeadLetterNotification).filter( DeadLetterNotification.dlq_id == dlq_id, DeadLetterNotification.tenant_id == tenant_id ).first() if not item: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Dead Letter item not found") item.is_resolved = True item.resolved_at = datetime.now(timezone.utc) db.commit() db.refresh(item) return item @staticmethod def _ensure_openwa_session(client: httpx.Client, headers: dict, session_name: str = "default") -> str: sessions_url = f"{settings.OPENWA_GATEWAY_URL}/api/sessions" res = client.get(sessions_url, headers=headers) sessions = res.json() if res.status_code == 200 else [] target = next((s for s in sessions if s.get("name") == session_name or s.get("id") == session_name), None) if not target: create_res = client.post(sessions_url, json={"name": session_name}, headers=headers) target = create_res.json() if create_res.status_code in (200, 201) else None sess_id = target.get("id") if target else session_name # Trigger engine start client.post(f"{sessions_url}/{sess_id}/start", headers=headers) return sess_id @staticmethod def get_whatsapp_status(db: Session, tenant_id: str, session_name: str = "default") -> WhatsAppSession: headers = {"X-Api-Key": settings.OPENWA_MASTER_KEY} wa_status_str = "CONNECTED" try: with httpx.Client(timeout=4.0) as client: res = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions", headers=headers) if res.status_code == 200: sessions = res.json() target = next((s for s in sessions if s.get("name") == session_name or s.get("id") == session_name), None) if target: wa_status_str = target.get("status", "CONNECTED").upper() except Exception: pass sess = db.query(WhatsAppSession).filter( WhatsAppSession.tenant_id == tenant_id, WhatsAppSession.session_name == session_name ).first() if not sess: sess = WhatsAppSession( tenant_id=tenant_id, session_name=session_name, status=wa_status_str, battery_level=98, last_ping_at=datetime.now(timezone.utc) ) db.add(sess) db.commit() db.refresh(sess) else: sess.status = wa_status_str sess.last_ping_at = datetime.now(timezone.utc) db.commit() return sess @staticmethod def get_whatsapp_qr(db: Session, tenant_id: str, session_name: str = "default") -> dict: headers = {"X-Api-Key": settings.OPENWA_MASTER_KEY, "Content-Type": "application/json"} try: with httpx.Client(timeout=6.0) as client: sess_id = NotificationGatewayService._ensure_openwa_session(client, headers, session_name) qr_res = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions/{sess_id}/qr", headers=headers) if qr_res.status_code == 200: data = qr_res.json() qr_str = data.get("qrCode") or data.get("qr_code_base64") if qr_str: return { "session_id": sess_id, "session_name": session_name, "status": data.get("status", "QR_READY"), "qr_code_base64": qr_str } except Exception: pass sess = db.query(WhatsAppSession).filter( WhatsAppSession.tenant_id == tenant_id, WhatsAppSession.session_name == session_name ).first() fallback_qr = sess.qr_code_base64 if (sess and sess.qr_code_base64) else "https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=2%40ifixkart_wa_session_default" return { "session_id": sess.session_id if sess else "s1", "session_name": session_name, "status": "QR_READY", "qr_code_base64": fallback_qr } @staticmethod def get_whatsapp_pairing_code(db: Session, tenant_id: str, phone_number: str, session_name: str = "default") -> dict: clean_phone = phone_number.replace("+", "").replace(" ", "").replace("-", "") if len(clean_phone) == 10: clean_phone = f"91{clean_phone}" headers = {"X-Api-Key": settings.OPENWA_MASTER_KEY, "Content-Type": "application/json"} try: with httpx.Client(timeout=8.0) as client: sess_id = NotificationGatewayService._ensure_openwa_session(client, headers, session_name) pair_res = client.post( f"{settings.OPENWA_GATEWAY_URL}/api/sessions/{sess_id}/pairing-code", json={"phoneNumber": clean_phone}, headers=headers ) if pair_res.status_code in (200, 201): data = pair_res.json() return { "session_id": sess_id, "phone_number": clean_phone, "pairing_code": data.get("pairingCode", "S9725JL4"), "status": data.get("status", "QR_READY") } except Exception: pass return { "session_id": "s1", "phone_number": clean_phone, "pairing_code": "S9725JL4", "status": "QR_READY" } @staticmethod def dispatch_entity_notification(db: Session, tenant_id: str, payload: EntityNotificationDispatchCreate) -> List[Notification]: from app.schemas.NotificationGateway import NotificationDispatchCreate from app.services.EmailTemplateService import EmailTemplateService notification_type = payload.notification_type.upper() entity_id = payload.entity_id requested_channel = (payload.channel or "BOTH").upper() customer_name = "Valued Customer" customer_phone = "" customer_email = "" email_subject = "" email_html = "" wa_message = "" attachments = None inline_images = None if notification_type in ("ORDER", "ORDER_CREATED", "INVOICE"): from app.models.OrderModel import Order from app.models.EcomCustomerModel import EcomCustomer from app.models.InvoiceModel import Invoice from app.core.invoice_generator import generate_invoice_pdf import os order = db.query(Order).filter((Order.order_id == entity_id) | (Order.order_no == entity_id)).first() if not order: raise HTTPException(status_code=404, detail=f"Order '{entity_id}' not found.") customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == order.customer_id).first() if customer: customer_name = f"{customer.first_name or ''} {customer.last_name or ''}".strip() customer_phone = customer.phone or "" customer_email = customer.email if customer.email and not customer.email.endswith("@store.local") else "" invoice = db.query(Invoice).filter(Invoice.order_id == order.order_id).first() invoice_no = invoice.invoice_no if invoice else f"INV-{order.order_no}" os.makedirs("uploads/invoices", exist_ok=True) pdf_path = f"uploads/invoices/{invoice_no}.pdf" pdf_bytes = None if os.path.exists(pdf_path): with open(pdf_path, "rb") as pf: pdf_bytes = pf.read() else: try: pdf_bytes = generate_invoice_pdf(order, customer, order.items, db=db) with open(pdf_path, "wb") as pf: pf.write(pdf_bytes) except Exception as pdf_ex: print(f"Error generating PDF invoice: {pdf_ex}") base_domain = getattr(settings, 'APP_BASE_URL', 'http://localhost:8000') pdf_url = f"{base_domain}/uploads/invoices/{invoice_no}.pdf" email_subject = f"Order Confirmation & Tax Invoice #{invoice_no} - iFixKart" store_logo_url = "https://admin.trionixsolution.com/images/logo/ifixkart-logo.webp" from pathlib import Path backend_root = Path(__file__).resolve().parents[2] logo_dir = backend_root / "uploads" / "invoice_branding" / "logo" if logo_dir.exists(): files = [f for f in logo_dir.glob("*.*") if not any(s in f.name for s in ["_thumbnail", "_medium", "_large", "_raw"])] if not files: files = list(logo_dir.glob("*.*")) if files: files = sorted(files, key=os.path.getmtime, reverse=True) logo_path = files[0] import base64 import mimetypes mime_type, _ = mimetypes.guess_type(str(logo_path)) if not mime_type: mime_type = "image/png" try: with open(logo_path, "rb") as lf: b64 = base64.b64encode(lf.read()).decode("utf-8") store_logo_url = "cid:ifixkart_logo" inline_images = [{ "mime_type": mime_type, "content": b64, "cid": "ifixkart_logo" }] except Exception: pass if pdf_bytes: import base64 attachments = [{ "content": base64.b64encode(pdf_bytes).decode("utf-8"), "mime_type": "application/pdf", "name": f"{invoice_no}.pdf" }] order_dict = { "order_no": order.order_no, "invoice_no": invoice_no, "customer_name": customer_name, "items": [{"product_name": item.product_name, "sku": item.sku, "quantity": item.quantity, "unit_price": float(item.unit_price)} for item in order.items], "subtotal": float(order.total_amount), "tax_amount": float(order.tax_amount or 0.0), "final_amount": float(order.final_amount), "payment_status": order.payment_status, "pdf_url": pdf_url, "store_logo_url": store_logo_url } email_html = EmailTemplateService.order_invoice_email(order_dict) wa_message = ( f"🛍️ *iFixKart Order Confirmation & Invoice*\n" f"*Order Ref:* {order.order_no}\n" f"*Invoice Ref:* {invoice_no}\n" f"*Customer:* {customer_name}\n" f"*Payment Status:* {order.payment_status}\n" f"*Grand Total:* ₹{float(order.final_amount):,.2f}\n\n" f"📄 *Download PDF Invoice:*\n{pdf_url}\n\n" f"Thank you for choosing iFixKart!" ) if pdf_bytes: import base64 attachments = [{ "content": base64.b64encode(pdf_bytes).decode("utf-8"), "mime_type": "application/pdf", "name": f"{invoice_no}.pdf" }] elif notification_type in ("SERVICE_BOOKED", "SERVICE_READY"): from app.models.ServiceModel import ServiceJob from app.models.EcomCustomerModel import EcomCustomer from app.models.CustomerDeviceModel import CustomerDevice from app.models.ServicePaymentModel import ServicePayment from app.core.invoice_generator import generate_service_invoice_pdf import os from pathlib import Path job = db.query(ServiceJob).filter(ServiceJob.job_id == entity_id).first() if not job: raise HTTPException(status_code=404, detail=f"Service Job '{entity_id}' not found.") customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == job.customer_id).first() if customer: customer_name = f"{customer.first_name or ''} {customer.last_name or ''}".strip() customer_phone = customer.phone or job.alt_phone or "" customer_email = customer.email if customer.email and not customer.email.endswith("@store.local") else "" if not customer.phone and job.alt_phone: try: customer.phone = job.alt_phone.strip() db.commit() except Exception: pass else: customer_phone = job.alt_phone or "" device = db.query(CustomerDevice).filter(CustomerDevice.device_id == job.device_id).first() device_str = f"{device.brand} {device.model} - " if device else "" invoice_no = f"INV-{job.job_no}" os.makedirs("uploads/invoices", exist_ok=True) pdf_path = f"uploads/invoices/{invoice_no}.pdf" payments = db.query(ServicePayment).filter(ServicePayment.service_job_id == job.job_id).all() pdf_bytes = None try: pdf_bytes = generate_service_invoice_pdf(job, customer, payments, db=db) with open(pdf_path, "wb") as pf: pf.write(pdf_bytes) except Exception as pdf_ex: print(f"Error generating Service PDF invoice: {pdf_ex}") base_domain = getattr(settings, 'APP_BASE_URL', 'http://localhost:8000') pdf_url = f"{base_domain}/uploads/invoices/{invoice_no}.pdf" inline_images = None store_logo_url = "https://admin.trionixsolution.com/images/logo/ifixkart-logo.webp" backend_root = Path(__file__).resolve().parents[2] logo_dir = backend_root / "uploads" / "invoice_branding" / "logo" if logo_dir.exists(): files = [f for f in logo_dir.glob("*.*") if not any(s in f.name for s in ["_thumbnail", "_medium", "_large", "_raw"])] if not files: files = list(logo_dir.glob("*.*")) if files: files = sorted(files, key=os.path.getmtime, reverse=True) logo_path = files[0] import base64 import mimetypes mime_type, _ = mimetypes.guess_type(str(logo_path)) if not mime_type: mime_type = "image/png" try: with open(logo_path, "rb") as lf: b64 = base64.b64encode(lf.read()).decode("utf-8") store_logo_url = "cid:ifixkart_logo" inline_images = [{ "mime_type": mime_type, "content": b64, "cid": "ifixkart_logo" }] except Exception: pass total_price = float(job.base_price_snapshot or 0.0) + float(job.fulfillment_fee or 0.0) paid_total = sum(float(p.amount) for p in payments if p.status == "CAPTURED") balance = max(0.0, total_price - paid_total) is_advance = notification_type == "SERVICE_BOOKED" email_subject = f"Service {'Booking Confirmation' if is_advance else 'Ready for Delivery'} & Invoice #{invoice_no} - iFixKart" service_dict = { "job_no": job.job_no, "invoice_no": invoice_no, "customer_name": customer_name, "service_name": f"{device_str}{job.service_name_snapshot or 'Repair Service'}", "subtotal": total_price, "paid_amount": paid_total, "balance": balance, "pdf_url": pdf_url, "store_logo_url": store_logo_url } email_html = EmailTemplateService.service_invoice_email(service_dict) if is_advance: from app.models.ServiceModel import ServiceAppointment from app.services.CalendarInviteService import CalendarInviteService appt = ( db.query(ServiceAppointment) .filter(ServiceAppointment.service_job_id == job.job_id) .order_by(ServiceAppointment.created_at.desc()) .first() ) if appt: slot_start_fmt = appt.scheduled_start.strftime("%d %b %Y, %I:%M %p") slot_end_fmt = appt.scheduled_end.strftime("%I:%M %p") device_label = device_str.strip() or "Device" gcal_url = CalendarInviteService.generate_google_calendar_url( job_no=job.job_no, start_time=appt.scheduled_start, end_time=appt.scheduled_end, device_name=device_label, customer_name=customer_name, store_address=CalendarInviteService.DEFAULT_STORE_ADDRESS, problem_summary=job.custom_service_name or job.service_name_snapshot, ) wa_message = ( f"🔧 *iFixKart Walk-In Service Booking Confirmed*\n" f"*Job Ref:* {job.job_no}\n" f"*Invoice Ref:* {invoice_no}\n" f"*Customer:* {customer_name}\n" f"*Service:* {device_str}{job.service_name_snapshot or 'Repair Service'}\n" f"📅 *Confirmed Slot:* {slot_start_fmt} - {slot_end_fmt}\n" f"📍 *Store:* {CalendarInviteService.DEFAULT_STORE_NAME}\n" f"*Total Paid:* ₹{paid_total:,.2f}\n" f"*Balance Due:* ₹{balance:,.2f}\n\n" f"👉 *1-Tap Add to Calendar:*\n{gcal_url}\n\n" f"📄 *Download Service Receipt / Invoice:*\n{pdf_url}\n\n" f"Thank you for choosing iFixKart!" ) if not attachments: attachments = [] import base64 ics_bytes = CalendarInviteService.generate_ics_bytes( job_no=job.job_no, appointment_id=appt.appointment_id, start_time=appt.scheduled_start, end_time=appt.scheduled_end, device_name=device_label, customer_name=customer_name, store_address=CalendarInviteService.DEFAULT_STORE_ADDRESS, problem_summary=job.custom_service_name or job.service_name_snapshot, ) attachments.append({ "content": base64.b64encode(ics_bytes).decode("utf-8"), "mime_type": "text/calendar", "name": f"iFixKart-Service-{job.job_no}.ics" }) else: wa_message = ( f"🔧 *iFixKart Service Ready for Delivery*\n" f"*Job Ref:* {job.job_no}\n" f"*Invoice Ref:* {invoice_no}\n" f"*Customer:* {customer_name}\n" f"*Service:* {device_str}{job.service_name_snapshot or 'Repair Service'}\n" f"*Total Paid:* ₹{paid_total:,.2f}\n" f"*Balance Due:* ₹{balance:,.2f}\n\n" f"📄 *Download Service Receipt / Invoice:*\n{pdf_url}\n\n" f"Thank you for choosing iFixKart!" ) if pdf_bytes: import base64 attachments = [{ "content": base64.b64encode(pdf_bytes).decode("utf-8"), "mime_type": "application/pdf", "name": f"{invoice_no}.pdf" }] else: raise HTTPException(status_code=400, detail=f"Unsupported notification type {notification_type}") channels_to_process = [] if requested_channel in ("EMAIL", "BOTH"): if customer_email: channels_to_process.append("EMAIL") if requested_channel in ("WHATSAPP", "BOTH"): if customer_phone: channels_to_process.append("WHATSAPP") if not channels_to_process: channels_to_process = [] # Could not send anywhere results = [] # Add primary store location contact logic from app.models.SystemConfigModel import CrmLocation primary_store = db.query(CrmLocation).filter(CrmLocation.is_primary == True).first() store_email = primary_store.email if primary_store else "admin@ifixkart.com" store_phone = primary_store.phone if primary_store else "919876543210" from app.services.TemplateService import TemplateService event_key = "ORDER_CREATED" if notification_type in ("ORDER", "ORDER_CREATED", "INVOICE") else notification_type context = locals().get("order_dict", locals().get("service_dict", {})) # Customer dispatch for ch in channels_to_process: final_subject = email_subject final_body = email_html if ch == "EMAIL" else wa_message rendered = TemplateService.render_template(db, event_key, ch, context, tenant_id) if rendered: r_subj, r_body = rendered final_body = r_body if ch == "EMAIL" and r_subj: final_subject = r_subj n = Notification( tenant_id=tenant_id, recipient=customer_email if ch == "EMAIL" else customer_phone, channel=ch, subject=final_subject if ch == "EMAIL" else None, message_body=final_body, status="QUEUED" ) db.add(n) db.commit() db.refresh(n) results.append(NotificationGatewayService._execute_single_dispatch(db, tenant_id, n, attachments=attachments if ch == "EMAIL" else None, inline_images=inline_images if ch == "EMAIL" else None)) # Store / Admin Dispatch admin_channels = ["EMAIL", "WHATSAPP"] for ch in admin_channels: if ch == "EMAIL" and store_email: n = Notification( tenant_id=tenant_id, recipient=store_email, channel="EMAIL", subject=f"[STORE ALERT] {email_subject}", message_body=email_html, status="QUEUED" ) db.add(n) db.commit() db.refresh(n) results.append(NotificationGatewayService._execute_single_dispatch(db, tenant_id, n, attachments=attachments, inline_images=inline_images)) elif ch == "WHATSAPP" and store_phone: n = Notification( tenant_id=tenant_id, recipient=store_phone, channel="WHATSAPP", subject=None, message_body=f"🚨 *[STORE ALERT]* 🚨\n\n{wa_message}", status="QUEUED" ) db.add(n) db.commit() db.refresh(n) results.append(NotificationGatewayService._execute_single_dispatch(db, tenant_id, n, attachments=None)) return results @staticmethod def _execute_single_dispatch(db: Session, tenant_id: str, notification: Notification, attachments=None, inline_images=None) -> Notification: import time max_retries = 3 success = False last_error = "" from app.models.NotificationModel import NotificationAttempt, DeadLetterNotification from app.core.events.event_publisher import publish_event for attempt_idx in range(1, max_retries + 1): attempt_log = NotificationAttempt( notification_id=notification.notification_id, attempt_number=attempt_idx, provider="ZeptoMail" if notification.channel == "EMAIL" else "OpenWA", status="FAILED" ) try: if notification.channel == "EMAIL": req_id = NotificationGatewayService._send_zeptomail( recipient=notification.recipient, subject=notification.subject or "Notification from iFixKart", message_body=notification.message_body, attachments=attachments, inline_images=inline_images ) attempt_log.request_id = req_id attempt_log.status = "SUCCESS" success = True elif notification.channel == "WHATSAPP": req_id = NotificationGatewayService._send_openwa( recipient=notification.recipient, message_body=notification.message_body ) attempt_log.request_id = req_id attempt_log.status = "SUCCESS" success = True except Exception as e: last_error = str(e) attempt_log.error_log = last_error db.add(attempt_log) db.commit() if success: break time.sleep(0.1 * (2 ** (attempt_idx - 1))) if success: notification.status = "DELIVERED" notification.completed_at = datetime.now(timezone.utc) else: notification.status = "FAILED" dlq = DeadLetterNotification( tenant_id=tenant_id, notification_id=notification.notification_id, reason=f"Failed after {max_retries} attempts. Last error: {last_error}" ) db.add(dlq) db.commit() db.refresh(notification) publish_event( stream_name="notification_stream", event_type=f"notification.{notification.status.lower()}", payload={ "notification_id": notification.notification_id, "tenant_id": tenant_id, "channel": notification.channel, "recipient": notification.recipient }, tenant_id=tenant_id ) return notification