Files
xenia-pos-local/local_backend/routers/notifications.py
T
bonaminandClaude Opus 5.5 5a21f67b42 feat(backend): platform notifications service with audiences, dedupe, read state and first producers
Platform v2 step 1.11 (APPS_PLATFORM section 10).
- notifications + notification_reads (revision 0010). Text = i18n key notification.<key> + params,
  rendered in the reader's language (en, el added).
- core/notifications.py: notify(key, severity, audience, params, dedupe_key, ttl/expires_at, fold)
  never raises; audience all_managers | perm:<key> | user:<id>; a live duplicate only bumps
  count/last_at (no unread reset, no event). New ones emit WS platform_notification {id} to the
  audience's users (current apps ignore it; phase 2 manager shows it).
- API (core, /api/platform/notifications; /api/notifications is chat's): list with unread count,
  POST /{id}/read, POST /read-all.
- Producers: license.limit_reached (device pairing/reassign/over-limit device, per module/limit/day,
  owners), license.expiring (14/7/3/1 days, from apply_license, owners), support.access_used (each
  use, core.settings.manage), print.failed_final (abandoned retry job, per printer/hour, managers).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:13:37 +02:00

74 lines
3.1 KiB
Python

"""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)}