feat(signage): gallery widget (pictures and videos one after another, from a list or a media folder); media folders on the Media page
Folders are only a grouping in the database (media_folders, media.folder_id, Alembic 0046): made, renamed, deleted (files stay) on the Media page, a file filed from its details, uploads go into the folder shown, the picker filters by folder. The gallery widget: its own pictures/videos in order or a folder as it is now, seconds each, fade / slide / zoom, cover / contain. Plan 6R.16, F-114. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
File diff suppressed because one or more lines are too long
@@ -126,6 +126,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"menu_tablet.order_not_found": (404, "This order was not found."),
|
"menu_tablet.order_not_found": (404, "This order was not found."),
|
||||||
"menu_tablet.order_answered": (409, "This order was already answered."),
|
"menu_tablet.order_answered": (409, "This order was already answered."),
|
||||||
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
||||||
|
"media.folder_unknown": (404, "That folder isn't in the media library any more."),
|
||||||
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
"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.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."),
|
"reservation.table_unknown": (404, "Table {table_id} not found."),
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Media folders (6R.16, owner 2026-11-22): the Media page groups files in folders. Only a grouping in
|
||||||
|
the database (media.folder_id); the files stay where they are on disk. A gallery widget can show a folder.
|
||||||
|
|
||||||
|
Revision ID: 0046_media_folders
|
||||||
|
Revises: 0045_signage_shapes
|
||||||
|
Create Date: 2026-11-22 16:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0046_media_folders'
|
||||||
|
down_revision = '0045_signage_shapes'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'media_folders',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_media_folders_id', 'media_folders', ['id'])
|
||||||
|
with op.batch_alter_table('media') as b:
|
||||||
|
b.add_column(sa.Column('folder_id', sa.Integer(), nullable=True))
|
||||||
|
b.create_index('ix_media_folder_id', ['folder_id'])
|
||||||
|
b.create_foreign_key('fk_media_folder', 'media_folders', ['folder_id'], ['id'], ondelete='SET NULL')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('media') as b:
|
||||||
|
b.drop_constraint('fk_media_folder', type_='foreignkey')
|
||||||
|
b.drop_index('ix_media_folder_id')
|
||||||
|
b.drop_column('folder_id')
|
||||||
|
op.drop_index('ix_media_folders_id', 'media_folders')
|
||||||
|
op.drop_table('media_folders')
|
||||||
@@ -39,9 +39,21 @@ class Media(Base):
|
|||||||
# or no video tool on this server). `progress` 0-100 while working.
|
# or no video tool on this server). `progress` 0-100 while working.
|
||||||
processing = Column(String, nullable=True)
|
processing = Column(String, nullable=True)
|
||||||
progress = Column(Integer, nullable=True)
|
progress = Column(Integer, nullable=True)
|
||||||
|
# its folder on the Media page (6R.16): only a grouping, the file stays where it is
|
||||||
|
folder_id = Column(Integer, ForeignKey("media_folders.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
|
||||||
uploader = relationship("User", lazy="joined")
|
uploader = relationship("User", lazy="joined")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def uploaded_by_name(self):
|
def uploaded_by_name(self):
|
||||||
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None
|
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
class MediaFolder(Base):
|
||||||
|
"""A folder of the media library (6R.16): a name and a place in the list; its files point at it."""
|
||||||
|
__tablename__ = "media_folders"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
position = Column(Integer, nullable=False, default=0, server_default='0')
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ def identity_out(db) -> dict:
|
|||||||
|
|
||||||
def _uses(db, media_id: int) -> list:
|
def _uses(db, media_id: int) -> list:
|
||||||
logos = stored(db).logos
|
logos = stored(db).logos
|
||||||
return [{"id": 0, "name": f"identity.{k}"} for k in LOGOS if getattr(logos, k) == media_id]
|
return [{"id": 0, "name": k} for k in LOGOS if getattr(logos, k) == media_id]
|
||||||
|
|
||||||
|
|
||||||
def _register():
|
def _register():
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ from core.access.deps import public, require_any
|
|||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from models.media import Media
|
from models.media import Media, MediaFolder
|
||||||
from services import media as store
|
from services import media as store
|
||||||
from services import video
|
from services import video
|
||||||
|
|
||||||
@@ -57,6 +57,7 @@ class MediaOut(BaseModel):
|
|||||||
builtin: bool = False
|
builtin: bool = False
|
||||||
processing: Optional[str] = None # videos: waiting | working | done | failed (5.4e)
|
processing: Optional[str] = None # videos: waiting | working | done | failed (5.4e)
|
||||||
progress: Optional[int] = None
|
progress: Optional[int] = None
|
||||||
|
folder_id: Optional[int] = None # 6R.16
|
||||||
urls: dict = Field(default_factory=dict)
|
urls: dict = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
@@ -75,17 +76,53 @@ class MediaPage(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class RenameBody(BaseModel):
|
class RenameBody(BaseModel):
|
||||||
name: str = Field(min_length=1, max_length=120)
|
name: Optional[str] = Field(default=None, min_length=1, max_length=120)
|
||||||
|
folder_id: Optional[int] = None # 6R.16: its folder (None: none)
|
||||||
|
|
||||||
@field_validator("name")
|
@field_validator("name")
|
||||||
@classmethod
|
@classmethod
|
||||||
def _strip(cls, v):
|
def _strip(cls, v):
|
||||||
|
if v is None:
|
||||||
|
return v
|
||||||
v = v.strip()
|
v = v.strip()
|
||||||
if not v:
|
if not v:
|
||||||
raise ValueError("empty")
|
raise ValueError("empty")
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class FolderBody(BaseModel):
|
||||||
|
name: str = Field(min_length=1, max_length=60)
|
||||||
|
|
||||||
|
@field_validator("name")
|
||||||
|
@classmethod
|
||||||
|
def _strip(cls, v):
|
||||||
|
v = " ".join(v.split())
|
||||||
|
if not v:
|
||||||
|
raise ValueError("empty")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class MoveBody(BaseModel):
|
||||||
|
ids: List[int] = Field(min_length=1, max_length=500)
|
||||||
|
folder_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
def _folder(db: Session, folder_id: Optional[int]) -> Optional[MediaFolder]:
|
||||||
|
if folder_id is None:
|
||||||
|
return None
|
||||||
|
f = db.get(MediaFolder, folder_id)
|
||||||
|
if f is None:
|
||||||
|
raise XeniaError("media.folder_unknown", folder_id=folder_id)
|
||||||
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
def _folders_out(db: Session) -> list:
|
||||||
|
from sqlalchemy import func
|
||||||
|
counts = dict(db.query(Media.folder_id, func.count(Media.id)).group_by(Media.folder_id).all())
|
||||||
|
rows = db.query(MediaFolder).order_by(MediaFolder.position, MediaFolder.name).all()
|
||||||
|
return [{"id": f.id, "name": f.name, "count": counts.get(f.id, 0)} for f in rows]
|
||||||
|
|
||||||
|
|
||||||
def _out(item: Media, cls=MediaOut, **extra):
|
def _out(item: Media, cls=MediaOut, **extra):
|
||||||
return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra})
|
return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra})
|
||||||
|
|
||||||
@@ -105,9 +142,14 @@ def _name_from(filename: str | None) -> str:
|
|||||||
|
|
||||||
@router.get("", response_model=MediaPage)
|
@router.get("", response_model=MediaPage)
|
||||||
def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None,
|
def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None,
|
||||||
collection: Optional[Literal["builtin", "own"]] = None, limit: int = 100, offset: int = 0,
|
collection: Optional[Literal["builtin", "own"]] = None, folder: Optional[str] = None, limit: int = 100, offset: int = 0,
|
||||||
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
|
"""`folder`: a folder's id, or "none" for the files in no folder (6R.16)."""
|
||||||
query = db.query(Media)
|
query = db.query(Media)
|
||||||
|
if folder == "none":
|
||||||
|
query = query.filter(Media.folder_id.is_(None))
|
||||||
|
elif folder and folder.isdigit():
|
||||||
|
query = query.filter(Media.folder_id == int(folder))
|
||||||
if kind:
|
if kind:
|
||||||
query = query.filter(Media.kind == kind)
|
query = query.filter(Media.kind == kind)
|
||||||
if q and q.strip():
|
if q and q.strip():
|
||||||
@@ -122,11 +164,13 @@ def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str
|
|||||||
|
|
||||||
@router.post("", response_model=UploadOut, status_code=201)
|
@router.post("", response_model=UploadOut, status_code=201)
|
||||||
def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None),
|
def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None),
|
||||||
|
folder_id: Optional[int] = Form(None),
|
||||||
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
# The type comes from the bytes; the browser's content type only picks the size limit.
|
# The type comes from the bytes; the browser's content type only picks the size limit.
|
||||||
declared = (file.content_type or "").lower()
|
declared = (file.content_type or "").lower()
|
||||||
limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES
|
limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES
|
||||||
tmp, sha, size = store.receive(file.file, limit)
|
tmp, sha, size = store.receive(file.file, limit)
|
||||||
|
folder = _folder(db, folder_id)
|
||||||
existing = db.query(Media).filter(Media.sha256 == sha).first()
|
existing = db.query(Media).filter(Media.sha256 == sha).first()
|
||||||
if existing is not None:
|
if existing is not None:
|
||||||
store._remove(tmp)
|
store._remove(tmp)
|
||||||
@@ -134,7 +178,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
|
|||||||
return _out(existing, UploadOut, existing=True)
|
return _out(existing, UploadOut, existing=True)
|
||||||
info = store.ingest(tmp, sha, size)
|
info = store.ingest(tmp, sha, size)
|
||||||
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename),
|
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)
|
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id,
|
||||||
|
folder_id=folder.id if folder else None, **info)
|
||||||
if item.kind == "video":
|
if item.kind == "video":
|
||||||
video.queued(item) # its still frame and playable version, in the background
|
video.queued(item) # its still frame and playable version, in the background
|
||||||
try:
|
try:
|
||||||
@@ -195,6 +240,50 @@ def _ranged(path: str, ctype: str, rng: str, headers: dict):
|
|||||||
**headers, "Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end - start + 1)})
|
**headers, "Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end - start + 1)})
|
||||||
|
|
||||||
|
|
||||||
|
# ── folders (6R.16): only a grouping; files keep their place on disk ─────────────
|
||||||
|
|
||||||
|
@router.get("/folders")
|
||||||
|
def list_folders(db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
|
return {"folders": _folders_out(db), "none": db.query(Media).filter(Media.folder_id.is_(None)).count()}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/folders", status_code=201)
|
||||||
|
def create_folder(body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
|
last = db.query(MediaFolder).count()
|
||||||
|
f = MediaFolder(name=body.name, position=last)
|
||||||
|
db.add(f)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(f)
|
||||||
|
return {"id": f.id, "name": f.name, "count": 0}
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/folders/{folder_id}")
|
||||||
|
def rename_folder(folder_id: int, body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
|
f = _folder(db, folder_id)
|
||||||
|
f.name = body.name
|
||||||
|
db.commit()
|
||||||
|
return next(x for x in _folders_out(db) if x["id"] == f.id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/folders/{folder_id}", status_code=204)
|
||||||
|
def delete_folder(folder_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
|
"""The folder goes; its files stay in the library, in no folder."""
|
||||||
|
f = _folder(db, folder_id)
|
||||||
|
db.query(Media).filter(Media.folder_id == f.id).update({Media.folder_id: None})
|
||||||
|
db.delete(f)
|
||||||
|
db.commit()
|
||||||
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/move")
|
||||||
|
def move_media(body: MoveBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
|
"""Several files into a folder (or out of any: folder_id null)."""
|
||||||
|
folder = _folder(db, body.folder_id)
|
||||||
|
n = db.query(Media).filter(Media.id.in_(body.ids)).update({Media.folder_id: folder.id if folder else None}, synchronize_session=False)
|
||||||
|
db.commit()
|
||||||
|
return {"moved": n}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{media_id}", response_model=MediaDetail)
|
@router.get("/{media_id}", response_model=MediaDetail)
|
||||||
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
item = _get(db, media_id)
|
item = _get(db, media_id)
|
||||||
@@ -204,9 +293,12 @@ def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require
|
|||||||
@router.patch("/{media_id}", response_model=MediaOut)
|
@router.patch("/{media_id}", response_model=MediaOut)
|
||||||
def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||||
item = _get(db, media_id)
|
item = _get(db, media_id)
|
||||||
if item.builtin:
|
if "name" in body.model_fields_set and body.name is not None:
|
||||||
raise XeniaError("media.builtin")
|
if item.builtin:
|
||||||
item.name = body.name
|
raise XeniaError("media.builtin")
|
||||||
|
item.name = body.name
|
||||||
|
if "folder_id" in body.model_fields_set:
|
||||||
|
item.folder_id = _folder(db, body.folder_id).id if body.folder_id is not None else None # built-in pictures may be filed too
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(item)
|
db.refresh(item)
|
||||||
return _out(item)
|
return _out(item)
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ class Background(_Strict):
|
|||||||
|
|
||||||
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack",
|
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack",
|
||||||
"shape", "ticker", "countdown", "hours", "wifi", "contact", # 6R.15
|
"shape", "ticker", "countdown", "hours", "wifi", "contact", # 6R.15
|
||||||
"reviews"] # 6R.19
|
"reviews", "gallery"] # 6R.19, 6R.16
|
||||||
WHEN = r"^(\d{4}-\d{2}-\d{2}T)?([01]\d|2[0-3]):[0-5]\d$" # a countdown's moment: "HH:MM" (every day) or "YYYY-MM-DDTHH:MM"
|
WHEN = r"^(\d{4}-\d{2}-\d{2}T)?([01]\d|2[0-3]):[0-5]\d$" # a countdown's moment: "HH:MM" (every day) or "YYYY-MM-DDTHH:MM"
|
||||||
ContactKey = Literal["phone", "phone2", "email", "address", "website", "google", "facebook", "instagram", "tiktok", "tripadvisor", "whatsapp", "viber"]
|
ContactKey = Literal["phone", "phone2", "email", "address", "website", "google", "facebook", "instagram", "tiktok", "tripadvisor", "whatsapp", "viber"]
|
||||||
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
|
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
|
||||||
@@ -316,6 +316,13 @@ class Widget(_Strict):
|
|||||||
reviews_min: int = Field(default=4, ge=1, le=5) # only reviews with at least these stars
|
reviews_min: int = Field(default=4, ge=1, le=5) # only reviews with at least these stars
|
||||||
reviews_stars: bool = True
|
reviews_stars: bool = True
|
||||||
reviews_name: bool = True
|
reviews_name: bool = True
|
||||||
|
# a gallery (6R.16): pictures and videos one after another, from its own list or a media folder
|
||||||
|
gallery_source: Literal["pictures", "folder"] = "pictures"
|
||||||
|
media_ids: List[int] = Field(default_factory=list, max_length=100)
|
||||||
|
gallery_folder: Optional[int] = None
|
||||||
|
gallery_seconds: int = Field(default=5, ge=3, le=120)
|
||||||
|
gallery_transition: Literal["fade", "slide", "zoom", "none"] = "fade"
|
||||||
|
gallery_fit: Literal["cover", "contain"] = "cover"
|
||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
def _place(self):
|
def _place(self):
|
||||||
@@ -661,6 +668,10 @@ def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0):
|
|||||||
out[path] = {"link": _qr_link(w)}
|
out[path] = {"link": _qr_link(w)}
|
||||||
elif w.get("kind") == "menu":
|
elif w.get("kind") == "menu":
|
||||||
out[path] = {"menu": resolve(db, w.get("board") or {}, keep_hidden=keep_hidden)}
|
out[path] = {"menu": resolve(db, w.get("board") or {}, keep_hidden=keep_hidden)}
|
||||||
|
elif w.get("kind") == "gallery" and w.get("gallery_source") == "folder":
|
||||||
|
ids = gallery_folder_ids(db, w.get("gallery_folder")) # 6R.16: the folder as it is now
|
||||||
|
out[path] = {"gallery": ids}
|
||||||
|
mids += ids
|
||||||
elif depth == 0:
|
elif depth == 0:
|
||||||
s = db.get(SignageSavedSlide, sid)
|
s = db.get(SignageSavedSlide, sid)
|
||||||
if s is None:
|
if s is None:
|
||||||
@@ -675,6 +686,14 @@ def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0):
|
|||||||
return out, mids
|
return out, mids
|
||||||
|
|
||||||
|
|
||||||
|
def gallery_folder_ids(db, folder_id) -> list[int]:
|
||||||
|
"""A media folder's files for a gallery (6R.16), newest last as uploaded; none for a folder that's gone."""
|
||||||
|
from models.media import Media
|
||||||
|
if not folder_id:
|
||||||
|
return []
|
||||||
|
return [m.id for m in db.query(Media).filter(Media.folder_id == folder_id).order_by(Media.created_at, Media.id).limit(200)]
|
||||||
|
|
||||||
|
|
||||||
def _content(db, kind: str, raw: dict | None) -> dict:
|
def _content(db, kind: str, raw: dict | None) -> dict:
|
||||||
"""The content as stored: typed for its kind, every media id an existing file of the right kind."""
|
"""The content as stored: typed for its kind, every media id an existing file of the right kind."""
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Media folders (6R.16): made, renamed, deleted (files stay), files moved and uploaded into one,
|
||||||
|
the list filtered; a gallery widget showing a folder gets its files (and the screen their addresses)."""
|
||||||
|
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||||
|
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
|
||||||
|
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
|
||||||
|
|
||||||
|
|
||||||
|
def test_folders(client, owner_h, media_dir):
|
||||||
|
f = client.post("/api/media/folders", headers=owner_h, json={"name": " Summer menu "}).json()
|
||||||
|
assert f["name"] == "Summer menu" and f["count"] == 0
|
||||||
|
a = up(client, owner_h, jpeg(300, 200)).json()
|
||||||
|
b = up(client, owner_h, jpeg(300, 200, (9, 9, 9))).json()
|
||||||
|
assert client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"], b["id"]], "folder_id": f["id"]}).json()["moved"] == 2
|
||||||
|
got = client.get("/api/media/folders", headers=owner_h).json()
|
||||||
|
assert got["folders"] == [{"id": f["id"], "name": "Summer menu", "count": 2}]
|
||||||
|
listed = client.get(f"/api/media?folder={f['id']}", headers=owner_h).json()
|
||||||
|
assert {i["id"] for i in listed["items"]} == {a["id"], b["id"]} and listed["items"][0]["folder_id"] == f["id"]
|
||||||
|
assert all(i["folder_id"] is None for i in client.get("/api/media?folder=none", headers=owner_h).json()["items"])
|
||||||
|
r = client.patch(f"/api/media/{a['id']}", headers=owner_h, json={"folder_id": None})
|
||||||
|
assert r.status_code == 200 and r.json()["folder_id"] is None and r.json()["name"] == a["name"]
|
||||||
|
assert client.patch(f"/api/media/folders/{f['id']}", headers=owner_h, json={"name": "Winter"}).json()["name"] == "Winter"
|
||||||
|
# an upload straight into a folder
|
||||||
|
c = client.post("/api/media", headers=owner_h, files={"file": ("x.jpg", jpeg(100, 100, (1, 2, 3)), "image/jpeg")}, data={"folder_id": str(f["id"])}).json()
|
||||||
|
assert c["folder_id"] == f["id"]
|
||||||
|
assert err(client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"]], "folder_id": 9999})) == "media.folder_unknown"
|
||||||
|
assert client.delete(f"/api/media/folders/{f['id']}", headers=owner_h).status_code == 204
|
||||||
|
assert client.get(f"/api/media/{b['id']}", headers=owner_h).json()["folder_id"] is None # the file stays
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_gallery_of_a_folder(client, owner_h, screens, media_dir):
|
||||||
|
f = client.post("/api/media/folders", headers=owner_h, json={"name": "Dishes"}).json()
|
||||||
|
pics = [up(client, owner_h, jpeg(400, 300, (i * 40, 10, 10))).json() for i in range(3)]
|
||||||
|
client.post("/api/media/move", headers=owner_h, json={"ids": [p["id"] for p in pics], "folder_id": f["id"]})
|
||||||
|
p = playlist(client, owner_h)
|
||||||
|
slide(client, owner_h, p["id"], "blank", content={"widgets": [
|
||||||
|
{"kind": "gallery", "position": "custom", "box": {"x": 0, "y": 0, "w": 50, "h": 50}, "gallery_source": "folder", "gallery_folder": f["id"], "gallery_seconds": 4},
|
||||||
|
{"kind": "gallery", "position": "top-left", "media_ids": [pics[0]["id"]], "gallery_transition": "slide"}]})
|
||||||
|
client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||||
|
pl = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["playlist"]
|
||||||
|
s = pl["slides"][0]
|
||||||
|
assert s["extras"]["0"]["gallery"] == [x["id"] for x in pics]
|
||||||
|
assert all(str(x["id"]) in pl["media"] for x in pics)
|
||||||
|
# the pictures in a gallery's own list are protected
|
||||||
|
assert err(client.delete(f"/api/media/{pics[0]['id']}", headers=owner_h)) == "media.in_use"
|
||||||
@@ -6,11 +6,11 @@ import toast from 'react-hot-toast'
|
|||||||
import { Trash2 } from 'lucide-react'
|
import { Trash2 } from 'lucide-react'
|
||||||
import { errorMessage } from '@xenia/api'
|
import { errorMessage } from '@xenia/api'
|
||||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||||
import { Button, Dialog, Field, Input, Spinner, cx } from '@xenia/ui'
|
import { Button, Dialog, Dropdown, Field, Input, Spinner, cx } from '@xenia/ui'
|
||||||
import { deleteMedia, getMedia, renameMedia } from './mediaApi'
|
import { deleteMedia, getMedia, renameMedia, setFolder } from './mediaApi'
|
||||||
import { duration, fileSize, preparing, resolution, VARIANT_ORDER, videoState } from './mediaLogic'
|
import { duration, fileSize, preparing, resolution, VARIANT_ORDER, videoState } from './mediaLogic'
|
||||||
|
|
||||||
export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
export default function MediaDetails({ id, onClose, onChanged, onDeleted, folders = [] }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
const { formatDateTime, formatNumber } = useFormat()
|
const { formatDateTime, formatNumber } = useFormat()
|
||||||
const [item, setItem] = useState(null)
|
const [item, setItem] = useState(null)
|
||||||
@@ -43,6 +43,10 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
|||||||
catch (err) { toast.error(errorMessage(err, t)) }
|
catch (err) { toast.error(errorMessage(err, t)) }
|
||||||
setBusy(false)
|
setBusy(false)
|
||||||
}
|
}
|
||||||
|
const fileIn = async folderId => {
|
||||||
|
try { const m = await setFolder(id, folderId); setItem(it => ({ ...it, ...m })); onChanged?.(m); toast.success(t('media.folders.moved')) }
|
||||||
|
catch (err) { toast.error(errorMessage(err, t)) }
|
||||||
|
}
|
||||||
const remove = async () => {
|
const remove = async () => {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
try { await deleteMedia(id); toast.success(t('media.deleted')); onDeleted?.(id); onClose() }
|
try { await deleteMedia(id); toast.success(t('media.deleted')); onDeleted?.(id); onClose() }
|
||||||
@@ -93,6 +97,11 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
|||||||
<p className="text-caption text-ink-3">{t(item.builtin ? 'media.builtinHint' : 'media.displayNameHint')}</p>
|
<p className="text-caption text-ink-3">{t(item.builtin ? 'media.builtinHint' : 'media.displayNameHint')}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Field label={t('media.folders.folder')} className="max-w-sm">
|
||||||
|
<Dropdown value={item.folder_id ?? ''} onChange={v => fileIn(v === '' ? null : Number(v))} data-testid="media-folder-pick"
|
||||||
|
options={[{ value: '', label: t('media.folders.none') }, ...folders.map(f => ({ value: f.id, label: f.name }))]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
<dl className="grid gap-x-4 gap-y-1 text-label" style={{ gridTemplateColumns: 'max-content 1fr' }}>
|
<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>)}
|
{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>
|
</dl>
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
// The media library's folders (6R.16, owner 2026-11-22): only a grouping in the database, the files
|
||||||
|
// stay where they are. The bar picks what the page shows (everything, the files in no folder, a
|
||||||
|
// folder) and where uploads go; a folder is made, renamed or deleted here (its files stay, in no folder).
|
||||||
|
import { useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import { FolderPlus, Pencil, Trash2 } from 'lucide-react'
|
||||||
|
import { errorMessage } from '@xenia/api'
|
||||||
|
import { useTranslation } from '@xenia/i18n'
|
||||||
|
import { Button, Dialog, Field, FilterChip, IconButton, Input, useConfirm } from '@xenia/ui'
|
||||||
|
import { createFolder, deleteFolder, renameFolder } from './mediaApi'
|
||||||
|
|
||||||
|
/** value: '' (all) | 'none' | a folder id as a string. */
|
||||||
|
export default function MediaFolders({ folders, none, total, value, onChange, onChanged }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [naming, setNaming] = useState(null) // { id?, name }
|
||||||
|
const [confirm, confirmDialog] = useConfirm()
|
||||||
|
const current = folders?.find(f => String(f.id) === value)
|
||||||
|
const save = async () => {
|
||||||
|
try {
|
||||||
|
const f = naming.id ? await renameFolder(naming.id, naming.name.trim()) : await createFolder(naming.name.trim())
|
||||||
|
setNaming(null)
|
||||||
|
await onChanged?.()
|
||||||
|
onChange(String(f.id))
|
||||||
|
} catch (err) { toast.error(errorMessage(err, t)) }
|
||||||
|
}
|
||||||
|
const remove = async () => {
|
||||||
|
if (!await confirm({ title: t('media.folders.deleteTitle', { name: current.name }), body: t('media.folders.deleteBody'), confirmLabel: t('media.delete'), tone: 'danger', testId: 'media-folder-delete-confirm' })) return
|
||||||
|
try { await deleteFolder(current.id); onChange(''); await onChanged?.() } catch (err) { toast.error(errorMessage(err, t)) }
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5" data-testid="media-folders" role="toolbar" aria-label={t('media.folders.title')}>
|
||||||
|
<FilterChip pressed={value === ''} count={total} onClick={() => onChange('')} data-testid="media-folder-all">{t('media.folders.all')}</FilterChip>
|
||||||
|
<FilterChip pressed={value === 'none'} count={none} onClick={() => onChange('none')} data-testid="media-folder-none">{t('media.folders.none')}</FilterChip>
|
||||||
|
{(folders || []).map(f => (
|
||||||
|
<FilterChip key={f.id} pressed={value === String(f.id)} count={f.count} onClick={() => onChange(String(f.id))} data-testid="media-folder" data-name={f.name}>{f.name}</FilterChip>
|
||||||
|
))}
|
||||||
|
<Button size="sm" variant="ghost" icon={<FolderPlus size={15} />} onClick={() => setNaming({ name: '' })} data-testid="media-folder-new">{t('media.folders.new')}</Button>
|
||||||
|
{current && <>
|
||||||
|
<IconButton size="sm" label={t('media.folders.rename')} onClick={() => setNaming({ id: current.id, name: current.name })} data-testid="media-folder-rename"><Pencil size={15} /></IconButton>
|
||||||
|
<IconButton size="sm" tone="danger" label={t('media.folders.delete')} onClick={remove} data-testid="media-folder-delete"><Trash2 size={15} /></IconButton>
|
||||||
|
</>}
|
||||||
|
{naming && (
|
||||||
|
<Dialog open size="sm" title={t(naming.id ? 'media.folders.rename' : 'media.folders.new')} onClose={() => setNaming(null)}
|
||||||
|
footer={<>
|
||||||
|
<Button variant="secondary" onClick={() => setNaming(null)}>{t('fees.cancel')}</Button>
|
||||||
|
<Button disabled={!naming.name.trim()} onClick={save} data-testid="media-folder-save">{t('fees.save')}</Button>
|
||||||
|
</>}>
|
||||||
|
<Field label={t('media.folders.name')}>
|
||||||
|
<Input value={naming.name} autoFocus maxLength={60} onChange={e => setNaming(n => ({ ...n, name: e.target.value }))}
|
||||||
|
onKeyDown={e => { if (e.key === 'Enter' && naming.name.trim()) save() }} data-testid="media-folder-name" />
|
||||||
|
</Field>
|
||||||
|
</Dialog>
|
||||||
|
)}
|
||||||
|
{confirmDialog}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -2,13 +2,15 @@
|
|||||||
// library. Batch upload (pick many files or drop them on the page) to use later anywhere that
|
// 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
|
// 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.
|
// and stores the files; here people see a display name, the details and the sizes made.
|
||||||
// Backend: /api/media (routers/media.py).
|
// Folders (6R.16): the bar under the toolbar picks a folder (uploads go into it); a file's folder is
|
||||||
|
// changed in its details. Backend: /api/media (routers/media.py).
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { Upload } from 'lucide-react'
|
import { Upload } from 'lucide-react'
|
||||||
import { errorMessage } from '@xenia/api'
|
import { errorMessage } from '@xenia/api'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
import { useTranslation } from '@xenia/i18n'
|
||||||
import { Button, EmptyState, Input, Page, Select, Spinner, cx } from '@xenia/ui'
|
import { Button, EmptyState, Input, Page, Select, Spinner, cx } from '@xenia/ui'
|
||||||
import { listMedia } from './mediaApi'
|
import { listFolders, listMedia } from './mediaApi'
|
||||||
|
import MediaFolders from './MediaFolders'
|
||||||
import { ACCEPT, preparing } from './mediaLogic'
|
import { ACCEPT, preparing } from './mediaLogic'
|
||||||
import MediaDetails from './MediaDetails'
|
import MediaDetails from './MediaDetails'
|
||||||
import { MediaGrid, UploadQueue } from './MediaParts'
|
import { MediaGrid, UploadQueue } from './MediaParts'
|
||||||
@@ -24,13 +26,17 @@ export default function MediaPage() {
|
|||||||
const [error, setError] = useState(null)
|
const [error, setError] = useState(null)
|
||||||
const [open, setOpen] = useState(null)
|
const [open, setOpen] = useState(null)
|
||||||
const [dragging, setDragging] = useState(false)
|
const [dragging, setDragging] = useState(false)
|
||||||
|
const [folder, setFolder] = useState('') // '' all | 'none' | a folder id
|
||||||
|
const [folders, setFolders] = useState(null) // { folders, none }
|
||||||
|
const loadFolders = useCallback(async () => { try { setFolders(await listFolders()) } catch { /* the bar waits */ } }, [])
|
||||||
|
useEffect(() => { loadFolders() }, [loadFolders])
|
||||||
const input = useRef(null)
|
const input = useRef(null)
|
||||||
|
|
||||||
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
|
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
try { setPage(await listMedia({ kind, q: search, collection })); setError(null) } catch (err) { setError(errorMessage(err, t)) }
|
try { setPage(await listMedia({ kind, q: search, collection, folder })); setError(null) } catch (err) { setError(errorMessage(err, t)) }
|
||||||
}, [kind, search, collection, t])
|
}, [kind, search, collection, folder, t])
|
||||||
useEffect(() => { load() }, [load])
|
useEffect(() => { load() }, [load])
|
||||||
// Videos are prepared for screens in the background (5.4e): read the list again while any is.
|
// Videos are prepared for screens in the background (5.4e): read the list again while any is.
|
||||||
const busy = preparing(page?.items)
|
const busy = preparing(page?.items)
|
||||||
@@ -45,16 +51,18 @@ export default function MediaPage() {
|
|||||||
setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p))
|
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)
|
const wasBusy = useRef(false)
|
||||||
useEffect(() => { if (wasBusy.current && !summary.busy) load(); wasBusy.current = summary.busy }, [summary.busy, load])
|
useEffect(() => { if (wasBusy.current && !summary.busy) { load(); loadFolders() } wasBusy.current = summary.busy }, [summary.busy, load, loadFolders])
|
||||||
|
|
||||||
const onDrop = e => {
|
const onDrop = e => {
|
||||||
e.preventDefault(); setDragging(false)
|
e.preventDefault(); setDragging(false)
|
||||||
if (e.dataTransfer.files?.length) add(e.dataTransfer.files)
|
if (e.dataTransfer.files?.length) add(e.dataTransfer.files, upTo)
|
||||||
}
|
}
|
||||||
const kinds = useMemo(() => [
|
const kinds = useMemo(() => [
|
||||||
{ value: '', label: t('media.kinds.all') }, { value: 'image', label: t('media.kinds.images') }, { value: 'video', label: t('media.kinds.videos') },
|
{ value: '', label: t('media.kinds.all') }, { value: 'image', label: t('media.kinds.images') }, { value: 'video', label: t('media.kinds.videos') },
|
||||||
], [t])
|
], [t])
|
||||||
const closeDetails = useCallback(() => setOpen(null), [])
|
const closeDetails = useCallback(() => setOpen(null), [])
|
||||||
|
const upTo = /^\d+$/.test(folder) ? Number(folder) : null // uploads go into the folder shown
|
||||||
|
const allCount = folders ? folders.none + folders.folders.reduce((n, f) => n + f.count, 0) : undefined
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Page className={cx(dragging && 'outline-2 outline-dashed outline-accent -outline-offset-8')}
|
<Page className={cx(dragging && 'outline-2 outline-dashed outline-accent -outline-offset-8')}
|
||||||
@@ -70,7 +78,7 @@ export default function MediaPage() {
|
|||||||
<div className="flex flex-wrap gap-2 items-center">
|
<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>
|
<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"
|
<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 = '' }} />
|
onChange={e => { if (e.target.files?.length) add(e.target.files, upTo); e.target.value = '' }} />
|
||||||
<span className="text-label text-ink-3 hidden md:inline">{t('media.dropHint')}</span>
|
<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">
|
<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')}
|
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')}
|
||||||
@@ -81,6 +89,8 @@ export default function MediaPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<MediaFolders folders={folders?.folders} none={folders?.none} total={allCount} value={folder} onChange={setFolder} onChanged={loadFolders} />
|
||||||
|
|
||||||
<UploadQueue queue={queue} summary={summary} onClear={clear} />
|
<UploadQueue queue={queue} summary={summary} onClear={clear} />
|
||||||
|
|
||||||
{error ? <EmptyState title={error} />
|
{error ? <EmptyState title={error} />
|
||||||
@@ -92,8 +102,8 @@ export default function MediaPage() {
|
|||||||
{page.total > page.items.length && <p className="text-label text-ink-3">{t('media.more', { shown: page.items.length, total: page.total })}</p>}
|
{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}
|
{open && <MediaDetails id={open} onClose={closeDetails} folders={folders?.folders || []}
|
||||||
onChanged={m => setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) })}
|
onChanged={m => { setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) }); loadFolders() }}
|
||||||
onDeleted={id => setPage(p => p && { ...p, items: p.items.filter(x => x.id !== id), total: p.total - 1 })} />}
|
onDeleted={id => setPage(p => p && { ...p, items: p.items.filter(x => x.id !== id), total: p.total - 1 })} />}
|
||||||
</Page>
|
</Page>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { Upload } from 'lucide-react'
|
|||||||
import { errorMessage } from '@xenia/api'
|
import { errorMessage } from '@xenia/api'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
import { useTranslation } from '@xenia/i18n'
|
||||||
import { Button, Dialog, EmptyState, Input, Select, Spinner } from '@xenia/ui'
|
import { Button, Dialog, EmptyState, Input, Select, Spinner } from '@xenia/ui'
|
||||||
import { listMedia } from './mediaApi'
|
import { listFolders, listMedia } from './mediaApi'
|
||||||
import { ACCEPT } from './mediaLogic'
|
import { ACCEPT } from './mediaLogic'
|
||||||
import { MediaGrid, UploadQueue } from './MediaParts'
|
import { MediaGrid, UploadQueue } from './MediaParts'
|
||||||
import { useUploadQueue } from './mediaHooks'
|
import { useUploadQueue } from './mediaHooks'
|
||||||
@@ -22,13 +22,16 @@ export default function MediaPicker({ open, onClose, onPick, onPickMany, multipl
|
|||||||
const [chosen, setChosen] = useState([]) // multiple: the items picked so far, in order
|
const [chosen, setChosen] = useState([]) // multiple: the items picked so far, in order
|
||||||
const toggle = item => setChosen(c => (c.some(x => x.id === item.id) ? c.filter(x => x.id !== item.id) : [...c, item]))
|
const toggle = item => setChosen(c => (c.some(x => x.id === item.id) ? c.filter(x => x.id !== item.id) : [...c, item]))
|
||||||
|
|
||||||
|
const [folder, setFolder] = useState('') // 6R.16: '' all | 'none' | a folder id
|
||||||
|
const [folders, setFolders] = useState([])
|
||||||
|
useEffect(() => { if (open) listFolders().then(r => setFolders(r.folders)).catch(() => {}) }, [open])
|
||||||
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
|
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return
|
if (!open) return
|
||||||
let live = true
|
let live = true
|
||||||
listMedia({ kind, q: search, collection }).then(p => { if (live) { setPage(p); setError(null) } }).catch(err => live && setError(errorMessage(err, t)))
|
listMedia({ kind, q: search, collection, folder }).then(p => { if (live) { setPage(p); setError(null) } }).catch(err => live && setError(errorMessage(err, t)))
|
||||||
return () => { live = false }
|
return () => { live = false }
|
||||||
}, [open, kind, search, collection, t])
|
}, [open, kind, search, collection, folder, t])
|
||||||
|
|
||||||
const { queue, add, clear, summary } = useUploadQueue(useCallback(item => {
|
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))
|
setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p))
|
||||||
@@ -49,9 +52,13 @@ export default function MediaPicker({ open, onClose, onPick, onPickMany, multipl
|
|||||||
className="flex-1 min-w-[10rem]" data-testid="media-picker-search" />
|
className="flex-1 min-w-[10rem]" data-testid="media-picker-search" />
|
||||||
<Select value={collection} onChange={e => setCollection(e.target.value)} aria-label={t('media.collection')} data-testid="media-picker-collection"
|
<Select value={collection} onChange={e => setCollection(e.target.value)} aria-label={t('media.collection')} data-testid="media-picker-collection"
|
||||||
options={[{ value: '', label: t('media.collections.all') }, { value: 'own', label: t('media.collections.own') }, { value: 'builtin', label: t('media.collections.builtin') }]} />
|
options={[{ value: '', label: t('media.collections.all') }, { value: 'own', label: t('media.collections.own') }, { value: 'builtin', label: t('media.collections.builtin') }]} />
|
||||||
|
{folders.length > 0 && (
|
||||||
|
<Select value={folder} onChange={e => setFolder(e.target.value)} aria-label={t('media.folders.folder')} data-testid="media-picker-folder"
|
||||||
|
options={[{ value: '', label: t('media.folders.all') }, { value: 'none', label: t('media.folders.none') }, ...folders.map(f => ({ value: String(f.id), label: f.name }))]} />
|
||||||
|
)}
|
||||||
<Button variant="secondary" icon={<Upload size={16} />} onClick={() => input.current?.click()} disabled={summary.busy}>{t('media.uploadNew')}</Button>
|
<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}
|
<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" multiple={multiple} onChange={e => { if (e.target.files?.length) add(multiple ? e.target.files : [e.target.files[0]]); e.target.value = '' }} />
|
className="sr-only" data-testid="media-picker-file" multiple={multiple} onChange={e => { if (e.target.files?.length) add(multiple ? e.target.files : [e.target.files[0]], /^\d+$/.test(folder) ? Number(folder) : null); e.target.value = '' }} />
|
||||||
</div>
|
</div>
|
||||||
<UploadQueue queue={queue} summary={summary} onClear={clear} />
|
<UploadQueue queue={queue} summary={summary} onClear={clear} />
|
||||||
{error ? <EmptyState title={error} />
|
{error ? <EmptyState title={error} />
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
// The media library's API (backend: local_backend/routers/media.py, plan steps 5.1 / 5.2).
|
// The media library's API (backend: local_backend/routers/media.py, plan steps 5.1 / 5.2).
|
||||||
import client from '../../api/client'
|
import client from '../../api/client'
|
||||||
|
|
||||||
export const listMedia = ({ kind, q, collection, limit = 500 } = {}) =>
|
export const listMedia = ({ kind, q, collection, folder, limit = 500 } = {}) =>
|
||||||
client.get('/api/media', { params: { kind: kind || undefined, q: q || undefined, collection: collection || undefined, limit } }).then(r => r.data)
|
client.get('/api/media', { params: { kind: kind || undefined, q: q || undefined, collection: collection || undefined, folder: folder || undefined, limit } }).then(r => r.data)
|
||||||
|
|
||||||
export const getMedia = id => client.get(`/api/media/${id}`).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). */
|
/** Upload one file → the library item (`existing: true` when the same file was already there). */
|
||||||
export function uploadMedia(file, { name, onProgress } = {}) {
|
export function uploadMedia(file, { name, folderId, onProgress } = {}) {
|
||||||
const fd = new FormData()
|
const fd = new FormData()
|
||||||
fd.append('file', file)
|
fd.append('file', file)
|
||||||
if (name) fd.append('name', name)
|
if (name) fd.append('name', name)
|
||||||
|
if (folderId) fd.append('folder_id', String(folderId))
|
||||||
return client.post('/api/media', fd, {
|
return client.post('/api/media', fd, {
|
||||||
onUploadProgress: e => { if (onProgress && e.total) onProgress(Math.round((e.loaded / e.total) * 100)) },
|
onUploadProgress: e => { if (onProgress && e.total) onProgress(Math.round((e.loaded / e.total) * 100)) },
|
||||||
}).then(r => r.data)
|
}).then(r => r.data)
|
||||||
@@ -19,3 +20,11 @@ export function uploadMedia(file, { name, onProgress } = {}) {
|
|||||||
export const renameMedia = (id, name) => client.patch(`/api/media/${id}`, { name }).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}`)
|
export const deleteMedia = id => client.delete(`/api/media/${id}`)
|
||||||
|
|
||||||
|
// folders (6R.16): only a grouping in the database; the files stay where they are
|
||||||
|
export const listFolders = () => client.get('/api/media/folders').then(r => r.data)
|
||||||
|
export const createFolder = name => client.post('/api/media/folders', { name }).then(r => r.data)
|
||||||
|
export const renameFolder = (id, name) => client.patch(`/api/media/folders/${id}`, { name }).then(r => r.data)
|
||||||
|
export const deleteFolder = id => client.delete(`/api/media/folders/${id}`)
|
||||||
|
export const moveMedia = (ids, folderId) => client.post('/api/media/move', { ids, folder_id: folderId ?? null }).then(r => r.data)
|
||||||
|
export const setFolder = (id, folderId) => client.patch(`/api/media/${id}`, { folder_id: folderId ?? null }).then(r => r.data)
|
||||||
|
|||||||
@@ -27,8 +27,8 @@ export function useUploadQueue(onDone) {
|
|||||||
useEffect(() => { done.current = onDone })
|
useEffect(() => { done.current = onDone })
|
||||||
const counter = useRef(0)
|
const counter = useRef(0)
|
||||||
|
|
||||||
const add = useCallback(files => {
|
const add = useCallback((files, folderId = null) => {
|
||||||
const list = queueFrom(files, counter.current)
|
const list = queueFrom(files, counter.current).map(x => ({ ...x, folderId }))
|
||||||
counter.current += list.length
|
counter.current += list.length
|
||||||
setQueue(q => [...q, ...list])
|
setQueue(q => [...q, ...list])
|
||||||
}, [])
|
}, [])
|
||||||
@@ -41,7 +41,7 @@ export function useUploadQueue(onDone) {
|
|||||||
running.current = true
|
running.current = true
|
||||||
const set = patch => setQueue(q => q.map(x => (x.key === next.key ? { ...x, ...patch } : x)))
|
const set = patch => setQueue(q => q.map(x => (x.key === next.key ? { ...x, ...patch } : x)))
|
||||||
set({ status: 'uploading' })
|
set({ status: 'uploading' })
|
||||||
uploadMedia(next.file, { onProgress: progress => set({ progress }) })
|
uploadMedia(next.file, { folderId: next.folderId, onProgress: progress => set({ progress }) })
|
||||||
.then(item => { set({ status: item.existing ? 'existing' : 'added', progress: 100, item }); done.current?.(item, !!item.existing) })
|
.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) }))
|
.catch(err => set({ status: 'failed', error: errorMessage(err, t) }))
|
||||||
.finally(() => { running.current = false; setQueue(q => [...q]) })
|
.finally(() => { running.current = false; setQueue(q => [...q]) })
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
// The settings of the widgets added in 6R.15 (owner 2026-11-22): a shape, a scrolling text, a
|
// The settings of the widgets added in 6R.15 (owner 2026-11-22): a shape, a scrolling text, a
|
||||||
// countdown, the opening hours, the guests' Wi-Fi and the contact details; the reviews (6R.19). The last three read the
|
// countdown, the opening hours, the guests' Wi-Fi and the contact details; the reviews (6R.19); a gallery (6R.16). The last three read the
|
||||||
// venue (Settings → Identity, the Schedule page's opening hours): when that is missing the card says
|
// venue (Settings → Identity, the Schedule page's opening hours): when that is missing the card says
|
||||||
// so with a link to where it is set. Used by WidgetsEditor (its row and the part under it).
|
// so with a link to where it is set. Used by WidgetsEditor (its row and the part under it).
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
|
import { ArrowLeft, ArrowRight, Film, Plus, X } from 'lucide-react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
import { useTranslation } from '@xenia/i18n'
|
||||||
import { ColourField, Dropdown, Field, Input, Notice, NumberInput, Segmented, Slider, Switch } from '@xenia/ui'
|
import { Button, ColourField, Dropdown, Field, IconButton, Input, Notice, NumberInput, Segmented, Slider, Switch } from '@xenia/ui'
|
||||||
|
import { listFolders } from '../media/mediaApi'
|
||||||
|
import MediaPicker from '../media/MediaPicker'
|
||||||
import { useHours, useIdentity } from '../../shell/useIdentity'
|
import { useHours, useIdentity } from '../../shell/useIdentity'
|
||||||
import * as api from './signageApi'
|
import * as api from './signageApi'
|
||||||
import { CONTACT_KEYS, WIDGET_COLOURS } from './signageLogic'
|
import { CONTACT_KEYS, moved, WIDGET_COLOURS } from './signageLogic'
|
||||||
|
|
||||||
const SHAPES = ['rectangle', 'circle', 'triangle', 'polygon', 'star', 'custom']
|
const SHAPES = ['rectangle', 'circle', 'triangle', 'polygon', 'star', 'custom']
|
||||||
const isDate = v => !!v && v.length > 5
|
const isDate = v => !!v && v.length > 5
|
||||||
@@ -79,6 +82,25 @@ export function MoreInlineFields({ w, set }) {
|
|||||||
</Field>
|
</Field>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
if (w.kind === 'gallery') {
|
||||||
|
return (<>
|
||||||
|
<Field label={t(`${k}.gallery.source`)}>
|
||||||
|
<Segmented fill value={w.gallery_source || 'pictures'} onChange={gallery_source => set({ gallery_source })} data-testid="signage-widget-gallery-source"
|
||||||
|
options={['pictures', 'folder'].map(v => ({ value: v, label: t(`${k}.gallery.sources.${v}`) }))} />
|
||||||
|
</Field>
|
||||||
|
<Field label={t(`${k}.gallery.seconds`)}>
|
||||||
|
<NumberInput value={w.gallery_seconds ?? 5} min={3} max={120} suffix="s" onChange={v => set({ gallery_seconds: v ?? 3 })} />
|
||||||
|
</Field>
|
||||||
|
<Field label={t('signage.transition')}>
|
||||||
|
<Dropdown value={w.gallery_transition || 'fade'} onChange={gallery_transition => set({ gallery_transition })}
|
||||||
|
options={['fade', 'slide', 'zoom', 'none'].map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))} />
|
||||||
|
</Field>
|
||||||
|
<Field label={t('signage.fit')}>
|
||||||
|
<Dropdown value={w.gallery_fit || 'cover'} onChange={gallery_fit => set({ gallery_fit })}
|
||||||
|
options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} />
|
||||||
|
</Field>
|
||||||
|
</>)
|
||||||
|
}
|
||||||
if (w.kind === 'reviews') {
|
if (w.kind === 'reviews') {
|
||||||
return (<>
|
return (<>
|
||||||
<Field label={t(`${k}.reviews.min`)}>
|
<Field label={t(`${k}.reviews.min`)}>
|
||||||
@@ -102,7 +124,7 @@ export function MoreInlineFields({ w, set }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Under the row: what needs more room, and what the venue still has to set. */
|
/** Under the row: what needs more room, and what the venue still has to set. */
|
||||||
export function MoreBelowFields({ w, set }) {
|
export function MoreBelowFields({ w, set, media = {}, onMedia }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
const { data: identity } = useIdentity()
|
const { data: identity } = useIdentity()
|
||||||
const { data: hours } = useHours()
|
const { data: hours } = useHours()
|
||||||
@@ -172,6 +194,7 @@ export function MoreBelowFields({ w, set }) {
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
if (w.kind === 'gallery') return <GalleryItems w={w} set={set} media={media} onMedia={onMedia} />
|
||||||
if (w.kind === 'reviews') {
|
if (w.kind === 'reviews') {
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-3">
|
<div className="grid gap-3">
|
||||||
@@ -206,3 +229,54 @@ function ReviewsNote() {
|
|||||||
? <Notice tone="warning" title={t('signage.widgets.reviews.missing')} data-testid="signage-widget-reviews-missing">{link}</Notice>
|
? <Notice tone="warning" title={t('signage.widgets.reviews.missing')} data-testid="signage-widget-reviews-missing">{link}</Notice>
|
||||||
: <p className="text-caption text-ink-3 -mt-2">{t('signage.widgets.reviews.hint')} {link}</p>
|
: <p className="text-caption text-ink-3 -mt-2">{t('signage.widgets.reviews.hint')} {link}</p>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A gallery's pictures and videos (its own list, in order) or the media folder it shows (6R.16). */
|
||||||
|
function GalleryItems({ w, set, media, onMedia }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [picking, setPicking] = useState(false)
|
||||||
|
const [folders, setFolders] = useState(null)
|
||||||
|
const folder = w.gallery_source === 'folder'
|
||||||
|
useEffect(() => { if (folder) listFolders().then(r => setFolders(r.folders)).catch(() => setFolders([])) }, [folder])
|
||||||
|
const k = 'signage.widgets.gallery'
|
||||||
|
if (folder) {
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Field label={t(`${k}.folder`)} hint={t(`${k}.folderHint`)} className="max-w-sm">
|
||||||
|
<Dropdown value={w.gallery_folder ?? ''} onChange={v => set({ gallery_folder: v === '' ? null : Number(v) })} data-testid="signage-widget-gallery-folder"
|
||||||
|
options={[{ value: '', label: t(`${k}.noFolder`) }, ...(folders || []).map(f => ({ value: f.id, label: f.name, hint: String(f.count) }))]} />
|
||||||
|
</Field>
|
||||||
|
{folders && folders.length === 0 && (
|
||||||
|
<Notice tone="warning" title={t(`${k}.noFolders`)}><Link to="/management/media" className="text-accent-ink font-medium underline">{t(`${k}.toMedia`)}</Link></Notice>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const ids = w.media_ids || []
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2" data-testid="signage-widget-gallery-items">
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{ids.map((id, i) => {
|
||||||
|
const m = media[String(id)]
|
||||||
|
return (
|
||||||
|
<div key={`${id}-${i}`} className="relative w-24 h-16 rounded-control border border-line bg-surface-3 overflow-hidden group" data-testid="signage-gallery-item">
|
||||||
|
{m?.thumb ? <img src={m.thumb} alt={m.name || ''} className="w-full h-full object-cover" /> : <Film size={18} className="m-auto mt-5 text-ink-3" aria-hidden="true" />}
|
||||||
|
<div className="absolute inset-x-0 bottom-0 flex justify-between bg-surface/80 opacity-0 group-hover:opacity-100 focus-within:opacity-100">
|
||||||
|
<IconButton size="sm" label={t('signage.widgets.backward')} disabled={i === 0} onClick={() => set({ media_ids: moved(ids, i, i - 1) })}><ArrowLeft size={13} /></IconButton>
|
||||||
|
<IconButton size="sm" tone="danger" label={t('fees.delete')} onClick={() => set({ media_ids: ids.filter((_, j) => j !== i) })}><X size={13} /></IconButton>
|
||||||
|
<IconButton size="sm" label={t('signage.widgets.forward')} disabled={i === ids.length - 1} onClick={() => set({ media_ids: moved(ids, i, i + 1) })}><ArrowRight size={13} /></IconButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{ids.length < 100 && (
|
||||||
|
<Button variant="secondary" icon={<Plus size={14} />} onClick={() => setPicking(true)} className="h-16" data-testid="signage-widget-gallery-add">{t(`${k}.add`)}</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{ids.length === 0 && <p className="text-caption text-ink-3">{t(`${k}.empty`)}</p>}
|
||||||
|
{picking && (
|
||||||
|
<MediaPicker open multiple kind="" onClose={() => setPicking(false)}
|
||||||
|
onPickMany={items => { items.forEach(it => onMedia?.(it)); set({ media_ids: [...ids, ...items.map(it => it.id)].slice(0, 100) }); setPicking(false) }} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ import { Fragment, useEffect, useRef, useState } from 'react'
|
|||||||
import {
|
import {
|
||||||
AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Bold, Italic, Palette, RotateCcw, Underline, BookImage, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical,
|
AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Bold, Italic, Palette, RotateCcw, Underline, BookImage, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical,
|
||||||
ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed,
|
ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed,
|
||||||
CalendarClock, Contact, MessageSquareQuote, MoveHorizontal, Shapes, Timer, Wifi,
|
CalendarClock, Contact, GalleryHorizontal, MessageSquareQuote, MoveHorizontal, Shapes, Timer, Wifi,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { cellWidgets, evenShares, setShare } from '@xenia/signage'
|
import { cellWidgets, evenShares, setShare } from '@xenia/signage'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
import { useTranslation } from '@xenia/i18n'
|
||||||
@@ -44,8 +44,8 @@ import {
|
|||||||
} from './signageLogic'
|
} from './signageLogic'
|
||||||
|
|
||||||
const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3,
|
const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3,
|
||||||
shape: Shapes, ticker: MoveHorizontal, countdown: Timer, hours: CalendarClock, wifi: Wifi, contact: Contact, reviews: MessageSquareQuote }
|
shape: Shapes, ticker: MoveHorizontal, countdown: Timer, hours: CalendarClock, wifi: Wifi, contact: Contact, reviews: MessageSquareQuote, gallery: GalleryHorizontal }
|
||||||
const MORE_KINDS = ['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews'] // MoreWidgetFields
|
const MORE_KINDS = ['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews', 'gallery'] // MoreWidgetFields
|
||||||
const iconOf = w => (w.kind === 'stack' ? (w.direction === 'column' ? Rows3 : Columns3) : ICON[w.kind] || LayoutList)
|
const iconOf = w => (w.kind === 'stack' ? (w.direction === 'column' ? Rows3 : Columns3) : ICON[w.kind] || LayoutList)
|
||||||
const kindLabel = (t, w) => t(`signage.widgets.kinds.${w.kind === 'stack' ? (w.direction === 'column' ? 'vstack' : 'hstack') : w.kind}`)
|
const kindLabel = (t, w) => t(`signage.widgets.kinds.${w.kind === 'stack' ? (w.direction === 'column' ? 'vstack' : 'hstack') : w.kind}`)
|
||||||
const ROW = 'grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]'
|
const ROW = 'grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]'
|
||||||
@@ -307,7 +307,7 @@ function InlineFields({ w, set }) {
|
|||||||
/** What needs more room, under the row: the picture, hints, the QR's own link, a menu's list, a stack's parts. */
|
/** What needs more room, under the row: the picture, hints, the QR's own link, a menu's list, a stack's parts. */
|
||||||
function BelowFields({ w, set, media, onMedia, extras, path, depth, selected, onSelect }) {
|
function BelowFields({ w, set, media, onMedia, extras, path, depth, selected, onSelect }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
if (MORE_KINDS.includes(w.kind)) return <MoreBelow w={w} set={set} />
|
if (MORE_KINDS.includes(w.kind)) return <MoreBelow w={w} set={set} media={media} onMedia={onMedia} />
|
||||||
if (w.kind === 'logo') {
|
if (w.kind === 'logo') {
|
||||||
return <MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-logo"
|
return <MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-logo"
|
||||||
onChange={item => { onMedia(item); set({ media_id: item.id }) }} />
|
onChange={item => { onMedia(item); set({ media_id: item.id }) }} />
|
||||||
|
|||||||
@@ -137,9 +137,9 @@ export function mediaLookup(map) {
|
|||||||
|
|
||||||
// ── menu boards and widgets (5.6b) ───────────────────────────────────────────
|
// ── menu boards and widgets (5.6b) ───────────────────────────────────────────
|
||||||
|
|
||||||
export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews']
|
export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews', 'gallery']
|
||||||
/** What a stack's part can show (2026-11-21): a widget, a stack one level deep, a library slide. */
|
/** What a stack's part can show (2026-11-21): a widget, a stack one level deep, a library slide. */
|
||||||
export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews']
|
export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews', 'gallery']
|
||||||
|
|
||||||
/** A new widget of a kind ('hstack' / 'vstack': a stack side by side / one over the other), where it
|
/** A new widget of a kind ('hstack' / 'vstack': a stack side by side / one over the other), where it
|
||||||
* usually goes: a menu or a stack in a box of its own (they fill a box). */
|
* usually goes: a menu or a stack in a box of its own (they fill a box). */
|
||||||
@@ -152,6 +152,7 @@ export function newWidget(kind) {
|
|||||||
return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 10, w: 40, h: 80 }, board: { select: 'all', columns: 1, sales_point: 'in_store' } }
|
return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 10, w: 40, h: 80 }, board: { select: 'all', columns: 1, sales_point: 'in_store' } }
|
||||||
}
|
}
|
||||||
if (kind === 'shape') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 40, y: 30, w: 20, h: 35 }, shape: 'rectangle', radius: 10 }
|
if (kind === 'shape') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 40, y: 30, w: 20, h: 35 }, shape: 'rectangle', radius: 10 }
|
||||||
|
if (kind === 'gallery') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 15, w: 40, h: 50 }, media_ids: [] }
|
||||||
if (kind === 'reviews') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 25, y: 55, w: 50, h: 32 } }
|
if (kind === 'reviews') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 25, y: 55, w: 50, h: 32 } }
|
||||||
return { kind, position: NEW_PLACE[kind] || 'top-right', size: 'medium', align: 'auto',
|
return { kind, position: NEW_PLACE[kind] || 'top-right', size: 'medium', align: 'auto',
|
||||||
...(kind === 'text' || kind === 'ticker' ? { text: '' } : {}), ...(kind === 'countdown' ? { countdown_to: '17:00' } : {}) }
|
...(kind === 'text' || kind === 'ticker' ? { text: '' } : {}), ...(kind === 'countdown' ? { countdown_to: '17:00' } : {}) }
|
||||||
|
|||||||
@@ -174,7 +174,8 @@
|
|||||||
"unreadable": "Αυτή η εικόνα δεν διαβάζεται. Αποθηκεύστε τη ξανά ως JPG ή PNG και ανεβάστε τη.",
|
"unreadable": "Αυτή η εικόνα δεν διαβάζεται. Αποθηκεύστε τη ξανά ως JPG ή PNG και ανεβάστε τη.",
|
||||||
"in_use": "Αυτό το αρχείο χρησιμοποιείται από: {{uses}}. Αφαιρέστε το πρώτα από εκεί.",
|
"in_use": "Αυτό το αρχείο χρησιμοποιείται από: {{uses}}. Αφαιρέστε το πρώτα από εκεί.",
|
||||||
"not_a_picture": "Εδώ διαλέξτε εικόνα, όχι βίντεο.",
|
"not_a_picture": "Εδώ διαλέξτε εικόνα, όχι βίντεο.",
|
||||||
"builtin": "Οι ενσωματωμένες εικόνες δεν διαγράφονται ούτε μετονομάζονται."
|
"builtin": "Οι ενσωματωμένες εικόνες δεν διαγράφονται ούτε μετονομάζονται.",
|
||||||
|
"folder_unknown": "Αυτός ο φάκελος δεν υπάρχει πια στη βιβλιοθήκη πολυμέσων."
|
||||||
},
|
},
|
||||||
"caller_id": {
|
"caller_id": {
|
||||||
"key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος."
|
"key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος."
|
||||||
|
|||||||
@@ -1215,7 +1215,10 @@
|
|||||||
"usedCantDelete": "Ένα αρχείο σε χρήση δεν διαγράφεται. Αφαιρέστε το πρώτα από εκεί.",
|
"usedCantDelete": "Ένα αρχείο σε χρήση δεν διαγράφεται. Αφαιρέστε το πρώτα από εκεί.",
|
||||||
"uses": {
|
"uses": {
|
||||||
"product": "Προϊόν",
|
"product": "Προϊόν",
|
||||||
"category": "Κατηγορία"
|
"category": "Κατηγορία",
|
||||||
|
"identity": "Το λογότυπο του καταστήματος",
|
||||||
|
"signage_slide": "Διαφάνεια σήμανσης",
|
||||||
|
"signage_saved_slide": "Αποθηκευμένη διαφάνεια"
|
||||||
},
|
},
|
||||||
"pickTitle": "Επιλογή εικόνας",
|
"pickTitle": "Επιλογή εικόνας",
|
||||||
"photo": "Φωτογραφία",
|
"photo": "Φωτογραφία",
|
||||||
@@ -1246,6 +1249,19 @@
|
|||||||
"waiting": "Σε αναμονή…",
|
"waiting": "Σε αναμονή…",
|
||||||
"working": "Ετοιμάζεται {{progress}}%",
|
"working": "Ετοιμάζεται {{progress}}%",
|
||||||
"failed": "Δεν ετοιμάστηκε"
|
"failed": "Δεν ετοιμάστηκε"
|
||||||
|
},
|
||||||
|
"folders": {
|
||||||
|
"title": "Φάκελοι",
|
||||||
|
"all": "Όλα",
|
||||||
|
"none": "Χωρίς φάκελο",
|
||||||
|
"new": "Νέος φάκελος",
|
||||||
|
"rename": "Μετονομασία φακέλου",
|
||||||
|
"delete": "Διαγραφή φακέλου",
|
||||||
|
"deleteTitle": "Διαγραφή του φακέλου «{{name}}»;",
|
||||||
|
"deleteBody": "Τα αρχεία του μένουν στη βιβλιοθήκη, χωρίς φάκελο. Μια συλλογή που δείχνει αυτόν τον φάκελο δεν θα δείχνει τίποτα.",
|
||||||
|
"name": "Όνομα φακέλου",
|
||||||
|
"folder": "Φάκελος",
|
||||||
|
"moved": "Μετακινήθηκε"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"signage": {
|
"signage": {
|
||||||
@@ -1487,7 +1503,8 @@
|
|||||||
"hours": "Ωράριο",
|
"hours": "Ωράριο",
|
||||||
"wifi": "Wi-Fi",
|
"wifi": "Wi-Fi",
|
||||||
"contact": "Στοιχεία επικοινωνίας",
|
"contact": "Στοιχεία επικοινωνίας",
|
||||||
"reviews": "Κριτικές"
|
"reviews": "Κριτικές",
|
||||||
|
"gallery": "Συλλογή"
|
||||||
},
|
},
|
||||||
"position": "Πού",
|
"position": "Πού",
|
||||||
"size": "Μέγεθος",
|
"size": "Μέγεθος",
|
||||||
@@ -1675,6 +1692,21 @@
|
|||||||
"missing": "Δεν υπάρχουν κριτικές ακόμη: το widget μένει κρυφό.",
|
"missing": "Δεν υπάρχουν κριτικές ακόμη: το widget μένει κρυφό.",
|
||||||
"hint": "Οι κριτικές που καταχωρίσατε, μία κάθε φορά.",
|
"hint": "Οι κριτικές που καταχωρίσατε, μία κάθε φορά.",
|
||||||
"where": "Προσθέστε τις στο Ψηφιακή σήμανση → Μήνυμα & ρυθμίσεις"
|
"where": "Προσθέστε τις στο Ψηφιακή σήμανση → Μήνυμα & ρυθμίσεις"
|
||||||
|
},
|
||||||
|
"gallery": {
|
||||||
|
"source": "Δείχνει",
|
||||||
|
"sources": {
|
||||||
|
"pictures": "Επιλεγμένες εικόνες",
|
||||||
|
"folder": "Έναν φάκελο"
|
||||||
|
},
|
||||||
|
"seconds": "Καθεμία για",
|
||||||
|
"folder": "Φάκελος",
|
||||||
|
"folderHint": "Ό,τι υπάρχει τώρα στον φάκελο, και ό,τι προσθέσετε αργότερα.",
|
||||||
|
"noFolder": "Διαλέξτε φάκελο",
|
||||||
|
"noFolders": "Δεν υπάρχουν φάκελοι πολυμέσων ακόμη.",
|
||||||
|
"toMedia": "Φτιάξτε έναν στη σελίδα Πολυμέσα",
|
||||||
|
"add": "Προσθήκη εικόνων ή βίντεο",
|
||||||
|
"empty": "Η συλλογή είναι άδεια ακόμη: μένει κρυφή."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"tabs": {
|
"tabs": {
|
||||||
|
|||||||
@@ -174,7 +174,8 @@
|
|||||||
"unreadable": "This picture can't be read. Save it again as JPG or PNG and upload it.",
|
"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.",
|
"not_a_picture": "Pick a picture here, not a video.",
|
||||||
"builtin": "Built-in pictures can't be deleted or renamed."
|
"builtin": "Built-in pictures can't be deleted or renamed.",
|
||||||
|
"folder_unknown": "That folder isn't in the media library any more."
|
||||||
},
|
},
|
||||||
"caller_id": {
|
"caller_id": {
|
||||||
"key_invalid": "The phone system's key is missing or wrong."
|
"key_invalid": "The phone system's key is missing or wrong."
|
||||||
|
|||||||
@@ -1215,7 +1215,10 @@
|
|||||||
"usedCantDelete": "A file in use can't be deleted. Remove it there first.",
|
"usedCantDelete": "A file in use can't be deleted. Remove it there first.",
|
||||||
"uses": {
|
"uses": {
|
||||||
"product": "Product",
|
"product": "Product",
|
||||||
"category": "Category"
|
"category": "Category",
|
||||||
|
"identity": "The venue's logo",
|
||||||
|
"signage_slide": "Signage slide",
|
||||||
|
"signage_saved_slide": "Saved slide"
|
||||||
},
|
},
|
||||||
"pickTitle": "Pick a picture",
|
"pickTitle": "Pick a picture",
|
||||||
"photo": "Photo",
|
"photo": "Photo",
|
||||||
@@ -1246,6 +1249,19 @@
|
|||||||
"waiting": "Waiting…",
|
"waiting": "Waiting…",
|
||||||
"working": "Preparing {{progress}}%",
|
"working": "Preparing {{progress}}%",
|
||||||
"failed": "Not prepared"
|
"failed": "Not prepared"
|
||||||
|
},
|
||||||
|
"folders": {
|
||||||
|
"title": "Folders",
|
||||||
|
"all": "All",
|
||||||
|
"none": "In no folder",
|
||||||
|
"new": "New folder",
|
||||||
|
"rename": "Rename the folder",
|
||||||
|
"delete": "Delete the folder",
|
||||||
|
"deleteTitle": "Delete the folder \"{{name}}\"?",
|
||||||
|
"deleteBody": "Its files stay in the library, in no folder. A gallery that shows this folder will show nothing.",
|
||||||
|
"name": "Folder name",
|
||||||
|
"folder": "Folder",
|
||||||
|
"moved": "Moved"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"signage": {
|
"signage": {
|
||||||
@@ -1487,7 +1503,8 @@
|
|||||||
"hours": "Opening hours",
|
"hours": "Opening hours",
|
||||||
"wifi": "Wi-Fi",
|
"wifi": "Wi-Fi",
|
||||||
"contact": "Contact details",
|
"contact": "Contact details",
|
||||||
"reviews": "Reviews"
|
"reviews": "Reviews",
|
||||||
|
"gallery": "Gallery"
|
||||||
},
|
},
|
||||||
"position": "Where",
|
"position": "Where",
|
||||||
"size": "Size",
|
"size": "Size",
|
||||||
@@ -1675,6 +1692,21 @@
|
|||||||
"missing": "No reviews yet: the widget stays hidden.",
|
"missing": "No reviews yet: the widget stays hidden.",
|
||||||
"hint": "The reviews you typed in, one at a time.",
|
"hint": "The reviews you typed in, one at a time.",
|
||||||
"where": "Add them under Signage → Message & settings"
|
"where": "Add them under Signage → Message & settings"
|
||||||
|
},
|
||||||
|
"gallery": {
|
||||||
|
"source": "Shows",
|
||||||
|
"sources": {
|
||||||
|
"pictures": "Chosen pictures",
|
||||||
|
"folder": "A folder"
|
||||||
|
},
|
||||||
|
"seconds": "Each for",
|
||||||
|
"folder": "Folder",
|
||||||
|
"folderHint": "Whatever is in the folder now, also what you add to it later.",
|
||||||
|
"noFolder": "Choose a folder",
|
||||||
|
"noFolders": "No media folders yet.",
|
||||||
|
"toMedia": "Make one on the Media page",
|
||||||
|
"add": "Add pictures or videos",
|
||||||
|
"empty": "Nothing in the gallery yet: it stays hidden."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"tabs": {
|
"tabs": {
|
||||||
|
|||||||
@@ -175,7 +175,7 @@ const plate = (w, pad) => ({
|
|||||||
...(w.background_colour ? { background: w.background_colour, borderRadius: cq(1.2), ...(pad ? { padding: `${cq(0.8)} ${cq(1.6)}` } : {}) } : {}),
|
...(w.background_colour ? { background: w.background_colour, borderRadius: cq(1.2), ...(pad ? { padding: `${cq(0.8)} ${cq(1.6)}` } : {}) } : {}),
|
||||||
})
|
})
|
||||||
// a menu, a stack, a shape or a scrolling text in a corner or a bar has no box of its own: it gets one of this size (cqmin)
|
// a menu, a stack, a shape or a scrolling text in a corner or a bar has no box of its own: it gets one of this size (cqmin)
|
||||||
const BOXED = { menu: [48, 56], stack: [60, 36], shape: [18, 18], ticker: [80, 7], reviews: [56, 24] }
|
const BOXED = { menu: [48, 56], stack: [60, 36], shape: [18, 18], ticker: [80, 7], reviews: [56, 24], gallery: [40, 30] }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The widgets of a slide: in their corners and bars, or (moved and sized by hand: position
|
* The widgets of a slide: in their corners and bars, or (moved and sized by hand: position
|
||||||
@@ -336,6 +336,12 @@ function widgetBody(w, ctx, fit, path) {
|
|||||||
if (w.kind === 'hours') return hoursBody(w, ctx, unit, text)
|
if (w.kind === 'hours') return hoursBody(w, ctx, unit, text)
|
||||||
if (w.kind === 'wifi') return wifiBody(w, venue?.identity?.wifi, unit, text)
|
if (w.kind === 'wifi') return wifiBody(w, venue?.identity?.wifi, unit, text)
|
||||||
if (w.kind === 'contact') return contactBody(w, venue?.identity?.contact, unit, text)
|
if (w.kind === 'contact') return contactBody(w, venue?.identity?.contact, unit, text)
|
||||||
|
if (w.kind === 'gallery') {
|
||||||
|
const ids = w.gallery_source === 'folder' ? (x.gallery || []) : (w.media_ids || [])
|
||||||
|
const items = ids.map(id => media(id)).filter(Boolean)
|
||||||
|
if (!items.length) return null
|
||||||
|
return boxed(<Gallery w={w} items={items} now={now} />, 'gallery')
|
||||||
|
}
|
||||||
if (w.kind === 'reviews') {
|
if (w.kind === 'reviews') {
|
||||||
const list = (venue?.reviews || []).filter(r => r.stars >= (w.reviews_min || 4))
|
const list = (venue?.reviews || []).filter(r => r.stars >= (w.reviews_min || 4))
|
||||||
if (!list.length) return null
|
if (!list.length) return null
|
||||||
@@ -346,6 +352,34 @@ function widgetBody(w, ctx, fit, path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const STAR = '#fbbf24'
|
const STAR = '#fbbf24'
|
||||||
|
const GALLERY_IN = {
|
||||||
|
fade: [{ opacity: 0 }, { opacity: 1 }],
|
||||||
|
slide: [{ transform: 'translateX(100%)' }, { transform: 'translateX(0)' }],
|
||||||
|
zoom: [{ opacity: 0, transform: 'scale(1.12)' }, { opacity: 1, transform: 'scale(1)' }],
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A gallery (6R.16): its pictures and videos one after another, each for its seconds, coming in with its transition. */
|
||||||
|
function Gallery({ w, items, now }) {
|
||||||
|
const i = pageAt(items.length, w.gallery_seconds || 5, now.getTime())
|
||||||
|
const m = items[i]
|
||||||
|
const el = useRef(null)
|
||||||
|
const frames = GALLERY_IN[w.gallery_transition || 'fade']
|
||||||
|
useEffect(() => {
|
||||||
|
if (!frames || !el.current?.animate) return undefined
|
||||||
|
const a = el.current.animate(frames, { duration: 700, easing: 'ease-out' })
|
||||||
|
return () => a.cancel()
|
||||||
|
}, [i, frames])
|
||||||
|
const fit = { width: '100%', height: '100%', objectFit: w.gallery_fit || 'cover', display: 'block' }
|
||||||
|
return (
|
||||||
|
<div style={{ width: '100%', height: '100%', overflow: 'hidden', position: 'relative' }} data-testid="signage-w-gallery" data-index={i} data-count={items.length}>
|
||||||
|
<div key={`${i}-${m.src}`} ref={el} style={{ position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 }}>
|
||||||
|
{m.kind === 'video'
|
||||||
|
? <video src={m.src} poster={m.poster} muted autoPlay loop playsInline style={fit} />
|
||||||
|
: <img src={m.src} alt="" style={fit} />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One of the venue's reviews (6R.19), the next one every few seconds: its stars, what they wrote,
|
* One of the venue's reviews (6R.19), the next one every few seconds: its stars, what they wrote,
|
||||||
|
|||||||
@@ -179,6 +179,23 @@ try {
|
|||||||
(await page.getByTestId('media-used-by').innerText().catch(() => '')).includes(p1.name) && await page.getByTestId('media-delete').isDisabled())
|
(await page.getByTestId('media-used-by').innerText().catch(() => '')).includes(p1.name) && await page.getByTestId('media-delete').isDisabled())
|
||||||
await page.keyboard.press('Escape')
|
await page.keyboard.press('Escape')
|
||||||
|
|
||||||
|
// ── 6R.16: folders: one made on the page, a file filed from its details, the folder shows only it ──
|
||||||
|
await page.getByTestId('media-folder-new').click()
|
||||||
|
await page.getByTestId('media-folder-name').fill('Dishes')
|
||||||
|
await page.getByTestId('media-folder-save').click()
|
||||||
|
const made = await waitFor(async () => (await page.locator('[data-testid="media-folder"][data-name="Dishes"]').getAttribute('aria-pressed').catch(() => null)) === 'true' || null, 8000, 200)
|
||||||
|
r.check('6R.16: a folder made on the Media page (and opened: empty)', made === true && (await page.getByTestId('media-item').count()) === 0)
|
||||||
|
await page.getByTestId('media-folder-all').click()
|
||||||
|
await page.locator(`[data-testid="media-item"][data-id="${after1.image.id}"]`).click()
|
||||||
|
await page.getByTestId('media-folder-pick').click()
|
||||||
|
await page.getByRole('option', { name: 'Dishes' }).click()
|
||||||
|
await sleep(600)
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await page.locator('[data-testid="media-folder"][data-name="Dishes"]').click()
|
||||||
|
r.check('6R.16: a file filed in it from its details; the folder shows just that file',
|
||||||
|
await waitFor(async () => (await page.getByTestId('media-item').count()) === 1 || null, 8000, 200) === true
|
||||||
|
&& (await page.locator('[data-testid="media-folder"][data-name="Dishes"]').textContent()).includes('1'))
|
||||||
|
|
||||||
// ── 5.3: the customer display's looks pick their pictures from the library ──
|
// ── 5.3: the customer display's looks pick their pictures from the library ──
|
||||||
await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {})
|
await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {})
|
||||||
await page.goto(`${MANAGER}/settings`)
|
await page.goto(`${MANAGER}/settings`)
|
||||||
|
|||||||
@@ -589,19 +589,24 @@ try {
|
|||||||
contact: { phone: '2310 123456', instagram: '@xenia' } } })
|
contact: { phone: '2310 123456', instagram: '@xenia' } } })
|
||||||
await api('PUT', '/api/signage/reviews', { token: boss, body: { reviews: [{ name: 'Maria', stars: 5, text: 'Best octopus on the island' }, { name: 'Bob', stars: 2, text: 'Meh' }] } })
|
await api('PUT', '/api/signage/reviews', { token: boss, body: { reviews: [{ name: 'Maria', stars: 5, text: 'Best octopus on the island' }, { name: 'Bob', stars: 2, text: 'Meh' }] } })
|
||||||
await api('PUT', '/api/identity/hours', { token: boss, body: { days: [[{ from: '12:00', to: '23:00' }], [], [], [], [], [], []] } })
|
await api('PUT', '/api/identity/hours', { token: boss, body: { days: [[{ from: '12:00', to: '23:00' }], [], [], [], [], [], []] } })
|
||||||
|
const dishes = await api('POST', '/api/media/folders', { token: boss, body: { name: 'Dishes' } })
|
||||||
|
await api('POST', '/api/media/move', { token: boss, body: { ids: [photo.id], folder_id: dishes.id } })
|
||||||
const wl = await api('POST', '/api/signage/playlists', { token: boss, body: { name: 'New widgets', orientation: 'landscape' } })
|
const wl = await api('POST', '/api/signage/playlists', { token: boss, body: { name: 'New widgets', orientation: 'landscape' } })
|
||||||
await api('POST', `/api/signage/playlists/${wl.id}/slides`, { token: boss, body: { kind: 'blank', duration_s: 60, content: { widgets: [
|
await api('POST', `/api/signage/playlists/${wl.id}/slides`, { token: boss, body: { kind: 'blank', duration_s: 60, content: { widgets: [
|
||||||
{ kind: 'shape', position: 'custom', box: { x: 2, y: 2, w: 10, h: 15 }, shape: 'star' },
|
{ kind: 'shape', position: 'custom', box: { x: 2, y: 2, w: 10, h: 15 }, shape: 'star' },
|
||||||
{ kind: 'countdown', position: 'top-center', countdown_to: '2099-01-01T00:00', text: 'Opening in' },
|
{ kind: 'countdown', position: 'top-center', countdown_to: '2099-01-01T00:00', text: 'Opening in' },
|
||||||
{ kind: 'hours', position: 'top-left' }, { kind: 'wifi', position: 'bottom-right' }, { kind: 'contact', position: 'bottom-left' },
|
{ kind: 'hours', position: 'top-left' }, { kind: 'wifi', position: 'bottom-right' }, { kind: 'contact', position: 'bottom-left' },
|
||||||
{ kind: 'ticker', position: 'top-bar', text: 'Fresh fish today' },
|
{ kind: 'ticker', position: 'top-bar', text: 'Fresh fish today' },
|
||||||
{ kind: 'reviews', position: 'custom', box: { x: 30, y: 40, w: 40, h: 25 } }] } } })
|
{ kind: 'reviews', position: 'custom', box: { x: 30, y: 40, w: 40, h: 25 } },
|
||||||
|
{ kind: 'gallery', position: 'custom', box: { x: 75, y: 30, w: 20, h: 20 }, gallery_source: 'folder', gallery_folder: dishes.id }] } } })
|
||||||
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: wl.id } })
|
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: wl.id } })
|
||||||
const widgetsOn = async () => (await Promise.all(['shape', 'countdown', 'hours', 'wifi', 'contact', 'ticker', 'reviews'].map(k => tv.getByTestId(`signage-w-${k}`).count()))).every(n => n === 1)
|
const widgetsOn = async () => (await Promise.all(['shape', 'countdown', 'hours', 'wifi', 'contact', 'ticker', 'reviews', 'gallery'].map(k => tv.getByTestId(`signage-w-${k}`).count()))).every(n => n === 1)
|
||||||
r.check('6R.15: a shape, a countdown, the opening hours, Wi-Fi (from the identity), contact details and a scrolling text on the TV',
|
r.check('6R.15: a shape, a countdown, the opening hours, Wi-Fi (from the identity), contact details and a scrolling text on the TV',
|
||||||
await waitFor(async () => (await widgetsOn()) || null, 15_000, 300) === true)
|
await waitFor(async () => (await widgetsOn()) || null, 15_000, 300) === true)
|
||||||
r.check('6R.15: the Wi-Fi widget carries the code that joins the network', (await tv.getByTestId('signage-w-wifi').textContent()).includes('Xenia Guests')
|
r.check('6R.15: the Wi-Fi widget carries the code that joins the network', (await tv.getByTestId('signage-w-wifi').textContent()).includes('Xenia Guests')
|
||||||
&& await tv.getByTestId('signage-w-wifi').locator('svg').count() > 0)
|
&& await tv.getByTestId('signage-w-wifi').locator('svg').count() > 0)
|
||||||
|
r.check('6R.16: a gallery of a media folder shows its picture (kept on the TV)', await tv.getByTestId('signage-w-gallery').getAttribute('data-count') === '1'
|
||||||
|
&& (await tv.getByTestId('signage-w-gallery').locator('img').getAttribute('src')).startsWith('blob:'))
|
||||||
r.check('6R.19: a review typed in by hand shows (the 2-star one is left out)', await tv.getByTestId('signage-w-reviews').getAttribute('data-count') === '1'
|
r.check('6R.19: a review typed in by hand shows (the 2-star one is left out)', await tv.getByTestId('signage-w-reviews').getAttribute('data-count') === '1'
|
||||||
&& (await tv.getByTestId('signage-w-reviews').textContent()).includes('Best octopus'))
|
&& (await tv.getByTestId('signage-w-reviews').textContent()).includes('Best octopus'))
|
||||||
r.check('6R.15: the countdown runs (days left to 2099)', /^\d+d \d\d:\d\d:\d\d$/.test((await tv.getByTestId('signage-w-countdown').textContent()).replace('Opening in', '').trim()))
|
r.check('6R.15: the countdown runs (days left to 2099)', /^\d+d \d\d:\d\d:\d\d$/.test((await tv.getByTestId('signage-w-countdown').textContent()).replace('Opening in', '').trim()))
|
||||||
|
|||||||
Reference in New Issue
Block a user