Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87dff573df | ||
|
|
15bd0f5b57 | ||
|
|
e09056a7a4 | ||
|
|
5ad4c4ef55 |
+1
-1
@@ -47,7 +47,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
|
||||
| `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` |
|
||||
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
|
||||
| `local_backend/routers/customer_display.py`, `terminal/src/apps/customer-display/` | The customer display (3.4): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is the venue's design (`customer_display.idle`: name, logo, both, blank, image, slideshow, QR, a line of text, dark/light), images in `/app/data/display_media`, served by name at `/api/display/media/{name}` (public, LAN, random names). The POS's last state lives in memory |
|
||||
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py` | The media library (5.1): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (original + `thumb`/`card`/`full` WebP for pictures; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). Whoever manages the menu, customer display, signage or menu tablets manages it. **Anything that points at a media item registers `register_usage(kind, fn)`** so delete is refused (`media.in_use`) while it's used. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` (the default 1 MB refused phone photos) |
|
||||
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
|
||||
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
|
||||
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
|
||||
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
||||
|
||||
@@ -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
|
||||
@@ -8,7 +8,7 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test \"tests/*.test.mjs\"",
|
||||
"lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/online src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/PhoneListener.jsx src/pages/PhonePage.jsx src/store/phoneStore.js src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx"
|
||||
"lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/online src/pages/media src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/PhoneListener.jsx src/pages/PhonePage.jsx src/store/phoneStore.js src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.107.1",
|
||||
|
||||
@@ -30,6 +30,7 @@ import TabsPage from './pages/financials/TabsPage'
|
||||
|
||||
// Management
|
||||
import ProductsPage from './pages/Management/ProductsPage'
|
||||
import MediaPage from './pages/media/MediaPage'
|
||||
import TablesConfigPage from './pages/Management/TablesConfigPage'
|
||||
import StaffPage from './pages/Management/StaffPage'
|
||||
import SessionsPage from './pages/staff/SessionsPage'
|
||||
@@ -161,6 +162,7 @@ export default function App() {
|
||||
|
||||
{/* ── Management (Headquarters) ── */}
|
||||
<Route path="management/products" element={<ProductsPage />} />
|
||||
<Route path="management/media" element={<MediaPage />} />
|
||||
<Route path="management/tables" element={<TablesConfigPage />} />
|
||||
<Route path="management/staff" element={<StaffPage />} />
|
||||
<Route path="management/sessions" element={<SessionsPage />} />
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import client from '../../api/client'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { SALES_POINTS } from '@xenia/access'
|
||||
import MediaField from '../media/MediaField'
|
||||
|
||||
// ── Small helpers ─────────────────────────────────────────────────────────────
|
||||
function moveItem(arr, i, dir) {
|
||||
@@ -202,6 +202,8 @@ function buildFormFromProduct(product) {
|
||||
digital_name: product.digital_name ?? '',
|
||||
digital_description: product.digital_description ?? '',
|
||||
digital_image_url: product.digital_image_url ?? '',
|
||||
// Its photo in the media library (plan step 5.2): { id, name, thumb, card, full } or null
|
||||
image: product.image ?? null,
|
||||
// Phase 2A — cost tracking
|
||||
cost_mode: product.cost_breakdown?.length ? 'detailed' : 'simple',
|
||||
cost_simple: product.cost_simple ?? '',
|
||||
@@ -261,9 +263,7 @@ export default function ProductFormModal({ product, categories, printers, prepZo
|
||||
const [form, setForm] = useState(() => buildFormFromProduct(product))
|
||||
const [activeTab, setActiveTab] = useState('favorites')
|
||||
const [leftTab, setLeftTab] = useState('info')
|
||||
const [imageFile, setImageFile] = useState(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const qc = useQueryClient()
|
||||
const { t: tm } = useTranslation('manager')
|
||||
|
||||
// Fetch fiscal VAT groups from settings (needed for the Ταμειακή tab dropdown)
|
||||
const { data: settingsData } = useQuery({
|
||||
@@ -277,7 +277,8 @@ export default function ProductFormModal({ product, categories, printers, prepZo
|
||||
})()
|
||||
|
||||
useEffect(() => {
|
||||
function onKey(e) { if (e.key === 'Escape') onClose() }
|
||||
// Escape inside a dialog on top (the media picker) closes only that dialog
|
||||
function onKey(e) { if (e.key === 'Escape' && !document.querySelector('.x-dialog')) onClose() }
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose])
|
||||
@@ -286,7 +287,6 @@ export default function ProductFormModal({ product, categories, printers, prepZo
|
||||
setForm(buildFormFromProduct(product))
|
||||
setActiveTab('favorites')
|
||||
setLeftTab('info')
|
||||
setImageFile(null)
|
||||
}, [product.id, product.name])
|
||||
|
||||
function setField(k, v) { setForm(f => ({ ...f, [k]: v })) }
|
||||
@@ -575,33 +575,11 @@ export default function ProductFormModal({ product, categories, printers, prepZo
|
||||
// Fiscal printer (ΦΗΜ)
|
||||
fiscal_name: form.fiscal_name?.trim() || null,
|
||||
fiscal_vat_group_id: form.fiscal_vat_group_id ? parseInt(form.fiscal_vat_group_id, 10) : null,
|
||||
media_id: form.image?.id ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!imageFile) { onSave(buildBody()); return }
|
||||
if (!isNew) {
|
||||
onSave(buildBody())
|
||||
setUploading(true)
|
||||
try {
|
||||
const fd = new FormData(); fd.append('file', imageFile)
|
||||
await client.post(`/api/products/${product.id}/image`, fd)
|
||||
qc.invalidateQueries({ queryKey: ['products-all'] })
|
||||
} catch { toast.error('Σφάλμα ανεβάσματος εικόνας') }
|
||||
finally { setUploading(false) }
|
||||
} else {
|
||||
setUploading(true)
|
||||
try {
|
||||
const res = await client.post('/api/products/', buildBody())
|
||||
const newId = res.data.id
|
||||
const fd = new FormData(); fd.append('file', imageFile)
|
||||
await client.post(`/api/products/${newId}/image`, fd)
|
||||
qc.invalidateQueries({ queryKey: ['products-all'] })
|
||||
onClose()
|
||||
} catch { toast.error('Σφάλμα αποθήκευσης') }
|
||||
finally { setUploading(false) }
|
||||
}
|
||||
}
|
||||
function submit() { onSave(buildBody()) }
|
||||
|
||||
const isNew = !product.id
|
||||
const canSave = form.name.trim() && (form.is_service_item || (form.base_price !== '' && form.base_price !== null && form.base_price !== undefined))
|
||||
@@ -825,19 +803,10 @@ export default function ProductFormModal({ product, categories, printers, prepZo
|
||||
</button>
|
||||
</div>}
|
||||
|
||||
{!form.is_service_item && <div>
|
||||
<label className="label">Εικόνα προϊόντος</label>
|
||||
{product.image_url && (
|
||||
<img src={product.image_url}
|
||||
className="w-16 h-16 rounded-xl object-cover border border-gray-200 mb-2" alt="" />
|
||||
{!form.is_service_item && (
|
||||
<MediaField value={form.image} onChange={image => setField('image', image)} nameAfter={form.name}
|
||||
label={tm('media.photo')} testid="product-photo" />
|
||||
)}
|
||||
{imageFile && <div className="text-xs text-primary-700 font-medium mb-1 break-all">{imageFile.name}</div>}
|
||||
<label className="cursor-pointer inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-300 bg-white hover:bg-gray-50 text-sm text-gray-600 transition-colors">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
|
||||
{imageFile ? 'Αλλαγή εικόνας' : 'Επιλογή εικόνας'}
|
||||
<input type="file" accept="image/*" className="sr-only" onChange={e => setImageFile(e.target.files[0] ?? null)} />
|
||||
</label>
|
||||
</div>}
|
||||
</>)}
|
||||
|
||||
{/* Tab 2: where it's sold (phase 3S) and what the customer apps show */}
|
||||
@@ -1330,8 +1299,8 @@ export default function ProductFormModal({ product, categories, printers, prepZo
|
||||
📋 Αντιγραφή
|
||||
</button>
|
||||
)}
|
||||
<button onClick={submit} disabled={!canSave || uploading} className="btn btn-primary px-8">
|
||||
{uploading ? 'Ανέβασμα…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
|
||||
<button onClick={submit} disabled={!canSave} className="btn btn-primary px-8">
|
||||
{isNew ? 'Δημιουργία' : 'Αποθήκευση'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,8 @@ import toast from 'react-hot-toast'
|
||||
import client from '../../api/client'
|
||||
import { ConfirmModal } from '../../ui/Modal'
|
||||
import ProductFormModal from './ProductFormModal'
|
||||
import MediaField from '../media/MediaField'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
|
||||
// ── Icons ─────────────────────────────────────────────────────────────────────
|
||||
function Icon({ name, size = 14, className = '' }) {
|
||||
@@ -50,7 +52,7 @@ function PhotoThumb({ product, size = 44 }) {
|
||||
if (product.image_url) {
|
||||
return (
|
||||
<img
|
||||
src={product.image_url}
|
||||
src={product.image?.thumb || product.image_url}
|
||||
alt={product.name}
|
||||
style={{ width: size, height: size }}
|
||||
className="rounded-lg object-cover shrink-0 border border-gray-100"
|
||||
@@ -814,6 +816,7 @@ function ProductRow({ p, cat, parentCat, selected, onToggleSelect, onEdit, onArc
|
||||
opacity: dragging ? 0.5 : 1,
|
||||
}}
|
||||
className="group hover:bg-gray-50"
|
||||
data-testid="product-row" data-name={p.name}
|
||||
>
|
||||
{/* Drag grip */}
|
||||
<span style={{ color: '#d1d5db', cursor: 'grab', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
@@ -912,7 +915,7 @@ function ProductRow({ p, cat, parentCat, selected, onToggleSelect, onEdit, onArc
|
||||
)}
|
||||
|
||||
{/* Edit — pill style */}
|
||||
<button onClick={e => { e.stopPropagation(); onEdit(p) }}
|
||||
<button onClick={e => { e.stopPropagation(); onEdit(p) }} data-testid="product-edit"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, padding: '4px 10px',
|
||||
background: '#f3f4f6', border: '1px solid #e5e7eb',
|
||||
@@ -1647,7 +1650,7 @@ export default function ProductsTab() {
|
||||
<CategoryModal
|
||||
cat={editCat}
|
||||
parentName={editCat.parent_id ? categories.find(c => c.id === editCat.parent_id)?.name : null}
|
||||
onSave={(name, color) => saveCat.mutate({ name, color, parent_id: editCat.parent_id ?? null })}
|
||||
onSave={(name, color, image) => saveCat.mutate({ name, color, parent_id: editCat.parent_id ?? null, media_id: image?.id ?? null })}
|
||||
onClose={() => setEditCat(null)}
|
||||
/>
|
||||
)}
|
||||
@@ -1711,12 +1714,14 @@ const COLORS = ['#6366f1','#0ea5e9','#10b981','#f59e0b','#ef4444','#ec4899','#8b
|
||||
function CategoryModal({ cat, parentName, onSave, onClose }) {
|
||||
const [name, setName] = useState(cat.name || '')
|
||||
const [color, setColor] = useState(cat.color || COLORS[0])
|
||||
const [image, setImage] = useState(cat.image ?? null)
|
||||
const { t } = useTranslation('manager')
|
||||
const isNew = !cat.id
|
||||
const isSub = !!cat.parent_id
|
||||
|
||||
return (
|
||||
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50, padding: 16 }}>
|
||||
<div style={{ background: '#fff', borderRadius: 16, boxShadow: '0 20px 60px rgba(0,0,0,0.15)', width: '100%', maxWidth: 380, padding: 24 }}>
|
||||
<div style={{ background: '#fff', borderRadius: 16, boxShadow: '0 20px 60px rgba(0,0,0,0.15)', width: '100%', maxWidth: 440, padding: 24 }}>
|
||||
<h2 style={{ margin: '0 0 4px', fontWeight: 700, fontSize: 16, color: '#111827' }}>
|
||||
{isNew ? (isSub ? 'Νέα υποκατηγορία' : 'Νέα κατηγορία') : (isSub ? 'Επεξεργασία υποκατηγορίας' : 'Επεξεργασία κατηγορίας')}
|
||||
</h2>
|
||||
@@ -1732,6 +1737,10 @@ function CategoryModal({ cat, parentName, onSave, onClose }) {
|
||||
style={{ width: '100%', padding: '9px 12px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 14, outline: 'none', boxSizing: 'border-box' }}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<MediaField value={image} onChange={setImage} nameAfter={name} nameAfterLabel={t('media.nameAfterCategory')}
|
||||
label={t('media.photo')} testid="category-photo" />
|
||||
</div>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 600, color: '#6b7280', display: 'block', marginBottom: 8 }}>Χρώμα</label>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8 }}>
|
||||
@@ -1746,7 +1755,7 @@ function CategoryModal({ cat, parentName, onSave, onClose }) {
|
||||
<button onClick={onClose} style={{ flex: 1, padding: '9px 0', border: '1px solid #e5e7eb', background: '#fff', borderRadius: 8, fontSize: 14, cursor: 'pointer', color: '#374151' }}>
|
||||
Ακύρωση
|
||||
</button>
|
||||
<button onClick={() => onSave(name, color)} disabled={!name.trim()}
|
||||
<button onClick={() => onSave(name, color, image)} disabled={!name.trim()}
|
||||
style={{ flex: 1, padding: '9px 0', border: 'none', background: name.trim() ? '#111827' : '#d1d5db', color: '#fff', borderRadius: 8, fontSize: 14, fontWeight: 600, cursor: name.trim() ? 'pointer' : 'not-allowed' }}>
|
||||
Αποθήκευση
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// One library item in full (plan step 5.2): the picture or video, its display name (editable),
|
||||
// everything known about it (type, resolution, length, sizes, who uploaded it and when, the
|
||||
// original file's name), the sizes the server made, what uses it, and delete (refused while used).
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { Trash2 } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Field, Input, Spinner } from '@xenia/ui'
|
||||
import { deleteMedia, getMedia, renameMedia } from './mediaApi'
|
||||
import { duration, fileSize, resolution, VARIANT_ORDER } from './mediaLogic'
|
||||
|
||||
export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatDateTime, formatNumber } = useFormat()
|
||||
const [item, setItem] = useState(null)
|
||||
const [name, setName] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [confirm, setConfirm] = useState(false)
|
||||
|
||||
const close = useRef(onClose)
|
||||
useEffect(() => { close.current = onClose })
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
getMedia(id).then(m => { if (live) { setItem(m); setName(m.name) } })
|
||||
.catch(err => { toast.error(errorMessage(err, t)); close.current() })
|
||||
return () => { live = false }
|
||||
}, [id, t])
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true)
|
||||
try { const m = await renameMedia(id, name.trim()); setItem(it => ({ ...it, ...m })); onChanged?.(m); toast.success(t('media.renamed')) }
|
||||
catch (err) { toast.error(errorMessage(err, t)) }
|
||||
setBusy(false)
|
||||
}
|
||||
const remove = async () => {
|
||||
setBusy(true)
|
||||
try { await deleteMedia(id); toast.success(t('media.deleted')); onDeleted?.(id); onClose() }
|
||||
catch (err) { toast.error(errorMessage(err, t)); setConfirm(false) }
|
||||
setBusy(false)
|
||||
}
|
||||
|
||||
const used = item?.used_by || []
|
||||
const rows = item ? [
|
||||
[t('media.kind'), t(`media.kinds.${item.kind}`) + ` (${item.content_type.split('/')[1].toUpperCase()})`],
|
||||
[t('media.resolution'), resolution(item.width, item.height)],
|
||||
[t('media.length'), item.kind === 'video' ? duration(item.duration_ms) : ''],
|
||||
[t('media.fileSize'), fileSize(item.bytes, formatNumber)],
|
||||
[t('media.originalName'), item.original_name],
|
||||
[t('media.uploadedAt'), formatDateTime(item.created_at)],
|
||||
[t('media.uploadedBy'), item.uploaded_by_name],
|
||||
].filter(([, v]) => v) : []
|
||||
|
||||
return (
|
||||
<Dialog open size="lg" title={item?.name || t('media.title')} onClose={onClose}
|
||||
footer={item && <>
|
||||
{confirm ? <>
|
||||
<span className="text-label text-ink-2 mr-auto">{t('media.deleteConfirm')}</span>
|
||||
<Button variant="secondary" onClick={() => setConfirm(false)}>{t('fees.cancel')}</Button>
|
||||
<Button variant="danger" loading={busy} onClick={remove} data-testid="media-delete-confirm">{t('media.delete')}</Button>
|
||||
</> : <>
|
||||
<Button variant="ghost" icon={<Trash2 size={16} />} disabled={busy || used.length > 0} onClick={() => setConfirm(true)}
|
||||
className="mr-auto" data-testid="media-delete">{t('media.delete')}</Button>
|
||||
<Button variant="secondary" onClick={onClose}>{t('media.close')}</Button>
|
||||
</>}
|
||||
</>}>
|
||||
{!item ? <div className="flex justify-center p-6"><Spinner /></div> : (
|
||||
<div className="grid gap-4" data-testid="media-details" data-id={item.id}>
|
||||
<div className="rounded-card bg-surface-3 overflow-hidden flex items-center justify-center" style={{ maxHeight: '45vh' }}>
|
||||
{item.kind === 'video'
|
||||
? <video src={item.urls.original} controls preload="metadata" className="max-h-[45vh] max-w-full" />
|
||||
: <img src={item.urls.full} alt={item.name} className="max-h-[45vh] max-w-full object-contain" />}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-1">
|
||||
<div className="flex gap-2 items-end">
|
||||
<Field label={t('media.displayName')} className="flex-1">
|
||||
<Input value={name} maxLength={120} onChange={e => setName(e.target.value)} data-testid="media-name" />
|
||||
</Field>
|
||||
<Button variant="secondary" loading={busy} disabled={!name.trim() || name.trim() === item.name} onClick={save}
|
||||
data-testid="media-rename">{t('media.saveName')}</Button>
|
||||
</div>
|
||||
<p className="text-caption text-ink-3">{t('media.displayNameHint')}</p>
|
||||
</div>
|
||||
|
||||
<dl className="grid gap-x-4 gap-y-1 text-label" style={{ gridTemplateColumns: 'max-content 1fr' }}>
|
||||
{rows.map(([k, v]) => <div key={k} className="contents"><dt className="text-ink-3">{k}</dt><dd className="text-ink break-all">{v}</dd></div>)}
|
||||
</dl>
|
||||
|
||||
<section className="grid gap-1">
|
||||
<h3 className="text-label font-semibold text-ink">{t('media.sizes')}</h3>
|
||||
<p className="text-caption text-ink-3">{t(item.kind === 'video' ? 'media.sizesVideo' : 'media.sizesHint')}</p>
|
||||
<ul className="grid gap-1" data-testid="media-sizes">
|
||||
{VARIANT_ORDER.filter(v => item.files?.[v]).map(v => (
|
||||
<li key={v} className="flex gap-3 text-label">
|
||||
<span className="text-ink w-28">{t(`media.variants.${v}`)}</span>
|
||||
<span className="text-ink-2 w-28">{resolution(item.files[v].width, item.files[v].height)}</span>
|
||||
<span className="text-ink-2">{fileSize(item.files[v].bytes, formatNumber)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section className="grid gap-1">
|
||||
<h3 className="text-label font-semibold text-ink">{t('media.usedBy')}</h3>
|
||||
{used.length === 0
|
||||
? <p className="text-label text-ink-3">{t('media.unused')}</p>
|
||||
: <>
|
||||
<ul className="flex flex-wrap gap-1.5" data-testid="media-used-by">
|
||||
{used.map(u => <li key={`${u.kind}:${u.id}`} className="px-2 py-0.5 rounded-control bg-surface-2 text-label text-ink">
|
||||
{t(`media.uses.${u.kind}`, { defaultValue: u.kind })}: {u.name}</li>)}
|
||||
</ul>
|
||||
<p className="text-caption text-ink-3">{t('media.usedCantDelete')}</p>
|
||||
</>}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// A photo field (plan step 5.2): the picture something uses, from the media library.
|
||||
// Upload → into the library and set here at once ("upload on the spot")
|
||||
// From library → the picker
|
||||
// Remove → nothing here any more (the photo stays in the library)
|
||||
// After an upload on the spot, "Name it after <the product>" sets the photo's display name to
|
||||
// `nameAfter` in Latin letters (latin() from @xenia/i18n). The file names on disk are the backend's.
|
||||
//
|
||||
// <MediaField value={form.image} onChange={image => setField('image', image)} nameAfter={form.name} />
|
||||
// `value` / onChange use the API's `image` shape: { id, name, thumb, card, full } or null.
|
||||
import { useRef, useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { ImagePlus, Images, X } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { latin, useTranslation } from '@xenia/i18n'
|
||||
import { Button } from '@xenia/ui'
|
||||
import { renameMedia, uploadMedia } from './mediaApi'
|
||||
import { ACCEPT, imageOf } from './mediaLogic'
|
||||
import { MediaThumb } from './MediaParts'
|
||||
import MediaPicker from './MediaPicker'
|
||||
|
||||
const IMAGES = ACCEPT.split(',').filter(a => a.startsWith('image/')).join(',')
|
||||
|
||||
export default function MediaField({ value, onChange, nameAfter, nameAfterLabel, label, testid = 'media-field' }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [picking, setPicking] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [fresh, setFresh] = useState(null) // the id of a photo uploaded here (offers the rename)
|
||||
const input = useRef(null)
|
||||
const suggested = latin(nameAfter || '')
|
||||
|
||||
const upload = async file => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const item = await uploadMedia(file)
|
||||
onChange(imageOf(item))
|
||||
setFresh(item.existing ? null : item.id)
|
||||
if (item.existing) toast(t('media.alreadyThereUsed', { name: item.name }))
|
||||
} catch (err) { toast.error(errorMessage(err, t)) }
|
||||
setBusy(false)
|
||||
}
|
||||
const rename = async () => {
|
||||
setBusy(true)
|
||||
try { const m = await renameMedia(value.id, suggested); onChange({ ...value, name: m.name }); setFresh(null) }
|
||||
catch (err) { toast.error(errorMessage(err, t)) }
|
||||
setBusy(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-2" data-testid={testid}>
|
||||
{label && <span className="text-label font-medium text-ink-2">{label}</span>}
|
||||
<div className="flex gap-3 items-start">
|
||||
<MediaThumb item={value} className="w-20 h-20 rounded-card border border-line shrink-0" />
|
||||
<div className="grid gap-2 min-w-0">
|
||||
{value && <span className="text-label text-ink truncate" title={value.name} data-testid="media-field-name">{value.name}</span>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="secondary" icon={<ImagePlus size={14} />} loading={busy} onClick={() => input.current?.click()}
|
||||
data-testid="media-field-upload">{t(value ? 'media.replace' : 'media.uploadPhoto')}</Button>
|
||||
<Button size="sm" variant="secondary" icon={<Images size={14} />} disabled={busy} onClick={() => setPicking(true)}
|
||||
data-testid="media-field-pick">{t('media.fromLibrary')}</Button>
|
||||
{value && <Button size="sm" variant="ghost" icon={<X size={14} />} disabled={busy} onClick={() => { onChange(null); setFresh(null) }}
|
||||
data-testid="media-field-remove">{t('media.removePhoto')}</Button>}
|
||||
</div>
|
||||
{value && fresh === value.id && suggested && suggested !== value.name && (
|
||||
<button type="button" className="text-label text-accent-ink font-medium text-left disabled:opacity-50" disabled={busy}
|
||||
onClick={rename} data-testid="media-field-name-after">
|
||||
{nameAfterLabel || t('media.nameAfterProduct')} <span className="text-ink-3 font-normal">("{suggested}")</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<input ref={input} type="file" accept={IMAGES} className="sr-only" data-testid="media-field-file"
|
||||
onChange={e => { const f = e.target.files?.[0]; e.target.value = ''; if (f) upload(f) }} />
|
||||
{picking && <MediaPicker open selectedId={value?.id} onClose={() => setPicking(false)}
|
||||
onPick={(item, { uploaded }) => { onChange(imageOf(item)); setFresh(uploaded ? item.id : null); setPicking(false) }} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// The Media page (plan step 5.2, owner 2026-11-17): every picture and video of the venue in one
|
||||
// library. Batch upload (pick many files or drop them on the page) to use later anywhere that
|
||||
// takes media (products, categories; the customer display and signage next). The backend names
|
||||
// and stores the files; here people see a display name, the details and the sizes made.
|
||||
// Backend: /api/media (routers/media.py).
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Upload } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, EmptyState, Input, Select, Spinner, cx } from '@xenia/ui'
|
||||
import { listMedia } from './mediaApi'
|
||||
import { ACCEPT } from './mediaLogic'
|
||||
import MediaDetails from './MediaDetails'
|
||||
import { MediaGrid, UploadQueue } from './MediaParts'
|
||||
import { useUploadQueue } from './mediaHooks'
|
||||
|
||||
export default function MediaPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
const [kind, setKind] = useState('')
|
||||
const [q, setQ] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const [open, setOpen] = useState(null)
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const input = useRef(null)
|
||||
|
||||
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try { setPage(await listMedia({ kind, q: search })); setError(null) } catch (err) { setError(errorMessage(err, t)) }
|
||||
}, [kind, search, t])
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
// Each finished upload shows at once; the list is read again when the batch is done.
|
||||
const { queue, add, clear, summary } = useUploadQueue(useCallback(item => {
|
||||
setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p))
|
||||
}, []))
|
||||
const wasBusy = useRef(false)
|
||||
useEffect(() => { if (wasBusy.current && !summary.busy) load(); wasBusy.current = summary.busy }, [summary.busy, load])
|
||||
|
||||
const onDrop = e => {
|
||||
e.preventDefault(); setDragging(false)
|
||||
if (e.dataTransfer.files?.length) add(e.dataTransfer.files)
|
||||
}
|
||||
const kinds = useMemo(() => [
|
||||
{ value: '', label: t('media.kinds.all') }, { value: 'image', label: t('media.kinds.images') }, { value: 'video', label: t('media.kinds.videos') },
|
||||
], [t])
|
||||
const closeDetails = useCallback(() => setOpen(null), [])
|
||||
|
||||
return (
|
||||
<div className={cx('p-4 md:p-6 grid gap-5 max-w-7xl min-h-full content-start', dragging && 'outline-2 outline-dashed outline-accent -outline-offset-8')}
|
||||
data-testid="media-page"
|
||||
onDragOver={e => { if ([...(e.dataTransfer?.types || [])].includes('Files')) { e.preventDefault(); setDragging(true) } }}
|
||||
onDragLeave={e => { if (e.currentTarget === e.target) setDragging(false) }}
|
||||
onDrop={onDrop}>
|
||||
<header className="grid gap-1">
|
||||
<h1 className="text-heading font-semibold text-ink">{t('media.title')}</h1>
|
||||
<p className="text-body text-ink-2 max-w-3xl">{t('media.intro')}</p>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-wrap gap-2 items-center">
|
||||
<Button icon={<Upload size={16} />} onClick={() => input.current?.click()} data-testid="media-upload">{t('media.upload')}</Button>
|
||||
<input ref={input} type="file" multiple accept={ACCEPT} className="sr-only" data-testid="media-file-input"
|
||||
onChange={e => { if (e.target.files?.length) add(e.target.files); e.target.value = '' }} />
|
||||
<span className="text-label text-ink-3 hidden md:inline">{t('media.dropHint')}</span>
|
||||
<div className="flex gap-2 ml-auto w-full sm:w-auto">
|
||||
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')}
|
||||
className="flex-1 sm:w-56" data-testid="media-search" />
|
||||
<Select value={kind} onChange={e => setKind(e.target.value)} options={kinds} aria-label={t('media.kind')} data-testid="media-kind" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UploadQueue queue={queue} summary={summary} onClear={clear} />
|
||||
|
||||
{error ? <EmptyState title={error} />
|
||||
: !page ? <div className="flex justify-center p-6"><Spinner /></div>
|
||||
: page.items.length === 0 ? <EmptyState title={t(search || kind ? 'media.noMatch' : 'media.empty')} description={search || kind ? undefined : t('media.emptyHint')} />
|
||||
: <>
|
||||
<p className="text-label text-ink-3" data-testid="media-count">{t('media.count', { count: page.total })}</p>
|
||||
<MediaGrid items={page.items} onOpen={item => setOpen(item.id)} />
|
||||
{page.total > page.items.length && <p className="text-label text-ink-3">{t('media.more', { shown: page.items.length, total: page.total })}</p>}
|
||||
</>}
|
||||
|
||||
{open && <MediaDetails id={open} onClose={closeDetails}
|
||||
onChanged={m => setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) })}
|
||||
onDeleted={id => setPage(p => p && { ...p, items: p.items.filter(x => x.id !== id), total: p.total - 1 })} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Pieces shared by the Media page, the picker and the photo field (plan step 5.2).
|
||||
import { useState } from 'react'
|
||||
import { CheckCircle2, Copy, Film, ImageOff, Loader2, XCircle } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { cx } from '@xenia/ui'
|
||||
import { useMediaMeta } from './mediaHooks'
|
||||
|
||||
/** The small picture of a library item (a film mark for videos, which have no still frame yet: 5.4b). */
|
||||
export function MediaThumb({ item, className }) {
|
||||
const [broken, setBroken] = useState(false)
|
||||
if (item?.kind === 'video') {
|
||||
return <div className={cx('flex items-center justify-center bg-surface-3 text-ink-2', className)}><Film size={28} aria-hidden="true" /></div>
|
||||
}
|
||||
const src = item?.urls?.thumb || item?.thumb
|
||||
if (!src || broken) {
|
||||
return <div className={cx('flex items-center justify-center bg-surface-3 text-ink-3', className)}><ImageOff size={24} aria-hidden="true" /></div>
|
||||
}
|
||||
return <img src={src} alt="" loading="lazy" onError={() => setBroken(true)} className={cx('object-cover bg-surface-3', className)} />
|
||||
}
|
||||
|
||||
/** A grid of library items; `selectedId` marks one (the picker). */
|
||||
export function MediaGrid({ items, onOpen, selectedId, testid = 'media-grid' }) {
|
||||
const meta = useMediaMeta()
|
||||
return (
|
||||
<ul className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }} data-testid={testid}>
|
||||
{items.map(item => (
|
||||
<li key={item.id}>
|
||||
<button type="button" onClick={() => onOpen(item)} data-testid="media-item" data-id={item.id} data-name={item.name}
|
||||
className={cx('w-full text-left rounded-card border bg-surface overflow-hidden transition-colors duration-fast hover:border-line-strong focus-visible:shadow-focus outline-none',
|
||||
selectedId === item.id ? 'border-accent ring-2 ring-accent' : 'border-line')}>
|
||||
<MediaThumb item={item} className="w-full aspect-square" />
|
||||
<span className="block px-2 pt-1.5 text-label font-medium text-ink truncate" title={item.name}>{item.name}</span>
|
||||
<span className="block px-2 pb-2 text-caption text-ink-3 truncate">{meta(item)}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** The list of files being uploaded, with how each one went. */
|
||||
export function UploadQueue({ queue, summary, onClear }) {
|
||||
const { t } = useTranslation('manager')
|
||||
if (!queue.length) return null
|
||||
const icon = s => ({
|
||||
uploading: <Loader2 size={16} className="animate-spin text-accent-ink" aria-hidden="true" />,
|
||||
added: <CheckCircle2 size={16} className="text-success-ink" aria-hidden="true" />,
|
||||
existing: <Copy size={16} className="text-info-ink" aria-hidden="true" />,
|
||||
failed: <XCircle size={16} className="text-danger-ink" aria-hidden="true" />,
|
||||
})[s] || <span className="w-4 h-4 rounded-full border border-line-strong inline-block" aria-hidden="true" />
|
||||
return (
|
||||
<section className="rounded-card border border-line bg-surface p-3 grid gap-2" data-testid="media-queue" aria-live="polite">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span className="text-label font-semibold text-ink">
|
||||
{summary.busy ? t('media.uploading', { done: summary.added + summary.existing + summary.failed, total: summary.total })
|
||||
: t('media.uploaded', { added: summary.added, existing: summary.existing, failed: summary.failed })}
|
||||
</span>
|
||||
{!summary.busy && <button type="button" className="text-label text-accent-ink font-medium ml-auto" onClick={onClear}>{t('media.clearList')}</button>}
|
||||
</div>
|
||||
<ul className="grid gap-1 max-h-56 overflow-auto">
|
||||
{queue.map(q => (
|
||||
<li key={q.key} className="flex items-center gap-2 text-label" data-testid="media-queue-item" data-status={q.status}>
|
||||
{icon(q.status)}
|
||||
<span className="truncate text-ink flex-1 min-w-0" title={q.name}>{q.name}</span>
|
||||
{q.status === 'uploading' && <span className="text-ink-3 tabular-nums">{q.progress}%</span>}
|
||||
{q.status === 'existing' && <span className="text-ink-3">{t('media.alreadyThere')}</span>}
|
||||
{q.status === 'failed' && <span className="text-danger-ink truncate max-w-[50%]" title={q.error}>{q.error}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Pick a picture from the media library (plan step 5.2), or upload one here: an upload made from
|
||||
// the picker is picked at once. Used by MediaField (products, categories; more places later).
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Upload } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Input, Spinner } from '@xenia/ui'
|
||||
import { listMedia } from './mediaApi'
|
||||
import { ACCEPT } from './mediaLogic'
|
||||
import { MediaGrid, UploadQueue } from './MediaParts'
|
||||
import { useUploadQueue } from './mediaHooks'
|
||||
|
||||
export default function MediaPicker({ open, onClose, onPick, kind = 'image', selectedId }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [q, setQ] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const input = useRef(null)
|
||||
|
||||
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
let live = true
|
||||
listMedia({ kind, q: search }).then(p => { if (live) { setPage(p); setError(null) } }).catch(err => live && setError(errorMessage(err, t)))
|
||||
return () => { live = false }
|
||||
}, [open, kind, search, t])
|
||||
|
||||
const { queue, add, clear, summary } = useUploadQueue(useCallback(item => onPick(item, { uploaded: !item.existing }), [onPick]))
|
||||
|
||||
return (
|
||||
<Dialog open={open} size="lg" title={t('media.pickTitle')} onClose={onClose}
|
||||
footer={<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>}>
|
||||
<div className="grid gap-3" data-testid="media-picker">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')}
|
||||
className="flex-1 min-w-[10rem]" data-testid="media-picker-search" />
|
||||
<Button variant="secondary" icon={<Upload size={16} />} onClick={() => input.current?.click()} disabled={summary.busy}>{t('media.uploadNew')}</Button>
|
||||
<input ref={input} type="file" accept={kind === 'image' ? ACCEPT.split(',').filter(a => a.startsWith('image/')).join(',') : ACCEPT}
|
||||
className="sr-only" data-testid="media-picker-file" onChange={e => { if (e.target.files?.length) add([e.target.files[0]]); e.target.value = '' }} />
|
||||
</div>
|
||||
<UploadQueue queue={queue} summary={summary} onClear={clear} />
|
||||
{error ? <EmptyState title={error} />
|
||||
: !page ? <div className="flex justify-center p-6"><Spinner /></div>
|
||||
: page.items.length === 0 ? <EmptyState title={t(search ? 'media.noMatch' : 'media.empty')} />
|
||||
: <div className="max-h-[55vh] overflow-auto pr-1">
|
||||
<MediaGrid items={page.items} selectedId={selectedId} onOpen={item => onPick(item, { uploaded: false })} testid="media-picker-grid" />
|
||||
</div>}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// The media library's API (backend: local_backend/routers/media.py, plan steps 5.1 / 5.2).
|
||||
import client from '../../api/client'
|
||||
|
||||
export const listMedia = ({ kind, q, limit = 500 } = {}) =>
|
||||
client.get('/api/media', { params: { kind: kind || undefined, q: q || undefined, limit } }).then(r => r.data)
|
||||
|
||||
export const getMedia = id => client.get(`/api/media/${id}`).then(r => r.data)
|
||||
|
||||
/** Upload one file → the library item (`existing: true` when the same file was already there). */
|
||||
export function uploadMedia(file, { name, onProgress } = {}) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
if (name) fd.append('name', name)
|
||||
return client.post('/api/media', fd, {
|
||||
onUploadProgress: e => { if (onProgress && e.total) onProgress(Math.round((e.loaded / e.total) * 100)) },
|
||||
}).then(r => r.data)
|
||||
}
|
||||
|
||||
export const renameMedia = (id, name) => client.patch(`/api/media/${id}`, { name }).then(r => r.data)
|
||||
|
||||
export const deleteMedia = id => client.delete(`/api/media/${id}`)
|
||||
@@ -0,0 +1,51 @@
|
||||
// Hooks of the media library's screens (plan step 5.2).
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { uploadMedia } from './mediaApi'
|
||||
import { duration, fileSize, queueFrom, queueSummary, resolution } from './mediaLogic'
|
||||
|
||||
/** "1600 × 1200 · 245 KB" (or the length for a video) */
|
||||
export function useMediaMeta() {
|
||||
const { formatNumber } = useFormat()
|
||||
return useCallback(item => [
|
||||
item.kind === 'video' ? duration(item.duration_ms) : '',
|
||||
resolution(item.width, item.height),
|
||||
fileSize(item.bytes, formatNumber),
|
||||
].filter(Boolean).join(' · '), [formatNumber])
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads files one after another. `add(files)` queues them; `onDone(item, existing)` runs for
|
||||
* every file that made it into the library.
|
||||
*/
|
||||
export function useUploadQueue(onDone) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [queue, setQueue] = useState([])
|
||||
const running = useRef(false)
|
||||
const done = useRef(onDone)
|
||||
useEffect(() => { done.current = onDone })
|
||||
const counter = useRef(0)
|
||||
|
||||
const add = useCallback(files => {
|
||||
const list = queueFrom(files, counter.current)
|
||||
counter.current += list.length
|
||||
setQueue(q => [...q, ...list])
|
||||
}, [])
|
||||
const clear = useCallback(() => setQueue(q => q.filter(x => x.status === 'waiting' || x.status === 'uploading')), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (running.current) return
|
||||
const next = queue.find(q => q.status === 'waiting')
|
||||
if (!next) return
|
||||
running.current = true
|
||||
const set = patch => setQueue(q => q.map(x => (x.key === next.key ? { ...x, ...patch } : x)))
|
||||
set({ status: 'uploading' })
|
||||
uploadMedia(next.file, { onProgress: progress => set({ progress }) })
|
||||
.then(item => { set({ status: item.existing ? 'existing' : 'added', progress: 100, item }); done.current?.(item, !!item.existing) })
|
||||
.catch(err => set({ status: 'failed', error: errorMessage(err, t) }))
|
||||
.finally(() => { running.current = false; setQueue(q => [...q]) })
|
||||
}, [queue, t])
|
||||
|
||||
return { queue, add, clear, summary: queueSummary(queue) }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// The media library's pure helpers (plan step 5.2): no React, unit-tested in tests/media.test.mjs.
|
||||
|
||||
/** What file inputs accept: everything the backend takes (services/media.py). */
|
||||
export const ACCEPT = 'image/jpeg,image/png,image/webp,image/avif,image/gif,video/mp4,video/webm'
|
||||
|
||||
/** What an app needs to show a library picture (the same shape as the API's `image`). */
|
||||
export function imageOf(item) {
|
||||
if (!item || item.kind !== 'image') return null
|
||||
const u = item.urls || {}
|
||||
return { id: item.id, name: item.name, thumb: u.thumb, card: u.card, full: u.full }
|
||||
}
|
||||
|
||||
/** "245 KB", "3.4 MB": file sizes for people, with the venue's number format. */
|
||||
export function fileSize(bytes, formatNumber = n => String(n)) {
|
||||
if (bytes == null) return ''
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${formatNumber(Math.round(bytes / 1024), { maxDecimals: 0 })} KB`
|
||||
return `${formatNumber(bytes / (1024 * 1024), { maxDecimals: 1 })} MB`
|
||||
}
|
||||
|
||||
/** "1920 × 1080" or '' */
|
||||
export function resolution(w, h) {
|
||||
return w && h ? `${w} × ${h}` : ''
|
||||
}
|
||||
|
||||
/** "0:12", "1:05:09" from milliseconds, or '' */
|
||||
export function duration(ms) {
|
||||
if (!ms && ms !== 0) return ''
|
||||
const s = Math.round(ms / 1000)
|
||||
const h = Math.floor(s / 3600)
|
||||
const m = Math.floor((s % 3600) / 60)
|
||||
const sec = String(s % 60).padStart(2, '0')
|
||||
return h ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`
|
||||
}
|
||||
|
||||
/** Sizes in the order people read them: small → large → the original. */
|
||||
export const VARIANT_ORDER = ['thumb', 'card', 'full', 'original']
|
||||
|
||||
/**
|
||||
* A batch upload's queue: one entry per file, uploaded one after another.
|
||||
* status: 'waiting' | 'uploading' | 'added' | 'existing' | 'failed'
|
||||
*/
|
||||
export function queueFrom(files, start = 0) {
|
||||
return [...files].map((file, i) => ({ key: `${start + i}:${file.name}`, file, name: file.name, status: 'waiting', progress: 0, error: null, item: null }))
|
||||
}
|
||||
|
||||
export function queueSummary(queue) {
|
||||
const count = s => queue.filter(q => q.status === s).length
|
||||
return {
|
||||
total: queue.length,
|
||||
added: count('added'),
|
||||
existing: count('existing'),
|
||||
failed: count('failed'),
|
||||
busy: queue.some(q => q.status === 'waiting' || q.status === 'uploading'),
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { ModuleOff, NoAccess, useAccess } from '@xenia/access'
|
||||
import { pageFor } from './nav'
|
||||
import { canSee, pageFor } from './nav'
|
||||
|
||||
/**
|
||||
* Guards whatever route is showing by its path, with the same rules as the sidebar
|
||||
@@ -12,7 +12,7 @@ export default function RouteGuard({ children }) {
|
||||
const { modules, permissions } = useAccess()
|
||||
const page = pageFor(pathname)
|
||||
if (page?.module && !modules.has(page.module)) return <Centered><ModuleOff /></Centered>
|
||||
if (page?.perm && !permissions.has(page.perm)) return <Centered><NoAccess /></Centered>
|
||||
if (page && !canSee(page, { modules, permissions })) return <Centered><NoAccess /></Centered>
|
||||
return children
|
||||
}
|
||||
|
||||
|
||||
@@ -10,16 +10,19 @@
|
||||
// permission need core.dashboard.access (what their APIs check, require_manager).
|
||||
// Finer keys (pricing.manage, expenses.manage…) replace these when phase 6
|
||||
// converts those routers.
|
||||
// anyPerm instead of perm: any one of these keys is enough (the media library)
|
||||
// label a key in the i18n `manager` namespace
|
||||
import {
|
||||
LayoutDashboard, LayoutGrid, ShoppingBag,
|
||||
BookUser, Users, Receipt, CreditCard,
|
||||
Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
|
||||
BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText,
|
||||
AppWindow, Settings, CookingPot, Truck, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck, QrCode,
|
||||
AppWindow, Settings, CookingPot, Truck, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck, QrCode, Images,
|
||||
} from 'lucide-react'
|
||||
|
||||
const DASH = 'core.dashboard.access'
|
||||
// The media library: whoever manages something that shows pictures (routers/media.py MANAGE)
|
||||
const MEDIA = ['catalog.menu.manage', 'customer_display.manage', 'signage.manage', 'menu_tablet.manage']
|
||||
|
||||
export const NAV = [
|
||||
{
|
||||
@@ -58,6 +61,7 @@ export const NAV = [
|
||||
group: 'management', icon: Package, label: 'nav.management',
|
||||
children: [
|
||||
{ to: '/management/products', icon: Package, label: 'nav.products', module: 'catalog', perm: 'catalog.menu.manage' },
|
||||
{ to: '/management/media', icon: Images, label: 'nav.media', module: 'core', anyPerm: MEDIA },
|
||||
{ to: '/management/tables', icon: TableProperties, label: 'nav.tablesConfig', module: 'catalog', perm: 'catalog.tables.manage' },
|
||||
{ to: '/management/staff', icon: UserCog, label: 'nav.staff', module: 'core', perm: 'core.staff.manage' },
|
||||
{ to: '/management/sessions', icon: LogIn, label: 'nav.sessions', module: 'core', perm: 'core.staff.manage' },
|
||||
@@ -129,5 +133,6 @@ export function pageFor(pathname) {
|
||||
export function canSee(page, { modules, permissions }) {
|
||||
if (!page) return true
|
||||
if (page.module && !modules.has(page.module)) return false
|
||||
if (page.anyPerm) return page.anyPerm.some(k => permissions.has(k))
|
||||
return !page.perm || permissions.has(page.perm)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// The media library's helpers and its nav rule (plan step 5.2).
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { duration, fileSize, imageOf, queueFrom, queueSummary, resolution } from '../src/pages/media/mediaLogic.js'
|
||||
import { canSee, pageFor } from '../src/shell/nav.js'
|
||||
|
||||
test('sizes, resolutions and lengths for people', () => {
|
||||
assert.equal(fileSize(512), '512 B')
|
||||
assert.equal(fileSize(250_000), '244 KB')
|
||||
assert.equal(fileSize(3.4 * 1024 * 1024, (n, o) => n.toFixed(o.maxDecimals)), '3.4 MB')
|
||||
assert.equal(fileSize(null), '')
|
||||
assert.equal(resolution(1920, 1080), '1920 × 1080')
|
||||
assert.equal(resolution(null, 5), '')
|
||||
assert.equal(duration(12_500), '0:13')
|
||||
assert.equal(duration(3_909_000), '1:05:09')
|
||||
})
|
||||
|
||||
test('a library item as the picture an app shows', () => {
|
||||
const item = { id: 4, kind: 'image', name: 'Gyros', urls: { thumb: '/t', card: '/c', full: '/f', original: '/o' } }
|
||||
assert.deepEqual(imageOf(item), { id: 4, name: 'Gyros', thumb: '/t', card: '/c', full: '/f' })
|
||||
assert.equal(imageOf({ ...item, kind: 'video' }), null)
|
||||
assert.equal(imageOf(null), null)
|
||||
})
|
||||
|
||||
test('a batch upload queue and its summary', () => {
|
||||
const q = queueFrom([{ name: 'a.jpg' }, { name: 'b.jpg' }], 3)
|
||||
assert.deepEqual(q.map(x => [x.key, x.status]), [['3:a.jpg', 'waiting'], ['4:b.jpg', 'waiting']])
|
||||
assert.equal(queueSummary(q).busy, true)
|
||||
const done = [{ ...q[0], status: 'added' }, { ...q[1], status: 'existing' }, { key: 'x', status: 'failed' }]
|
||||
assert.deepEqual(queueSummary(done), { total: 3, added: 1, existing: 1, failed: 1, busy: false })
|
||||
})
|
||||
|
||||
test('the Media page is for anyone who manages something with pictures', () => {
|
||||
const page = pageFor('/management/media')
|
||||
const access = keys => ({ modules: new Set(['core']), permissions: new Set(keys) })
|
||||
assert.equal(canSee(page, access(['customer_display.manage'])), true)
|
||||
assert.equal(canSee(page, access(['catalog.menu.manage'])), true)
|
||||
assert.equal(canSee(page, access(['core.dashboard.access'])), false)
|
||||
})
|
||||
@@ -129,11 +129,12 @@
|
||||
},
|
||||
"media": {
|
||||
"not_found": "Το αρχείο {{media_id}} δεν υπάρχει στη βιβλιοθήκη πολυμέσων.",
|
||||
"type": "Ανεβάστε εικόνα (JPG, PNG, WebP ή GIF) ή βίντεο (MP4 ή WebM).",
|
||||
"type": "Ανεβάστε εικόνα (JPG, PNG, WebP, AVIF ή GIF) ή βίντεο (MP4 ή WebM).",
|
||||
"too_big": "Το αρχείο είναι πολύ μεγάλο (έως {{max_mb}} MB).",
|
||||
"too_many_pixels": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mp}} megapixel).",
|
||||
"unreadable": "Αυτή η εικόνα δεν διαβάζεται. Αποθηκεύστε τη ξανά ως JPG ή PNG και ανεβάστε τη.",
|
||||
"in_use": "Αυτό το αρχείο χρησιμοποιείται από: {{uses}}. Αφαιρέστε το πρώτα από εκεί."
|
||||
"in_use": "Αυτό το αρχείο χρησιμοποιείται από: {{uses}}. Αφαιρέστε το πρώτα από εκεί.",
|
||||
"not_a_picture": "Εδώ διαλέξτε εικόνα, όχι βίντεο."
|
||||
},
|
||||
"caller_id": {
|
||||
"key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος."
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
"sessions": "Συνδεδεμένοι τώρα",
|
||||
"approvals": "Εγκρίσεις υπευθύνου",
|
||||
"deliveryFees": "Online παραγγελίες (ρύθμιση)",
|
||||
"qrCodes": "QR τραπεζιών"
|
||||
"qrCodes": "QR τραπεζιών",
|
||||
"media": "Πολυμέσα"
|
||||
},
|
||||
"profile": {
|
||||
"edit": "Επεξεργασία προφίλ",
|
||||
@@ -702,5 +703,70 @@
|
||||
"setup": "Σύνδεση του τηλεφωνικού κέντρου",
|
||||
"setupBody": "Στο Grandstream UCM, ορίστε το Action URL για τις εισερχόμενες κλήσεις σε αυτή τη διεύθυνση (λειτουργεί μόνο μέσα από το κατάστημα):",
|
||||
"setupSecret": "Για επιπλέον ασφάλεια, ορίστε ένα κλειδί στις Ρυθμίσεις (caller_id.secret) και προσθέστε &key=<το κλειδί> στη διεύθυνση."
|
||||
},
|
||||
"media": {
|
||||
"title": "Πολυμέσα",
|
||||
"intro": "Όλες οι εικόνες και τα βίντεο του καταστήματος σε ένα μέρος. Ανεβάστε πολλά μαζί και διαλέξτε τα μετά για προϊόντα, κατηγορίες και οθόνες. Ο διακομιστής κρατά το πρωτότυπο και φτιάχνει μικρότερα αντίγραφα που φορτώνουν γρήγορα· το όνομα είναι μόνο για εσάς.",
|
||||
"upload": "Ανέβασμα αρχείων",
|
||||
"uploadNew": "Ανέβασμα νέου",
|
||||
"dropHint": "ή αφήστε αρχεία οπουδήποτε σε αυτή τη σελίδα",
|
||||
"search": "Αναζήτηση με όνομα",
|
||||
"kind": "Είδος",
|
||||
"kinds": {
|
||||
"all": "Όλα",
|
||||
"images": "Εικόνες",
|
||||
"videos": "Βίντεο",
|
||||
"image": "Εικόνα",
|
||||
"video": "Βίντεο"
|
||||
},
|
||||
"noMatch": "Δεν βρέθηκε τίποτα.",
|
||||
"empty": "Η βιβλιοθήκη είναι άδεια.",
|
||||
"emptyHint": "Ανεβάστε εδώ τις φωτογραφίες σας ή προσθέστε μία απευθείας από ένα προϊόν.",
|
||||
"count_one": "{{count}} αρχείο",
|
||||
"count_other": "{{count}} αρχεία",
|
||||
"more": "Εμφανίζονται τα νεότερα {{shown}} από {{total}}. Αναζητήστε για να βρείτε παλαιότερα.",
|
||||
"uploading": "Ανέβασμα {{done}} από {{total}}…",
|
||||
"uploaded": "Έτοιμο: {{added}} νέα, {{existing}} υπήρχαν ήδη, {{failed}} απέτυχαν.",
|
||||
"clearList": "Καθαρισμός λίστας",
|
||||
"alreadyThere": "υπάρχει ήδη στη βιβλιοθήκη",
|
||||
"alreadyThereUsed": "Αυτή η φωτογραφία υπήρχε ήδη στη βιβλιοθήκη ως «{{name}}»: χρησιμοποιείται αυτή.",
|
||||
"renamed": "Το όνομα αποθηκεύτηκε.",
|
||||
"deleted": "Διαγράφηκε από τη βιβλιοθήκη.",
|
||||
"deleteConfirm": "Οριστική διαγραφή αυτού του αρχείου;",
|
||||
"delete": "Διαγραφή",
|
||||
"close": "Κλείσιμο",
|
||||
"resolution": "Ανάλυση",
|
||||
"length": "Διάρκεια",
|
||||
"fileSize": "Μέγεθος αρχείου",
|
||||
"originalName": "Αρχείο που ανέβηκε",
|
||||
"uploadedAt": "Ανέβηκε",
|
||||
"uploadedBy": "Από",
|
||||
"displayName": "Όνομα",
|
||||
"displayNameHint": "Αυτό που βλέπετε στη βιβλιοθήκη. Το ίδιο το αρχείο έχει όνομα που χρησιμοποιεί μόνο ο διακομιστής.",
|
||||
"saveName": "Αποθήκευση ονόματος",
|
||||
"sizes": "Μεγέθη που φτιάχτηκαν",
|
||||
"sizesHint": "Ο διακομιστής τα έφτιαξε από το πρωτότυπο· κάθε οθόνη φορτώνει το μικρότερο που χρειάζεται.",
|
||||
"sizesVideo": "Τα βίντεο κρατιούνται όπως ανέβηκαν προς το παρόν· μικρότερες εκδοχές και στιγμιότυπο έρχονται αργότερα.",
|
||||
"variants": {
|
||||
"thumb": "Μικρό (λίστες)",
|
||||
"card": "Κάρτα (μενού)",
|
||||
"full": "Μεγάλο (πλήρης οθόνη)",
|
||||
"original": "Πρωτότυπο"
|
||||
},
|
||||
"usedBy": "Χρησιμοποιείται από",
|
||||
"unused": "Δεν χρησιμοποιείται ακόμα.",
|
||||
"usedCantDelete": "Ένα αρχείο σε χρήση δεν διαγράφεται. Αφαιρέστε το πρώτα από εκεί.",
|
||||
"uses": {
|
||||
"product": "Προϊόν",
|
||||
"category": "Κατηγορία"
|
||||
},
|
||||
"pickTitle": "Επιλογή εικόνας",
|
||||
"photo": "Φωτογραφία",
|
||||
"uploadPhoto": "Ανέβασμα φωτογραφίας",
|
||||
"replace": "Ανέβασμα άλλης",
|
||||
"fromLibrary": "Από τη βιβλιοθήκη",
|
||||
"removePhoto": "Αφαίρεση",
|
||||
"nameAfterProduct": "Ονομασία με το όνομα του προϊόντος",
|
||||
"nameAfterCategory": "Ονομασία με το όνομα της κατηγορίας"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,11 +129,12 @@
|
||||
},
|
||||
"media": {
|
||||
"not_found": "File {{media_id}} isn't in the media library.",
|
||||
"type": "Upload a picture (JPG, PNG, WebP or GIF) or a video (MP4 or WebM).",
|
||||
"type": "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM).",
|
||||
"too_big": "The file is too big (at most {{max_mb}} MB).",
|
||||
"too_many_pixels": "The picture is too large (at most {{max_mp}} megapixels).",
|
||||
"unreadable": "This picture can't be read. Save it again as JPG or PNG and upload it.",
|
||||
"in_use": "This file is used by {{uses}}. Remove it there first."
|
||||
"in_use": "This file is used by {{uses}}. Remove it there first.",
|
||||
"not_a_picture": "Pick a picture here, not a video."
|
||||
},
|
||||
"caller_id": {
|
||||
"key_invalid": "The phone system's key is missing or wrong."
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
"sessions": "Signed in now",
|
||||
"approvals": "Manager approvals",
|
||||
"deliveryFees": "Online ordering",
|
||||
"qrCodes": "Table QR codes"
|
||||
"qrCodes": "Table QR codes",
|
||||
"media": "Media"
|
||||
},
|
||||
"profile": {
|
||||
"edit": "Edit profile",
|
||||
@@ -702,5 +703,70 @@
|
||||
"setup": "Connect the phone system",
|
||||
"setupBody": "In the Grandstream UCM, set the Action URL for incoming calls to this address (it only works from inside the venue):",
|
||||
"setupSecret": "For extra safety, set a key in Settings (caller_id.secret) and add &key=<the key> to the address."
|
||||
},
|
||||
"media": {
|
||||
"title": "Media",
|
||||
"intro": "Every picture and video of the venue, in one place. Upload many at once, then pick them for products, categories and screens. The server keeps the original and makes smaller copies that load fast; the name is only for you.",
|
||||
"upload": "Upload files",
|
||||
"uploadNew": "Upload a new one",
|
||||
"dropHint": "or drop files anywhere on this page",
|
||||
"search": "Search by name",
|
||||
"kind": "Kind",
|
||||
"kinds": {
|
||||
"all": "All",
|
||||
"images": "Pictures",
|
||||
"videos": "Videos",
|
||||
"image": "Picture",
|
||||
"video": "Video"
|
||||
},
|
||||
"noMatch": "Nothing matches.",
|
||||
"empty": "The library is empty.",
|
||||
"emptyHint": "Upload your photos here, or add one straight from a product.",
|
||||
"count_one": "{{count}} file",
|
||||
"count_other": "{{count}} files",
|
||||
"more": "Showing the newest {{shown}} of {{total}}. Search to find older ones.",
|
||||
"uploading": "Uploading {{done}} of {{total}}…",
|
||||
"uploaded": "Done: {{added}} added, {{existing}} already in the library, {{failed}} failed.",
|
||||
"clearList": "Clear the list",
|
||||
"alreadyThere": "already in the library",
|
||||
"alreadyThereUsed": "This photo was already in the library as \"{{name}}\": using that one.",
|
||||
"renamed": "Name saved.",
|
||||
"deleted": "Deleted from the library.",
|
||||
"deleteConfirm": "Delete this file for good?",
|
||||
"delete": "Delete",
|
||||
"close": "Close",
|
||||
"resolution": "Resolution",
|
||||
"length": "Length",
|
||||
"fileSize": "File size",
|
||||
"originalName": "Uploaded file",
|
||||
"uploadedAt": "Uploaded",
|
||||
"uploadedBy": "By",
|
||||
"displayName": "Name",
|
||||
"displayNameHint": "What you see in the library. The file itself keeps a name only the server uses.",
|
||||
"saveName": "Save name",
|
||||
"sizes": "Sizes made",
|
||||
"sizesHint": "The server made these from the original; each screen loads the smallest one it needs.",
|
||||
"sizesVideo": "Videos are kept as uploaded for now; smaller versions and a still frame come later.",
|
||||
"variants": {
|
||||
"thumb": "Small (lists)",
|
||||
"card": "Card (menus)",
|
||||
"full": "Large (full screen)",
|
||||
"original": "Original"
|
||||
},
|
||||
"usedBy": "Used by",
|
||||
"unused": "Nothing uses it yet.",
|
||||
"usedCantDelete": "A file in use can't be deleted. Remove it there first.",
|
||||
"uses": {
|
||||
"product": "Product",
|
||||
"category": "Category"
|
||||
},
|
||||
"pickTitle": "Pick a picture",
|
||||
"photo": "Photo",
|
||||
"uploadPhoto": "Upload a photo",
|
||||
"replace": "Upload another",
|
||||
"fromLibrary": "From the library",
|
||||
"removePhoto": "Remove",
|
||||
"nameAfterProduct": "Name it after the product",
|
||||
"nameAfterCategory": "Name it after the category"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export { I18nProvider } from './provider.jsx'
|
||||
export { useFormat, useLanguage, useUiLabels } from './hooks.js'
|
||||
export { createFormatters, toDate, DATE_STYLES } from './format.js'
|
||||
export { parseNumber } from './number.js'
|
||||
export { latin } from './latin.js'
|
||||
export {
|
||||
SUPPORTED_LANGUAGES, FALLBACK_LANGUAGE, LANGUAGE_NAMES, DEFAULT_TIMEZONE, DEFAULT_CURRENCY,
|
||||
resolveLanguage, normalizeLanguage, intlLocale,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Greek → Latin letters ("Greeklish"), for names that must be plain English characters, e.g. a
|
||||
// media item named after its product ("Γύρος χοιρινός" → "Gyros xoirinos", plan step 5.2).
|
||||
// The style follows how Greek venues write it themselves: χ → x, ξ → ks, η → i, υ → y,
|
||||
// ου → ou, αυ / ευ → av / ev. Accents go; anything that still isn't plain ASCII is dropped.
|
||||
const ONE = {
|
||||
α: 'a', β: 'v', γ: 'g', δ: 'd', ε: 'e', ζ: 'z', η: 'i', θ: 'th', ι: 'i', κ: 'k', λ: 'l', μ: 'm',
|
||||
ν: 'n', ξ: 'ks', ο: 'o', π: 'p', ρ: 'r', σ: 's', ς: 's', τ: 't', υ: 'y', φ: 'f', χ: 'x', ψ: 'ps', ω: 'o',
|
||||
}
|
||||
const TWO = { ου: 'ou', αυ: 'av', ευ: 'ev', γγ: 'ng', ει: 'ei', οι: 'oi', αι: 'ai' }
|
||||
|
||||
function matchCase(src, out) {
|
||||
return src === src.toLowerCase() ? out : out[0].toUpperCase() + out.slice(1)
|
||||
}
|
||||
|
||||
function word(w) {
|
||||
let out = ''
|
||||
for (let i = 0; i < w.length; i++) {
|
||||
const two = TWO[w.slice(i, i + 2).toLowerCase()]
|
||||
if (two) { out += matchCase(w[i], two); i++; continue }
|
||||
const one = ONE[w[i].toLowerCase()]
|
||||
out += one ? matchCase(w[i], one) : w[i]
|
||||
}
|
||||
// an all-caps word stays all caps ("ΘΕΑ" → "THEA", not "ThEA")
|
||||
const letters = w.replace(/[^\p{L}]/gu, '')
|
||||
return letters.length > 1 && letters === letters.toUpperCase() ? out.toUpperCase() : out
|
||||
}
|
||||
|
||||
/** Latin letters for Greek text; other text passes through (accents removed). */
|
||||
export function latin(text) {
|
||||
const s = String(text ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').normalize('NFC')
|
||||
return s.split(/(\s+)/).map(word).join('').replace(/[^\x20-\x7e]/g, '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { latin } from '../src/latin.js'
|
||||
|
||||
test('Greek names in plain Latin letters, the way venues write them', () => {
|
||||
assert.equal(latin('Γύρος χοιρινός'), 'Gyros xoirinos')
|
||||
assert.equal(latin('Χυμός βύσσινο'), 'Xymos vyssino')
|
||||
assert.equal(latin('Ούζο Πλωμαρίου'), 'Ouzo Plomariou')
|
||||
assert.equal(latin('Σουβλάκι κοτόπουλο'), 'Souvlaki kotopoulo')
|
||||
assert.equal(latin('Ψητά'), 'Psita')
|
||||
assert.equal(latin('Φρέντο εσπρέσο'), 'Frento espreso')
|
||||
assert.equal(latin('Ταξίδι'), 'Taksidi')
|
||||
assert.equal(latin('Ευχή'), 'Evxi')
|
||||
assert.equal(latin('Θεά'), 'Thea')
|
||||
})
|
||||
|
||||
test('all caps stay all caps; Latin, digits and signs pass through', () => {
|
||||
assert.equal(latin('ΘΕΑ'), 'THEA')
|
||||
assert.equal(latin('ΜΠΥΡΑ 500ml'), 'MPYRA 500ml')
|
||||
assert.equal(latin('Coca-Cola 330ml'), 'Coca-Cola 330ml')
|
||||
assert.equal(latin('Café crème'), 'Cafe creme')
|
||||
assert.equal(latin(' Pita 🌯 gyros '), 'Pita gyros')
|
||||
assert.equal(latin(null), '')
|
||||
})
|
||||
@@ -72,7 +72,9 @@ export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKe
|
||||
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
|
||||
// No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl.
|
||||
LICENSE_MODE: cloudUrl ? 'enforced' : 'off',
|
||||
SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId), ...env,
|
||||
SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId),
|
||||
// the media library's files stay in this backend's own data folder (not /app/data)
|
||||
XENIA_MEDIA_DIR: path.join(dataDir, 'media'), ...env,
|
||||
},
|
||||
})
|
||||
const url = `http://127.0.0.1:${port}`
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
// Media suite (plan step 5.2): the Media page takes a batch upload (the owner's ITEM PHOTOS
|
||||
// folders when they are there: JPG, PNG, WebP, AVIF), shows an item's details and the sizes made;
|
||||
// a product gets its photo from the library and another one uploaded on the spot ("Name it after
|
||||
// the product"); a photo in use can't be deleted; the waiter's phone fetches the menu's photos
|
||||
// ahead and still shows them with no connection.
|
||||
// Starts its own backend (:8063), the manager (:5190) and the waiter's native-mode build (:5191).
|
||||
// node media.mjs
|
||||
import { spawn, execFileSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, openSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { chromium } from 'playwright'
|
||||
import { BROWSER_CHANNEL, CS, OUT, PYTHON, REPO, reporter, sleep, waitFor } from './lib/env.mjs'
|
||||
import { killTree, login, startBackend, startViteNative, waitHttp } from './lib/proc.mjs'
|
||||
|
||||
const backend = await startBackend({ port: 8063, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } })
|
||||
const MPORT = 5190
|
||||
const MANAGER = `http://localhost:${MPORT}`
|
||||
const mlog = openSync(path.join(OUT, `vite-${MPORT}.log`), 'w')
|
||||
const managerVite = spawn('npx', ['vite', '--port', String(MPORT), '--strictPort'], {
|
||||
cwd: path.join(CS, 'manager_dashboard'), shell: process.platform === 'win32', detached: process.platform !== 'win32',
|
||||
stdio: ['ignore', mlog, mlog], env: { ...process.env, XENIA_BACKEND: backend.url },
|
||||
})
|
||||
const waiterVite = await startViteNative({ port: 5191, backendUrl: backend.url })
|
||||
const WAITER = 'http://localhost:5191'
|
||||
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
|
||||
const r = reporter('media: Media page (batch upload, details), product photos (library + on the spot), waiter offline photos (5.2)')
|
||||
const errors = []
|
||||
let failures = 0
|
||||
|
||||
async function api(method, url, { token, body } = {}) {
|
||||
const res = await fetch(backend.url + url, {
|
||||
method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
const text = await res.text()
|
||||
let data = null
|
||||
try { data = JSON.parse(text) } catch { data = text }
|
||||
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
|
||||
return data
|
||||
}
|
||||
|
||||
/** The files to batch-upload: the owner's photo folders, or a few made here when they aren't in this checkout. */
|
||||
function photoFiles() {
|
||||
const root = path.join(REPO, 'ITEM PHOTOS')
|
||||
if (existsSync(root)) {
|
||||
const files = readdirSync(root).flatMap(d => {
|
||||
const dir = path.join(root, d)
|
||||
return statSync(dir).isDirectory() ? readdirSync(dir).map(f => path.join(dir, f)) : []
|
||||
}).filter(f => /\.(jpe?g|png|webp|avif|gif)$/i.test(f))
|
||||
if (files.length) return { files, source: 'ITEM PHOTOS' }
|
||||
}
|
||||
const dir = path.join(OUT, 'media-photos')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const made = ['souvlaki', 'gyros', 'salad', 'beer', 'frappe'].map((n, i) => {
|
||||
const f = path.join(dir, `${n}.jpg`)
|
||||
writeFileSync(f, execFileSync(PYTHON, ['-c', `import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(1200,900),(${40 * i},120,${200 - 30 * i})).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())`]))
|
||||
return f
|
||||
})
|
||||
return { files: made, source: 'generated' }
|
||||
}
|
||||
|
||||
const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ timeout }).then(() => true).catch(() => false)
|
||||
|
||||
try {
|
||||
await waitHttp(`${MANAGER}/`)
|
||||
const boss = await login(backend.url)
|
||||
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
|
||||
|
||||
// ── Manager: the Media page, batch upload ──────────────────────────────────
|
||||
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } })
|
||||
const page = await ctx.newPage()
|
||||
page.on('pageerror', e => errors.push(e.message))
|
||||
await page.goto(`${MANAGER}/login`)
|
||||
await page.getByTestId('login-form').waitFor({ timeout: 60_000 })
|
||||
if (!(await page.getByTestId('login-account').count())) await page.getByLabel('Username').fill('manager')
|
||||
await page.getByLabel('Password').fill('password')
|
||||
await page.getByRole('button', { name: 'Sign in', exact: true }).click()
|
||||
await page.waitForURL(u => u.pathname !== '/login', { timeout: 20_000 })
|
||||
|
||||
await page.goto(`${MANAGER}/management/media`)
|
||||
r.check('Media page opens (Management → Media)', await shown(page, 'media-page', 20_000))
|
||||
r.check('the sidebar lists it', await page.getByRole('link', { name: 'Media' }).count() > 0)
|
||||
const { files, source } = photoFiles()
|
||||
await page.getByTestId('media-file-input').setInputFiles(files)
|
||||
const finished = await waitFor(async () => {
|
||||
const items = await page.getByTestId('media-queue-item').evaluateAll(els => els.map(e => e.dataset.status))
|
||||
return items.length === files.length && items.every(s => ['added', 'existing', 'failed'].includes(s)) ? items : null
|
||||
}, 300_000, 1000)
|
||||
const failed = await page.locator('[data-testid="media-queue-item"][data-status="failed"]').allInnerTexts()
|
||||
r.check(`batch upload of ${files.length} files (${source}): every file in the library, none refused`,
|
||||
!!finished && failed.length === 0, failed.join(' | ') || `${finished?.length}`)
|
||||
await page.screenshot({ path: path.join(OUT, 'media-page.png'), fullPage: false })
|
||||
const lib = await api('GET', '/api/media?limit=500', { token: boss })
|
||||
const distinct = new Set(lib.items.map(i => i.sha256)).size
|
||||
r.check('the library lists them (duplicates kept once)', lib.total > 0 && lib.total === distinct && lib.total <= files.length, `${lib.total}/${files.length}`)
|
||||
if (source === 'ITEM PHOTOS') {
|
||||
r.check('the AVIF photo went in too', lib.items.some(i => i.content_type === 'image/avif'))
|
||||
}
|
||||
r.check('the grid shows them all', await page.getByTestId('media-item').count() === lib.total)
|
||||
|
||||
// details: sizes made, rename
|
||||
await page.getByTestId('media-item').first().click()
|
||||
r.check('details: the sizes the server made (small, card, large, original)', await shown(page, 'media-details') &&
|
||||
await page.getByTestId('media-sizes').locator('li').count() === 4)
|
||||
await page.getByTestId('media-name').fill('Test photo renamed')
|
||||
await page.getByTestId('media-rename').click()
|
||||
await sleep(800)
|
||||
const firstId = Number(await page.getByTestId('media-details').getAttribute('data-id'))
|
||||
r.check('details: the display name changes', (await api('GET', `/api/media/${firstId}`, { token: boss })).name === 'Test photo renamed')
|
||||
await page.screenshot({ path: path.join(OUT, 'media-details.png') })
|
||||
await page.keyboard.press('Escape')
|
||||
|
||||
// ── A product's photo from the library, another one uploaded on the spot ────
|
||||
const products = await api('GET', '/api/products/?sold_at=in_store,in_store_takeaway', { token: boss })
|
||||
const [p1, p2] = products.filter(p => !p.is_service_item && p.lifecycle_status === 'active')
|
||||
await page.goto(`${MANAGER}/management/products`)
|
||||
const edit = async name => {
|
||||
const row = page.locator(`[data-testid="product-row"][data-name="${name}"]`).first()
|
||||
await row.waitFor({ timeout: 20_000 })
|
||||
await row.hover()
|
||||
await row.getByTestId('product-edit').click()
|
||||
await page.getByTestId('product-photo').waitFor({ timeout: 10_000 })
|
||||
}
|
||||
const save = async () => { await page.getByRole('button', { name: 'Αποθήκευση', exact: true }).last().click(); await sleep(1200) }
|
||||
|
||||
await edit(p1.name)
|
||||
await page.getByTestId('product-photo').getByTestId('media-field-pick').click()
|
||||
await page.getByTestId('media-picker').getByTestId('media-item').nth(1).click()
|
||||
const pickedName = await page.getByTestId('product-photo').getByTestId('media-field-name').innerText()
|
||||
r.check('product: "From the library" puts the picked photo on the form', !!pickedName)
|
||||
r.check('product: no "Name it after" for a photo picked from the library', await page.getByTestId('media-field-name-after').count() === 0)
|
||||
await save()
|
||||
const after1 = (await api('GET', '/api/products/', { token: boss })).find(p => p.id === p1.id)
|
||||
r.check('product: saved with the library photo (thumb / card / full)', after1.image?.name === pickedName && !!after1.image?.card && after1.image_url === after1.image.card, JSON.stringify(after1.image))
|
||||
|
||||
await edit(p2.name)
|
||||
// a photo not yet in the library (else it would just reuse the existing one)
|
||||
writeFileSync(path.join(OUT, 'media-onspot.jpg'), execFileSync(PYTHON, ['-c', "import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(1000,800),(7,77,177)).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())"]))
|
||||
await page.getByTestId('product-photo').getByTestId('media-field-file').setInputFiles(path.join(OUT, 'media-onspot.jpg'))
|
||||
const nameAfter = page.getByTestId('product-photo').getByTestId('media-field-name-after')
|
||||
r.check('product: an upload on the spot offers "Name it after the product"', await nameAfter.waitFor({ timeout: 15_000 }).then(() => true).catch(() => false))
|
||||
await page.screenshot({ path: path.join(OUT, 'media-product-field.png') })
|
||||
await nameAfter.click()
|
||||
await sleep(800)
|
||||
const renamed = await page.getByTestId('product-photo').getByTestId('media-field-name').innerText()
|
||||
r.check('product: the photo is named after the product in Latin letters', /^[\x20-\x7e]+$/.test(renamed) && renamed.length > 0, `${p2.name} → ${renamed}`)
|
||||
await save()
|
||||
const after2 = (await api('GET', '/api/products/', { token: boss })).find(p => p.id === p2.id)
|
||||
r.check('product: saved with the photo uploaded on the spot', after2.image?.name === renamed, JSON.stringify(after2.image))
|
||||
|
||||
// a photo in use can't be deleted
|
||||
await page.goto(`${MANAGER}/management/media`)
|
||||
await page.locator(`[data-testid="media-item"][data-id="${after1.image.id}"]`).click()
|
||||
await page.getByTestId('media-used-by').waitFor({ timeout: 10_000 }).catch(() => {})
|
||||
r.check('a photo in use: the details say what uses it and delete is off',
|
||||
(await page.getByTestId('media-used-by').innerText().catch(() => '')).includes(p1.name) && await page.getByTestId('media-delete').isDisabled())
|
||||
await page.keyboard.press('Escape')
|
||||
|
||||
// ── The waiter's phone: photos fetched ahead, shown offline ─────────────────
|
||||
const phone = await browser.newContext({ viewport: { width: 393, height: 852 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true })
|
||||
const w = await phone.newPage()
|
||||
w.on('pageerror', e => errors.push(e.message))
|
||||
await w.goto(`${WAITER}/login`)
|
||||
await w.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 30_000 })
|
||||
for (const d of '3302') await w.getByRole('button', { name: d, exact: true }).first().click()
|
||||
await w.waitForURL(u => u.pathname !== '/login', { timeout: 15_000 }).catch(() => {})
|
||||
await w.getByRole('button', { name: /Start shift/ }).click({ timeout: 10_000 }).catch(() => {})
|
||||
await w.waitForURL(u => u.pathname.startsWith('/tables'), { timeout: 15_000 }).catch(() => {})
|
||||
const cards = [after1.image.card, after2.image.card]
|
||||
const fetched = await waitFor(async () => {
|
||||
const got = await w.evaluate(() => performance.getEntriesByType('resource').map(e => e.name))
|
||||
return cards.every(c => got.some(u => u.endsWith(c))) ? true : null
|
||||
}, 30_000, 1000)
|
||||
r.check("waiter: the menu's photos are fetched ahead (before any screen shows them)", !!fetched)
|
||||
await phone.setOffline(true)
|
||||
const offline = await w.evaluate(async ({ urls, base }) => Promise.all(urls.map(u => new Promise(res => {
|
||||
const img = new Image()
|
||||
img.onload = () => res(img.naturalWidth)
|
||||
img.onerror = () => res(0)
|
||||
img.src = base + u
|
||||
}))), { urls: cards, base: backend.url })
|
||||
r.check('waiter: offline, both photos still show (from the phone\'s cache)', offline.every(n => n > 0), JSON.stringify(offline))
|
||||
await phone.setOffline(false)
|
||||
await phone.close()
|
||||
|
||||
r.check('no page errors', errors.length === 0, errors.join(' | '))
|
||||
failures += r.done()
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
failures += 1 + r.done()
|
||||
} finally {
|
||||
await browser.close()
|
||||
waiterVite.stop()
|
||||
killTree(managerVite)
|
||||
await backend.stop()
|
||||
}
|
||||
process.exit(failures ? 1 : 0)
|
||||
@@ -25,6 +25,7 @@ const suites = [
|
||||
['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E],
|
||||
['waiter (sign-in, keys, prices, languages, history, look, bookings)', 'node', ['waiter.mjs'], E2E],
|
||||
['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E],
|
||||
['media (Media page, product photos, waiter offline photos)', 'node', ['media.mjs'], E2E],
|
||||
['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E],
|
||||
['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E],
|
||||
['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { warmPhotos } from '../services/photoCache'
|
||||
import { createContext, useContext, useCallback, useEffect, useRef } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import useAuthStore from '../store/authStore'
|
||||
@@ -67,6 +68,7 @@ export function LiveProvider({ children }) {
|
||||
])
|
||||
await db.products.bulkPut(prodRes.data)
|
||||
await db.categories.bulkPut(catRes.data)
|
||||
warmPhotos(prodRes.data, catRes.data) // the menu's photos kept for offline (5.2)
|
||||
// Also update React Query cache so AddItemsPage gets it immediately
|
||||
queryClient.setQueryData(['products'], { products: prodRes.data, categories: catRes.data })
|
||||
} catch { /* offline — snapshot stays as-is */ }
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useState } from 'react'
|
||||
import client from '../api/client'
|
||||
import db from '../db/posdb'
|
||||
import { warmPhotos } from '../services/photoCache'
|
||||
|
||||
export const PRODUCTS_KEY = ['products']
|
||||
|
||||
@@ -15,6 +16,7 @@ async function fetchAndCacheProducts() {
|
||||
|
||||
db.products.bulkPut(products).catch(() => {})
|
||||
db.categories.bulkPut(categories).catch(() => {})
|
||||
warmPhotos(products, categories) // kept for offline (5.2)
|
||||
|
||||
return { products, categories }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// The menu's photos kept for offline (plan step 5.2). Photos come from the media library at
|
||||
// /api/media/file/<hash>/card: an address that never changes meaning, served with a year-long
|
||||
// `immutable` cache header. So once a photo is downloaded the phone keeps it (the browser's
|
||||
// cache; in the installed PWA also the service worker's `xenia-media` cache) and shows it
|
||||
// without a connection. warmPhotos() downloads the menu's photos ahead, a few at a time, right
|
||||
// after the menu is read, so a product never shown before still has its photo offline.
|
||||
import { assetUrl } from '../config/server'
|
||||
|
||||
const warmed = new Set()
|
||||
const AT_ONCE = 4
|
||||
|
||||
function load(url) {
|
||||
return new Promise(resolve => {
|
||||
const img = new Image()
|
||||
img.onload = img.onerror = () => resolve()
|
||||
img.decoding = 'async'
|
||||
img.src = url
|
||||
})
|
||||
}
|
||||
|
||||
/** Download the photos of these products (and categories) that this app run hasn't fetched yet. */
|
||||
export async function warmPhotos(...lists) {
|
||||
if (typeof Image === 'undefined' || (typeof navigator !== 'undefined' && navigator.onLine === false)) return
|
||||
const urls = [...new Set(lists.flat().map(x => x?.image_url || x?.image?.card).filter(Boolean).map(u => assetUrl(u)))]
|
||||
.filter(u => !warmed.has(u))
|
||||
urls.forEach(u => warmed.add(u))
|
||||
const queue = [...urls]
|
||||
const worker = async () => { while (queue.length) await load(queue.shift()) }
|
||||
await Promise.all(Array.from({ length: Math.min(AT_ONCE, queue.length) }, worker))
|
||||
}
|
||||
@@ -64,7 +64,17 @@ export default defineConfig(({ mode }) => {
|
||||
},
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
|
||||
runtimeCaching: [],
|
||||
// The media library's files (plan step 5.2): an address never changes meaning
|
||||
// (/api/media/file/<hash>/<size>), so the cached copy is always right: cache first.
|
||||
runtimeCaching: [{
|
||||
urlPattern: ({ url }) => url.pathname.startsWith('/api/media/file/'),
|
||||
handler: 'CacheFirst',
|
||||
options: {
|
||||
cacheName: 'xenia-media',
|
||||
expiration: { maxEntries: 800, maxAgeSeconds: 365 * 24 * 3600 },
|
||||
cacheableResponse: { statuses: [0, 200] },
|
||||
},
|
||||
}],
|
||||
},
|
||||
devOptions: {
|
||||
enabled: false,
|
||||
|
||||
Reference in New Issue
Block a user