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
+37 -38
View File
@@ -1,8 +1,6 @@
from core.access.check import holds
import os
import uuid
import json
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from typing import List
@@ -22,6 +20,8 @@ from schemas.product import (
)
from routers.deps import get_current_user, require_menu_manager
from services.ws_bus import broadcast_sync
from services import media as media_store
from core.errors import XeniaError
router = APIRouter()
@@ -29,7 +29,6 @@ router = APIRouter()
def _broadcast_products_changed():
broadcast_sync("products_changed", {})
IMAGE_DIR = "/app/data/product_images"
def _replace_modifier_groups(db, product, groups):
@@ -151,6 +150,32 @@ def list_all_tags(db: Session = Depends(get_db), user: User = Depends(get_curren
return sorted(tag_set)
def _picture(db: Session, media_id):
"""A media id a product or category may point at: an existing picture (None clears)."""
if media_id is None:
return None
from models.media import Media
item = db.get(Media, media_id)
if item is None:
raise XeniaError("media.not_found", media_id=media_id)
if item.kind != "image":
raise XeniaError("media.not_a_picture")
return item.id
def _product_uses(db: Session, media_id: int) -> list:
return [{"id": p.id, "name": p.name} for p in
db.query(Product).filter(Product.media_id == media_id, Product.lifecycle_status != "system").order_by(Product.name)]
def _category_uses(db: Session, media_id: int) -> list:
return [{"id": c.id, "name": c.name} for c in db.query(Category).filter(Category.media_id == media_id).order_by(Category.name)]
media_store.register_usage("product", _product_uses)
media_store.register_usage("category", _category_uses)
@router.get("/categories", response_model=List[CategoryOut])
def list_categories(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
return db.query(Category).order_by(Category.sort_order).all()
@@ -166,6 +191,7 @@ def create_category(body: CategoryCreate, db: Session = Depends(get_db), user: U
sort_order=sibling_count,
parent_id=body.parent_id,
general_sort_order=body.general_sort_order,
media_id=_picture(db, body.media_id),
)
db.add(cat)
db.commit()
@@ -241,8 +267,10 @@ def update_category(category_id: int, body: CategoryUpdate, db: Session = Depend
cat = db.query(Category).filter(Category.id == category_id).first()
if not cat:
raise HTTPException(status_code=404, detail="Category not found")
for field, value in body.model_dump(exclude_none=True).items():
for field, value in body.model_dump(exclude_none=True, exclude={"media_id"}).items():
setattr(cat, field, value)
if "media_id" in body.model_fields_set:
cat.media_id = _picture(db, body.media_id)
db.commit()
db.refresh(cat)
_broadcast_products_changed()
@@ -348,6 +376,7 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
data["cost_breakdown"] = json.dumps([item.model_dump() for item in body.cost_breakdown])
data["tags"] = json.dumps(body.tags) if body.tags is not None else None
data["sold_at"] = sales_points.dump(body.sold_at)
data["media_id"] = _picture(db, body.media_id)
product = Product(**data)
db.add(product)
db.flush()
@@ -403,8 +432,10 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
scalar_fields = body.model_dump(
exclude_none=True,
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
"category_id", "primary_category_id", "category_ids"},
"category_id", "primary_category_id", "category_ids", "media_id"},
)
if "media_id" in body.model_fields_set:
product.media_id = _picture(db, body.media_id)
for field, value in scalar_fields.items():
setattr(product, field, sales_points.dump(value) if field == "sold_at" else value)
_apply_categories(db, product, body, creating=False)
@@ -442,38 +473,6 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
return product
@router.post("/{product_id}/image", response_model=ProductOut)
async def upload_product_image(product_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
# system products (the delivery fee line, S.5) are not part of the catalogue
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
if not product:
raise HTTPException(status_code=404, detail="Product not found")
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image")
os.makedirs(IMAGE_DIR, exist_ok=True)
if product.image_url:
old_path = os.path.join(IMAGE_DIR, os.path.basename(product.image_url))
if os.path.exists(old_path):
os.remove(old_path)
ext = file.filename.rsplit(".", 1)[-1].lower() if "." in file.filename else "jpg"
filename = f"{product_id}_{uuid.uuid4().hex[:8]}.{ext}"
filepath = os.path.join(IMAGE_DIR, filename)
contents = await file.read()
with open(filepath, "wb") as f:
f.write(contents)
product.image_url = f"/static/product_images/{filename}"
db.commit()
db.refresh(product)
_broadcast_products_changed()
return product
# ── Modifier Groups ───────────────────────────────────────────────────────────
@router.get("/{product_id}/modifier-groups", response_model=List[ModifierGroupOut])