feat(backend): customer display looks on the media library, one per display (platform-v2 step 5.3)

- display_looks (Alembic 0028): named idle screens, one default; config is
  the 3.4 design with pictures as media library ids. 0028 turns the setting
  customer_display.idle into the look "Main" and moves its data/display_media
  pictures into the library (the old folder stays on disk).
- A display shows the look in its device config `look` (ref ConfigField,
  choices_from "display_looks", validated in device_config) or the default.
- /api/display/looks (GET also for core.devices.manage), POST, PUT,
  POST /{id}/default, DELETE (not the default; its displays go back to it);
  /api/display/displays and PUT /displays/{id}/look. A change sends
  display.settings only to the displays showing that look.
- /api/display/settings, /api/display/media* and their error codes are gone;
  GET /api/display/state keeps its shape (logo card size, image/slides full).
- Looks register their media usage (a picture in a look can't be deleted).
- tests: test_customer_display.py (7, incl. two displays two slideshows and
  the 0028 data move); 501 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 17:50:51 +02:00
co-authored by Claude Opus 5.5
parent 87dff573df
commit 27d7bbb976
13 changed files with 495 additions and 173 deletions
+117 -40
View File
@@ -1,22 +1,17 @@
"""The customer display (plan step 3.4): a POS pushes what its customer sees, only its own
displays hear it; the idle screen is the venue's design (name, logo, both, blank, an image, a
slideshow, a QR code), with images the venue uploads."""
import io
"""The customer display (plan steps 3.4, 5.3): a POS pushes what its customer sees, only its own
displays hear it; the idle screen is a look the venue designs (name, logo, both, blank, an image,
a slideshow, a QR code) with pictures from the media library, and each display can show its own."""
import pytest
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
PNG = (b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
b"\x00\x00\x00\rIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82")
from tests.test_media import jpeg, media_dir, mp4, png_alpha, up # noqa: F401 (fixture + helpers)
@pytest.fixture(autouse=True)
def media_dir(tmp_path, monkeypatch):
def _fresh(media_dir):
import routers.customer_display as cd
monkeypatch.setattr(cd, "MEDIA_DIR", str(tmp_path / "media"))
cd._last.clear()
return tmp_path / "media"
@pytest.fixture
@@ -65,43 +60,125 @@ def test_a_sale_shows_only_on_its_own_display(client, counters, sent):
assert client.post("/api/display/state", headers=one["pos"], json={"mode": "dance"}).status_code == 422
def test_the_idle_screen_is_the_venues_design(client, owner_h, counters, sent, media_dir, monkeypatch):
def test_the_idle_screen_is_a_look_from_the_library(client, owner_h, counters, sent, monkeypatch):
from services import cloud_sync
monkeypatch.setitem(cloud_sync.license_state, "apps_url", "https://menu.example.com")
monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1")
s = client.get("/api/display/settings", headers=owner_h).json()
assert s["idle"]["style"] == "name" and s["media"] == []
up = lambda data, ctype="image/png": client.post("/api/display/media", headers=owner_h, # noqa: E731
files={"file": ("x.png", io.BytesIO(data), ctype)})
logo, photo = up(PNG).json(), up(PNG).json()
assert logo["url"].startswith("/api/display/media/") and len(list(media_dir.iterdir())) == 2
assert err(up(b"hello", "text/plain")) == "display.media_type"
assert client.get(logo["url"]).content == PNG # the displays load it with <img>
assert client.get("/api/display/media/../../secret.png").status_code == 404
# a slideshow of the two photos, with a line of text
body = {"style": "slideshow", "slides": [logo["name"], photo["name"]], "slide_seconds": 5, "message": "Kalimera!"}
r = client.put("/api/display/settings", headers=owner_h, json=body)
looks = client.get("/api/display/looks", headers=owner_h).json()
assert [(x["name"], x["is_default"], x["config"]["style"]) for x in looks] == [("Main", True, "name")]
main = looks[0]
assert sorted(d["id"] for d in main["displays"]) == sorted([counters[1]["display_id"], counters[2]["display_id"]])
logo, photo = up(client, owner_h, jpeg(400, 200, (1, 1, 1))).json(), up(client, owner_h, jpeg(1600, 900, (2, 2, 2))).json()
# a slideshow of two library photos, with a line of text: the displays hear it at once
body = {"style": "slideshow", "slides": [logo["id"], photo["id"]], "slide_seconds": 5, "message": "Kalimera!"}
r = client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": body})
assert r.status_code == 200, r.text
assert sorted(kw["device_ids"] for k, _, kw in sent if k == "display.settings")[0] == sorted([counters[1]["display_id"], counters[2]["display_id"]])
idle = client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]
assert idle["style"] == "slideshow" and idle["slide_urls"] == [logo["url"], photo["url"]] and idle["message"] == "Kalimera!"
assert idle["style"] == "slideshow" and idle["slide_urls"] == [logo["urls"]["full"], photo["urls"]["full"]] and idle["message"] == "Kalimera!"
# a QR code: the venue's ordering link, or any link
client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "ordering", "qr_caption": "Order online"})
client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "qr", "qr_target": "ordering", "qr_caption": "Order online"}})
assert client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]["qr_link"] == "https://menu.example.com/order/taverna-1"
assert err(client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "custom"})) == "display.qr_url_missing"
assert client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "custom", "qr_url": "javascript:x"}).status_code == 422
# an image that isn't there; deleting one takes it off the screen
assert err(client.put("/api/display/settings", headers=owner_h, json={"style": "logo", "logo": "0" * 32 + ".png"})) == "display.media_unknown"
client.put("/api/display/settings", headers=owner_h, json={"style": "name_logo", "logo": logo["name"], "theme": "light"})
assert client.delete(f"/api/display/media/{logo['name']}", headers=owner_h).status_code == 204
after = client.get("/api/display/settings", headers=owner_h).json()
assert after["idle"]["logo"] is None and [m["name"] for m in after["media"]] == [photo["name"]] and after["idle"]["theme"] == "light"
assert err(client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "qr", "qr_target": "custom"}})) == "display.qr_url_missing"
assert client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "qr", "qr_target": "custom", "qr_url": "javascript:x"}}).status_code == 422
# pictures must be library pictures
assert err(client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "logo", "logo": 99999}})) == "media.not_found"
video = up(client, owner_h, mp4(), name="v.mp4", ctype="video/mp4").json()
assert err(client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "image", "image": video["id"]}})) == "media.not_a_picture"
# a picture a look uses can't be deleted from the library
client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "name_logo", "logo": logo["id"], "theme": "light"}})
r = client.delete(f"/api/media/{logo['id']}", headers=owner_h)
assert r.status_code == 409 and r.json()["error"]["params"]["used_by"] == [{"kind": "display_look", "id": main["id"], "name": "Main"}]
assert client.get("/api/display/state", headers=counters[2]["display"]).json()["idle"]["logo_url"] == logo["urls"]["card"]
def test_settings_need_the_key(client, make_user):
from tests.conftest import TEST_PASSWORD
waiter = make_user(role="waiter", username="w_display")
tok = client.post("/api/auth/login", json={"client": "manager", "username": "w_display", "password": TEST_PASSWORD}).json().get("access_token")
h = {"Authorization": f"Bearer {tok}"} if tok else {}
assert client.get("/api/display/settings", headers=h).status_code in (401, 403)
assert waiter.id
def test_two_displays_two_slideshows(client, owner_h, counters, sent):
"""Done when (5.3): two displays show two different slideshows from the library."""
a, b, c = (up(client, owner_h, jpeg(800, 600, (i, i, i))).json() for i in (10, 20, 30))
main = client.get("/api/display/looks", headers=owner_h).json()[0]
client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "slideshow", "slides": [a["id"], b["id"]]}})
promo = client.post("/api/display/looks", headers=owner_h, json={"name": "Promo", "config": {"style": "slideshow", "slides": [c["id"]], "slide_seconds": 4}})
assert promo.status_code == 201, promo.text
promo = promo.json()
assert promo["displays"] == [] and promo["is_default"] is False
two = counters[2]["display_id"]
sent.clear()
r = client.put(f"/api/display/displays/{two}/look", headers=owner_h, json={"look_id": promo["id"]})
assert r.status_code == 200 and r.json()["look_id"] == promo["id"]
assert [(k, kw["device_ids"]) for k, _, kw in sent] == [("display.settings", [two])]
one_idle = client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]
two_idle = client.get("/api/display/state", headers=counters[2]["display"]).json()["idle"]
assert one_idle["slide_urls"] == [a["urls"]["full"], b["urls"]["full"]]
assert two_idle["slide_urls"] == [c["urls"]["full"]] and two_idle["slide_seconds"] == 4
looks = {x["name"]: x for x in client.get("/api/display/looks", headers=owner_h).json()}
assert [d["id"] for d in looks["Promo"]["displays"]] == [two] and [d["id"] for d in looks["Main"]["displays"]] == [counters[1]["display_id"]]
assert {d["id"]: d["look_id"] for d in client.get("/api/display/displays", headers=owner_h).json()} == {counters[1]["display_id"]: None, two: promo["id"]}
# a change to Promo reaches only the display that shows it
sent.clear()
client.put(f"/api/display/looks/{promo['id']}", headers=owner_h, json={"name": "Summer promo"})
assert [kw["device_ids"] for k, _, kw in sent] == [[two]]
# the default can't be deleted; deleting Promo puts its display back on the default
assert err(client.delete(f"/api/display/looks/{main['id']}", headers=owner_h)) == "display.look_default"
assert client.delete(f"/api/display/looks/{promo['id']}", headers=owner_h).status_code == 204
assert client.get("/api/display/state", headers=counters[2]["display"]).json()["idle"]["slide_urls"] == one_idle["slide_urls"]
def test_a_new_default_and_copies(client, owner_h, counters, sent):
main = client.get("/api/display/looks", headers=owner_h).json()[0]
client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "blank", "theme": "light"}})
copy = client.post("/api/display/looks", headers=owner_h, json={"name": "Copy", "copy_of": main["id"]}).json()
assert copy["config"]["style"] == "blank" and copy["config"]["theme"] == "light"
client.put(f"/api/display/looks/{copy['id']}", headers=owner_h, json={"config": {"style": "name", "theme": "dark"}})
sent.clear()
assert client.post(f"/api/display/looks/{copy['id']}/default", headers=owner_h).json()["is_default"] is True
assert sorted(kw["device_ids"] for k, _, kw in sent)[0] == sorted([counters[1]["display_id"], counters[2]["display_id"]])
assert client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]["style"] == "name"
assert [x["name"] for x in client.get("/api/display/looks", headers=owner_h).json() if x["is_default"]] == ["Copy"]
def test_the_devices_page_offers_the_looks(client, owner_h, counters):
"""The display's `look` is a device config ref (the Devices page edits it too)."""
promo = client.post("/api/display/looks", headers=owner_h, json={"name": "Promo"}).json()
one = counters[1]["display_id"]
r = client.patch(f"/api/devices/{one}", headers=owner_h, json={"config": {"look": promo["id"]}})
assert r.status_code == 200, r.text
assert [d["look_id"] for d in client.get("/api/display/displays", headers=owner_h).json() if d["id"] == one] == [promo["id"]]
assert err(client.patch(f"/api/devices/{one}", headers=owner_h, json={"config": {"look": 99999}})) == "validation.device_config"
assert err(client.put(f"/api/display/displays/{counters[1]['pos_id']}/look", headers=owner_h, json={"look_id": None})) == "display.not_a_display"
def test_migration_0028_turns_the_idle_setting_into_a_look(tmp_path, monkeypatch, media_dir):
import json
from alembic import command
from sqlalchemy import create_engine, text
from core.schema import alembic_config, upgrade_to_head
old = tmp_path / "display_media"
old.mkdir()
(old / ("a" * 32 + ".jpg")).write_bytes(jpeg(640, 480, (5, 6, 7)))
(old / ("b" * 32 + ".png")).write_bytes(png_alpha(64, 64))
monkeypatch.setenv("XENIA_DISPLAY_MEDIA_DIR", str(old))
eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}")
cfg = {"style": "slideshow", "slides": ["a" * 32 + ".jpg", "c" * 32 + ".jpg", "b" * 32 + ".png"], "logo": "a" * 32 + ".jpg",
"message": "Hi", "theme": "light"}
with eng.begin() as conn:
command.upgrade(alembic_config(conn), "0027_product_media")
conn.execute(text("insert into pos_settings (key, value, updated_at) values ('customer_display.idle', :v, '2026-11-01 10:00:00.000000')"), {"v": json.dumps(cfg)})
upgrade_to_head(eng)
with eng.connect() as conn:
looks = conn.execute(text("select name, is_default, config from display_looks")).fetchall()
media = dict(conn.execute(text("select original_name, id from media")).fetchall())
left = conn.execute(text("select count(*) from pos_settings where key = 'customer_display.idle'")).scalar()
eng.dispose()
assert len(looks) == 1 and looks[0][0] == "Main" and looks[0][1]
moved = json.loads(looks[0][2])
a, b = media["a" * 32 + ".jpg"], media["b" * 32 + ".png"]
assert moved["slides"] == [a, b] and moved["logo"] == a and moved["message"] == "Hi" and moved["theme"] == "light"
assert left == 0
def test_looks_need_the_key(client, make_user, login):
waiter = login(make_user(role="waiter"))
assert client.get("/api/display/looks", headers=waiter).status_code == 403
assert client.post("/api/display/looks", headers=waiter, json={"name": "x"}).status_code == 403
devices_only = login(make_user(role="waiter", keys=["core.devices.manage"]))
assert client.get("/api/display/looks", headers=devices_only).status_code == 200
+1 -1
View File
@@ -217,7 +217,7 @@ def test_module_catalogue_describes_config(client, owner_h):
assert kds["prep_zone_id"] == {"key": "prep_zone_id", "type": "ref", "default": None, "choices": [], "min": None,
"max": None, "choices_from": "prep_zones", "group": "zone", "after": None}
assert kds["age_late_minutes"]["after"] == "age_warning_minutes" and kds["colour_fresh"]["type"] == "color"
assert mods["customer_display"]["device_app"]["config"] == []
assert [f["key"] for f in mods["customer_display"]["device_app"]["config"]] == ["look"] # its idle screen (5.3)
def test_config_field_types(db, pair):