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:
@@ -92,6 +92,8 @@ def lookup_device(db, token: str):
|
|||||||
raise XeniaError("device.revoked")
|
raise XeniaError("device.revoked")
|
||||||
cap = over_limit(db, dev)
|
cap = over_limit(db, dev)
|
||||||
if cap is not None:
|
if cap is not None:
|
||||||
|
from routers.devices import notify_limit
|
||||||
|
notify_limit(dev.app_key, "devices", cap, db)
|
||||||
raise XeniaError("license.limit_reached", module=dev.app_key, limit="devices", max=cap)
|
raise XeniaError("license.limit_reached", module=dev.app_key, limit="devices", max=cap)
|
||||||
set_log_context(device=dev.id)
|
set_log_context(device=dev.id)
|
||||||
now = utcnow()
|
now = utcnow()
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
||||||
# domain
|
# domain
|
||||||
"order.not_found": (404, "Order {order_id} not found."),
|
"order.not_found": (404, "Order {order_id} not found."),
|
||||||
|
"notification.not_found": (404, "Notification {notification_id} not found."),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -68,5 +68,17 @@
|
|||||||
"waiter_label": "Σερβιτορος:",
|
"waiter_label": "Σερβιτορος:",
|
||||||
"without": "ΧΩΡΙΣ:"
|
"without": "ΧΩΡΙΣ:"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"notification": {
|
||||||
|
"license": {
|
||||||
|
"limit_reached": "Συμπληρώθηκε το όριο της άδειας: το {module} επιτρέπει {max} {limit}. Αναβαθμίστε την άδεια για περισσότερα.",
|
||||||
|
"expiring": "Η άδεια λήγει σε {days} ημέρες ({expires_at}). Ανανεώστε την για να κρατήσετε όλες τις λειτουργίες."
|
||||||
|
},
|
||||||
|
"support": {
|
||||||
|
"access_used": "Η υποστήριξη της Xenia συνδέθηκε στο κατάστημα (από {ip})."
|
||||||
|
},
|
||||||
|
"print": {
|
||||||
|
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες)."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,5 +68,17 @@
|
|||||||
"waiter_label": "Waiter:",
|
"waiter_label": "Waiter:",
|
||||||
"without": "NO:"
|
"without": "NO:"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"notification": {
|
||||||
|
"license": {
|
||||||
|
"limit_reached": "License limit reached: {module} allows {max} {limit}. Upgrade the license to add more.",
|
||||||
|
"expiring": "The license expires in {days} days ({expires_at}). Renew it to keep every feature."
|
||||||
|
},
|
||||||
|
"support": {
|
||||||
|
"access_used": "Xenia support logged in to this venue (from {ip})."
|
||||||
|
},
|
||||||
|
"print": {
|
||||||
|
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts)."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""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)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""notifications + notification_reads (platform notifications)
|
||||||
|
|
||||||
|
Revision ID: 0010_notifications
|
||||||
|
Revises: 0009_support_access
|
||||||
|
Create Date: 2026-11-13 11:06:59.999254
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0010_notifications'
|
||||||
|
down_revision = '0009_support_access'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('notifications',
|
||||||
|
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column('key', sa.String(), nullable=False),
|
||||||
|
sa.Column('severity', sa.String(), nullable=False),
|
||||||
|
sa.Column('audience', sa.String(), nullable=False),
|
||||||
|
sa.Column('params', sa.JSON(), nullable=True),
|
||||||
|
sa.Column('dedupe_key', sa.String(), nullable=True),
|
||||||
|
sa.Column('count', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('last_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('expires_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sqlite_autoincrement=True
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('notifications', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_notifications_audience'), ['audience'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_notifications_created_at'), ['created_at'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_notifications_dedupe_key'), ['dedupe_key'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_notifications_key'), ['key'], unique=False)
|
||||||
|
|
||||||
|
op.create_table('notification_reads',
|
||||||
|
sa.Column('notification_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('read_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['notification_id'], ['notifications.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('notification_id', 'user_id')
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table('notification_reads')
|
||||||
|
with op.batch_alter_table('notifications', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_notifications_key'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_notifications_dedupe_key'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_notifications_created_at'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_notifications_audience'))
|
||||||
|
|
||||||
|
op.drop_table('notifications')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -33,3 +33,4 @@ import models.session # noqa: F401 LoginSession (step 1.6)
|
|||||||
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
||||||
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
|
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
|
||||||
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
|
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
|
||||||
|
import models.notification # noqa: F401 Notification, NotificationRead (step 1.11)
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Platform notifications (APPS_PLATFORM §10, plan step 1.11).
|
||||||
|
|
||||||
|
System messages to staff: license limits and expiry, support access used, print
|
||||||
|
failures (later: Ergani, close-day reminders). NOT staff chat or manager messages
|
||||||
|
(models/message.py, F-030), which stay separate.
|
||||||
|
|
||||||
|
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
|
||||||
|
in the reader's language when listed.
|
||||||
|
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
|
||||||
|
- dedupe_key: while a row with the same key is still live (expires_at NULL or future),
|
||||||
|
notify() bumps its `count` / `last_at` instead of adding a row.
|
||||||
|
Written through core/notifications.py only.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Notification(Base):
|
||||||
|
__tablename__ = "notifications"
|
||||||
|
__table_args__ = {"sqlite_autoincrement": True}
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
key = Column(String, nullable=False, index=True) # e.g. "license.limit_reached"
|
||||||
|
severity = Column(String, nullable=False, default="info") # info | warning | critical
|
||||||
|
audience = Column(String, nullable=False, index=True)
|
||||||
|
params = Column(JSON, nullable=True)
|
||||||
|
dedupe_key = Column(String, nullable=True, index=True)
|
||||||
|
count = Column(Integer, nullable=False, default=1) # occurrences folded in by dedupe
|
||||||
|
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
|
||||||
|
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
|
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
|
||||||
|
|
||||||
|
|
||||||
|
class NotificationRead(Base):
|
||||||
|
__tablename__ = "notification_reads"
|
||||||
|
|
||||||
|
notification_id = Column(Integer, ForeignKey("notifications.id", ondelete="CASCADE"), primary_key=True)
|
||||||
|
user_id = Column(Integer, primary_key=True) # no FK: the support account (id 0) can read too
|
||||||
|
read_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
@@ -45,6 +45,7 @@ MODULE = Module(
|
|||||||
Mount('routers.recovery', '/api/recovery'),
|
Mount('routers.recovery', '/api/recovery'),
|
||||||
Mount('routers.devices', '/api/devices'),
|
Mount('routers.devices', '/api/devices'),
|
||||||
Mount('routers.access', '/api/access'),
|
Mount('routers.access', '/api/access'),
|
||||||
|
Mount('routers.notifications', '/api/platform/notifications'),
|
||||||
Mount('core.modules.api', '/api/platform'),
|
Mount('core.modules.api', '/api/platform'),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -230,7 +230,9 @@ def support_verify(body: SupportVerifyRequest, request: Request, db: Session = D
|
|||||||
row.session_id = session.id
|
row.session_id = session.id
|
||||||
db.commit()
|
db.commit()
|
||||||
_logger.warning("support.access_used challenge=%s sid=%s ip=%s", row.id, session.id[:8], session.ip)
|
_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),
|
return TokenResponse(access_token=make_token(support, session.id, hours=SUPPORT_SESSION_HOURS),
|
||||||
user=UserOut.model_validate(support))
|
user=UserOut.model_validate(support))
|
||||||
|
|
||||||
|
|||||||
@@ -106,9 +106,18 @@ def _check_limit(db, app_key: str, exclude_id: int | None = None) -> None:
|
|||||||
if exclude_id is not None:
|
if exclude_id is not None:
|
||||||
q = q.filter(Device.id != exclude_id)
|
q = q.filter(Device.id != exclude_id)
|
||||||
if q.count() >= cap:
|
if q.count() >= cap:
|
||||||
|
notify_limit(app_key, "devices", cap, db)
|
||||||
raise XeniaError("license.limit_reached", module=app_key, limit="devices", max=cap)
|
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:
|
def _check_mode(app_key: str, mode: str | None) -> str | None:
|
||||||
if not mode:
|
if not mode:
|
||||||
return None # site default
|
return None # site default
|
||||||
|
|||||||
@@ -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)}
|
||||||
@@ -127,6 +127,8 @@ def apply_license(now: datetime | None = None) -> None:
|
|||||||
"offline_days": (now - last_sync).days if last_sync else None})
|
"offline_days": (now - last_sync).days if last_sync else None})
|
||||||
_persist_state()
|
_persist_state()
|
||||||
entitlements.set_current(ent)
|
entitlements.set_current(ent)
|
||||||
|
from core.notifications import check_license_expiry
|
||||||
|
check_license_expiry(result.get("expires_at"), result.get("days_until_expiry"), bool(result["licensed"]))
|
||||||
if result["license_problem"]:
|
if result["license_problem"]:
|
||||||
logger.warning("License problem: %s (licensed=%s, entitlements=%s)",
|
logger.warning("License problem: %s (licensed=%s, entitlements=%s)",
|
||||||
result["license_problem"], result["licensed"], ent.mode)
|
result["license_problem"], result["licensed"], ent.mode)
|
||||||
|
|||||||
@@ -2184,6 +2184,7 @@ def _retry_sweep():
|
|||||||
# The ticket never printed and never will: this is the job's final failure.
|
# The ticket never printed and never will: this is the job's final failure.
|
||||||
logger.warning("print.job.abandoned job=%s order=%s attempts=%s reason=order_closed",
|
logger.warning("print.job.abandoned job=%s order=%s attempts=%s reason=order_closed",
|
||||||
pj.id, pj.order_id, pj.retry_count)
|
pj.id, pj.order_id, pj.retry_count)
|
||||||
|
_notify_print_failed(db, pj)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
item_ids = json.loads(pj.item_ids or "[]")
|
item_ids = json.loads(pj.item_ids or "[]")
|
||||||
@@ -2249,6 +2250,17 @@ def _retry_sweep():
|
|||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _notify_print_failed(db, pj) -> None:
|
||||||
|
"""print.failed_final: managers learn that a ticket never printed (one notification per
|
||||||
|
printer per hour; further failures in that hour are counted on it)."""
|
||||||
|
from core.notifications import notify
|
||||||
|
printer = db.get(Printer, pj.printer_id)
|
||||||
|
notify("print.failed_final", "critical", "all_managers",
|
||||||
|
{"order_id": pj.order_id, "printer": printer.name if printer else str(pj.printer_id),
|
||||||
|
"attempts": pj.retry_count or 0, "job_id": pj.id},
|
||||||
|
dedupe_key=f"print.failed_final:{pj.printer_id}", ttl=datetime.timedelta(hours=1), db=db)
|
||||||
|
|
||||||
|
|
||||||
def _retry_loop():
|
def _retry_loop():
|
||||||
while True:
|
while True:
|
||||||
_time.sleep(_RETRY_INTERVAL)
|
_time.sleep(_RETRY_INTERVAL)
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"""Platform notifications (plan step 1.11, APPS_PLATFORM §10)."""
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from core.notifications import check_license_expiry, notify
|
||||||
|
|
||||||
|
URL = "/api/platform/notifications"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def events(monkeypatch):
|
||||||
|
sent = []
|
||||||
|
import services.sse_bus as bus
|
||||||
|
monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, user_ids=None: sent.append((t, d, sorted(user_ids or []))))
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def people(make_user, login):
|
||||||
|
users = {r: make_user(role=r) for r in ("owner", "store_manager", "waiter", "superadmin")}
|
||||||
|
return {r: (u, login(u)) for r, u in users.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def listing(client, h, **q):
|
||||||
|
r = client.get(URL, headers=h, params=q)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
|
||||||
|
def keys(client, h):
|
||||||
|
return [i["key"] for i in listing(client, h)["items"]]
|
||||||
|
|
||||||
|
|
||||||
|
# ── audience ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_audience_filtering(client, db, people, events):
|
||||||
|
owner, manager, waiter, admin = (people[r] for r in ("owner", "store_manager", "waiter", "superadmin"))
|
||||||
|
notify("license.expiring", "warning", "perm:core.modules.manage", {"days": 7, "expires_at": "x"}, db=db)
|
||||||
|
notify("print.failed_final", "critical", "all_managers", {"order_id": 1, "printer": "Bar", "attempts": 3}, db=db)
|
||||||
|
notify("support.access_used", "warning", f"user:{waiter[0].id}", {"ip": "1.2.3.4"}, db=db)
|
||||||
|
|
||||||
|
assert sorted(keys(client, owner[1])) == ["license.expiring", "print.failed_final"]
|
||||||
|
assert keys(client, manager[1]) == ["print.failed_final"] # no core.modules.manage
|
||||||
|
assert keys(client, waiter[1]) == ["support.access_used"] # only what's addressed to them
|
||||||
|
assert sorted(keys(client, admin[1])) == ["license.expiring", "print.failed_final"]
|
||||||
|
|
||||||
|
# the event names the audience's users, ids only (CS-2)
|
||||||
|
t, data, uids = events[1]
|
||||||
|
assert t == "platform_notification" and set(data) == {"id"}
|
||||||
|
assert owner[0].id in uids and manager[0].id in uids and waiter[0].id not in uids
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_audience_is_refused_not_raised(db):
|
||||||
|
assert notify("x", "info", "perm:no.such.key", db=db) is None
|
||||||
|
assert notify("x", "loud", "all_managers", db=db) is None
|
||||||
|
|
||||||
|
|
||||||
|
# ── dedupe ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_dedupe_folds_repeats_quietly(client, db, people, events):
|
||||||
|
owner = people["owner"]
|
||||||
|
a = notify("print.failed_final", "critical", "all_managers", {"order_id": 1, "printer": "Bar", "attempts": 3},
|
||||||
|
dedupe_key="p:1", ttl=timedelta(hours=1), db=db)
|
||||||
|
client.post(f"{URL}/{a}/read", headers=owner[1])
|
||||||
|
b = notify("print.failed_final", "critical", "all_managers", {"order_id": 2, "printer": "Bar", "attempts": 4},
|
||||||
|
dedupe_key="p:1", ttl=timedelta(hours=1), db=db)
|
||||||
|
assert a == b and len(events) == 1 # no second event
|
||||||
|
item = listing(client, owner[1])["items"][0]
|
||||||
|
assert item["count"] == 2 and item["params"]["order_id"] == 2 and item["read"] is True
|
||||||
|
|
||||||
|
# once the first one expired, the same key makes a new notification
|
||||||
|
from models.notification import Notification
|
||||||
|
db.get(Notification, a).expires_at = datetime.now(timezone.utc) - timedelta(seconds=1)
|
||||||
|
db.commit()
|
||||||
|
c = notify("print.failed_final", "critical", "all_managers", {"order_id": 3, "printer": "Bar", "attempts": 1},
|
||||||
|
dedupe_key="p:1", ttl=timedelta(hours=1), db=db)
|
||||||
|
assert c != a and [i["id"] for i in listing(client, owner[1])["items"]] == [c] # expired ones are hidden
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_and_read_all(client, db, people):
|
||||||
|
owner, waiter = people["owner"], people["waiter"]
|
||||||
|
ids = [notify("print.failed_final", "critical", "all_managers", {"order_id": i, "printer": "P", "attempts": 1}, db=db)
|
||||||
|
for i in range(3)]
|
||||||
|
assert listing(client, owner[1])["unread"] == 3
|
||||||
|
assert client.post(f"{URL}/{ids[0]}/read", headers=owner[1]).status_code == 200
|
||||||
|
body = listing(client, owner[1], unread_only=True)
|
||||||
|
assert body["unread"] == 2 and {i["id"] for i in body["items"]} == set(ids[1:])
|
||||||
|
assert client.post(f"{URL}/read-all", headers=owner[1]).json() == {"marked": 2}
|
||||||
|
assert listing(client, owner[1])["unread"] == 0
|
||||||
|
# someone outside the audience can't touch it
|
||||||
|
r = client.post(f"{URL}/{ids[0]}/read", headers=waiter[1])
|
||||||
|
assert r.status_code == 404 and r.json()["error"]["code"] == "notification.not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_message_in_the_readers_language(client, db, make_user, login):
|
||||||
|
u = make_user(role="owner", language="el")
|
||||||
|
notify("print.failed_final", "critical", "all_managers", {"order_id": 7, "printer": "Bar", "attempts": 2}, db=db)
|
||||||
|
msg = listing(client, login(u))["items"][0]["message"]
|
||||||
|
assert msg.startswith("Ένα δελτίο της παραγγελίας #7")
|
||||||
|
|
||||||
|
|
||||||
|
# ── producers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_license_expiring_steps(client, db, people):
|
||||||
|
owner = people["owner"]
|
||||||
|
end = "2026-11-20T00:00:00+00:00"
|
||||||
|
check_license_expiry(end, 20, True, db)
|
||||||
|
assert keys(client, owner[1]) == []
|
||||||
|
check_license_expiry(end, 12, True, db)
|
||||||
|
check_license_expiry(end, 9, True, db) # same 14-day step: nothing new
|
||||||
|
check_license_expiry(end, 6, True, db)
|
||||||
|
check_license_expiry(end, 3, True, db)
|
||||||
|
check_license_expiry(end, 0, True, db) # the last day
|
||||||
|
items = listing(client, owner[1])["items"]
|
||||||
|
assert [i["params"]["days"] for i in items] == [0, 3, 6, 12] and all(i["count"] == 1 for i in items)
|
||||||
|
assert [i["severity"] for i in items] == ["critical", "critical", "warning", "warning"]
|
||||||
|
check_license_expiry(end, 5, False, db) # unlicensed (free tier): no warning
|
||||||
|
assert len(listing(client, owner[1])["items"]) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_limit_reached_is_notified_once_and_counted(client, db, people):
|
||||||
|
from core.modules import entitlements as E
|
||||||
|
owner = people["owner"]
|
||||||
|
E.set_current(E.compute({"v": 2, "site_id": "s", "modules": {"ordering": {}, "kds": {"limits": {"devices": 0}}}},
|
||||||
|
True, False, datetime(2026, 11, 12, tzinfo=timezone.utc), False), notify=False)
|
||||||
|
for _ in range(2):
|
||||||
|
code = client.post("/api/devices/pair-request").json()["code"]
|
||||||
|
r = client.post("/api/devices", headers=owner[1], json={"code": code, "app_key": "kds", "name": "K"})
|
||||||
|
assert r.json()["error"]["code"] == "license.limit_reached"
|
||||||
|
item = listing(client, owner[1])["items"][0]
|
||||||
|
assert item["key"] == "license.limit_reached" and item["count"] == 2
|
||||||
|
assert item["params"] == {"module": "kds", "limit": "devices", "max": 0}
|
||||||
|
assert keys(client, people["store_manager"][1]) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_support_access_used_notifies_owners(client, db, people, monkeypatch):
|
||||||
|
from config import settings
|
||||||
|
from core import support_codes as C
|
||||||
|
monkeypatch.setattr(settings, "SITE_ID", "site-A")
|
||||||
|
monkeypatch.setattr(settings, "SUPPORT_SECRET", C.site_secret("k" * 32, "site-A"))
|
||||||
|
ch = client.post("/api/auth/support/challenge").json()["challenge"]
|
||||||
|
r = client.post("/api/auth/support/verify", json={"challenge": ch, "code": C.code_for(settings.SUPPORT_SECRET, "site-A", ch)})
|
||||||
|
assert r.status_code == 200
|
||||||
|
item = listing(client, people["owner"][1])["items"][0]
|
||||||
|
assert item["key"] == "support.access_used" and item["severity"] == "warning" and item["params"]["ip"]
|
||||||
|
assert keys(client, people["store_manager"][1]) == [] # owners (core.settings.manage) only
|
||||||
|
|
||||||
|
|
||||||
|
def test_print_failed_final(client, db, people):
|
||||||
|
from services.printer_service import _notify_print_failed
|
||||||
|
pj = SimpleNamespace(id=5, order_id=42, printer_id=999, retry_count=7)
|
||||||
|
_notify_print_failed(db, pj)
|
||||||
|
_notify_print_failed(db, pj)
|
||||||
|
item = listing(client, people["store_manager"][1])["items"][0]
|
||||||
|
assert item["key"] == "print.failed_final" and item["count"] == 2
|
||||||
|
assert item["message"] == "A ticket for order #42 never printed on 999 (7 attempts)."
|
||||||
|
assert keys(client, people["waiter"][1]) == []
|
||||||
Reference in New Issue
Block a user