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>
This commit is contained in:
2026-11-13 11:13:37 +02:00
co-authored by Claude Opus 5.5
parent 94a68b1c06
commit 5a21f67b42
15 changed files with 526 additions and 1 deletions
+3 -1
View File
@@ -230,7 +230,9 @@ def support_verify(body: SupportVerifyRequest, request: Request, db: Session = D
row.session_id = session.id
db.commit()
_logger.warning("support.access_used challenge=%s sid=%s ip=%s", row.id, session.id[:8], session.ip)
# >>> step 1.11: notify owners (support.access_used)
from core.notifications import notify
notify("support.access_used", "warning", "perm:core.settings.manage", {"ip": session.ip or "?"},
dedupe_key=f"support.access_used:{row.id}", db=db)
return TokenResponse(access_token=make_token(support, session.id, hours=SUPPORT_SESSION_HOURS),
user=UserOut.model_validate(support))
+9
View File
@@ -106,9 +106,18 @@ def _check_limit(db, app_key: str, exclude_id: int | None = None) -> None:
if exclude_id is not None:
q = q.filter(Device.id != exclude_id)
if q.count() >= cap:
notify_limit(app_key, "devices", cap, db)
raise XeniaError("license.limit_reached", module=app_key, limit="devices", max=cap)
def notify_limit(module: str, limit: str, cap: int, db) -> None:
"""Tell the owners (once a day per module/limit, repeats are counted) that a limit stopped something."""
from core.notifications import notify
notify("license.limit_reached", "warning", "perm:core.modules.manage",
{"module": module, "limit": limit, "max": cap},
dedupe_key=f"license.limit_reached:{module}:{limit}", ttl=timedelta(days=1), db=db)
def _check_mode(app_key: str, mode: str | None) -> str | None:
if not mode:
return None # site default
+73
View File
@@ -0,0 +1,73 @@
"""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)}