Files
xenia-pos-local/local_backend/core/notifications.py
T
bonaminandClaude Opus 5.5 096bd53dbd feat(backend,manager): the business day opens and closes by itself (opening hours, a time, or only an alert)
- services/day_auto.py: a minute loop (venue time, offline) opens the day when the opening
  hours start (or at business_day.auto_open_time) and closes it when they end (or at
  auto_close_time); 'alert' only tells the managers. Offsets before / after, one day across
  the break or one per span, spans past midnight belong to the day they start, a day closed
  by hand isn't reopened in the same span, a restart catches up the open (until the business
  date changes for 'time') and alerts a missed close instead of doing it late.
- The close runs only when no order of the day is unclosed (Q-10): otherwise a sticky alert
  and a new try every 15 minutes. A locked / expired license turns the open into an alert.
- Sticky notifications: notifications.resolved_at + core.notifications.resolve(); the
  alerts resolve when the day opens / closes (by hand or by itself).
- services/business_days.py: the one open / close path (the routes and the loop); days opened
  or closed by the system have no opener / closer and opened_auto / closed_auto (Alembic 0052).
- Manager: Settings -> Operation "Opening and closing the day"; the bell's action buttons
  ("Open now", "Go to the overview"); Reports -> Days marks days opened / closed by itself.

Plan platform-v2 6F.8.

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

162 lines
6.7 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),
Notification.resolved_at.is_(None),
).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.ws_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()
def resolve(db, dedupe_keys) -> int:
"""Sticky alerts whose cause is gone (6F.8): hide the live rows with these dedupe keys.
Sends `platform_notification` {id, resolved: true} so open bells refresh. Commits."""
from models.notification import Notification
rows = db.query(Notification).filter(Notification.dedupe_key.in_(list(dedupe_keys)),
Notification.resolved_at.is_(None)).all()
if not rows:
return 0
now = utcnow()
for r in rows:
r.resolved_at = now
db.commit()
try:
from services.ws_bus import broadcast_sync
for r in rows:
broadcast_sync(EVENT, {"id": r.id, "resolved": True}, user_ids=recipients(db, r.audience))
except Exception:
logger.exception("notification.resolve_event_failed")
return len(rows)
# ── 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)