diff --git a/docs/README.md b/docs/README.md index a78fcf6..b5f5d8f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -47,7 +47,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` | | `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) | | `local_backend/routers/customer_display.py`, `terminal/src/apps/customer-display/` | The customer display (3.4): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is the venue's design (`customer_display.idle`: name, logo, both, blank, image, slideshow, QR, a line of text, dark/light), images in `/app/data/display_media`, served by name at `/api/display/media/{name}` (public, LAN, random names). The POS's last state lives in memory | -| `local_backend/routers/media.py`, `services/media.py`, `models/media.py` | The media library (5.1): every picture and video once, by sha256, under `/app/data/media///` (original + `thumb`/`card`/`full` WebP for pictures; videos kept as uploaded). Served public by hash at `/api/media/file//` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). Whoever manages the menu, customer display, signage or menu tablets manages it. **Anything that points at a media item registers `register_usage(kind, fn)`** so delete is refused (`media.in_use`) while it's used. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` (the default 1 MB refused phone photos) | +| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media///` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file//` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` | | `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more | | `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | diff --git a/tests/e2e/lib/proc.mjs b/tests/e2e/lib/proc.mjs index ca49de8..7f1e992 100644 --- a/tests/e2e/lib/proc.mjs +++ b/tests/e2e/lib/proc.mjs @@ -72,7 +72,9 @@ export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKe SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret', // No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl. LICENSE_MODE: cloudUrl ? 'enforced' : 'off', - SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId), ...env, + SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId), + // the media library's files stay in this backend's own data folder (not /app/data) + XENIA_MEDIA_DIR: path.join(dataDir, 'media'), ...env, }, }) const url = `http://127.0.0.1:${port}` diff --git a/tests/e2e/media.mjs b/tests/e2e/media.mjs new file mode 100644 index 0000000..4e778f5 --- /dev/null +++ b/tests/e2e/media.mjs @@ -0,0 +1,197 @@ +// Media suite (plan step 5.2): the Media page takes a batch upload (the owner's ITEM PHOTOS +// folders when they are there: JPG, PNG, WebP, AVIF), shows an item's details and the sizes made; +// a product gets its photo from the library and another one uploaded on the spot ("Name it after +// the product"); a photo in use can't be deleted; the waiter's phone fetches the menu's photos +// ahead and still shows them with no connection. +// Starts its own backend (:8063), the manager (:5190) and the waiter's native-mode build (:5191). +// node media.mjs +import { spawn, execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, openSync, readdirSync, statSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { chromium } from 'playwright' +import { BROWSER_CHANNEL, CS, OUT, PYTHON, REPO, reporter, sleep, waitFor } from './lib/env.mjs' +import { killTree, login, startBackend, startViteNative, waitHttp } from './lib/proc.mjs' + +const backend = await startBackend({ port: 8063, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } }) +const MPORT = 5190 +const MANAGER = `http://localhost:${MPORT}` +const mlog = openSync(path.join(OUT, `vite-${MPORT}.log`), 'w') +const managerVite = spawn('npx', ['vite', '--port', String(MPORT), '--strictPort'], { + cwd: path.join(CS, 'manager_dashboard'), shell: process.platform === 'win32', detached: process.platform !== 'win32', + stdio: ['ignore', mlog, mlog], env: { ...process.env, XENIA_BACKEND: backend.url }, +}) +const waiterVite = await startViteNative({ port: 5191, backendUrl: backend.url }) +const WAITER = 'http://localhost:5191' +const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) +const r = reporter('media: Media page (batch upload, details), product photos (library + on the spot), waiter offline photos (5.2)') +const errors = [] +let failures = 0 + +async function api(method, url, { token, body } = {}) { + const res = await fetch(backend.url + url, { + method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }) + const text = await res.text() + let data = null + try { data = JSON.parse(text) } catch { data = text } + if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`) + return data +} + +/** The files to batch-upload: the owner's photo folders, or a few made here when they aren't in this checkout. */ +function photoFiles() { + const root = path.join(REPO, 'ITEM PHOTOS') + if (existsSync(root)) { + const files = readdirSync(root).flatMap(d => { + const dir = path.join(root, d) + return statSync(dir).isDirectory() ? readdirSync(dir).map(f => path.join(dir, f)) : [] + }).filter(f => /\.(jpe?g|png|webp|avif|gif)$/i.test(f)) + if (files.length) return { files, source: 'ITEM PHOTOS' } + } + const dir = path.join(OUT, 'media-photos') + mkdirSync(dir, { recursive: true }) + const made = ['souvlaki', 'gyros', 'salad', 'beer', 'frappe'].map((n, i) => { + const f = path.join(dir, `${n}.jpg`) + writeFileSync(f, execFileSync(PYTHON, ['-c', `import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(1200,900),(${40 * i},120,${200 - 30 * i})).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())`])) + return f + }) + return { files: made, source: 'generated' } +} + +const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ timeout }).then(() => true).catch(() => false) + +try { + await waitHttp(`${MANAGER}/`) + const boss = await login(backend.url) + await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {}) + + // ── Manager: the Media page, batch upload ────────────────────────────────── + const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } }) + const page = await ctx.newPage() + page.on('pageerror', e => errors.push(e.message)) + await page.goto(`${MANAGER}/login`) + await page.getByTestId('login-form').waitFor({ timeout: 60_000 }) + if (!(await page.getByTestId('login-account').count())) await page.getByLabel('Username').fill('manager') + await page.getByLabel('Password').fill('password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await page.waitForURL(u => u.pathname !== '/login', { timeout: 20_000 }) + + await page.goto(`${MANAGER}/management/media`) + r.check('Media page opens (Management → Media)', await shown(page, 'media-page', 20_000)) + r.check('the sidebar lists it', await page.getByRole('link', { name: 'Media' }).count() > 0) + const { files, source } = photoFiles() + await page.getByTestId('media-file-input').setInputFiles(files) + const finished = await waitFor(async () => { + const items = await page.getByTestId('media-queue-item').evaluateAll(els => els.map(e => e.dataset.status)) + return items.length === files.length && items.every(s => ['added', 'existing', 'failed'].includes(s)) ? items : null + }, 300_000, 1000) + const failed = await page.locator('[data-testid="media-queue-item"][data-status="failed"]').allInnerTexts() + r.check(`batch upload of ${files.length} files (${source}): every file in the library, none refused`, + !!finished && failed.length === 0, failed.join(' | ') || `${finished?.length}`) + await page.screenshot({ path: path.join(OUT, 'media-page.png'), fullPage: false }) + const lib = await api('GET', '/api/media?limit=500', { token: boss }) + const distinct = new Set(lib.items.map(i => i.sha256)).size + r.check('the library lists them (duplicates kept once)', lib.total > 0 && lib.total === distinct && lib.total <= files.length, `${lib.total}/${files.length}`) + if (source === 'ITEM PHOTOS') { + r.check('the AVIF photo went in too', lib.items.some(i => i.content_type === 'image/avif')) + } + r.check('the grid shows them all', await page.getByTestId('media-item').count() === lib.total) + + // details: sizes made, rename + await page.getByTestId('media-item').first().click() + r.check('details: the sizes the server made (small, card, large, original)', await shown(page, 'media-details') && + await page.getByTestId('media-sizes').locator('li').count() === 4) + await page.getByTestId('media-name').fill('Test photo renamed') + await page.getByTestId('media-rename').click() + await sleep(800) + const firstId = Number(await page.getByTestId('media-details').getAttribute('data-id')) + r.check('details: the display name changes', (await api('GET', `/api/media/${firstId}`, { token: boss })).name === 'Test photo renamed') + await page.screenshot({ path: path.join(OUT, 'media-details.png') }) + await page.keyboard.press('Escape') + + // ── A product's photo from the library, another one uploaded on the spot ──── + const products = await api('GET', '/api/products/?sold_at=in_store,in_store_takeaway', { token: boss }) + const [p1, p2] = products.filter(p => !p.is_service_item && p.lifecycle_status === 'active') + await page.goto(`${MANAGER}/management/products`) + const edit = async name => { + const row = page.locator(`[data-testid="product-row"][data-name="${name}"]`).first() + await row.waitFor({ timeout: 20_000 }) + await row.hover() + await row.getByTestId('product-edit').click() + await page.getByTestId('product-photo').waitFor({ timeout: 10_000 }) + } + const save = async () => { await page.getByRole('button', { name: 'Αποθήκευση', exact: true }).last().click(); await sleep(1200) } + + await edit(p1.name) + await page.getByTestId('product-photo').getByTestId('media-field-pick').click() + await page.getByTestId('media-picker').getByTestId('media-item').nth(1).click() + const pickedName = await page.getByTestId('product-photo').getByTestId('media-field-name').innerText() + r.check('product: "From the library" puts the picked photo on the form', !!pickedName) + r.check('product: no "Name it after" for a photo picked from the library', await page.getByTestId('media-field-name-after').count() === 0) + await save() + const after1 = (await api('GET', '/api/products/', { token: boss })).find(p => p.id === p1.id) + r.check('product: saved with the library photo (thumb / card / full)', after1.image?.name === pickedName && !!after1.image?.card && after1.image_url === after1.image.card, JSON.stringify(after1.image)) + + await edit(p2.name) + // a photo not yet in the library (else it would just reuse the existing one) + writeFileSync(path.join(OUT, 'media-onspot.jpg'), execFileSync(PYTHON, ['-c', "import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(1000,800),(7,77,177)).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())"])) + await page.getByTestId('product-photo').getByTestId('media-field-file').setInputFiles(path.join(OUT, 'media-onspot.jpg')) + const nameAfter = page.getByTestId('product-photo').getByTestId('media-field-name-after') + r.check('product: an upload on the spot offers "Name it after the product"', await nameAfter.waitFor({ timeout: 15_000 }).then(() => true).catch(() => false)) + await page.screenshot({ path: path.join(OUT, 'media-product-field.png') }) + await nameAfter.click() + await sleep(800) + const renamed = await page.getByTestId('product-photo').getByTestId('media-field-name').innerText() + r.check('product: the photo is named after the product in Latin letters', /^[\x20-\x7e]+$/.test(renamed) && renamed.length > 0, `${p2.name} → ${renamed}`) + await save() + const after2 = (await api('GET', '/api/products/', { token: boss })).find(p => p.id === p2.id) + r.check('product: saved with the photo uploaded on the spot', after2.image?.name === renamed, JSON.stringify(after2.image)) + + // a photo in use can't be deleted + await page.goto(`${MANAGER}/management/media`) + await page.locator(`[data-testid="media-item"][data-id="${after1.image.id}"]`).click() + await page.getByTestId('media-used-by').waitFor({ timeout: 10_000 }).catch(() => {}) + r.check('a photo in use: the details say what uses it and delete is off', + (await page.getByTestId('media-used-by').innerText().catch(() => '')).includes(p1.name) && await page.getByTestId('media-delete').isDisabled()) + await page.keyboard.press('Escape') + + // ── The waiter's phone: photos fetched ahead, shown offline ───────────────── + const phone = await browser.newContext({ viewport: { width: 393, height: 852 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }) + const w = await phone.newPage() + w.on('pageerror', e => errors.push(e.message)) + await w.goto(`${WAITER}/login`) + await w.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 30_000 }) + for (const d of '3302') await w.getByRole('button', { name: d, exact: true }).first().click() + await w.waitForURL(u => u.pathname !== '/login', { timeout: 15_000 }).catch(() => {}) + await w.getByRole('button', { name: /Start shift/ }).click({ timeout: 10_000 }).catch(() => {}) + await w.waitForURL(u => u.pathname.startsWith('/tables'), { timeout: 15_000 }).catch(() => {}) + const cards = [after1.image.card, after2.image.card] + const fetched = await waitFor(async () => { + const got = await w.evaluate(() => performance.getEntriesByType('resource').map(e => e.name)) + return cards.every(c => got.some(u => u.endsWith(c))) ? true : null + }, 30_000, 1000) + r.check("waiter: the menu's photos are fetched ahead (before any screen shows them)", !!fetched) + await phone.setOffline(true) + const offline = await w.evaluate(async ({ urls, base }) => Promise.all(urls.map(u => new Promise(res => { + const img = new Image() + img.onload = () => res(img.naturalWidth) + img.onerror = () => res(0) + img.src = base + u + }))), { urls: cards, base: backend.url }) + r.check('waiter: offline, both photos still show (from the phone\'s cache)', offline.every(n => n > 0), JSON.stringify(offline)) + await phone.setOffline(false) + await phone.close() + + r.check('no page errors', errors.length === 0, errors.join(' | ')) + failures += r.done() +} catch (e) { + console.error(e) + failures += 1 + r.done() +} finally { + await browser.close() + waiterVite.stop() + killTree(managerVite) + await backend.stop() +} +process.exit(failures ? 1 : 0) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index 3197655..69317f7 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -25,6 +25,7 @@ const suites = [ ['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E], ['waiter (sign-in, keys, prices, languages, history, look, bookings)', 'node', ['waiter.mjs'], E2E], ['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E], + ['media (Media page, product photos, waiter offline photos)', 'node', ['media.mjs'], E2E], ['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E], ['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E], ['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E],