Plan phase 3S, step S.6. - Pull: "reservation" / "preorder" orders become Reservations waiting for an answer (status "requested"; services/online_reservations.py), with the food ordered ahead kept on the booking (items_json at the cloud's prices, the site's price check) — no order yet. Migration 0020 (reservations: online_order_cloud_id, online_ref, items_json, total, online_price_diff, fire_at, order_id, response_note). - Confirm → the food's fire time = booking time − fire minutes (setting); the fire worker (connect_orders, every 20 s) turns the food into an order at that time (needs an open business day; waits otherwise): kitchen tickets, KDS (reference and time). Early arrival fires at once. Seating moves the order to the table (refused if the table has an open order). Decline / cancel / no-show with a reason. Every step mirrored to the cloud. - Found: the KDS filter dropped every online order without an online status (SQL NULL in NOT(a AND b)) — made NULL-safe. - Counter: Online → Bookings (requests first, then upcoming), BookingPanel (confirm, decline with reasons, food and when it goes to the kitchen, seat at a free table, cancel, no-show); the Online badge and chime count booking requests. - Manager: Online ordering → Table bookings settings (on, food ahead, hours, slot, notice, days ahead, party size, fire minutes); the dashboard's reservations card confirms / declines online requests; the reservations router delegates online bookings' status steps. - Tests: tests/test_online_bookings.py (8), unit tests (terminal, manager), e2e: order app (book with food → the venue confirms), terminal (request → confirm → the two dishes reach the KDS at the fire time, not before → seated), manager (booking settings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
204 lines
9.9 KiB
Python
204 lines
9.9 KiB
Python
"""Module registry, enablement, gating, workers and bootstrap (plan step 1.3, D-19, §4)."""
|
|
import asyncio
|
|
import importlib
|
|
import pkgutil
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from fastapi import APIRouter
|
|
|
|
from core.modules import state, supervisor
|
|
from core.modules.model import DeviceApp, Module, Mount, Perm, SettingDef
|
|
from core.modules.registry import ManifestError, registry, validate
|
|
|
|
BACKEND = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
# ── registry ─────────────────────────────────────────────────────────────────
|
|
|
|
def test_registry_has_the_section_4_2_map():
|
|
expected = {"core", "history", "catalog", "ordering", "waiter_app", "reports", "pricing", "tabs", "crm",
|
|
"expenses", "inventory", "staff_planning", "notes", "chat", "reservations", "kds", "pos_counter",
|
|
"customer_display", "signage", "menu_tablet", "connect_menu", "connect_orders", "connect_remote",
|
|
"caller_id", "fiscal"}
|
|
assert set(registry()) == expected
|
|
|
|
|
|
def test_every_router_in_routers_is_mounted_by_exactly_one_module():
|
|
mounted = {(mt.module, mt.attr) for m in registry().values() for mt in m.routers}
|
|
found = set()
|
|
for info in pkgutil.iter_modules([str(BACKEND / "routers")]):
|
|
mod = importlib.import_module(f"routers.{info.name}")
|
|
for attr, obj in vars(mod).items():
|
|
if isinstance(obj, APIRouter) and obj.routes and _defined_in(mod, attr):
|
|
found.add((f"routers.{info.name}", attr))
|
|
assert len(found) >= 30, f"scan found too few routers: {sorted(found)}"
|
|
assert found - mounted == set(), f"routers not mounted by any manifest: {found - mounted}"
|
|
|
|
|
|
def _defined_in(mod, attr):
|
|
"""True unless the router object was imported from another module."""
|
|
obj = getattr(mod, attr)
|
|
for other in list(vars(mod).values()):
|
|
if other is not obj and hasattr(other, attr) and getattr(other, attr) is obj:
|
|
return False
|
|
return True
|
|
|
|
|
|
def _m(key="x", **kw):
|
|
return Module(key=key, kind=kw.pop("kind", "feature"), name=key, **kw)
|
|
|
|
|
|
@pytest.mark.parametrize("modules,msg", [
|
|
([_m("x", permissions=(Perm("y.do", "d"),))], "must start with"),
|
|
([_m("x", depends=("nope",))], "unknown module"),
|
|
([_m("a", depends=("b",)), _m("b", depends=("a",))], "cycle"),
|
|
([_m("x", permissions=(Perm("x.do", "d", roles=("emperor",)),))], "unknown roles"),
|
|
([_m("x", permissions=(Perm("x.do", "d", roles=("superadmin",)),))], "unknown roles"),
|
|
([_m("a", settings=(SettingDef("s.k", "1", "d"),)), _m("b", settings=(SettingDef("s.k", "1", "d"),))], "already declared"),
|
|
([_m("a", routers=(Mount("routers.tabs", "/a"),)), _m("b", routers=(Mount("routers.tabs", "/b"),))], "already mounted"),
|
|
([_m("x", device_app=DeviceApp())], "only for kind='app'"),
|
|
([_m("x"), _m("x")], "duplicate key"),
|
|
([_m("x", kind="app", device_app=DeviceApp(login_modes=("pin",)))], "must declare the permission 'x.access'"),
|
|
([_m("x", kind="app", device_app=DeviceApp(login_modes=("face",)))], "login_modes must be"),
|
|
([_m("x", kind="app", device_app=DeviceApp(login_modes=()))], "login_modes must be"),
|
|
([_m("Bad-Key")], "must match"),
|
|
([_m("x", workers=("no_colon",))], "package.module:function"),
|
|
([_m("x", settings=(SettingDef("x.e", "c", "d", type="enum", choices=("a", "b")),))], "not in choices"),
|
|
])
|
|
def test_bad_manifests_are_rejected(modules, msg):
|
|
with pytest.raises(ManifestError, match=msg):
|
|
validate(modules, check_imports=False)
|
|
|
|
|
|
def test_unimportable_router_is_rejected():
|
|
with pytest.raises(ManifestError, match="cannot import"):
|
|
validate([_m("x", routers=(Mount("routers.no_such_router", "/x"),))])
|
|
|
|
|
|
# ── enablement + gating ──────────────────────────────────────────────────────
|
|
|
|
def test_disabling_tabs_blocks_its_api_and_enabling_restores_it(client, make_user, login): # "done when"
|
|
admin = make_user(role="superadmin")
|
|
h = login(admin)
|
|
assert client.get("/api/tabs/", headers=h).status_code == 200
|
|
|
|
r = client.put("/api/platform/modules/tabs", headers=h, json={"enabled": False})
|
|
assert r.status_code == 200 and r.json()["enabled"] is False and r.json()["effective"] is False
|
|
blocked = client.get("/api/tabs/", headers=h)
|
|
assert blocked.status_code == 403
|
|
assert blocked.json()["error"] == {"code": "module.disabled", "params": {"module": "tabs"},
|
|
"message": "The tabs module is turned off."}
|
|
|
|
assert client.put("/api/platform/modules/tabs", headers=h, json={"enabled": True}).status_code == 200
|
|
assert client.get("/api/tabs/", headers=h).status_code == 200
|
|
|
|
|
|
def test_disabling_a_dependency_turns_dependents_off(client, make_user, login):
|
|
h = login(make_user(role="superadmin"))
|
|
client.put("/api/platform/modules/crm", headers=h, json={"enabled": False})
|
|
mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=h).json()["modules"]}
|
|
assert mods["crm"]["effective"] is False
|
|
assert mods["tabs"]["enabled"] is True and mods["tabs"]["effective"] is False # tabs needs crm
|
|
assert client.get("/api/tabs/", headers=h).json()["error"]["code"] == "module.disabled"
|
|
|
|
|
|
def test_core_cannot_be_disabled(client, make_user, login):
|
|
r = client.put("/api/platform/modules/core", headers=login(make_user(role="superadmin")), json={"enabled": False})
|
|
assert r.status_code == 400 and r.json()["error"]["code"] == "module.cannot_disable"
|
|
|
|
|
|
def test_unknown_module(client, make_user, login):
|
|
r = client.put("/api/platform/modules/nope", headers=login(make_user(role="superadmin")), json={"enabled": False})
|
|
assert r.status_code == 404 and r.json()["error"]["code"] == "module.unknown"
|
|
|
|
|
|
def test_waiter_cannot_toggle_modules(client, make_user, login):
|
|
r = client.put("/api/platform/modules/tabs", headers=login(make_user(role="waiter")), json={"enabled": False})
|
|
assert r.status_code == 403
|
|
|
|
|
|
def test_core_routes_are_never_gated(client, make_user, login):
|
|
assert client.get("/api/auth/me", headers=login(make_user(role="waiter"))).status_code == 200
|
|
|
|
|
|
# ── bootstrap + catalogue ────────────────────────────────────────────────────
|
|
|
|
def test_bootstrap_without_login(client):
|
|
r = client.get("/api/platform/bootstrap")
|
|
assert r.status_code == 200
|
|
b = r.json()
|
|
assert b["venue"]["timezone"] == "Europe/Athens" and b["venue"]["currency"] == "EUR"
|
|
assert b["venue"]["language"] == "en" and b["languages"] == ["el", "en"]
|
|
assert b["user"] is None and b["permissions"] == []
|
|
assert {"core", "ordering", "kds"} <= {m["key"] for m in b["modules"]}
|
|
|
|
|
|
def test_bootstrap_with_login_lists_role_keys_of_effective_modules(client, make_user, login):
|
|
waiter = make_user(role="waiter", language="el")
|
|
b = client.get("/api/platform/bootstrap", headers=login(waiter)).json()
|
|
assert b["user"]["role"] == "waiter" and b["language"] == "el"
|
|
assert "waiter_app.access" in b["permissions"] and "ordering.orders.open" in b["permissions"]
|
|
assert "core.settings.manage" not in b["permissions"]
|
|
|
|
admin = make_user(role="superadmin")
|
|
client.put("/api/platform/modules/kds", headers=login(admin), json={"enabled": False})
|
|
keys = client.get("/api/platform/bootstrap", headers=login(admin)).json()["permissions"]
|
|
assert "core.modules.manage" in keys and "kds.access" not in keys
|
|
|
|
|
|
def test_bootstrap_with_bad_token_is_anonymous(client):
|
|
r = client.get("/api/platform/bootstrap", headers={"Authorization": "Bearer nonsense"})
|
|
assert r.status_code == 200 and r.json()["user"] is None
|
|
|
|
|
|
def test_modules_catalogue_shape(client, make_user, login):
|
|
body = client.get("/api/platform/modules", headers=login(make_user(role="store_manager"))).json()
|
|
kds = next(m for m in body["modules"] if m["key"] == "kds")
|
|
assert kds["kind"] == "app" and kds["depends"] == ["ordering"]
|
|
assert kds["limits"][0]["key"] == "devices" and kds["device_app"]["login_modes"]
|
|
assert {"entitled", "enabled", "effective", "can_disable", "permissions", "settings"} <= set(kds)
|
|
|
|
|
|
def test_settings_come_from_manifests(client, make_user, login):
|
|
s = client.get("/api/settings/", headers=login(make_user(role="superadmin"))).json()
|
|
assert s["venue.currency"]["value"] == "EUR"
|
|
assert s["fiscal.type"]["value"] == "txt_file"
|
|
assert "orders.courses_enabled" in s
|
|
|
|
|
|
# ── workers ──────────────────────────────────────────────────────────────────
|
|
|
|
def test_supervisor_starts_and_stops_workers(monkeypatch):
|
|
calls = []
|
|
|
|
async def fake_worker():
|
|
calls.append("run")
|
|
await asyncio.sleep(3600)
|
|
|
|
monkeypatch.setattr(supervisor, "_resolve", lambda spec: fake_worker)
|
|
|
|
async def scenario():
|
|
supervisor._reconcile(frozenset({"connect_menu", "connect_orders"}))
|
|
await asyncio.sleep(0)
|
|
started = supervisor.running()
|
|
supervisor._reconcile(frozenset({"connect_orders"}))
|
|
await asyncio.sleep(0)
|
|
after = supervisor.running()
|
|
supervisor.stop_all()
|
|
return started, after
|
|
|
|
started, after = asyncio.run(scenario())
|
|
assert started == ["connect_menu:services.cloud_sync:menu_push_worker",
|
|
"connect_orders:services.cloud_sync:order_pull_worker",
|
|
"connect_orders:services.online_reservations:fire_worker"] # S.6
|
|
assert after == ["connect_orders:services.cloud_sync:order_pull_worker",
|
|
"connect_orders:services.online_reservations:fire_worker"]
|
|
assert calls == ["run", "run", "run"]
|
|
|
|
|
|
def test_worker_specs_resolve_to_coroutines():
|
|
for m in registry().values():
|
|
for spec in m.workers:
|
|
assert asyncio.iscoroutinefunction(supervisor._resolve(spec)), spec
|