Files
xenia-pos-local/local_backend/tests/test_notifications.py

185 lines
9.7 KiB
Python

"""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.ws_bus as bus
monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, user_ids=None, device_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"]
# a date still ahead (the fixed "2026-11-20" became the past on that very day and the test began failing)
end = (datetime.now(timezone.utc) + timedelta(days=30)).replace(microsecond=0).isoformat()
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]) == []
@pytest.mark.parametrize("setting,alerted_at", [(None, 2), ("1", 1), ("3", 3), ("0", None)])
def test_print_failing_after_n_attempts(client, db, people, setting, alerted_at):
from models.settings import PosSettings
from services.printer_service import _notify_print_failing
if setting is not None:
db.merge(PosSettings(key="print.alert_after_failures", value=setting))
db.commit()
pj = SimpleNamespace(id=5, order_id=42, printer_id=3, retry_count=0)
seen = []
for attempt in range(1, 5):
pj.retry_count = attempt
_notify_print_failing(db, pj, "Bar")
if keys(client, people["store_manager"][1]) and not seen:
seen.append(attempt)
assert (seen[0] if seen else None) == alerted_at
if alerted_at:
item = listing(client, people["store_manager"][1])["items"][0]
assert item["key"] == "print.failing" and item["count"] == 1 # once per job
assert "still retrying" in item["message"]
# another job on the same printer within the hour folds in
_notify_print_failing(db, SimpleNamespace(id=6, order_id=43, printer_id=3, retry_count=alerted_at), "Bar")
assert listing(client, people["store_manager"][1])["items"][0]["count"] == 2