Spaces:
Running

File size: 8,451 Bytes
727ec8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c325cc
3b89d2d
727ec8d
3b89d2d
727ec8d
229300b
9c325cc
 
3b89d2d
 
 
 
 
 
 
727ec8d
 
 
9c325cc
108aace
727ec8d
108aace
 
727ec8d
229300b
9c325cc
 
108aace
 
 
 
 
 
 
727ec8d
9c325cc
727ec8d
 
6770e41
 
 
 
 
9c325cc
6770e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c325cc
6770e41
 
9c325cc
 
 
 
 
 
6770e41
 
 
 
 
 
 
 
 
9c325cc
6770e41
 
 
 
 
 
 
 
 
 
9c325cc
6770e41
 
 
 
 
 
 
 
 
 
 
 
9c325cc
 
 
 
 
 
 
 
 
 
6770e41
 
 
 
 
 
 
 
9c325cc
6770e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
727ec8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""
Notifications API endpoints.

Focus: Save time by notifying only about HOT leads.
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlmodel.ext.asyncio.session import AsyncSession
from pydantic import BaseModel
from typing import List, Optional
from uuid import UUID
from datetime import datetime

from app.core.database import get_async_session
from app.api.deps import get_current_user
from app.models import User, Notification, NotificationSettings
from sqlmodel import select, update, func

router = APIRouter(prefix="/notifications", tags=["Notifications"])


# ============================================================================
# Schemas
# ============================================================================

class NotificationResponse(BaseModel):
    id: UUID
    type: str
    title: str
    message: str
    is_read: bool
    created_at: str
    lead_id: UUID


class UnreadCountResponse(BaseModel):
    unread_count: int


class NotificationSettingsResponse(BaseModel):
    telegram_enabled: bool
    telegram_chat_id: Optional[str]
    telegram_channel_id: Optional[str] = None
    
    dashboard_enabled: bool
    
    notify_hot_leads: bool
    notify_qualification_complete: bool
    notify_orders: bool = True
    notify_bookings: bool = True
    
    # Escalation
    notify_escalation_high: bool = True
    notify_escalation_medium: bool = True
    notify_escalation_low: bool = False


class UpdateNotificationSettingsRequest(BaseModel):
    telegram_enabled: Optional[bool] = None
    telegram_chat_id: Optional[str] = None
    telegram_channel_id: Optional[str] = None
    
    dashboard_enabled: Optional[bool] = None
    
    # Notification Types
    notify_hot_leads: Optional[bool] = None
    notify_qualification_complete: Optional[bool] = None
    notify_orders: Optional[bool] = None
    notify_bookings: Optional[bool] = None
    
    # Escalation Levels
    notify_escalation_high: Optional[bool] = None
    notify_escalation_medium: Optional[bool] = None
    notify_escalation_low: Optional[bool] = None


# ============================================================================
# Settings Endpoints
# ============================================================================

@router.get("/settings", response_model=NotificationSettingsResponse)
async def get_notification_settings(
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(get_current_user)
):
    """Get notification settings for current user's tenant."""
    stmt = select(NotificationSettings).where(
        NotificationSettings.tenant_id == current_user.tenant_id
    )
    result = await session.execute(stmt)
    settings = result.scalar_one_or_none()
    
    if not settings:
        # Create default settings
        settings = NotificationSettings(tenant_id=current_user.tenant_id)
        session.add(settings)
        await session.commit()
        await session.refresh(settings)
    
    return NotificationSettingsResponse(
        telegram_enabled=settings.telegram_enabled,
        telegram_chat_id=settings.telegram_chat_id,
        telegram_channel_id=settings.telegram_channel_id,
        dashboard_enabled=settings.dashboard_enabled,
        notify_hot_leads=settings.notify_hot_leads,
        notify_qualification_complete=settings.notify_qualification_complete,
        notify_orders=settings.notify_orders,
        notify_bookings=settings.notify_bookings,
        notify_escalation_high=settings.notify_escalation_high,
        notify_escalation_medium=settings.notify_escalation_medium,
        notify_escalation_low=settings.notify_escalation_low
    )


@router.put("/settings")
async def update_notification_settings(
    request: UpdateNotificationSettingsRequest,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(get_current_user)
):
    """Update notification settings for current user's tenant."""
    stmt = select(NotificationSettings).where(
        NotificationSettings.tenant_id == current_user.tenant_id
    )
    result = await session.execute(stmt)
    settings = result.scalar_one_or_none()
    
    if not settings:
        settings = NotificationSettings(tenant_id=current_user.tenant_id)
        session.add(settings)
    
    # Update ALL fields
    if request.telegram_enabled is not None:
        settings.telegram_enabled = request.telegram_enabled
    if request.telegram_chat_id is not None:
        settings.telegram_chat_id = request.telegram_chat_id
    if request.telegram_channel_id is not None:
        settings.telegram_channel_id = request.telegram_channel_id
    if request.dashboard_enabled is not None:
        settings.dashboard_enabled = request.dashboard_enabled
    if request.notify_hot_leads is not None:
        settings.notify_hot_leads = request.notify_hot_leads
    if request.notify_qualification_complete is not None:
        settings.notify_qualification_complete = request.notify_qualification_complete
    if request.notify_orders is not None:
        settings.notify_orders = request.notify_orders
    if request.notify_bookings is not None:
        settings.notify_bookings = request.notify_bookings
    if request.notify_escalation_high is not None:
        settings.notify_escalation_high = request.notify_escalation_high
    if request.notify_escalation_medium is not None:
        settings.notify_escalation_medium = request.notify_escalation_medium
    if request.notify_escalation_low is not None:
        settings.notify_escalation_low = request.notify_escalation_low
    
    settings.updated_at = datetime.utcnow()
    await session.commit()
    
    return {"success": True}


# ============================================================================
# Notification List Endpoints
# ============================================================================

@router.get("/unread-count", response_model=UnreadCountResponse)
async def get_unread_count(
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(get_current_user)
):
    """Get count of unread notifications."""
    stmt = select(func.count(Notification.id)).where(
        Notification.tenant_id == current_user.tenant_id,
        Notification.is_read == False
    )
    count = await session.scalar(stmt)
    
    return UnreadCountResponse(unread_count=count or 0)


@router.get("/", response_model=List[NotificationResponse])
async def get_notifications(
    limit: int = 20,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(get_current_user)
):
    """Get list of notifications (last 20)."""
    stmt = select(Notification).where(
        Notification.tenant_id == current_user.tenant_id
    ).order_by(Notification.created_at.desc()).limit(limit)
    
    result = await session.execute(stmt)
    notifications = result.scalars().all()
    
    return [
        NotificationResponse(
            id=n.id,
            type=n.type,
            title=n.title,
            message=n.message,
            is_read=n.is_read,
            created_at=n.created_at.isoformat(),
            lead_id=n.lead_id
        )
        for n in notifications
    ]


@router.post("/{notification_id}/mark-read")
async def mark_notification_read(
    notification_id: UUID,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(get_current_user)
):
    """Mark notification as read."""
    stmt = select(Notification).where(
        Notification.id == notification_id,
        Notification.tenant_id == current_user.tenant_id
    )
    result = await session.execute(stmt)
    notification = result.scalar_one_or_none()
    
    if not notification:
        raise HTTPException(status_code=404, detail="Notification not found")
    
    notification.is_read = True
    notification.read_at = datetime.utcnow()
    await session.commit()
    
    return {"success": True}


@router.post("/mark-all-read")
async def mark_all_notifications_read(
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(get_current_user)
):
    """Mark all notifications as read."""
    stmt = update(Notification).where(
        Notification.tenant_id == current_user.tenant_id,
        Notification.is_read == False
    ).values(is_read=True, read_at=datetime.utcnow())
    
    await session.execute(stmt)
    await session.commit()
    
    return {"success": True}