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>
140 lines
5.8 KiB
Python
140 lines
5.8 KiB
Python
"""Platform notifications service (APPS_PLATFORM §10, plan step 1.11).
|
|
|
|
notify("license.limit_reached", "warning", "perm:core.modules.manage",
|
|
params={"module": "kds", "limit": "devices", "max": 2},
|
|
dedupe_key="license.limit_reached:kds:devices", ttl=timedelta(days=1))
|
|
|
|
- Text: i18n key `notification.<key>` + params (core/i18n/en.json, el.json). Add both.
|
|
- Audience: "all_managers" | "perm:<permission key>" | "user:<id>". Superadmins see every
|
|
perm/all_managers notification (they hold every key).
|
|
- Dedupe: while a row with the same dedupe_key is live (not expired), a repeat only
|
|
bumps its count / last_at (fold=True) or does nothing (fold=False). Repeats don't
|
|
mark it unread again and send no event, so a refusal on every request can't spam.
|
|
- After a NEW notification, WS event `platform_notification` {id} goes to the audience (ids only,
|
|
CS-2). The current waiter app and manager ignore it on purpose; the phase 2 manager
|
|
shell shows it.
|
|
- Safe to call from background threads: pass db=None and it uses its own session.
|
|
It never raises: a notification must not break the action that produced it.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import datetime, timedelta
|
|
|
|
from core.timeutil import utcnow
|
|
|
|
logger = logging.getLogger("xenia.notifications")
|
|
|
|
SEVERITIES = ("info", "warning", "critical")
|
|
EVENT = "platform_notification"
|
|
|
|
|
|
def _audience_ok(audience: str) -> bool:
|
|
if audience == "all_managers":
|
|
return True
|
|
kind, _, value = audience.partition(":")
|
|
if kind == "user":
|
|
return value.isdigit()
|
|
if kind == "perm":
|
|
from core.modules.registry import all_permissions
|
|
return value in all_permissions()
|
|
return False
|
|
|
|
|
|
def recipients(db, audience: str) -> list[int]:
|
|
"""User ids (active) the audience currently means."""
|
|
from core.access.queries import users_with_key
|
|
if audience.startswith("user:"):
|
|
return [int(audience[5:])]
|
|
key = "core.dashboard.access" if audience == "all_managers" else audience[5:]
|
|
return [u.id for u in users_with_key(db, key)]
|
|
|
|
|
|
def visible_filter(user):
|
|
"""SQLAlchemy filter: notifications this user may see (audience only, not expiry)."""
|
|
from sqlalchemy import or_
|
|
from core.access.check import holds, user_keys
|
|
from core.modules.registry import all_permissions
|
|
from models.notification import Notification
|
|
if getattr(user, "role", None) == "superadmin":
|
|
keys = set(all_permissions())
|
|
else:
|
|
keys = set(user_keys(user))
|
|
conds = [Notification.audience == f"user:{user.id}"]
|
|
if keys:
|
|
conds.append(Notification.audience.in_([f"perm:{k}" for k in keys]))
|
|
if holds(user, "core.dashboard.access"):
|
|
conds.append(Notification.audience == "all_managers")
|
|
return or_(*conds)
|
|
|
|
|
|
def notify(key: str, severity: str, audience: str, params: dict | None = None, *, dedupe_key: str | None = None,
|
|
ttl: timedelta | None = None, expires_at: datetime | None = None, fold: bool = True, db=None):
|
|
"""Create (or fold into a live duplicate) a notification. Returns its id, or None on error."""
|
|
from models.notification import Notification
|
|
own = db is None
|
|
if own:
|
|
from database import SessionLocal
|
|
db = SessionLocal()
|
|
try:
|
|
if severity not in SEVERITIES or not _audience_ok(audience):
|
|
raise ValueError(f"bad notification severity/audience: {severity!r} {audience!r}")
|
|
now = utcnow()
|
|
row = None
|
|
if dedupe_key:
|
|
row = db.query(Notification).filter(
|
|
Notification.dedupe_key == dedupe_key,
|
|
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
|
|
).order_by(Notification.id.desc()).first()
|
|
if row is not None:
|
|
if not fold:
|
|
return row.id
|
|
row.count += 1
|
|
row.last_at = now
|
|
row.params = params or row.params
|
|
db.commit()
|
|
return row.id
|
|
else:
|
|
row = Notification(key=key, severity=severity, audience=audience, params=params or {},
|
|
dedupe_key=dedupe_key, created_at=now, last_at=now,
|
|
expires_at=expires_at or (now + ttl if ttl else None))
|
|
db.add(row)
|
|
db.commit()
|
|
logger.info("notification.created id=%s key=%s audience=%s", row.id, key, audience)
|
|
try:
|
|
from services.sse_bus import broadcast_sync
|
|
broadcast_sync(EVENT, {"id": row.id}, user_ids=recipients(db, audience))
|
|
except Exception:
|
|
logger.exception("notification.event_failed id=%s", row.id)
|
|
return row.id
|
|
except Exception:
|
|
logger.exception("notification.failed key=%s audience=%s", key, audience)
|
|
try:
|
|
db.rollback()
|
|
except Exception:
|
|
pass
|
|
return None
|
|
finally:
|
|
if own:
|
|
db.close()
|
|
|
|
|
|
# ── producers that need a little logic ───────────────────────────────────────
|
|
|
|
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
|
|
|
|
|
|
def check_license_expiry(expires_at: str | None, days_until: int | None, licensed: bool, db=None) -> None:
|
|
"""license.expiring at 14/7/3/1 days before the license's expiry, once per step."""
|
|
if not licensed or days_until is None or days_until < 0 or days_until > EXPIRY_WARN_DAYS[0] or not expires_at:
|
|
return
|
|
step = min(d for d in EXPIRY_WARN_DAYS if d >= max(days_until, 1))
|
|
from core.timeutil import parse_api_datetime
|
|
try:
|
|
end = parse_api_datetime(expires_at)
|
|
except Exception:
|
|
end = None
|
|
notify("license.expiring", "critical" if step <= 3 else "warning", "perm:core.modules.manage",
|
|
{"days": days_until, "expires_at": expires_at},
|
|
dedupe_key=f"license.expiring:{expires_at[:10]}:{step}", expires_at=end, fold=False, db=db)
|