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:
@@ -50,12 +50,14 @@ class MediaOut(BaseModel):
|
||||
height: Optional[int] = None
|
||||
duration_ms: Optional[int] = None
|
||||
uploaded_by: Optional[int] = None
|
||||
uploaded_by_name: Optional[str] = None
|
||||
created_at: datetime
|
||||
urls: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
class MediaDetail(MediaOut):
|
||||
used_by: List[dict] = Field(default_factory=list)
|
||||
files: dict = Field(default_factory=dict) # what is stored: {variant: {bytes, width, height}}
|
||||
|
||||
|
||||
class UploadOut(MediaOut):
|
||||
@@ -123,40 +125,17 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
|
||||
store._remove(tmp)
|
||||
response.status_code = 200
|
||||
return _out(existing, UploadOut, existing=True)
|
||||
info = store.ingest(tmp, sha, size)
|
||||
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename),
|
||||
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, **info)
|
||||
try:
|
||||
found = store.sniff(tmp)
|
||||
info: dict = {}
|
||||
if found == "image":
|
||||
if size > store.IMAGE_MAX_BYTES:
|
||||
raise XeniaError("media.too_big", max_mb=store.IMAGE_MAX_BYTES // (1024 * 1024))
|
||||
img, fmt = store.open_image(tmp)
|
||||
content_type, ext = store.IMAGE_TYPES[fmt]
|
||||
kind = "image"
|
||||
info = {"width": img.width, "height": img.height}
|
||||
os.makedirs(store.folder(sha), exist_ok=True)
|
||||
store.make_variants(img, sha)
|
||||
elif found in store.VIDEO_TYPES:
|
||||
kind, ext, content_type = "video", found, store.VIDEO_TYPES[found]
|
||||
if found == "mp4":
|
||||
info = store.mp4_info(tmp)
|
||||
else:
|
||||
raise XeniaError("media.type")
|
||||
|
||||
store.store(tmp, sha, ext)
|
||||
tmp = None
|
||||
item = Media(kind=kind, name=(name or "").strip()[:120] or _name_from(file.filename),
|
||||
original_name=(file.filename or None), content_type=content_type,
|
||||
sha256=sha, bytes=size, uploaded_by=user.id, **info)
|
||||
db.add(item)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
return _out(item, UploadOut)
|
||||
except BaseException:
|
||||
# Refused or failed: keep nothing (the temp file, sizes already made, a stored original).
|
||||
if tmp is not None:
|
||||
store._remove(tmp)
|
||||
store.delete_files(sha)
|
||||
raise
|
||||
db.refresh(item)
|
||||
return _out(item, UploadOut)
|
||||
|
||||
|
||||
@router.get("/file/{sha}/{variant}", dependencies=[Depends(public())])
|
||||
@@ -208,7 +187,7 @@ def _ranged(path: str, ctype: str, rng: str, headers: dict):
|
||||
@router.get("/{media_id}", response_model=MediaDetail)
|
||||
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
item = _get(db, media_id)
|
||||
return _out(item, MediaDetail, used_by=store.uses(db, item.id))
|
||||
return _out(item, MediaDetail, used_by=store.uses(db, item.id), files=store.files_info(item))
|
||||
|
||||
|
||||
@router.patch("/{media_id}", response_model=MediaOut)
|
||||
|
||||
@@ -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])
|
||||
|
||||
Reference in New Issue
Block a user