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:
@@ -99,11 +99,12 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"display.media_too_big": (413, "The image is too big (at most {max_mb} MB)."),
|
||||
"display.qr_url_missing": (422, "Enter the link the QR code opens."),
|
||||
"media.not_found": (404, "File {media_id} isn't in the media library."),
|
||||
"media.type": (422, "Upload a picture (JPG, PNG, WebP or GIF) or a video (MP4 or WebM)."),
|
||||
"media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM)."),
|
||||
"media.too_big": (413, "The file is too big (at most {max_mb} MB)."),
|
||||
"media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."),
|
||||
"media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."),
|
||||
"media.in_use": (409, "This file is used by {uses}. Remove it there first."),
|
||||
"media.not_a_picture": (422, "Pick a picture here, not a video."),
|
||||
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
||||
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
||||
"reservation.table_unknown": (404, "Table {table_id} not found."),
|
||||
|
||||
@@ -107,10 +107,8 @@ async def _menu_change_push(request, call_next):
|
||||
# Added last = outermost: the request id exists before any other middleware runs.
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
|
||||
# Serve product images as static files
|
||||
IMAGE_DIR = "/app/data/product_images"
|
||||
os.makedirs(IMAGE_DIR, exist_ok=True)
|
||||
app.mount("/static/product_images", StaticFiles(directory=IMAGE_DIR), name="product_images")
|
||||
# Product photos live in the media library (/api/media/file/..., step 5.2); the old
|
||||
# data/product_images folder is left on disk untouched after Alembic 0027 copied it in.
|
||||
|
||||
# Serve waiter avatars as static files
|
||||
AVATAR_DIR = "/app/data/avatars"
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Products and categories point at the media library (plan step 5.2).
|
||||
|
||||
products.media_id and categories.media_id (a picture in `media`). The old product photos
|
||||
(products.image_url = /static/product_images/<file>) are copied into the library: each file
|
||||
is processed like an upload (sizes made, kept once by hash, display name = the product's
|
||||
name) and the product points at it. The old folder is left on disk untouched. A file that is
|
||||
missing or unreadable is logged and skipped (the product just has no photo). Then
|
||||
products.image_url goes; apps read `image` / `image_url` (the card size) from the API.
|
||||
|
||||
Revision ID: 0027_product_media
|
||||
Revises: 0026_media
|
||||
Create Date: 2026-11-17 15:00:00
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0027_product_media'
|
||||
down_revision = '0026_media'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
log = logging.getLogger("alembic.0027")
|
||||
OLD_DIR = os.environ.get("XENIA_PRODUCT_IMAGE_DIR", "/app/data/product_images")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('categories', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('media_id', sa.Integer(), nullable=True))
|
||||
batch_op.create_index(batch_op.f('ix_categories_media_id'), ['media_id'], unique=False)
|
||||
batch_op.create_foreign_key('fk_categories_media_id_media', 'media', ['media_id'], ['id'], ondelete='SET NULL')
|
||||
|
||||
with op.batch_alter_table('products', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('media_id', sa.Integer(), nullable=True))
|
||||
batch_op.create_index(batch_op.f('ix_products_media_id'), ['media_id'], unique=False)
|
||||
batch_op.create_foreign_key('fk_products_media_id_media', 'media', ['media_id'], ['id'], ondelete='SET NULL')
|
||||
|
||||
_move_photos(op.get_bind())
|
||||
|
||||
with op.batch_alter_table('products', schema=None) as batch_op:
|
||||
batch_op.drop_column('image_url')
|
||||
|
||||
|
||||
def _move_photos(conn) -> None:
|
||||
rows = conn.execute(sa.text("SELECT id, name, image_url FROM products WHERE image_url IS NOT NULL AND image_url != ''")).fetchall()
|
||||
if not rows:
|
||||
return
|
||||
from core.timeutil import DB_FORMAT, utcnow
|
||||
from services import media as store
|
||||
moved = 0
|
||||
for pid, name, url in rows:
|
||||
path = os.path.join(OLD_DIR, os.path.basename(url))
|
||||
if not os.path.isfile(path):
|
||||
log.warning("product %s: photo %s not found, skipped", pid, path)
|
||||
continue
|
||||
try:
|
||||
sha, size, info = store.ingest_path(path)
|
||||
except Exception as e: # refused (type, size) or unreadable
|
||||
log.warning("product %s: photo %s not moved (%s)", pid, path, getattr(e, "code", e))
|
||||
continue
|
||||
mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar()
|
||||
if mid is None:
|
||||
if not info: # files there from an earlier try, no row
|
||||
store.delete_files(sha)
|
||||
sha, size, info = store.ingest_path(path)
|
||||
conn.execute(sa.text(
|
||||
"INSERT INTO media (kind, name, original_name, content_type, sha256, bytes, width, height, duration_ms, created_at) "
|
||||
"VALUES (:kind, :name, :orig, :ctype, :sha, :bytes, :w, :h, :d, :at)"),
|
||||
{"kind": info["kind"], "name": (name or "photo")[:120], "orig": os.path.basename(path),
|
||||
"ctype": info["content_type"], "sha": sha, "bytes": size, "w": info.get("width"),
|
||||
"h": info.get("height"), "d": info.get("duration_ms"), "at": utcnow().strftime(DB_FORMAT)})
|
||||
mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar()
|
||||
conn.execute(sa.text("UPDATE products SET media_id = :m WHERE id = :p"), {"m": mid, "p": pid})
|
||||
moved += 1
|
||||
log.info("product photos moved into the media library: %d of %d", moved, len(rows))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('products', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('image_url', sa.VARCHAR(), nullable=True))
|
||||
batch_op.drop_constraint('fk_products_media_id_media', type_='foreignkey')
|
||||
batch_op.drop_index(batch_op.f('ix_products_media_id'))
|
||||
batch_op.drop_column('media_id')
|
||||
|
||||
with op.batch_alter_table('categories', schema=None) as batch_op:
|
||||
batch_op.drop_constraint('fk_categories_media_id_media', type_='foreignkey')
|
||||
batch_op.drop_index(batch_op.f('ix_categories_media_id'))
|
||||
batch_op.drop_column('media_id')
|
||||
@@ -11,6 +11,7 @@ steps 5.2-5.4). Those users register a usage check in services/media.py so a fil
|
||||
can't be deleted.
|
||||
"""
|
||||
from sqlalchemy import Column, ForeignKey, Integer, String
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from core.timeutil import UTCDateTime, utcnow
|
||||
from database import Base
|
||||
@@ -31,3 +32,9 @@ class Media(Base):
|
||||
duration_ms = Column(Integer, nullable=True) # videos (MP4) when the file says
|
||||
uploaded_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||
|
||||
uploader = relationship("User", lazy="joined")
|
||||
|
||||
@property
|
||||
def uploaded_by_name(self):
|
||||
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None
|
||||
|
||||
@@ -19,6 +19,14 @@ class Category(Base):
|
||||
general_sort_order = Column(Integer, default=0, nullable=False)
|
||||
# sub-categories only: if True, the accordion section is expanded by default on the PWA
|
||||
auto_expanded = Column(Boolean, default=False, nullable=False)
|
||||
# Its picture in the media library (plan step 5.2); the library refuses to delete it while set
|
||||
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
media = relationship("Media", lazy="joined")
|
||||
|
||||
@property
|
||||
def image(self):
|
||||
from services.media import image_of
|
||||
return image_of(self.media)
|
||||
|
||||
# Products whose PRIMARY category this is (tickets, reports). Every product listed in
|
||||
# this category, primary or not: `memberships` (ProductCategory, D-23).
|
||||
@@ -45,7 +53,9 @@ class Product(Base):
|
||||
lifecycle_status = Column(String, default="active", nullable=False)
|
||||
# system products only (phase 3S, S.5): what the line is, e.g. "delivery_fee"
|
||||
system_key = Column(String, nullable=True, unique=True, index=True)
|
||||
image_url = Column(String, nullable=True)
|
||||
# Its photo in the media library (plan step 5.2; the old image_url files moved there in 0027)
|
||||
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
media = relationship("Media", lazy="joined")
|
||||
sort_order = Column(Integer, default=0, nullable=False)
|
||||
|
||||
# Where it's sold (phase 3S): JSON list of sales points (core/sales_points.py). Prices
|
||||
@@ -57,7 +67,7 @@ class Product(Base):
|
||||
digital_name = Column(String, nullable=True)
|
||||
digital_description = Column(String, nullable=True)
|
||||
digital_image_url = Column(String, nullable=True)
|
||||
# sha256 of the image_url file last successfully pushed to the cloud — lets
|
||||
# sha256 of the photo file (card size) last successfully pushed to the cloud — lets
|
||||
# cloud_sync skip re-uploading unchanged images on every sync tick
|
||||
cloud_image_hash = Column(String, nullable=True)
|
||||
|
||||
@@ -101,6 +111,17 @@ class Product(Base):
|
||||
modifier_groups = relationship("ProductModifierGroup", back_populates="product", cascade="all, delete-orphan")
|
||||
order_items = relationship("OrderItem", back_populates="product")
|
||||
|
||||
@property
|
||||
def image(self):
|
||||
"""{"id", "name", "thumb", "card", "full"} of its photo, or None."""
|
||||
from services.media import image_of
|
||||
return image_of(self.media)
|
||||
|
||||
@property
|
||||
def image_url(self):
|
||||
"""The card size of its photo (what the phones and the counter show), or None."""
|
||||
return (self.image or {}).get("card")
|
||||
|
||||
|
||||
class ProductModifierGroup(Base):
|
||||
"""A named folder/group that can contain options, ingredients, or preference sets."""
|
||||
|
||||
@@ -4,7 +4,7 @@ websockets==13.1
|
||||
sqlalchemy==2.0.36
|
||||
pydantic-settings==2.6.1
|
||||
python-escpos==3.1
|
||||
Pillow==10.4.0
|
||||
Pillow==12.3.0
|
||||
bcrypt==4.2.0
|
||||
pyjwt==2.9.0
|
||||
httpx==0.27.2
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -14,6 +14,7 @@ class CategoryCreate(BaseModel):
|
||||
parent_id: Optional[int] = None
|
||||
general_sort_order: int = 0
|
||||
auto_expanded: bool = False
|
||||
media_id: Optional[int] = None # its picture in the media library (5.2)
|
||||
|
||||
|
||||
class CategoryUpdate(BaseModel):
|
||||
@@ -23,6 +24,7 @@ class CategoryUpdate(BaseModel):
|
||||
parent_id: Optional[int] = None
|
||||
general_sort_order: Optional[int] = None
|
||||
auto_expanded: Optional[bool] = None
|
||||
media_id: Optional[int] = None # null clears it (sent explicitly)
|
||||
|
||||
|
||||
class CategoryOut(BaseModel):
|
||||
@@ -33,6 +35,8 @@ class CategoryOut(BaseModel):
|
||||
parent_id: Optional[int] = None
|
||||
general_sort_order: int = 0
|
||||
auto_expanded: bool = False
|
||||
media_id: Optional[int] = None
|
||||
image: Optional[dict] = None # {id, name, thumb, card, full} (services/media.image_of)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -347,6 +351,8 @@ class ProductBase(BaseModel):
|
||||
# Fiscal printer (ΦΗΜ)
|
||||
fiscal_name: Optional[str] = None
|
||||
fiscal_vat_group_id: Optional[int] = None
|
||||
# Its photo in the media library (plan step 5.2)
|
||||
media_id: Optional[int] = None
|
||||
|
||||
|
||||
class ProductCreate(ProductBase):
|
||||
@@ -392,6 +398,7 @@ class ProductUpdate(BaseModel):
|
||||
# Fiscal printer (ΦΗΜ)
|
||||
fiscal_name: Optional[str] = None
|
||||
fiscal_vat_group_id: Optional[int] = None
|
||||
media_id: Optional[int] = None # null clears it (sent explicitly)
|
||||
|
||||
|
||||
class ProductReorderItem(BaseModel):
|
||||
@@ -413,7 +420,8 @@ class ProductOut(ProductBase):
|
||||
ingredients: List[ProductIngredientOut] = []
|
||||
preference_sets: List[PreferenceSetOut] = []
|
||||
modifier_groups: List[ModifierGroupOut] = []
|
||||
image_url: Optional[str] = None
|
||||
image_url: Optional[str] = None # the card size of `image` (phones, counter)
|
||||
image: Optional[dict] = None # {id, name, thumb, card, full} (services/media.image_of)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -444,6 +452,8 @@ class ProductOut(ProductBase):
|
||||
'prep_zone_ids': [z.id for z in data.prep_zones] if hasattr(data, 'prep_zones') else [],
|
||||
'sort_order': data.sort_order,
|
||||
'image_url': data.image_url,
|
||||
'image': data.image,
|
||||
'media_id': data.media_id,
|
||||
'sold_at': _sold_at(data),
|
||||
'digital_available': bool(data.digital_available),
|
||||
'digital_name': data.digital_name,
|
||||
|
||||
@@ -204,28 +204,28 @@ async def _sync_once():
|
||||
# Online or not: the stored signed license decides (no more 72h offline rule)
|
||||
apply_license()
|
||||
|
||||
IMAGE_DIR = Path("/app/data/product_images")
|
||||
|
||||
|
||||
async def _push_product_images(db, products):
|
||||
"""Upload the local image file for each product whose picture changed since
|
||||
the last successful push (tracked via Product.cloud_image_hash), so the
|
||||
public QR menu can show it without needing a manually-set digital_image_url.
|
||||
Skips products that already have a manual digital_image_url override."""
|
||||
"""Upload each product's photo (the library's card size, WebP) whose file changed since the
|
||||
last successful push (Product.cloud_image_hash), so the public QR menu can show it without a
|
||||
manually-set digital_image_url. Skips products with a manual digital_image_url override."""
|
||||
import hashlib
|
||||
from services import media as media_store
|
||||
|
||||
site_numeric_id = license_state.get("site_numeric_id")
|
||||
if not site_numeric_id:
|
||||
return
|
||||
|
||||
for p in products:
|
||||
if p.digital_image_url or not p.image_url:
|
||||
if p.digital_image_url or p.media is None or p.media.kind != "image":
|
||||
continue
|
||||
|
||||
filename = os.path.basename(p.image_url)
|
||||
filepath = IMAGE_DIR / filename
|
||||
if not filepath.exists():
|
||||
try:
|
||||
path = media_store.ensure_variant(p.media, "card")
|
||||
except Exception:
|
||||
path = None
|
||||
if not path:
|
||||
continue
|
||||
filepath = Path(path)
|
||||
filename = f"{p.media.sha256[:16]}.webp"
|
||||
|
||||
try:
|
||||
contents = filepath.read_bytes()
|
||||
@@ -238,7 +238,7 @@ async def _push_product_images(db, products):
|
||||
f"{settings.CLOUD_URL}/api/menu/sync-image",
|
||||
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
||||
data={"product_id": str(p.id)},
|
||||
files={"file": (filename, contents)},
|
||||
files={"file": (filename, contents, "image/webp")},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ whatever copies the database must copy this folder too):
|
||||
<sha[:2]>/<sha>/{thumb,card,full}.webp images only, made on upload (and again on
|
||||
request if missing, e.g. after a partial restore)
|
||||
|
||||
Images: JPEG, PNG, WebP or GIF (first frame), turned upright from their EXIF, never made
|
||||
Images: JPEG, PNG, WebP, AVIF or GIF (first frame), turned upright from their EXIF, never made
|
||||
bigger than they are. Videos: MP4 or WebM, kept as uploaded (no transcoding on the venue's
|
||||
box); an MP4's length and size are read from its header when it has them.
|
||||
|
||||
@@ -35,7 +35,7 @@ MAX_PIXELS = 60_000_000 # a 60 MP photo is fine; bigger is
|
||||
SIZES = {"thumb": 200, "card": 600, "full": 1920}
|
||||
WEBP_QUALITY = 80
|
||||
IMAGE_TYPES = {"JPEG": ("image/jpeg", "jpg"), "PNG": ("image/png", "png"),
|
||||
"WEBP": ("image/webp", "webp"), "GIF": ("image/gif", "gif")}
|
||||
"WEBP": ("image/webp", "webp"), "GIF": ("image/gif", "gif"), "AVIF": ("image/avif", "avif")}
|
||||
VIDEO_TYPES = {"mp4": "video/mp4", "webm": "video/webm"}
|
||||
VARIANTS = (*SIZES, "original")
|
||||
|
||||
@@ -63,6 +63,13 @@ def variant_path(sha: str, variant: str) -> str:
|
||||
return os.path.join(folder(sha), f"{variant}.webp")
|
||||
|
||||
|
||||
def image_of(item) -> dict | None:
|
||||
"""What an app needs to show a picture from the library: {"id", "name", "thumb", "card", "full"}."""
|
||||
if item is None or item.kind != "image":
|
||||
return None
|
||||
return {"id": item.id, "name": item.name, **{k: v for k, v in urls(item).items() if k != "original"}}
|
||||
|
||||
|
||||
def urls(item) -> dict:
|
||||
base = f"/api/media/file/{item.sha256}"
|
||||
out = {"original": f"{base}/original"}
|
||||
@@ -106,7 +113,7 @@ def sniff(path: str) -> str | None:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(16)
|
||||
if head[4:8] == b"ftyp":
|
||||
return "mp4"
|
||||
return "image" if head[8:12] in (b"avif", b"avis") else "mp4"
|
||||
if head[:4] == b"\x1a\x45\xdf\xa3":
|
||||
return "webm"
|
||||
if head[:3] == b"\xff\xd8\xff" or head[:8] == b"\x89PNG\r\n\x1a\n" or head[:6] in (b"GIF87a", b"GIF89a") \
|
||||
@@ -169,6 +176,66 @@ def ensure_variant(item, variant: str) -> str | None:
|
||||
return p
|
||||
|
||||
|
||||
def ingest(tmp: str, sha: str, size: int) -> dict:
|
||||
"""Check a received temp file, make its sizes and store it under its hash.
|
||||
→ {"kind", "content_type", "width", "height", "duration_ms"} (the last three may be missing).
|
||||
Refused or failed: nothing is kept (neither the temp file nor anything made from it)."""
|
||||
try:
|
||||
found = sniff(tmp)
|
||||
if found == "image":
|
||||
if size > IMAGE_MAX_BYTES:
|
||||
raise XeniaError("media.too_big", max_mb=IMAGE_MAX_BYTES // (1024 * 1024))
|
||||
img, fmt = open_image(tmp)
|
||||
content_type, ext = IMAGE_TYPES[fmt]
|
||||
info = {"kind": "image", "content_type": content_type, "width": img.width, "height": img.height}
|
||||
os.makedirs(folder(sha), exist_ok=True)
|
||||
make_variants(img, sha)
|
||||
elif found in VIDEO_TYPES:
|
||||
ext = found
|
||||
info = {"kind": "video", "content_type": VIDEO_TYPES[found], **(mp4_info(tmp) if found == "mp4" else {})}
|
||||
else:
|
||||
raise XeniaError("media.type")
|
||||
store(tmp, sha, ext)
|
||||
return info
|
||||
except BaseException:
|
||||
_remove(tmp)
|
||||
delete_files(sha)
|
||||
raise
|
||||
|
||||
|
||||
def ingest_path(path: str) -> tuple[str, int, dict]:
|
||||
"""A file already on disk (a data move, e.g. the old product images): → (sha, size, info).
|
||||
The file itself is left where it is."""
|
||||
with open(path, "rb") as f:
|
||||
tmp, sha, size = receive(f, VIDEO_MAX_BYTES)
|
||||
if original_path(sha): # already in the library
|
||||
_remove(tmp)
|
||||
return sha, size, {}
|
||||
return sha, size, ingest(tmp, sha, size)
|
||||
|
||||
|
||||
def files_info(item) -> dict:
|
||||
"""{variant: {"bytes", "width", "height"}} of what is stored for an item (missing sizes left out;
|
||||
a video's original has no picture size here)."""
|
||||
from PIL import Image
|
||||
out = {}
|
||||
for v in VARIANTS:
|
||||
p = original_path(item.sha256) if v == "original" else variant_path(item.sha256, v)
|
||||
if not p or not os.path.exists(p):
|
||||
continue
|
||||
info = {"bytes": os.path.getsize(p), "width": None, "height": None}
|
||||
if v == "original":
|
||||
info.update(width=item.width, height=item.height)
|
||||
else:
|
||||
try:
|
||||
with Image.open(p) as im:
|
||||
info.update(width=im.width, height=im.height)
|
||||
except Exception:
|
||||
pass
|
||||
out[v] = info
|
||||
return out
|
||||
|
||||
|
||||
def store(tmp: str, sha: str, ext: str) -> None:
|
||||
"""Move the received temp file into place as the original."""
|
||||
d = folder(sha)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user