639 lines
21 KiB
Markdown
639 lines
21 KiB
Markdown
# Subtask: Notification System
|
|
|
|
**Parent Task**: Decomp/004
|
|
**Subtask ID**: Decomp/004-08
|
|
**Dependencies**: Decomp-004-01 (Database Schema), Decomp-004-05 (Order Workflow Engine)
|
|
|
|
## Description
|
|
|
|
Implement notification system for order-related events. Support email, SMS, and push notifications. Handle templates, delivery tracking, and retry logic for failed notifications.
|
|
|
|
## Requirements
|
|
|
|
- Email notifications for order events
|
|
- SMS notifications for shipping/delivery
|
|
- Template-based message generation
|
|
- Notification delivery tracking
|
|
- Retry logic for failed notifications
|
|
- Unsubscribe handling
|
|
- Multi-language support
|
|
- Webhook notifications for external systems
|
|
|
|
## Technical Specifications
|
|
|
|
**Notification service**:
|
|
```python
|
|
from abc import ABC, abstractmethod
|
|
from typing import List, Optional, Dict, Any
|
|
from dataclasses import dataclass
|
|
from enum import Enum
|
|
import logging
|
|
import asyncio
|
|
from datetime import datetime, timezone, timedelta
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class NotificationType(Enum):
|
|
"""Types of notifications."""
|
|
EMAIL = "email"
|
|
SMS = "sms"
|
|
PUSH = "push"
|
|
WEBHOOK = "webhook"
|
|
|
|
class NotificationStatus(Enum):
|
|
"""Notification delivery status."""
|
|
PENDING = "pending"
|
|
SENT = "sent"
|
|
FAILED = "failed"
|
|
BOUNCED = "bounced"
|
|
|
|
class NotificationEvent(Enum):
|
|
"""Order-related events that trigger notifications."""
|
|
ORDER_CREATED = "order_created"
|
|
ORDER_CONFIRMED = "order_confirmed"
|
|
PAYMENT_RECEIVED = "payment_received"
|
|
PAYMENT_FAILED = "payment_failed"
|
|
ORDER_SHIPPED = "order_shipped"
|
|
ORDER_DELIVERED = "order_delivered"
|
|
ORDER_CANCELLED = "order_cancelled"
|
|
REFUND_PROCESSED = "refund_processed"
|
|
|
|
@dataclass
|
|
class NotificationMessage:
|
|
"""Notification message."""
|
|
recipient: str # Email or phone
|
|
type: NotificationType
|
|
subject: str = None
|
|
body: str = None
|
|
template: str = None
|
|
variables: Dict[str, Any] = None
|
|
metadata: Dict[str, Any] = None
|
|
|
|
@dataclass
|
|
class NotificationResult:
|
|
"""Result of notification send."""
|
|
success: bool
|
|
notification_id: int = None
|
|
error: str = None
|
|
|
|
class NotificationChannel(ABC):
|
|
"""Abstract base for notification channels."""
|
|
|
|
@abstractmethod
|
|
async def send(self, message: NotificationMessage) -> NotificationResult:
|
|
"""Send notification."""
|
|
pass
|
|
|
|
@abstractmethod
|
|
def validate_recipient(self, recipient: str) -> bool:
|
|
"""Validate recipient address."""
|
|
pass
|
|
```
|
|
|
|
**Email channel implementation**:
|
|
```python
|
|
import aiosmtplib
|
|
from email.message import EmailMessage
|
|
from string import Template
|
|
|
|
class EmailChannel(NotificationChannel):
|
|
"""Email notification channel."""
|
|
|
|
def __init__(
|
|
self,
|
|
smtp_host: str,
|
|
smtp_port: int,
|
|
username: str,
|
|
password: str,
|
|
from_email: str,
|
|
from_name: str = None
|
|
):
|
|
self.smtp_host = smtp_host
|
|
self.smtp_port = smtp_port
|
|
self.username = username
|
|
self.password = password
|
|
self.from_email = from_email
|
|
self.from_name = from_name or "Store"
|
|
self.templates = self._load_templates()
|
|
|
|
def _load_templates(self) -> Dict[str, Template]:
|
|
"""Load email templates."""
|
|
return {
|
|
"order_confirmation": Template(self._get_template("order_confirmation")),
|
|
"payment_received": Template(self._get_template("payment_received")),
|
|
"order_shipped": Template(self._get_template("order_shipped")),
|
|
"order_delivered": Template(self._get_template("order_delivered")),
|
|
"order_cancelled": Template(self._get_template("order_cancelled")),
|
|
"refund_processed": Template(self._get_template("refund_processed")),
|
|
}
|
|
|
|
def _get_template(self, name: str) -> str:
|
|
"""Get template content (in production, load from files)."""
|
|
templates = {
|
|
"order_confirmation": """
|
|
Subject: Order Confirmation - Order #$order_number
|
|
|
|
Dear $customer_name,
|
|
|
|
Thank you for your order!
|
|
|
|
Order: #$order_number
|
|
Total: $total_amount
|
|
|
|
We'll send another email when your order ships.
|
|
|
|
Thank you for shopping with us!
|
|
""",
|
|
"payment_received": """
|
|
Subject: Payment Confirmation - Order #$order_number
|
|
|
|
Dear $customer_name,
|
|
|
|
Your payment of $amount has been received for order #$order_number.
|
|
|
|
Your order is being prepared for shipment.
|
|
""",
|
|
"order_shipped": """
|
|
Subject: Your Order Has Shipped - Order #$order_number
|
|
|
|
Dear $customer_name,
|
|
|
|
Good news! Your order has shipped.
|
|
|
|
Tracking Number: $tracking_number
|
|
Carrier: $carrier
|
|
|
|
Estimated Delivery: $estimated_delivery
|
|
|
|
Track your package: $tracking_url
|
|
""",
|
|
"order_delivered": """
|
|
Subject: Order Delivered - Order #$order_number
|
|
|
|
Dear $customer_name,
|
|
|
|
Your order has been delivered!
|
|
|
|
We hope you enjoy your purchase. If you have any issues, please contact us.
|
|
""",
|
|
"order_cancelled": """
|
|
Subject: Order Cancelled - Order #$order_number
|
|
|
|
Dear $customer_name,
|
|
|
|
Your order #$order_number has been cancelled.
|
|
|
|
If you paid, a refund will be processed to your original payment method.
|
|
|
|
Reason: $reason
|
|
""",
|
|
"refund_processed": """
|
|
Subject: Refund Processed - Order #$order_number
|
|
|
|
Dear $customer_name,
|
|
|
|
A refund of $amount has been processed for order #$order_number.
|
|
|
|
The refund should appear on your statement within 3-5 business days.
|
|
"""
|
|
}
|
|
return templates.get(name, "")
|
|
|
|
async def send(self, message: NotificationMessage) -> NotificationResult:
|
|
"""Send email notification."""
|
|
try:
|
|
# Generate content from template
|
|
if message.template and message.variables:
|
|
template = self.templates.get(message.template)
|
|
if template:
|
|
content = template.safe_substitute(**message.variables)
|
|
# Parse subject and body
|
|
lines = content.strip().split('\n')
|
|
subject = next((l[8:] for l in lines if l.startswith('Subject:')), message.subject or "Notification")
|
|
body = '\n'.join(l for l in lines if not l.startswith('Subject:'))
|
|
else:
|
|
subject = message.subject or "Notification"
|
|
body = message.body or ""
|
|
else:
|
|
subject = message.subject or "Notification"
|
|
body = message.body or ""
|
|
|
|
# Create email message
|
|
email_msg = EmailMessage()
|
|
email_msg["From"] = f"{self.from_name} <{self.from_email}>"
|
|
email_msg["To"] = message.recipient
|
|
email_msg["Subject"] = subject
|
|
email_msg.set_content(body)
|
|
|
|
# Send via SMTP
|
|
async with aiosmtplib.SMTP(
|
|
hostname=self.smtp_host,
|
|
port=self.smtp_port,
|
|
use_tls=True
|
|
) as smtp:
|
|
await smtp.login(self.username, self.password)
|
|
await smtp.send_message(email_msg)
|
|
|
|
logger.info(f"Email sent to {message.recipient}")
|
|
return NotificationResult(success=True)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to send email to {message.recipient}: {e}")
|
|
return NotificationResult(
|
|
success=False,
|
|
error=str(e)
|
|
)
|
|
|
|
def validate_recipient(self, recipient: str) -> bool:
|
|
"""Validate email address."""
|
|
import re
|
|
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
return re.match(pattern, recipient) is not None
|
|
```
|
|
|
|
**SMS channel implementation**:
|
|
```python
|
|
import httpx
|
|
|
|
class SMSChannel(NotificationChannel):
|
|
"""SMS notification channel (e.g., Twilio)."""
|
|
|
|
def __init__(
|
|
self,
|
|
account_sid: str,
|
|
auth_token: str,
|
|
from_number: str
|
|
):
|
|
self.account_sid = account_sid
|
|
self.auth_token = auth_token
|
|
self.from_number = from_number
|
|
self.base_url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}"
|
|
|
|
async def send(self, message: NotificationMessage) -> NotificationResult:
|
|
"""Send SMS notification."""
|
|
try:
|
|
# For production, use Twilio SDK
|
|
async with httpx.AsyncClient() as client:
|
|
response = await client.post(
|
|
f"{self.base_url}/Messages.json",
|
|
auth=(self.account_sid, self.auth_token),
|
|
data={
|
|
"From": self.from_number,
|
|
"To": message.recipient,
|
|
"Body": message.body or self._get_sms_body(message)
|
|
},
|
|
timeout=10.0
|
|
)
|
|
response.raise_for_status()
|
|
|
|
logger.info(f"SMS sent to {message.recipient}")
|
|
return NotificationResult(success=True)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to send SMS to {message.recipient}: {e}")
|
|
return NotificationResult(
|
|
success=False,
|
|
error=str(e)
|
|
)
|
|
|
|
def _get_sms_body(self, message: NotificationMessage) -> str:
|
|
"""Generate SMS body from template/variables."""
|
|
if message.variables:
|
|
order_number = message.variables.get("order_number", "")
|
|
if message.template == "order_shipped":
|
|
tracking = message.variables.get("tracking_number", "")
|
|
return f"Order #{order_number} has shipped! Track: {tracking}"
|
|
elif message.template == "order_delivered":
|
|
return f"Order #{order_number} has been delivered. Thank you!"
|
|
elif message.template == "order_cancelled":
|
|
return f"Order #{order_number} has been cancelled."
|
|
|
|
return message.body or "Update on your order"
|
|
|
|
def validate_recipient(self, recipient: str) -> bool:
|
|
"""Validate phone number."""
|
|
# Basic validation - should be E.164 format
|
|
return recipient.startswith("+") and len(recipient) >= 10
|
|
```
|
|
|
|
**Webhook channel**:
|
|
```python
|
|
import httpx
|
|
import hmac
|
|
import hashlib
|
|
|
|
class WebhookChannel(NotificationChannel):
|
|
"""Webhook notification channel for external systems."""
|
|
|
|
def __init__(self, secret: str = None):
|
|
self.secret = secret
|
|
|
|
async def send(self, message: NotificationMessage) -> NotificationResult:
|
|
"""Send webhook notification."""
|
|
try:
|
|
# Build payload
|
|
payload = {
|
|
"event": message.template,
|
|
"recipient": message.recipient,
|
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
"data": message.variables or {}
|
|
}
|
|
|
|
# Add signature if secret configured
|
|
headers = {"Content-Type": "application/json"}
|
|
if self.secret:
|
|
signature = hmac.new(
|
|
self.secret.encode(),
|
|
json.dumps(payload).encode(),
|
|
hashlib.sha256
|
|
).hexdigest()
|
|
headers["X-Webhook-Signature"] = signature
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
response = await client.post(
|
|
message.recipient, # Webhook URL
|
|
json=payload,
|
|
headers=headers,
|
|
timeout=10.0
|
|
)
|
|
response.raise_for_status()
|
|
|
|
logger.info(f"Webhook sent to {message.recipient}")
|
|
return NotificationResult(success=True)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to send webhook to {message.recipient}: {e}")
|
|
return NotificationResult(
|
|
success=False,
|
|
error=str(e)
|
|
)
|
|
|
|
def validate_recipient(self, recipient: str) -> bool:
|
|
"""Validate webhook URL."""
|
|
return recipient.startswith(("http://", "https://"))
|
|
```
|
|
|
|
**Notification service**:
|
|
```python
|
|
class NotificationService:
|
|
"""Service for sending order-related notifications."""
|
|
|
|
def __init__(self, db):
|
|
self.db = db
|
|
self.channels: Dict[NotificationType, NotificationChannel] = {}
|
|
self.retry_queue = asyncio.Queue()
|
|
|
|
def register_channel(
|
|
self,
|
|
channel_type: NotificationType,
|
|
channel: NotificationChannel
|
|
):
|
|
"""Register a notification channel."""
|
|
self.channels[channel_type] = channel
|
|
logger.info(f"Registered notification channel: {channel_type.value}")
|
|
|
|
async def send_order_notification(
|
|
self,
|
|
order_id: int,
|
|
event: NotificationEvent,
|
|
channels: List[NotificationType] = None
|
|
):
|
|
"""Send notification for order event."""
|
|
if channels is None:
|
|
channels = [NotificationType.EMAIL]
|
|
|
|
# Get order and customer details
|
|
async with self.db.acquire() as conn:
|
|
order = await conn.fetchrow(
|
|
"""SELECT o.*, c.email, c.phone, c.first_name, c.last_name
|
|
FROM orders o
|
|
JOIN customers c ON c.id = o.customer_id
|
|
WHERE o.id = $1""",
|
|
order_id
|
|
)
|
|
|
|
if not order:
|
|
logger.warning(f"Order not found for notification: {order_id}")
|
|
return
|
|
|
|
variables = {
|
|
"order_number": order["order_number"],
|
|
"customer_name": f"{order['first_name']} {order['last_name']}".strip(),
|
|
"total_amount": str(order["total_amount"]),
|
|
"currency": order["currency"],
|
|
"tracking_number": order.get("tracking_number", ""),
|
|
"carrier": order.get("shipping_carrier", ""),
|
|
"estimated_delivery": order.get("estimated_delivery_at", ""),
|
|
}
|
|
|
|
# Add event-specific variables
|
|
if event == NotificationEvent.PAYMENT_RECEIVED:
|
|
variables["amount"] = str(order["total_amount"])
|
|
elif event == NotificationEvent.ORDER_CANCELLED:
|
|
variables["reason"] = order.get("cancelled_reason", "Customer request")
|
|
elif event == NotificationEvent.REFUND_PROCESSED:
|
|
variables["amount"] = str(order.get("refunded_amount", "0"))
|
|
|
|
# Send via each channel
|
|
for channel_type in channels:
|
|
channel = self.channels.get(channel_type)
|
|
if not channel:
|
|
logger.warning(f"Channel not configured: {channel_type.value}")
|
|
continue
|
|
|
|
# Determine recipient
|
|
recipient = None
|
|
if channel_type == NotificationType.EMAIL:
|
|
recipient = order["email"]
|
|
elif channel_type == NotificationType.SMS:
|
|
recipient = order.get("phone")
|
|
|
|
if not recipient or not channel.validate_recipient(recipient):
|
|
logger.warning(f"Invalid recipient for {channel_type.value}: {recipient}")
|
|
continue
|
|
|
|
# Create message
|
|
message = NotificationMessage(
|
|
recipient=recipient,
|
|
type=channel_type,
|
|
template=event.value,
|
|
variables=variables
|
|
)
|
|
|
|
# Send
|
|
result = await channel.send(message)
|
|
|
|
# Record in database
|
|
await self._record_notification(
|
|
order_id=order_id,
|
|
customer_id=order["customer_id"],
|
|
channel_type=channel_type.value,
|
|
template=event.value,
|
|
recipient=recipient,
|
|
status="sent" if result.success else "failed",
|
|
error_message=result.error
|
|
)
|
|
|
|
# Queue for retry if failed
|
|
if not result.success:
|
|
await self.retry_queue.put({
|
|
"order_id": order_id,
|
|
"event": event,
|
|
"channel": channel_type,
|
|
"variables": variables,
|
|
"attempts": 1
|
|
})
|
|
|
|
# Convenience methods for specific events
|
|
async def send_order_confirmation(self, order_id: int):
|
|
"""Send order confirmation notification."""
|
|
await self.send_order_notification(
|
|
order_id,
|
|
NotificationEvent.ORDER_CONFIRMED,
|
|
[NotificationType.EMAIL]
|
|
)
|
|
|
|
async def send_payment_confirmation(self, order_id: int):
|
|
"""Send payment confirmation notification."""
|
|
await self.send_order_notification(
|
|
order_id,
|
|
NotificationEvent.PAYMENT_RECEIVED,
|
|
[NotificationType.EMAIL]
|
|
)
|
|
|
|
async def send_shipping_notification(self, order_id: int):
|
|
"""Send shipping notification."""
|
|
await self.send_order_notification(
|
|
order_id,
|
|
NotificationEvent.ORDER_SHIPPED,
|
|
[NotificationType.EMAIL, NotificationType.SMS]
|
|
)
|
|
|
|
async def send_delivery_notification(self, order_id: int):
|
|
"""Send delivery notification."""
|
|
await self.send_order_notification(
|
|
order_id,
|
|
NotificationEvent.ORDER_DELIVERED,
|
|
[NotificationType.EMAIL]
|
|
)
|
|
|
|
async def send_cancellation_notification(self, order_id: int):
|
|
"""Send cancellation notification."""
|
|
await self.send_order_notification(
|
|
order_id,
|
|
NotificationEvent.ORDER_CANCELLED,
|
|
[NotificationType.EMAIL]
|
|
)
|
|
|
|
async def send_refund_notification(self, order_id: int):
|
|
"""Send refund notification."""
|
|
await self.send_order_notification(
|
|
order_id,
|
|
NotificationEvent.REFUND_PROCESSED,
|
|
[NotificationType.EMAIL]
|
|
)
|
|
|
|
async def _record_notification(
|
|
self,
|
|
order_id: int,
|
|
customer_id: int,
|
|
channel_type: str,
|
|
template: str,
|
|
recipient: str,
|
|
status: str,
|
|
error_message: str = None
|
|
):
|
|
"""Record notification in database."""
|
|
async with self.db.acquire() as conn:
|
|
await conn.execute(
|
|
"""INSERT INTO notifications
|
|
(customer_id, order_id, type, template, recipient, status, error_message)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)""",
|
|
customer_id, order_id, channel_type, template, recipient, status, error_message
|
|
)
|
|
|
|
async def process_retry_queue(self):
|
|
"""Background task to retry failed notifications."""
|
|
while True:
|
|
try:
|
|
item = await self.retry_queue.get()
|
|
|
|
if item["attempts"] >= 3:
|
|
logger.warning(f"Max retries exceeded for notification: {item}")
|
|
continue
|
|
|
|
# Wait before retry (exponential backoff)
|
|
await asyncio.sleep(60 * (2 ** item["attempts"]))
|
|
|
|
# Retry
|
|
channel = self.channels.get(item["channel"])
|
|
if channel:
|
|
message = NotificationMessage(
|
|
recipient=item["variables"].get("recipient", ""),
|
|
type=item["channel"],
|
|
template=item["event"].value,
|
|
variables=item["variables"]
|
|
)
|
|
|
|
result = await channel.send(message)
|
|
|
|
if result.success:
|
|
logger.info(f"Retry successful for notification to order {item['order_id']}")
|
|
else:
|
|
await self.retry_queue.put({
|
|
**item,
|
|
"attempts": item["attempts"] + 1
|
|
})
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error in retry queue: {e}")
|
|
|
|
await asyncio.sleep(1)
|
|
```
|
|
|
|
**Notification preferences**:
|
|
```sql
|
|
-- Customer notification preferences
|
|
CREATE TABLE notification_preferences (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
customer_id BIGINT NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
|
|
channel VARCHAR(20) NOT NULL,
|
|
enabled BOOLEAN DEFAULT TRUE,
|
|
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
UNIQUE(customer_id, channel)
|
|
);
|
|
|
|
CREATE INDEX idx_notif_prefs_customer ON notification_preferences(customer_id);
|
|
|
|
-- Default preferences
|
|
INSERT INTO notification_preferences (customer_id, channel, enabled)
|
|
SELECT id, 'email', TRUE FROM customers
|
|
ON CONFLICT DO NOTHING;
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] Order confirmation emails are sent
|
|
- [ ] Shipping notifications include tracking
|
|
- [ ] SMS notifications work for shipping
|
|
- [ ] Failed notifications are retried
|
|
- [ ] Notifications are recorded in database
|
|
- [ ] Invalid recipients are handled gracefully
|
|
- [ ] Customer preferences are respected
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Sync vs async sending: Async for responsiveness
|
|
- Built-in templates vs external service: Built-in for control
|
|
|
|
**Performance**:
|
|
- Use message queue for high volume
|
|
- Batch email sending
|
|
- Implement rate limiting for SMS
|
|
|
|
**Alternatives considered**:
|
|
- SendGrid/Mailgun: Simplifies email but adds dependency
|
|
- Push notifications: Mobile app required
|