Files
xenia-pos-local/tests/e2e/media.mjs
T
bonaminandClaude Opus 5.5 1eb7e5e3a9 feat(signage): gallery widget (pictures and videos one after another, from a list or a media folder); media folders on the Media page
Folders are only a grouping in the database (media_folders, media.folder_id, Alembic
0046): made, renamed, deleted (files stay) on the Media page, a file filed from its
details, uploads go into the folder shown, the picker filters by folder. The gallery
widget: its own pictures/videos in order or a folder as it is now, seconds each,
fade / slide / zoom, cover / contain. Plan 6R.16, F-114.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:41:17 +02:00

264 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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), video versions (5.4e)')
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')
// 5.4e: a phone video gets its still frame and a version every screen plays, in the background
const ff = execFileSync(PYTHON, ['-c', 'import imageio_ffmpeg as i; print(i.get_ffmpeg_exe())']).toString().trim()
const mov = path.join(OUT, 'IMG_0042.MOV')
execFileSync(ff, ['-hide_banner', '-loglevel', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc2=s=2560x1440:r=25:d=3', '-f', 'lavfi', '-i', 'sine=d=3',
'-c:v', 'libx265', '-x265-params', 'log-level=error', '-tag:v', 'hvc1', '-c:a', 'aac', '-shortest', mov])
await page.getByTestId('media-file-input').setInputFiles(mov)
const vidItem = page.locator('[data-testid="media-item"][data-name="IMG_0042"]')
r.check('5.4e: a phone video (HEVC .MOV, 2560 × 1440) goes into the library', await vidItem.waitFor({ timeout: 30_000 }).then(() => true).catch(() => false))
r.check('5.4e: …and its still frame shows in the grid by itself once the server made it (no reload)',
await vidItem.locator('img').waitFor({ timeout: 60_000 }).then(() => true).catch(() => false))
await vidItem.click()
const vstatus = page.getByTestId('media-video-status')
r.check('5.4e: details: "a version for every screen is ready", with its size listed',
await waitFor(async () => ((await vstatus.getAttribute('data-state').catch(() => null)) === 'ready' ? true : null), 60_000, 500)
&& await page.getByTestId('media-sizes').locator('li').count() === 5)
const vid = (await api('GET', '/api/media?kind=video', { token: boss })).items.find(i => i.name === 'IMG_0042')
const play = await fetch(backend.url + vid.urls.play, { headers: { range: 'bytes=0-15' } })
r.check('5.4e: the version plays as MP4 (seekable); the original MOV is kept as uploaded',
play.status === 206 && play.headers.get('content-type') === 'video/mp4' && vid.content_type === 'video/quicktime'
&& vid.bytes === statSync(mov).size, `${play.status} ${play.headers.get('content-type')}`)
await page.screenshot({ path: path.join(OUT, 'media-video.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.getByTestId('product-save').click(); await page.getByTestId('product-editor').waitFor({ state: 'detached', timeout: 10_000 }).catch(() => {}) }
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')
// ── 6R.16: folders: one made on the page, a file filed from its details, the folder shows only it ──
await page.getByTestId('media-folder-new').click()
await page.getByTestId('media-folder-name').fill('Dishes')
await page.getByTestId('media-folder-save').click()
const made = await waitFor(async () => (await page.locator('[data-testid="media-folder"][data-name="Dishes"]').getAttribute('aria-pressed').catch(() => null)) === 'true' || null, 8000, 200)
r.check('6R.16: a folder made on the Media page (and opened: empty)', made === true && (await page.getByTestId('media-item').count()) === 0)
await page.getByTestId('media-folder-all').click()
await page.locator(`[data-testid="media-item"][data-id="${after1.image.id}"]`).click()
await page.getByTestId('media-folder-pick').click()
await page.getByRole('option', { name: 'Dishes' }).click()
await sleep(600)
await page.keyboard.press('Escape')
await page.locator('[data-testid="media-folder"][data-name="Dishes"]').click()
r.check('6R.16: a file filed in it from its details; the folder shows just that file',
await waitFor(async () => (await page.getByTestId('media-item').count()) === 1 || null, 8000, 200) === true
&& (await page.locator('[data-testid="media-folder"][data-name="Dishes"]').textContent()).includes('1'))
// ── 5.3: the customer display's looks pick their pictures from the library ──
await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {})
await page.goto(`${MANAGER}/settings`)
await page.getByText('Customer display', { exact: true }).click()
await page.getByTestId('display-look-new').click({ timeout: 15_000 })
await page.getByTestId('display-look-new-name').fill('Promo')
await page.getByTestId('display-look-create').click()
await page.locator('[data-testid="display-look"][data-name="Promo"][aria-selected="true"]').waitFor({ timeout: 10_000 })
await page.getByTestId('display-style-slideshow').click()
await page.getByTestId('display-slides-add').click()
const picker = page.getByTestId('media-picker')
for (const i of [0, 1, 2]) await picker.getByTestId('media-item').nth(i).click()
await page.getByTestId('media-picker-add').click()
r.check('5.3: a new look "Promo": three pictures picked at once from the library, in order',
await page.getByTestId('display-slide-item').count() === 3)
await page.getByTestId('display-save').click()
await sleep(1000)
const looks = await api('GET', '/api/display/looks', { token: boss })
const promo = looks.find(l => l.name === 'Promo')
r.check('5.3: saved: the look is a slideshow of three library pictures; the default look is unchanged',
promo?.config.style === 'slideshow' && promo.config.slides.length === 3 && promo.preview.slide_urls.length === 3
&& looks.find(l => l.is_default)?.name === 'Main', JSON.stringify(looks.map(l => [l.name, l.config.style, l.config.slides])))
await page.screenshot({ path: path.join(OUT, 'media-display-looks.png'), fullPage: true })
const usedSlide = await api('DELETE', `/api/media/${promo.config.slides[0]}`, { token: boss }).then(() => 'deleted', e => e.message)
r.check('5.3: a picture in a look cannot be deleted from the library', usedSlide.includes('409'), usedSlide)
// ── 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)