"""Platform notifications API (APPS_PLATFORM ยง10, plan step 1.11). Service: core/notifications.py. Mounted by the core manifest at /api/platform/notifications (NOT /api/notifications, which is the chat module's staff messages and can be turned off). """ from __future__ import annotations from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from core import i18n from core.errors import XeniaError from core.notifications import visible_filter from core.timeutil import iso_z, utcnow from database import get_db from models.notification import Notification, NotificationRead from routers.deps import get_current_user router = APIRouter() def _live(user): now = utcnow() return (visible_filter(user), (Notification.expires_at.is_(None)) | (Notification.expires_at > now)) def _text(n, lang) -> str: try: return i18n.t(f"notification.{n.key}", lang, **(n.params or {})) except Exception: # a missing placeholder must not break the list return n.key @router.get("") def list_notifications(unread_only: bool = False, limit: int = 50, db: Session = Depends(get_db), user=Depends(get_current_user)): """The caller's notifications (by audience), newest activity first, with `unread` count. `message` is rendered in the caller's language; `key` + `params` are there for the UI.""" read_ids = {r.notification_id for r in db.query(NotificationRead).filter(NotificationRead.user_id == user.id)} rows = db.query(Notification).filter(*_live(user)).order_by(Notification.last_at.desc(), Notification.id.desc()).all() unread = sum(1 for n in rows if n.id not in read_ids) if unread_only: rows = [n for n in rows if n.id not in read_ids] lang = i18n.user_language(user) items = [{"id": n.id, "key": n.key, "severity": n.severity, "params": n.params or {}, "message": _text(n, lang), "count": n.count, "created_at": iso_z(n.created_at), "last_at": iso_z(n.last_at), "expires_at": iso_z(n.expires_at), "read": n.id in read_ids} for n in rows[:max(1, min(limit, 500))]] return {"items": items, "unread": unread} def _mark(db, user, ids) -> int: done = {r.notification_id for r in db.query(NotificationRead).filter( NotificationRead.user_id == user.id, NotificationRead.notification_id.in_(ids))} for nid in set(ids) - done: db.add(NotificationRead(notification_id=nid, user_id=user.id, read_at=utcnow())) db.commit() return len(set(ids) - done) @router.post("/{notification_id}/read") def mark_read(notification_id: int, db: Session = Depends(get_db), user=Depends(get_current_user)): n = db.query(Notification).filter(Notification.id == notification_id, visible_filter(user)).first() if n is None: raise XeniaError("notification.not_found", notification_id=notification_id) _mark(db, user, [n.id]) return {"ok": True} @router.post("/read-all") def mark_all_read(db: Session = Depends(get_db), user=Depends(get_current_user)): ids = [n.id for n in db.query(Notification.id).filter(*_live(user))] return {"marked": _mark(db, user, ids)}