""" 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] dashboard_enabled: bool notify_hot_leads: bool class UpdateNotificationSettingsRequest(BaseModel): telegram_enabled: Optional[bool] = None telegram_chat_id: Optional[str] = None dashboard_enabled: Optional[bool] = None notify_hot_leads: Optional[bool] = None # ============================================================================ # 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} @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.""" 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, dashboard_enabled=settings.dashboard_enabled, notify_hot_leads=settings.notify_hot_leads ) @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.""" 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 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.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 settings.updated_at = datetime.utcnow() await session.commit() return {"success": True}