"""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