feat(manager): Media page, photo field for products and categories (platform-v2 step 5.2)
- Management → Media (src/pages/media/): every picture and video, search, pictures / videos, batch upload (many files or drop on the page) with a result per file, details (preview, display name, kind, resolution, length, file size, uploaded file, when / who, the sizes made, what uses it, delete off while used). - MediaField: upload on the spot (into the library and set at once), pick from the library (MediaPicker, which can also upload), remove; after an upload on the spot "Name it after the product / category" renames it in Latin letters. Used by the product editor and the category dialog. - nav: `anyPerm` (any of the keys that manage pictures); the route guard uses the same rule. Product rows have test ids. - @xenia/i18n: latin() (Greek to Latin, the way venues write it) + tests. - tests: manager media.test.mjs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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="" />
|
||||
)}
|
||||
{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>}
|
||||
{!form.is_service_item && (
|
||||
<MediaField value={form.image} onChange={image => setField('image', image)} nameAfter={form.name}
|
||||
label={tm('media.photo')} testid="product-photo" />
|
||||
)}
|
||||
</>)}
|
||||
|
||||
{/* 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'),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user