diff --git a/manager_dashboard/package.json b/manager_dashboard/package.json index 62ed65d..f1aaaca 100644 --- a/manager_dashboard/package.json +++ b/manager_dashboard/package.json @@ -8,7 +8,7 @@ "build": "vite build", "preview": "vite preview", "test": "node --test \"tests/*.test.mjs\"", - "lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/online src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/PhoneListener.jsx src/pages/PhonePage.jsx src/store/phoneStore.js src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx" + "lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/online src/pages/media src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/PhoneListener.jsx src/pages/PhonePage.jsx src/store/phoneStore.js src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx" }, "dependencies": { "@tanstack/react-query": "^5.107.1", diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 49d6f84..61e1302 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -30,6 +30,7 @@ import TabsPage from './pages/financials/TabsPage' // Management import ProductsPage from './pages/Management/ProductsPage' +import MediaPage from './pages/media/MediaPage' import TablesConfigPage from './pages/Management/TablesConfigPage' import StaffPage from './pages/Management/StaffPage' import SessionsPage from './pages/staff/SessionsPage' @@ -161,6 +162,7 @@ export default function App() { {/* ── Management (Headquarters) ── */} } /> + } /> } /> } /> } /> diff --git a/manager_dashboard/src/pages/Management/ProductFormModal.jsx b/manager_dashboard/src/pages/Management/ProductFormModal.jsx index a7f0a06..fe20693 100644 --- a/manager_dashboard/src/pages/Management/ProductFormModal.jsx +++ b/manager_dashboard/src/pages/Management/ProductFormModal.jsx @@ -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 } - {!form.is_service_item &&
- - {product.image_url && ( - - )} - {imageFile &&
{imageFile.name}
} - -
} + {!form.is_service_item && ( + 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 📋 Αντιγραφή )} - diff --git a/manager_dashboard/src/pages/Management/ProductsTab.jsx b/manager_dashboard/src/pages/Management/ProductsTab.jsx index 19e5fa2..04b9733 100644 --- a/manager_dashboard/src/pages/Management/ProductsTab.jsx +++ b/manager_dashboard/src/pages/Management/ProductsTab.jsx @@ -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 ( {product.name} {/* Drag grip */} @@ -912,7 +915,7 @@ function ProductRow({ p, cat, parentCat, selected, onToggleSelect, onEdit, onArc )} {/* Edit — pill style */} - - diff --git a/manager_dashboard/src/pages/media/MediaDetails.jsx b/manager_dashboard/src/pages/media/MediaDetails.jsx new file mode 100644 index 0000000..b3b803d --- /dev/null +++ b/manager_dashboard/src/pages/media/MediaDetails.jsx @@ -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 ( + + {confirm ? <> + {t('media.deleteConfirm')} + + + : <> + + + } + }> + {!item ?
: ( +
+
+ {item.kind === 'video' + ?
+ +
+
+ + setName(e.target.value)} data-testid="media-name" /> + + +
+

{t('media.displayNameHint')}

+
+ +
+ {rows.map(([k, v]) =>
{k}
{v}
)} +
+ +
+

{t('media.sizes')}

+

{t(item.kind === 'video' ? 'media.sizesVideo' : 'media.sizesHint')}

+
    + {VARIANT_ORDER.filter(v => item.files?.[v]).map(v => ( +
  • + {t(`media.variants.${v}`)} + {resolution(item.files[v].width, item.files[v].height)} + {fileSize(item.files[v].bytes, formatNumber)} +
  • + ))} +
+
+ +
+

{t('media.usedBy')}

+ {used.length === 0 + ?

{t('media.unused')}

+ : <> +
    + {used.map(u =>
  • + {t(`media.uses.${u.kind}`, { defaultValue: u.kind })}: {u.name}
  • )} +
+

{t('media.usedCantDelete')}

+ } +
+
+ )} +
+ ) +} diff --git a/manager_dashboard/src/pages/media/MediaField.jsx b/manager_dashboard/src/pages/media/MediaField.jsx new file mode 100644 index 0000000..e4b1a10 --- /dev/null +++ b/manager_dashboard/src/pages/media/MediaField.jsx @@ -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 " sets the photo's display name to +// `nameAfter` in Latin letters (latin() from @xenia/i18n). The file names on disk are the backend's. +// +// 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 ( +
+ {label && {label}} +
+ +
+ {value && {value.name}} +
+ + + {value && } +
+ {value && fresh === value.id && suggested && suggested !== value.name && ( + + )} +
+
+ { const f = e.target.files?.[0]; e.target.value = ''; if (f) upload(f) }} /> + {picking && setPicking(false)} + onPick={(item, { uploaded }) => { onChange(imageOf(item)); setFresh(uploaded ? item.id : null); setPicking(false) }} />} +
+ ) +} diff --git a/manager_dashboard/src/pages/media/MediaPage.jsx b/manager_dashboard/src/pages/media/MediaPage.jsx new file mode 100644 index 0000000..d5bce7c --- /dev/null +++ b/manager_dashboard/src/pages/media/MediaPage.jsx @@ -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 ( +
{ if ([...(e.dataTransfer?.types || [])].includes('Files')) { e.preventDefault(); setDragging(true) } }} + onDragLeave={e => { if (e.currentTarget === e.target) setDragging(false) }} + onDrop={onDrop}> +
+

{t('media.title')}

+

{t('media.intro')}

+
+ +
+ + { if (e.target.files?.length) add(e.target.files); e.target.value = '' }} /> + {t('media.dropHint')} +
+ setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')} + className="flex-1 sm:w-56" data-testid="media-search" /> + setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')} + className="flex-1 min-w-[10rem]" data-testid="media-picker-search" /> + + 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 = '' }} /> +
+ + {error ? + : !page ?
+ : page.items.length === 0 ? + :
+ onPick(item, { uploaded: false })} testid="media-picker-grid" /> +
} +
+ + ) +} diff --git a/manager_dashboard/src/pages/media/mediaApi.js b/manager_dashboard/src/pages/media/mediaApi.js new file mode 100644 index 0000000..f93b98c --- /dev/null +++ b/manager_dashboard/src/pages/media/mediaApi.js @@ -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}`) diff --git a/manager_dashboard/src/pages/media/mediaHooks.js b/manager_dashboard/src/pages/media/mediaHooks.js new file mode 100644 index 0000000..3456ea6 --- /dev/null +++ b/manager_dashboard/src/pages/media/mediaHooks.js @@ -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) } +} diff --git a/manager_dashboard/src/pages/media/mediaLogic.js b/manager_dashboard/src/pages/media/mediaLogic.js new file mode 100644 index 0000000..b3d18de --- /dev/null +++ b/manager_dashboard/src/pages/media/mediaLogic.js @@ -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'), + } +} diff --git a/manager_dashboard/src/shell/RouteGuard.jsx b/manager_dashboard/src/shell/RouteGuard.jsx index 55c1c12..46c6c78 100644 --- a/manager_dashboard/src/shell/RouteGuard.jsx +++ b/manager_dashboard/src/shell/RouteGuard.jsx @@ -1,6 +1,6 @@ import { useLocation } from 'react-router-dom' import { ModuleOff, NoAccess, useAccess } from '@xenia/access' -import { pageFor } from './nav' +import { canSee, pageFor } from './nav' /** * Guards whatever route is showing by its path, with the same rules as the sidebar @@ -12,7 +12,7 @@ export default function RouteGuard({ children }) { const { modules, permissions } = useAccess() const page = pageFor(pathname) if (page?.module && !modules.has(page.module)) return - if (page?.perm && !permissions.has(page.perm)) return + if (page && !canSee(page, { modules, permissions })) return return children } diff --git a/manager_dashboard/src/shell/nav.js b/manager_dashboard/src/shell/nav.js index ec7348d..cb0c0b1 100644 --- a/manager_dashboard/src/shell/nav.js +++ b/manager_dashboard/src/shell/nav.js @@ -10,16 +10,19 @@ // permission need core.dashboard.access (what their APIs check, require_manager). // Finer keys (pricing.manage, expenses.manage…) replace these when phase 6 // converts those routers. +// anyPerm instead of perm: any one of these keys is enough (the media library) // label a key in the i18n `manager` namespace import { LayoutDashboard, LayoutGrid, ShoppingBag, BookUser, Users, Receipt, CreditCard, Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes, BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText, - AppWindow, Settings, CookingPot, Truck, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck, QrCode, + AppWindow, Settings, CookingPot, Truck, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck, QrCode, Images, } from 'lucide-react' const DASH = 'core.dashboard.access' +// The media library: whoever manages something that shows pictures (routers/media.py MANAGE) +const MEDIA = ['catalog.menu.manage', 'customer_display.manage', 'signage.manage', 'menu_tablet.manage'] export const NAV = [ { @@ -58,6 +61,7 @@ export const NAV = [ group: 'management', icon: Package, label: 'nav.management', children: [ { to: '/management/products', icon: Package, label: 'nav.products', module: 'catalog', perm: 'catalog.menu.manage' }, + { to: '/management/media', icon: Images, label: 'nav.media', module: 'core', anyPerm: MEDIA }, { to: '/management/tables', icon: TableProperties, label: 'nav.tablesConfig', module: 'catalog', perm: 'catalog.tables.manage' }, { to: '/management/staff', icon: UserCog, label: 'nav.staff', module: 'core', perm: 'core.staff.manage' }, { to: '/management/sessions', icon: LogIn, label: 'nav.sessions', module: 'core', perm: 'core.staff.manage' }, @@ -129,5 +133,6 @@ export function pageFor(pathname) { export function canSee(page, { modules, permissions }) { if (!page) return true if (page.module && !modules.has(page.module)) return false + if (page.anyPerm) return page.anyPerm.some(k => permissions.has(k)) return !page.perm || permissions.has(page.perm) } diff --git a/manager_dashboard/tests/media.test.mjs b/manager_dashboard/tests/media.test.mjs new file mode 100644 index 0000000..4ff3342 --- /dev/null +++ b/manager_dashboard/tests/media.test.mjs @@ -0,0 +1,39 @@ +// The media library's helpers and its nav rule (plan step 5.2). +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { duration, fileSize, imageOf, queueFrom, queueSummary, resolution } from '../src/pages/media/mediaLogic.js' +import { canSee, pageFor } from '../src/shell/nav.js' + +test('sizes, resolutions and lengths for people', () => { + assert.equal(fileSize(512), '512 B') + assert.equal(fileSize(250_000), '244 KB') + assert.equal(fileSize(3.4 * 1024 * 1024, (n, o) => n.toFixed(o.maxDecimals)), '3.4 MB') + assert.equal(fileSize(null), '') + assert.equal(resolution(1920, 1080), '1920 × 1080') + assert.equal(resolution(null, 5), '') + assert.equal(duration(12_500), '0:13') + assert.equal(duration(3_909_000), '1:05:09') +}) + +test('a library item as the picture an app shows', () => { + const item = { id: 4, kind: 'image', name: 'Gyros', urls: { thumb: '/t', card: '/c', full: '/f', original: '/o' } } + assert.deepEqual(imageOf(item), { id: 4, name: 'Gyros', thumb: '/t', card: '/c', full: '/f' }) + assert.equal(imageOf({ ...item, kind: 'video' }), null) + assert.equal(imageOf(null), null) +}) + +test('a batch upload queue and its summary', () => { + const q = queueFrom([{ name: 'a.jpg' }, { name: 'b.jpg' }], 3) + assert.deepEqual(q.map(x => [x.key, x.status]), [['3:a.jpg', 'waiting'], ['4:b.jpg', 'waiting']]) + assert.equal(queueSummary(q).busy, true) + const done = [{ ...q[0], status: 'added' }, { ...q[1], status: 'existing' }, { key: 'x', status: 'failed' }] + assert.deepEqual(queueSummary(done), { total: 3, added: 1, existing: 1, failed: 1, busy: false }) +}) + +test('the Media page is for anyone who manages something with pictures', () => { + const page = pageFor('/management/media') + const access = keys => ({ modules: new Set(['core']), permissions: new Set(keys) }) + assert.equal(canSee(page, access(['customer_display.manage'])), true) + assert.equal(canSee(page, access(['catalog.menu.manage'])), true) + assert.equal(canSee(page, access(['core.dashboard.access'])), false) +}) diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 55e62da..37d732b 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -46,7 +46,8 @@ "sessions": "Συνδεδεμένοι τώρα", "approvals": "Εγκρίσεις υπευθύνου", "deliveryFees": "Online παραγγελίες (ρύθμιση)", - "qrCodes": "QR τραπεζιών" + "qrCodes": "QR τραπεζιών", + "media": "Πολυμέσα" }, "profile": { "edit": "Επεξεργασία προφίλ", @@ -702,5 +703,70 @@ "setup": "Σύνδεση του τηλεφωνικού κέντρου", "setupBody": "Στο Grandstream UCM, ορίστε το Action URL για τις εισερχόμενες κλήσεις σε αυτή τη διεύθυνση (λειτουργεί μόνο μέσα από το κατάστημα):", "setupSecret": "Για επιπλέον ασφάλεια, ορίστε ένα κλειδί στις Ρυθμίσεις (caller_id.secret) και προσθέστε &key=<το κλειδί> στη διεύθυνση." + }, + "media": { + "title": "Πολυμέσα", + "intro": "Όλες οι εικόνες και τα βίντεο του καταστήματος σε ένα μέρος. Ανεβάστε πολλά μαζί και διαλέξτε τα μετά για προϊόντα, κατηγορίες και οθόνες. Ο διακομιστής κρατά το πρωτότυπο και φτιάχνει μικρότερα αντίγραφα που φορτώνουν γρήγορα· το όνομα είναι μόνο για εσάς.", + "upload": "Ανέβασμα αρχείων", + "uploadNew": "Ανέβασμα νέου", + "dropHint": "ή αφήστε αρχεία οπουδήποτε σε αυτή τη σελίδα", + "search": "Αναζήτηση με όνομα", + "kind": "Είδος", + "kinds": { + "all": "Όλα", + "images": "Εικόνες", + "videos": "Βίντεο", + "image": "Εικόνα", + "video": "Βίντεο" + }, + "noMatch": "Δεν βρέθηκε τίποτα.", + "empty": "Η βιβλιοθήκη είναι άδεια.", + "emptyHint": "Ανεβάστε εδώ τις φωτογραφίες σας ή προσθέστε μία απευθείας από ένα προϊόν.", + "count_one": "{{count}} αρχείο", + "count_other": "{{count}} αρχεία", + "more": "Εμφανίζονται τα νεότερα {{shown}} από {{total}}. Αναζητήστε για να βρείτε παλαιότερα.", + "uploading": "Ανέβασμα {{done}} από {{total}}…", + "uploaded": "Έτοιμο: {{added}} νέα, {{existing}} υπήρχαν ήδη, {{failed}} απέτυχαν.", + "clearList": "Καθαρισμός λίστας", + "alreadyThere": "υπάρχει ήδη στη βιβλιοθήκη", + "alreadyThereUsed": "Αυτή η φωτογραφία υπήρχε ήδη στη βιβλιοθήκη ως «{{name}}»: χρησιμοποιείται αυτή.", + "renamed": "Το όνομα αποθηκεύτηκε.", + "deleted": "Διαγράφηκε από τη βιβλιοθήκη.", + "deleteConfirm": "Οριστική διαγραφή αυτού του αρχείου;", + "delete": "Διαγραφή", + "close": "Κλείσιμο", + "resolution": "Ανάλυση", + "length": "Διάρκεια", + "fileSize": "Μέγεθος αρχείου", + "originalName": "Αρχείο που ανέβηκε", + "uploadedAt": "Ανέβηκε", + "uploadedBy": "Από", + "displayName": "Όνομα", + "displayNameHint": "Αυτό που βλέπετε στη βιβλιοθήκη. Το ίδιο το αρχείο έχει όνομα που χρησιμοποιεί μόνο ο διακομιστής.", + "saveName": "Αποθήκευση ονόματος", + "sizes": "Μεγέθη που φτιάχτηκαν", + "sizesHint": "Ο διακομιστής τα έφτιαξε από το πρωτότυπο· κάθε οθόνη φορτώνει το μικρότερο που χρειάζεται.", + "sizesVideo": "Τα βίντεο κρατιούνται όπως ανέβηκαν προς το παρόν· μικρότερες εκδοχές και στιγμιότυπο έρχονται αργότερα.", + "variants": { + "thumb": "Μικρό (λίστες)", + "card": "Κάρτα (μενού)", + "full": "Μεγάλο (πλήρης οθόνη)", + "original": "Πρωτότυπο" + }, + "usedBy": "Χρησιμοποιείται από", + "unused": "Δεν χρησιμοποιείται ακόμα.", + "usedCantDelete": "Ένα αρχείο σε χρήση δεν διαγράφεται. Αφαιρέστε το πρώτα από εκεί.", + "uses": { + "product": "Προϊόν", + "category": "Κατηγορία" + }, + "pickTitle": "Επιλογή εικόνας", + "photo": "Φωτογραφία", + "uploadPhoto": "Ανέβασμα φωτογραφίας", + "replace": "Ανέβασμα άλλης", + "fromLibrary": "Από τη βιβλιοθήκη", + "removePhoto": "Αφαίρεση", + "nameAfterProduct": "Ονομασία με το όνομα του προϊόντος", + "nameAfterCategory": "Ονομασία με το όνομα της κατηγορίας" } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 6250974..b75bad7 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -46,7 +46,8 @@ "sessions": "Signed in now", "approvals": "Manager approvals", "deliveryFees": "Online ordering", - "qrCodes": "Table QR codes" + "qrCodes": "Table QR codes", + "media": "Media" }, "profile": { "edit": "Edit profile", @@ -702,5 +703,70 @@ "setup": "Connect the phone system", "setupBody": "In the Grandstream UCM, set the Action URL for incoming calls to this address (it only works from inside the venue):", "setupSecret": "For extra safety, set a key in Settings (caller_id.secret) and add &key= to the address." + }, + "media": { + "title": "Media", + "intro": "Every picture and video of the venue, in one place. Upload many at once, then pick them for products, categories and screens. The server keeps the original and makes smaller copies that load fast; the name is only for you.", + "upload": "Upload files", + "uploadNew": "Upload a new one", + "dropHint": "or drop files anywhere on this page", + "search": "Search by name", + "kind": "Kind", + "kinds": { + "all": "All", + "images": "Pictures", + "videos": "Videos", + "image": "Picture", + "video": "Video" + }, + "noMatch": "Nothing matches.", + "empty": "The library is empty.", + "emptyHint": "Upload your photos here, or add one straight from a product.", + "count_one": "{{count}} file", + "count_other": "{{count}} files", + "more": "Showing the newest {{shown}} of {{total}}. Search to find older ones.", + "uploading": "Uploading {{done}} of {{total}}…", + "uploaded": "Done: {{added}} added, {{existing}} already in the library, {{failed}} failed.", + "clearList": "Clear the list", + "alreadyThere": "already in the library", + "alreadyThereUsed": "This photo was already in the library as \"{{name}}\": using that one.", + "renamed": "Name saved.", + "deleted": "Deleted from the library.", + "deleteConfirm": "Delete this file for good?", + "delete": "Delete", + "close": "Close", + "resolution": "Resolution", + "length": "Length", + "fileSize": "File size", + "originalName": "Uploaded file", + "uploadedAt": "Uploaded", + "uploadedBy": "By", + "displayName": "Name", + "displayNameHint": "What you see in the library. The file itself keeps a name only the server uses.", + "saveName": "Save name", + "sizes": "Sizes made", + "sizesHint": "The server made these from the original; each screen loads the smallest one it needs.", + "sizesVideo": "Videos are kept as uploaded for now; smaller versions and a still frame come later.", + "variants": { + "thumb": "Small (lists)", + "card": "Card (menus)", + "full": "Large (full screen)", + "original": "Original" + }, + "usedBy": "Used by", + "unused": "Nothing uses it yet.", + "usedCantDelete": "A file in use can't be deleted. Remove it there first.", + "uses": { + "product": "Product", + "category": "Category" + }, + "pickTitle": "Pick a picture", + "photo": "Photo", + "uploadPhoto": "Upload a photo", + "replace": "Upload another", + "fromLibrary": "From the library", + "removePhoto": "Remove", + "nameAfterProduct": "Name it after the product", + "nameAfterCategory": "Name it after the category" } } diff --git a/packages/i18n/src/index.js b/packages/i18n/src/index.js index d541069..1ffc97b 100644 --- a/packages/i18n/src/index.js +++ b/packages/i18n/src/index.js @@ -16,6 +16,7 @@ export { I18nProvider } from './provider.jsx' export { useFormat, useLanguage, useUiLabels } from './hooks.js' export { createFormatters, toDate, DATE_STYLES } from './format.js' export { parseNumber } from './number.js' +export { latin } from './latin.js' export { SUPPORTED_LANGUAGES, FALLBACK_LANGUAGE, LANGUAGE_NAMES, DEFAULT_TIMEZONE, DEFAULT_CURRENCY, resolveLanguage, normalizeLanguage, intlLocale, diff --git a/packages/i18n/src/latin.js b/packages/i18n/src/latin.js new file mode 100644 index 0000000..d45b510 --- /dev/null +++ b/packages/i18n/src/latin.js @@ -0,0 +1,32 @@ +// Greek → Latin letters ("Greeklish"), for names that must be plain English characters, e.g. a +// media item named after its product ("Γύρος χοιρινός" → "Gyros xoirinos", plan step 5.2). +// The style follows how Greek venues write it themselves: χ → x, ξ → ks, η → i, υ → y, +// ου → ou, αυ / ευ → av / ev. Accents go; anything that still isn't plain ASCII is dropped. +const ONE = { + α: 'a', β: 'v', γ: 'g', δ: 'd', ε: 'e', ζ: 'z', η: 'i', θ: 'th', ι: 'i', κ: 'k', λ: 'l', μ: 'm', + ν: 'n', ξ: 'ks', ο: 'o', π: 'p', ρ: 'r', σ: 's', ς: 's', τ: 't', υ: 'y', φ: 'f', χ: 'x', ψ: 'ps', ω: 'o', +} +const TWO = { ου: 'ou', αυ: 'av', ευ: 'ev', γγ: 'ng', ει: 'ei', οι: 'oi', αι: 'ai' } + +function matchCase(src, out) { + return src === src.toLowerCase() ? out : out[0].toUpperCase() + out.slice(1) +} + +function word(w) { + let out = '' + for (let i = 0; i < w.length; i++) { + const two = TWO[w.slice(i, i + 2).toLowerCase()] + if (two) { out += matchCase(w[i], two); i++; continue } + const one = ONE[w[i].toLowerCase()] + out += one ? matchCase(w[i], one) : w[i] + } + // an all-caps word stays all caps ("ΘΕΑ" → "THEA", not "ThEA") + const letters = w.replace(/[^\p{L}]/gu, '') + return letters.length > 1 && letters === letters.toUpperCase() ? out.toUpperCase() : out +} + +/** Latin letters for Greek text; other text passes through (accents removed). */ +export function latin(text) { + const s = String(text ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').normalize('NFC') + return s.split(/(\s+)/).map(word).join('').replace(/[^\x20-\x7e]/g, '').replace(/\s+/g, ' ').trim() +} diff --git a/packages/i18n/tests/latin.test.mjs b/packages/i18n/tests/latin.test.mjs new file mode 100644 index 0000000..0066c8e --- /dev/null +++ b/packages/i18n/tests/latin.test.mjs @@ -0,0 +1,24 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { latin } from '../src/latin.js' + +test('Greek names in plain Latin letters, the way venues write them', () => { + assert.equal(latin('Γύρος χοιρινός'), 'Gyros xoirinos') + assert.equal(latin('Χυμός βύσσινο'), 'Xymos vyssino') + assert.equal(latin('Ούζο Πλωμαρίου'), 'Ouzo Plomariou') + assert.equal(latin('Σουβλάκι κοτόπουλο'), 'Souvlaki kotopoulo') + assert.equal(latin('Ψητά'), 'Psita') + assert.equal(latin('Φρέντο εσπρέσο'), 'Frento espreso') + assert.equal(latin('Ταξίδι'), 'Taksidi') + assert.equal(latin('Ευχή'), 'Evxi') + assert.equal(latin('Θεά'), 'Thea') +}) + +test('all caps stay all caps; Latin, digits and signs pass through', () => { + assert.equal(latin('ΘΕΑ'), 'THEA') + assert.equal(latin('ΜΠΥΡΑ 500ml'), 'MPYRA 500ml') + assert.equal(latin('Coca-Cola 330ml'), 'Coca-Cola 330ml') + assert.equal(latin('Café crème'), 'Cafe creme') + assert.equal(latin(' Pita 🌯 gyros '), 'Pita gyros') + assert.equal(latin(null), '') +})