File size: 2,540 Bytes
8dafdf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from typing import List, Dict, Any
from fastapi import WebSocket
from datetime import datetime
from ..db.database import db
from ..utils.cache import cache
from ..db.models import Notification

# Store active WebSocket connections
active_connections: List[WebSocket] = []

async def connect(websocket: WebSocket):
    """Accept a new WebSocket connection"""
    await websocket.accept()
    active_connections.append(websocket)

async def disconnect(websocket: WebSocket):
    """Remove a WebSocket connection"""
    if websocket in active_connections:
        active_connections.remove(websocket)

async def broadcast_message(message: dict):
    """Broadcast a message to all connected clients"""
    disconnected = []
    for connection in active_connections:
        try:
            await connection.send_json(message)
        except:
            disconnected.append(connection)
    
    # Clean up disconnected clients
    for connection in disconnected:
        await disconnect(connection)

async def create_and_broadcast_notification(

    user_id: str,

    title: str,

    message: str,

    notification_type: str,

    data: Dict[str, Any] = None

) -> Dict[str, Any]:
    """Create and broadcast a notification"""
    async with db.session() as session:
        # Create notification
        notification = Notification(
            user_id=user_id,
            title=title,
            message=message,
            type=notification_type,
            data=data,
            created_at=datetime.utcnow(),
            read=False
        )
        
        # Store in database
        session.add(notification)
        await session.commit()
        await session.refresh(notification)
        
        # Convert to dict for broadcasting
        notification_dict = {
            "id": str(notification.id),
            "user_id": notification.user_id,
            "title": notification.title,
            "message": notification.message,
            "type": notification.type,
            "data": notification.data,
            "created_at": notification.created_at.isoformat(),
            "read": notification.read
        }
        
        # Broadcast to connected clients
        await broadcast_message({
            "type": "notification",
            "data": notification_dict
        })
        
        # Clear user's notification cache
        await cache.delete_cache(f"user_notifications:{user_id}")
        
        return notification_dict