feat(backend): products and categories point at the media library (platform-v2 step 5.2)

- products.media_id / categories.media_id (Alembic 0027): the old
  /static/product_images photos are processed into the library (named after
  their product; missing or unreadable files logged and skipped; the old
  folder is left on disk) and products.image_url goes. The static mount is gone.
- APIs give `image` {id, name, thumb, card, full}; a product's image_url is its
  card size. media_id on create/update (null clears); media.not_a_picture for
  a video. POST /api/products/{id}/image is gone: uploads go to /api/media.
- Products and categories register their media usage: a photo in use can't
  be deleted.
- Media: AVIF pictures (Pillow 12.3), GET /api/media/{id} gives each stored
  size's bytes and resolution and the uploader's name; upload processing moved
  into services/media.ingest (also used by the data move).
- QR menu photo push (contract C-3): the library's card size, WebP.
- tests: test_product_photos.py (7, incl. the 0027 data move); 497 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 15:57:50 +02:00
co-authored by Claude Opus 5.5
parent 238f8ec5a0
commit 5ad4c4ef55
15 changed files with 398 additions and 99 deletions
+7 -3
View File
@@ -67,6 +67,10 @@ def test_a_jpeg_gets_three_sizes_served_with_cache_headers(client, owner_h, medi
assert (img.format, img.size[0]) == ("WEBP", side) and abs(img.size[1] - side * 2 / 3) <= 1
orig = client.get(m["urls"]["original"])
assert orig.headers["content-type"] == "image/jpeg" and len(orig.content) == m["bytes"]
detail = client.get(f"/api/media/{m['id']}", headers=owner_h).json()
assert detail["uploaded_by_name"] and detail["used_by"] == []
assert {k: (v["width"], v["height"]) for k, v in detail["files"].items()} == {"thumb": (200, 133), "card": (600, 400), "full": (1920, 1280), "original": (3000, 2000)}
assert detail["files"]["original"]["bytes"] == m["bytes"] and detail["files"]["thumb"]["bytes"] < detail["files"]["card"]["bytes"]
sha = m["sha256"]
assert files_left(media_dir) == [f"{sha[:2]}/{sha}/{n}" for n in ("card.webp", "full.webp", "original.jpg", "thumb.webp")]
@@ -146,17 +150,17 @@ def test_delete_frees_the_files_but_a_file_in_use_is_refused(client, owner_h, me
import services.media as store
used = up(client, owner_h, jpeg(300, 300, (9, 9, 9)), name="used.jpg").json()
free = up(client, owner_h, jpeg(300, 300, (8, 8, 8)), name="free.jpg").json()
store.register_usage("product", lambda db, mid: [{"id": 7, "name": "Pork souvlaki"}] if mid == used["id"] else [])
store.register_usage("stand_in", lambda db, mid: [{"id": 7, "name": "Pork souvlaki"}] if mid == used["id"] else [])
try:
r = client.delete(f"/api/media/{used['id']}", headers=owner_h)
assert r.status_code == 409 and err(r) == "media.in_use"
assert r.json()["error"]["params"]["used_by"] == [{"kind": "product", "id": 7, "name": "Pork souvlaki"}]
assert r.json()["error"]["params"]["used_by"] == [{"kind": "stand_in", "id": 7, "name": "Pork souvlaki"}]
assert "Pork souvlaki" in r.json()["error"]["message"]
assert client.get(f"/api/media/{used['id']}", headers=owner_h).json()["used_by"][0]["name"] == "Pork souvlaki"
assert client.get(used["urls"]["card"]).status_code == 200
assert client.delete(f"/api/media/{free['id']}", headers=owner_h).status_code == 204
finally:
store.unregister_usage("product")
store.unregister_usage("stand_in")
assert client.get(f"/api/media/{free['id']}", headers=owner_h).status_code == 404
assert client.get(free["urls"]["card"]).status_code == 404
assert not any(free["sha256"] in f for f in files_left(media_dir))
+121
View File
@@ -0,0 +1,121 @@
"""Product and category photos from the media library (plan step 5.2): picked or uploaded on
the spot, shown at the right size, protected in the library while used, and the old
/static/product_images photos moved into the library by Alembic 0027."""
import io
import pytest
from PIL import Image
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_media import jpeg, media_dir, mp4, up # noqa: F401 (fixture + helpers)
from tests.test_pos import till # noqa: F401 (fixture)
@pytest.fixture
def cat(db):
from models.product import Category
c = Category(name="Grill", sort_order=0)
db.add(c)
db.commit()
return c.id
def product(client, h, name="Pork souvlaki", **body):
r = client.post("/api/products/", headers=h, json={"name": name, "base_price": 3.5, **body})
assert r.status_code == 201, r.text
return r.json()
def test_a_product_shows_its_photo_at_each_size(client, owner_h, cat):
photo = up(client, owner_h, jpeg(1600, 1200), name="IMG_2041.jpg").json()
p = product(client, owner_h, category_ids=[cat], media_id=photo["id"])
assert p["media_id"] == photo["id"]
assert p["image"] == {"id": photo["id"], "name": "IMG_2041", "thumb": photo["urls"]["thumb"],
"card": photo["urls"]["card"], "full": photo["urls"]["full"]}
assert p["image_url"] == photo["urls"]["card"] # what the phones and the counter show
listed = next(x for x in client.get("/api/products/", headers=owner_h).json() if x["id"] == p["id"])
assert listed["image"]["thumb"] == photo["urls"]["thumb"]
img = Image.open(io.BytesIO(client.get(p["image_url"]).content))
assert max(img.size) == 600
def test_change_and_remove_a_photo(client, owner_h):
a = up(client, owner_h, jpeg(500, 500, (1, 2, 3))).json()
b = up(client, owner_h, jpeg(500, 500, (3, 2, 1))).json()
p = product(client, owner_h, media_id=a["id"])
r = client.put(f"/api/products/{p['id']}", headers=owner_h, json={"media_id": b["id"]})
assert r.status_code == 200 and r.json()["image"]["id"] == b["id"]
r = client.put(f"/api/products/{p['id']}", headers=owner_h, json={"name": "Pork souvlaki pita"})
assert r.json()["image"]["id"] == b["id"] # other changes keep the photo
r = client.put(f"/api/products/{p['id']}", headers=owner_h, json={"media_id": None})
assert r.json()["image"] is None and r.json()["image_url"] is None
def test_only_pictures_from_the_library(client, owner_h):
video = up(client, owner_h, mp4(), name="promo.mp4", ctype="video/mp4").json()
r = client.post("/api/products/", headers=owner_h, json={"name": "X", "base_price": 1, "media_id": video["id"]})
assert r.status_code == 422 and err(r) == "media.not_a_picture"
r = client.post("/api/products/", headers=owner_h, json={"name": "X", "base_price": 1, "media_id": 99999})
assert r.status_code == 404 and err(r) == "media.not_found"
def test_a_photo_in_use_cant_be_deleted_from_the_library(client, owner_h, cat):
photo = up(client, owner_h, jpeg(400, 400)).json()
p = product(client, owner_h, media_id=photo["id"])
r = client.put(f"/api/products/categories/{cat}", headers=owner_h, json={"media_id": photo["id"]})
assert r.status_code == 200 and r.json()["image"]["card"] == photo["urls"]["card"]
r = client.delete(f"/api/media/{photo['id']}", headers=owner_h)
assert r.status_code == 409 and err(r) == "media.in_use"
assert r.json()["error"]["params"]["used_by"] == [{"kind": "product", "id": p["id"], "name": "Pork souvlaki"},
{"kind": "category", "id": cat, "name": "Grill"}]
client.put(f"/api/products/{p['id']}", headers=owner_h, json={"media_id": None})
r = client.put(f"/api/products/categories/{cat}", headers=owner_h, json={"media_id": None})
assert r.json()["image"] is None
assert client.delete(f"/api/media/{photo['id']}", headers=owner_h).status_code == 204
def test_a_category_with_a_photo_from_the_start(client, owner_h):
photo = up(client, owner_h, jpeg(400, 300)).json()
r = client.post("/api/products/categories", headers=owner_h, json={"name": "Salads", "media_id": photo["id"]})
assert r.status_code == 201 and r.json()["media_id"] == photo["id"]
listed = {c["name"]: c for c in client.get("/api/products/categories", headers=owner_h).json()}
assert listed["Salads"]["image"]["thumb"] == photo["urls"]["thumb"]
def test_the_counter_gets_the_card_size(client, owner_h, cat, till):
photo = up(client, owner_h, jpeg(900, 900)).json()
product(client, owner_h, category_ids=[cat], media_id=photo["id"])
items = [p for p in client.get("/api/pos/menu", headers=till["h"]).json()["products"] if p["name"] == "Pork souvlaki"]
assert items and items[0]["image_url"] == photo["urls"]["card"]
def test_migration_0027_moves_the_old_photos(tmp_path, monkeypatch, media_dir):
from alembic import command
from sqlalchemy import create_engine, text
from core.schema import alembic_config, upgrade_to_head
old = tmp_path / "product_images"
old.mkdir()
(old / "1_aaaa.jpg").write_bytes(jpeg(800, 600, (10, 20, 30)))
(old / "2_bbbb.jpg").write_bytes(jpeg(800, 600, (10, 20, 30))) # the same picture again
(old / "4_dddd.jpg").write_bytes(b"not a picture at all")
monkeypatch.setenv("XENIA_PRODUCT_IMAGE_DIR", str(old))
eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}")
with eng.begin() as conn:
command.upgrade(alembic_config(conn), "0026_media")
for pid, name, url in ((1, "Souvlaki", "/static/product_images/1_aaaa.jpg"), (2, "Souvlaki XL", "/static/product_images/2_bbbb.jpg"),
(3, "Gone", "/static/product_images/3_cccc.jpg"), (4, "Junk", "/static/product_images/4_dddd.jpg"),
(5, "No photo", None)):
conn.execute(text("insert into products (id, name, base_price, is_available, lifecycle_status, sort_order, sold_at, "
"digital_available, unit_type, quick_add_enabled, is_service_item, image_url) "
"values (:id, :n, 3, 1, 'active', 0, '[]', 1, 'piece', 1, 0, :u)"), {"id": pid, "n": name, "u": url})
upgrade_to_head(eng)
with eng.connect() as conn:
rows = dict(conn.execute(text("select id, media_id from products order by id")).fetchall())
media = conn.execute(text("select id, name, kind, width, height, original_name from media")).fetchall()
cols = [r[1] for r in conn.execute(text("pragma table_info(products)"))]
eng.dispose()
assert len(media) == 1 and media[0][1:] == ("Souvlaki", "image", 800, 600, "1_aaaa.jpg")
assert rows == {1: media[0][0], 2: media[0][0], 3: None, 4: None, 5: None}
assert "image_url" not in cols and "media_id" in cols
assert (old / "1_aaaa.jpg").exists() # the old folder is left alone
assert sum(1 for p in media_dir.rglob("*.webp")) == 3