"""Notification endpoints — /v1/notifications/*""" from fastapi import APIRouter, Depends, HTTPException from datetime import datetime, timezone from sqlalchemy import delete, func, select, update from sqlalchemy.ext.asyncio import AsyncSession from meshbay_hub.api.deps import get_current_user from meshbay_hub.db.engine import get_db from meshbay_hub.db.models import GroupMember, Notification, User router = APIRouter(prefix="/v1/notifications", tags=["notifications"]) @router.get("") async def list_notifications( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), limit: int = 50, offset: int = 0, unread_only: bool = False, ): query = select(Notification).where(Notification.user_id == current_user.id) if unread_only: query = query.where(Notification.read == False) # noqa: E712 result = await db.execute( query.order_by(Notification.created_at.desc()).limit(limit).offset(offset) ) notifs = result.scalars().all() count_q = select(func.count()).select_from(Notification).where( Notification.user_id == current_user.id, Notification.read == False # noqa: E712 ) unread = (await db.execute(count_q)).scalar() or 0 return { "notifications": [ { "id": n.id, "kind": n.kind, "title": n.title, "detail": n.detail, "link": n.link, "group_id": n.group_id, "read": n.read, "created_at": n.created_at.isoformat(), } for n in notifs ], "unread_count": unread, } @router.post("/{notification_id}/read") async def mark_read( notification_id: int, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): notif = await db.get(Notification, notification_id) if not notif or notif.user_id != current_user.id: raise HTTPException(status_code=404, detail="Notification not found") notif.read = True await db.commit() return {"status": "ok"} @router.delete("") async def purge_notifications( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): """ Throw them all away. These are signals, not a record: the group is still there, the message is still in the chat, the invitation is still an invitation. Nothing is lost by clearing the list, so it clears rather than marking a hundred rows read. """ result = await db.execute( delete(Notification).where(Notification.user_id == current_user.id)) await db.commit() return {"status": "ok", "removed": result.rowcount} @router.post("/read-all") async def mark_all_read( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): await db.execute( update(Notification) .where(Notification.user_id == current_user.id, Notification.read == False) # noqa: E712 .values(read=True) ) await db.commit() return {"status": "ok"} async def create_notification( db: AsyncSession, user_id: str, kind: str, title: str, detail: str | None = None, link: str | None = None, group_id: str | None = None, aggregate: bool = False, ) -> Notification | None: """ Create a notification, or refresh the one already standing for this group. `aggregate` is for anything that repeats — chat, above all. One row per (person, kind, group) whose date moves and whose read flag clears, so a busy conversation is a single line saying when it last spoke rather than forty saying that it spoke. Returns None when the person muted this group: the point of muting is that nothing is created, not that something is created and hidden. """ if group_id is not None: muted = await db.execute( select(GroupMember.muted).where( GroupMember.group_id == group_id, GroupMember.user_id == user_id, ) ) if muted.scalar() is True: return None if aggregate and group_id is not None: existing = (await db.execute( select(Notification).where( Notification.user_id == user_id, Notification.kind == kind, Notification.group_id == group_id, ).order_by(Notification.created_at.desc()).limit(1) )).scalar_one_or_none() if existing is not None: existing.title = title existing.detail = detail existing.link = link existing.read = False existing.created_at = datetime.now(timezone.utc) await db.flush() return existing notif = Notification( user_id=user_id, kind=kind, title=title, detail=detail, link=link, group_id=group_id, ) db.add(notif) await db.flush() return notif