Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
send_notification.py · 5.6 KB · 151 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | AI-Generated Service: send_notification |
| 4 | Description: Send order confirmation emails and SMS notifications |
| 5 | Generated: 2025-09-19T10:31:00.000000 |
| 6 | """ |
| 7 | |
| 8 | from typing import Dict, Any, List, Optional |
| 9 | import json |
| 10 | from datetime import datetime |
| 11 | import random |
| 12 | import hashlib |
| 13 | |
| 14 | async def send_notification(data: Dict[str, Any]) -> Dict[str, Any]: |
| 15 | """ |
| 16 | Send various types of notifications (email, SMS, push) based on event type. |
| 17 | |
| 18 | Inputs: notification_type, recipient, subject, message, order_data, priority |
| 19 | Outputs: notification_id, status, delivery_time, channel_used, queued_for_retry |
| 20 | """ |
| 21 | |
| 22 | try: |
| 23 | # Extract inputs |
| 24 | notification_type = data.get('notification_type', 'email') |
| 25 | recipient = data.get('recipient', {}) |
| 26 | subject = data.get('subject', 'Notification from DBBasic') |
| 27 | message = data.get('message', '') |
| 28 | order_data = data.get('order_data', {}) |
| 29 | priority = data.get('priority', 'normal') |
| 30 | |
| 31 | # Generate notification ID |
| 32 | timestamp = datetime.now().isoformat() |
| 33 | notification_id = hashlib.md5(f"{timestamp}{recipient}".encode()).hexdigest()[:12] |
| 34 | |
| 35 | # Determine recipient channels |
| 36 | channels_available = [] |
| 37 | if recipient.get('email'): |
| 38 | channels_available.append('email') |
| 39 | if recipient.get('phone'): |
| 40 | channels_available.append('sms') |
| 41 | if recipient.get('device_token'): |
| 42 | channels_available.append('push') |
| 43 | if recipient.get('slack_webhook'): |
| 44 | channels_available.append('slack') |
| 45 | |
| 46 | # Select best channel based on priority and type |
| 47 | channel_used = notification_type |
| 48 | if priority == 'urgent' and 'sms' in channels_available: |
| 49 | channel_used = 'sms' |
| 50 | elif priority == 'high' and 'push' in channels_available: |
| 51 | channel_used = 'push' |
| 52 | elif notification_type not in channels_available and channels_available: |
| 53 | channel_used = channels_available[0] |
| 54 | |
| 55 | # Build notification content based on type |
| 56 | if order_data: |
| 57 | order_id = order_data.get('order_id', 'N/A') |
| 58 | total = order_data.get('total', 0) |
| 59 | items_count = len(order_data.get('items', [])) |
| 60 | |
| 61 | if not message: |
| 62 | if notification_type == 'order_confirmation': |
| 63 | message = f"Your order #{order_id} for ${total:.2f} ({items_count} items) has been confirmed." |
| 64 | elif notification_type == 'shipping_update': |
| 65 | tracking = order_data.get('tracking_number', 'TRACK123') |
| 66 | message = f"Your order #{order_id} has shipped! Track it: {tracking}" |
| 67 | elif notification_type == 'delivery_confirmation': |
| 68 | message = f"Your order #{order_id} has been delivered successfully." |
| 69 | |
| 70 | # Simulate delivery time based on channel |
| 71 | delivery_times = { |
| 72 | 'email': random.uniform(0.5, 2.0), |
| 73 | 'sms': random.uniform(0.1, 0.5), |
| 74 | 'push': random.uniform(0.05, 0.2), |
| 75 | 'slack': random.uniform(0.2, 0.8) |
| 76 | } |
| 77 | delivery_time = delivery_times.get(channel_used, 1.0) |
| 78 | |
| 79 | # Check for delivery issues (simulated) |
| 80 | delivery_status = 'delivered' |
| 81 | queued_for_retry = False |
| 82 | |
| 83 | # Simulate occasional delivery issues |
| 84 | if random.random() < 0.05: # 5% failure rate |
| 85 | if channel_used == 'email': |
| 86 | delivery_status = 'bounced' |
| 87 | queued_for_retry = True |
| 88 | elif channel_used == 'sms': |
| 89 | delivery_status = 'failed' |
| 90 | queued_for_retry = True |
| 91 | |
| 92 | # Build notification log entry |
| 93 | log_entry = { |
| 94 | 'notification_id': notification_id, |
| 95 | 'type': notification_type, |
| 96 | 'channel': channel_used, |
| 97 | 'recipient': recipient.get(channel_used) or recipient.get('email') or 'unknown', |
| 98 | 'subject': subject, |
| 99 | 'priority': priority, |
| 100 | 'timestamp': timestamp |
| 101 | } |
| 102 | |
| 103 | result = { |
| 104 | 'notification_id': notification_id, |
| 105 | 'status': delivery_status, |
| 106 | 'delivery_time_ms': round(delivery_time * 1000, 2), |
| 107 | 'channel_used': channel_used, |
| 108 | 'queued_for_retry': queued_for_retry, |
| 109 | 'recipient': recipient.get(channel_used) or recipient.get('email'), |
| 110 | 'message_preview': message[:100] + '...' if len(message) > 100 else message, |
| 111 | 'log_entry': log_entry |
| 112 | } |
| 113 | |
| 114 | # Add delivery receipt if successful |
| 115 | if delivery_status == 'delivered': |
| 116 | result['delivery_receipt'] = { |
| 117 | 'delivered_at': datetime.now().isoformat(), |
| 118 | 'provider': { |
| 119 | 'email': 'SendGrid', |
| 120 | 'sms': 'Twilio', |
| 121 | 'push': 'Firebase', |
| 122 | 'slack': 'Slack API' |
| 123 | }.get(channel_used, 'Internal'), |
| 124 | 'cost': { |
| 125 | 'email': 0.001, |
| 126 | 'sms': 0.0075, |
| 127 | 'push': 0.0001, |
| 128 | 'slack': 0 |
| 129 | }.get(channel_used, 0) |
| 130 | } |
| 131 | |
| 132 | return { |
| 133 | "success": True, |
| 134 | "timestamp": datetime.now().isoformat(), |
| 135 | "data": result |
| 136 | } |
| 137 | |
| 138 | except Exception as e: |
| 139 | return { |
| 140 | "success": False, |
| 141 | "error": str(e), |
| 142 | "timestamp": datetime.now().isoformat() |
| 143 | } |
| 144 | |
| 145 | # Synchronous wrapper |
| 146 | def send_notification_sync(data: Dict[str, Any]) -> Dict[str, Any]: |
| 147 | """Synchronous wrapper for the async function""" |
| 148 | import asyncio |
| 149 | return asyncio.run(send_notification(data)) |
| 150 | |
| 151 | __all__ = ['send_notification', 'send_notification_sync'] |