diff --git a/docs/README.md b/docs/README.md index cd72a79..9d53d4d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -178,6 +178,8 @@ Routers are mounted from the module manifests (`local_backend/modules//mani Use `core.access.deps.require("..")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. A role's defaults are the manifests' plus the venue's changes (`role_permissions`, Settings → Operation → "What each role may do"): create users with `apply_role_template(user, db)`, and a **new key added to a role later must be granted to existing users of that role in its Alembic revision** (keys are copied at creation; see 0024). In endpoints a waiter can reach, check keys with `authorize(request, db, user, key)` (module, device scope, key, manager approval → `access.denied` / `access.override_possible`); the apps read `permissions` and `approvable` from bootstrap (`useAllowed(key)` → `yes` / `approve` / `no`), never a venue switch for what a person may do. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans are gone (step 2.99): `UserOut` carries only `permissions` (keys). **Apps never send a price (step 4.4).** Order lines go by id (`services/pos_cart.py`'s line: product, quick add-ons, extras with sub-choices, preferences, removed ingredients) to `POST /api/orders/{id}/items` (the waiter, the manager's ordering tab) or the counter's `/api/pos/*`; the server prices them through `orders.add_priced_items`, the one function that writes order items with prices. A line carrying prices or `selected_options` is refused (`order.line.client_price`), so is the shape before 4.4 (`items` → `order.lines_required`); a by-hand change (`price_adjustment`) needs `ordering.prices.modify` or a manager's approval. Totals before sending come from `POST /api/orders/quote` (the counter: `/api/pos/quote`), the same code; offline an app may show its menu's prices only as an estimate. Apps whose cart keeps the stored `selected_options` shape build lines with `@xenia/api` `wireLine` / `lineFromOptions` (an option no longer on the menu throws `LineError`, never dropped). A preference set left out of a line takes its default, and a set at its free default isn't stored (tickets show only what differs). + +**Waiter texts (step 4.5).** The waiter app has no text of its own: every label is a key in `packages/i18n/locales/{en,el}/waiter.json` (English first, Greek as the translation), read with `useTranslation('waiter')` in components and `tw('key')` (`waiter_pwa/src/i18n.js`) outside them; money with `useFormat().formatMoney` or `money()` from the same file, times with `useFormat()` (venue clock). `waiter_pwa/tests/no-greek.test.mjs` fails on any Greek letter in `waiter_pwa/src` (a Greek word the code must recognise is written with `\u` escapes). Don't name a variable `t` in a component that translates. The language is per person (user menu, saved with `PATCH /api/auth/me`), else the venue's. The e2e suites run the waiter in English (the test venue's language). Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: ` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `.*`) and only reach routes of those modules. A new device app with user logins must declare `.access`. Per-device settings are `ConfigField`s in `DeviceApp.config` (validated by `core/modules/device_config.py`, rendered by the manager's `DeviceConfigFields`), each with texts `modules:.config..label` (+ `.choices.`), never free JSON. Device-only endpoints use `require_device("")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header. Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent). diff --git a/packages/i18n/locales/el/waiter.json b/packages/i18n/locales/el/waiter.json index 342a80f..ce40985 100644 --- a/packages/i18n/locales/el/waiter.json +++ b/packages/i18n/locales/el/waiter.json @@ -657,5 +657,117 @@ "summaryModal": { "edit": "Επεξεργασία", "title": "Επισκόπηση Παραγγελίας" + }, + "log": { + "printProblem": "Πρόβλημα Εκτύπωσης", + "cancelPrint": "Ακύρωση Εκτύπωσης", + "ok": "Επιτυχής", + "failedF": "Αποτυχημένη", + "range": "Εύρος ημερομηνίας/ώρας", + "from": "Από", + "to": "Έως", + "clearDates": "Καθαρισμός ημερομηνίας", + "fiscal": "Φορολογική εκτύπωση", + "print": "Εκτύπωση", + "holdForOptions": "Κρατήστε πατημένο για επιλογές", + "titleShort": "Αρχ. Παραγγ.", + "searchPlaceholder": "Τραπέζι, #παραγγελία, αντικείμενο…", + "orderLine": "Παραγγελία #{{id}} · {{table}} · {{time}}", + "retries_one": "{{count}} επανάληψη", + "retries_other": "{{count}} επαναλήψεις", + "printNow": "Εκτύπωση Τώρα", + "pending": "Εκκρεμεί…", + "failed": "Αποτυχία", + "pendingRetries": "Εκκρεμεί ({{count}} επαν.)", + "itemsShort": "{{count}} αντ.", + "printProblems_one": "{{count}} παραγγελία με πρόβλημα εκτύπωσης", + "printProblems_other": "{{count}} παραγγελίες με πρόβλημα εκτύπωσης", + "printFailed": "Αποτυχημένη εκτύπωση", + "printOk": "Επιτυχής εκτύπωση", + "noneFound": "Δεν βρέθηκαν παραγγελίες", + "noneThisShift": "Δεν υπάρχουν παραγγελίες σε αυτή τη βάρδια", + "detailedView": "Λεπτομερής προβολή", + "compactView": "Συμπαγής προβολή", + "cancel": "Ακύρωση" + }, + "shiftPage": { + "none": "Δεν υπάρχει ενεργή βάρδια", + "noneSub": "Ξεκινήστε βάρδια για να δείτε στατιστικά.", + "onBreak": "Σε διάλειμμα", + "start": "Έναρξη", + "worked": "Ώρες Εργασίας", + "startCash": "Αρχ. Μετρητά", + "collected": "Είσπραξη", + "toHandIn": "Παραδ. Ποσό", + "toHandInSub": "Αρχ. + Είσπραξη", + "openTables": "Ανοιχτά Τραπέζια", + "openTablesSub": "τρέχουσες παραγγελίες", + "items": "Είδη (ανοιχτά)", + "breaks": "Διαλείμματα", + "perHour": "Ανά Ώρα", + "itemsShort": "Είδη", + "now": "Τώρα", + "breakSince": "από {{time}} · {{duration}} μέχρι τώρα", + "breaksSub": "{{duration}} διαλείμματα", + "totalSub": "{{duration}} σύνολο", + "breaksCount": "Διαλείμματα ({{count}})" + }, + "chat": { + "group": "Ομάδα", + "unknown": "Άγνωστος", + "deleted": "Το μήνυμα διαγράφηκε", + "noMessages": "Δεν υπάρχουν μηνύματα", + "usersFailed": "Αποτυχία φόρτωσης χρηστών", + "createFailed": "Σφάλμα δημιουργίας συνομιλίας", + "groupFailed": "Σφάλμα δημιουργίας ομάδας", + "new": "Νέα Συνομιλία", + "newGroup": "Νέα Ομάδα", + "noStaff": "Δεν υπάρχει άλλο προσωπικό", + "groupName": "Όνομα Ομάδας", + "groupNamePlaceholder": "π.χ. Βραδινή βάρδια", + "next": "Επόμενο", + "pickMembers": "Επιλογή Μελών", + "startHint": "Πατήστε «Νέα Συνομιλία» για να ξεκινήσετε μια συζήτηση.", + "now": "τώρα", + "yesterday": "χθες", + "creating": "Δημιουργία…", + "createGroup": "Δημιουργία Ομάδας", + "createGroupCount": "Δημιουργία Ομάδας ({{count}})", + "groupLabel": "Ομάδα:", + "leaveTitle": "Αποχώρηση από ομάδα;", + "leaveBody": "Δεν θα λαμβάνετε πλέον μηνύματα από αυτή την ομάδα.", + "leave": "Αποχώρηση", + "conversation": "Συνομιλία", + "loadingOlder": "Φόρτωση παλαιότερων…", + "placeholder": "Γράψτε μήνυμα…", + "today": "Σήμερα", + "yesterdayCap": "Χθες", + "members_one": "{{count}} μέλος", + "members_other": "{{count}} μέλη", + "emptyThread": "Δεν υπάρχουν μηνύματα ακόμα.", + "sayHi": "Πείτε γεια!" + }, + "offline": { + "title": "Δεν υπάρχει σύνδεση", + "body": "Δεν είναι δυνατή η επικοινωνία με το σύστημα. Ελέγξτε τη σύνδεση WiFi.", + "notFound": "Ο server δεν βρέθηκε στο δίκτυο. Ελέγξτε ότι είναι αναμμένος, ή σαρώστε ξανά το QR από τον διαχειριστή.", + "changeVenue": "Αλλαγή καταστήματος", + "searching": "Αναζήτηση… {{done}}/{{total}}", + "search": "Αναζήτηση server στο δίκτυο", + "moved": "Ο server άλλαξε διεύθυνση", + "reconnecting": "Επανασύνδεση…" + }, + "refused": { + "title": "Δεν στάλθηκαν", + "body": "Τα παρακάτω πάρθηκαν χωρίς σύνδεση και ο server δεν τα δέχτηκε. Ελέγξτε τα τραπέζια.", + "ok": "Το είδα", + "oldFormat": "Παλιά μορφή παραγγελίας: προσθέστε το ξανά", + "notAccepted": "Ο server δεν το δέχτηκε" + }, + "notify": { + "tables_one": "Τραπέζι: {{tables}}", + "tables_other": "Τραπέζια: {{tables}}", + "more_one": "+{{count}} ακόμα μήνυμα", + "more_other": "+{{count}} ακόμα μηνύματα" } } diff --git a/packages/i18n/locales/en/waiter.json b/packages/i18n/locales/en/waiter.json index 79fb390..15e318c 100644 --- a/packages/i18n/locales/en/waiter.json +++ b/packages/i18n/locales/en/waiter.json @@ -657,5 +657,117 @@ "summaryModal": { "edit": "Edit", "title": "Order summary" + }, + "log": { + "printProblem": "Print problem", + "cancelPrint": "Cancel printing", + "ok": "Succeeded", + "failedF": "Failed", + "range": "Date / time range", + "from": "From", + "to": "To", + "clearDates": "Clear the dates", + "fiscal": "Fiscal receipt", + "print": "Printing", + "holdForOptions": "Press and hold for options", + "titleShort": "Order log", + "searchPlaceholder": "Table, #order, item…", + "orderLine": "Order #{{id}} · {{table}} · {{time}}", + "retries_one": "{{count}} retry", + "retries_other": "{{count}} retries", + "printNow": "Print now", + "pending": "Pending…", + "failed": "Failed", + "pendingRetries": "Pending ({{count}} retries)", + "itemsShort": "{{count}} it.", + "printProblems_one": "{{count}} order with a print problem", + "printProblems_other": "{{count}} orders with a print problem", + "printFailed": "Printing failed", + "printOk": "Printed", + "noneFound": "No orders found", + "noneThisShift": "No orders in this shift", + "detailedView": "Detailed view", + "compactView": "Compact view", + "cancel": "Cancel" + }, + "shiftPage": { + "none": "No active shift", + "noneSub": "Start a shift to see the numbers.", + "onBreak": "On a break", + "start": "Started", + "worked": "Hours worked", + "startCash": "Starting cash", + "collected": "Collected", + "toHandIn": "To hand in", + "toHandInSub": "Start + collected", + "openTables": "Open tables", + "openTablesSub": "current orders", + "items": "Items (open)", + "breaks": "Breaks", + "perHour": "Per hour", + "itemsShort": "Items", + "now": "Now", + "breakSince": "since {{time}} · {{duration}} so far", + "breaksSub": "{{duration}} breaks", + "totalSub": "{{duration}} in all", + "breaksCount": "Breaks ({{count}})" + }, + "chat": { + "group": "Group", + "unknown": "Unknown", + "deleted": "The message was deleted", + "noMessages": "No messages", + "usersFailed": "Couldn't load the staff", + "createFailed": "Couldn't start the conversation", + "groupFailed": "Couldn't create the group", + "new": "New conversation", + "newGroup": "New group", + "noStaff": "No other staff", + "groupName": "Group name", + "groupNamePlaceholder": "e.g. Evening shift", + "next": "Next", + "pickMembers": "Choose members", + "startHint": "Tap «New conversation» to start one.", + "now": "now", + "yesterday": "yesterday", + "creating": "Creating…", + "createGroup": "Create group", + "createGroupCount": "Create group ({{count}})", + "groupLabel": "Group:", + "leaveTitle": "Leave the group?", + "leaveBody": "You won't get messages from this group any more.", + "leave": "Leave", + "conversation": "Conversation", + "loadingOlder": "Loading older messages…", + "placeholder": "Write a message…", + "today": "Today", + "yesterdayCap": "Yesterday", + "members_one": "{{count}} member", + "members_other": "{{count}} members", + "emptyThread": "No messages yet.", + "sayHi": "Say hello!" + }, + "offline": { + "title": "No connection", + "body": "Can't reach the system. Check the WiFi connection.", + "notFound": "The server wasn't found on the network. Check that it's on, or scan the QR code from the manager again.", + "changeVenue": "Change venue", + "searching": "Searching… {{done}}/{{total}}", + "search": "Search the network for the server", + "moved": "The server changed address", + "reconnecting": "Reconnecting…" + }, + "refused": { + "title": "Not sent", + "body": "These were taken offline and the server didn't accept them. Check the tables.", + "ok": "Got it", + "oldFormat": "Old order format: add it again", + "notAccepted": "The server didn't accept it" + }, + "notify": { + "tables_one": "Table: {{tables}}", + "tables_other": "Tables: {{tables}}", + "more_one": "+{{count}} more message", + "more_other": "+{{count}} more messages" } } diff --git a/tests/e2e/android.mjs b/tests/e2e/android.mjs index 73fe599..27750f3 100644 --- a/tests/e2e/android.mjs +++ b/tests/e2e/android.mjs @@ -54,28 +54,28 @@ async function basics() { let v = await freshApp() await typeInto(v, `${H}:9999`) - await tap(v, 'button', 'Σύνδεση') + await tap(v, 'button', 'Connect') await sleep(6500) - r.check('wrong address → "no server" error', (await v.evaluate('document.body.innerText')).includes('Δεν βρέθηκε server')) + r.check('wrong address → "no server" error', (await v.evaluate('document.body.innerText')).includes('No server found')) await typeInto(v, `http://${H}:8055/?pair=some-other-site`) - await tap(v, 'button', 'Σύνδεση') + await tap(v, 'button', 'Connect') await sleep(3000) - r.check("another venue's QR → refused", (await v.evaluate('document.body.innerText')).includes('διαφορετικό κατάστημα')) + r.check("another venue's QR → refused", (await v.evaluate('document.body.innerText')).includes('A different venue')) await typeInto(v, `${H}:8055`) - await tap(v, 'button', 'Σύνδεση') + await tap(v, 'button', 'Connect') await sleep(5000) v = await attach() const st = await venuesState(v) r.check('pairing saves and activates the venue', st?.active === 'test-site-1' && st.venues['test-site-1'].baseUrl.includes(`${H}:`), JSON.stringify(st)) - r.check('login screen shows the venue + "Αλλαγή"', (await v.evaluate('document.body.innerText')).includes('Αλλαγή')) + r.check('login screen shows the venue + "Change"', (await v.evaluate('document.body.innerText')).includes('Change')) // 4.2: a real sign-in in the native app: pick your name, PIN on the pad, start the shift await fetch(`${b1.url}/api/business-day/open`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, body: '{}' }).catch(() => {}) await tap(v, '[data-testid="waiter-card"]', 'Κωνσταντίνου') for (const d of '3302') await tap(v, 'button.pin-btn', d) - await tap(v, 'button', 'Έναρξη Βάρδιας', { timeout: 15_000 }) + await tap(v, 'button', 'Start shift', { timeout: 15_000 }) await waitFor(() => v.evaluate("location.pathname === '/tables'"), 15_000, 500) await sleep(3000) r.check('signed in with name + PIN on the pad: /tables', (await v.evaluate('location.pathname')) === '/tables' @@ -86,7 +86,7 @@ async function basics() { // 4.2: lock from the menu, unlock with the PIN on the pad (same session) const before = await v.evaluate("localStorage.getItem('xenia:test-site-1:token')") - await tap(v, 'button[title="Μενού χρήστη"]') + await tap(v, '[data-testid="user-menu"]') await tap(v, '[data-testid="menu-lock"]') const lockedOk = await waitFor(() => v.evaluate("!!document.querySelector('[data-testid=lock-screen]')"), 5000, 300) for (const d of '3302') await tap(v, '[data-testid="lock-screen"] button.pin-btn', d) @@ -102,9 +102,9 @@ async function basics() { r.check('restart: still paired and logged in', (await v.evaluate('location.pathname')) === '/tables') // venues - await tap(v, 'button[title="Μενού χρήστη"]') + await tap(v, '[data-testid="user-menu"]') await sleep(600) - await tap(v, 'button.user-menu-item', 'Κατάστημα') + await tap(v, 'button.user-menu-item', 'Venue') await sleep(1200) r.check('user menu → /venues', (await v.evaluate('location.pathname')) === '/venues') back() @@ -113,14 +113,14 @@ async function basics() { await goTo(v, '/venues') await sleep(1000) await typeInto(v, `${H}:8056`) - await tap(v, 'button', 'Σύνδεση') + await tap(v, 'button', 'Connect') await sleep(5000) v = await attach() let vs = await venuesState(v) r.check('second venue paired and active', vs.active === 'test-site-2' && Object.keys(vs.venues).length === 2) const path2 = await v.evaluate('location.pathname') r.check('second venue starts logged out (own session)', path2 === '/login', `${path2} ${JSON.stringify(vs)}`) - await tap(v, 'button', 'Αλλαγή') + await tap(v, 'button', 'Change') await sleep(1200) await tap(v, 'button', `${H}:8055`) await sleep(5000) @@ -139,14 +139,14 @@ async function basics() { v = await relaunch() await goTo(v, '/venues') await sleep(1000) - await tap(v, 'button', 'Σάρωση QR') + await tap(v, 'button', 'Scan QR') await sleep(2500) r.check(`camera ${label}: permission prompt shown`, /GrantPermissions/.test(focusedWindow())) tapDialogButton(button) await sleep(label === 'deny' ? 2000 : 4000) if (label === 'deny') { r.check('camera deny: asked only once', !/GrantPermissions/.test(focusedWindow())) - r.check('camera deny: explains the missing permission', (await v.evaluate('document.body.innerText')).includes('Δεν δόθηκε άδεια κάμερας')) + r.check('camera deny: explains the missing permission', (await v.evaluate('document.body.innerText')).includes("Camera permission wasn't given")) } else { const video = await v.evaluate("(() => { const x = document.querySelector('video'); return { ready: x.readyState, w: x.videoWidth, paused: x.paused } })()") r.check('camera allow: live preview', video.ready >= 2 && video.w > 0 && !video.paused, JSON.stringify(video)) @@ -219,8 +219,8 @@ async function rediscovery() { const offlineShown = await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/offline', 45_000) r.check('server really down: saved address untouched', (await venuesState(v)).venues['test-site-1'].baseUrl.includes('.99:')) r.check('server really down: offline screen', !!offlineShown, await v.evaluate('location.pathname + " | " + document.body.innerText.slice(0, 200)').catch(e => String(e))) - await v.evaluate("[...document.querySelectorAll('button')].find(e => e.textContent.includes('Αναζήτηση server')).click()") - const notFound = await waitFor(async () => (await v.evaluate('document.body.innerText')).includes('Ο server δεν βρέθηκε'), 60_000) + await v.evaluate("[...document.querySelectorAll('button')].find(e => e.textContent.includes('Search the network')).click()") + const notFound = await waitFor(async () => (await v.evaluate('document.body.innerText')).includes("The server wasn't found"), 60_000) r.check('manual search ends with "not found" guidance', !!notFound) // cold start while the server is down keeps the login @@ -272,11 +272,11 @@ server { listen 443 ssl; ssl_certificate /t/cert.pem; ssl_certificate_key /t/key // ── TLS ─────────────────────────────────────────────────────────────────── let v = await freshApp() await typeInto(v, qr('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=')) - await tap(v, 'button', 'Σύνδεση') + await tap(v, 'button', 'Connect') await sleep(4000) - r.check('TLS: QR with a wrong key → refused', (await v.evaluate('document.body.innerText')).includes('κλειδί ασφαλείας')) + r.check('TLS: QR with a wrong key → refused', (await v.evaluate('document.body.innerText')).includes('security key')) await typeInto(v, qr(pin)) - await tap(v, 'button', 'Σύνδεση') + await tap(v, 'button', 'Connect') await sleep(6000) v = await attach() let ven = (await venuesState(v)).venues['test-site-1'] @@ -344,7 +344,8 @@ server { listen 443 ssl; ssl_certificate /t/cert.pem; ssl_certificate_key /t/key serve({ ...manifest, version: 'e2e-new-apk', min_shell_build: 99 }) await bgAndBack(); await sleep(8000); v = await attach() - r.check('bundles: needs a newer APK → skipped + banner', (await current()) === 'e2e-staged' && (await v.evaluate('document.body.innerText')).includes('νεότερη έκδοση της εφαρμογής')) + const newer = { cur: await current(), text: await v.evaluate('document.body.innerText').catch(e => String(e)) } + r.check('bundles: needs a newer APK → skipped + banner', newer.cur === 'e2e-staged' && newer.text.includes('needs a newer version of the app'), `${newer.cur} | ${newer.text.replace(/\s+/g, ' ').slice(0, 160)}`) const broken = zipSync({ 'index.html': strToU8('

broken bundle

') }) execFileSync('docker', ['exec', '-i', WAITER1, 'sh', '-c', `cat > ${DL}/waiter-bundle-broken.zip`], { input: Buffer.from(broken) }) @@ -354,9 +355,10 @@ server { listen 443 ssl; ssl_certificate /t/cert.pem; ssl_certificate_key /t/key await bgAndBack() await waitFor(async () => { v = await attach(); return (await v.evaluate('document.body.innerText')).includes('broken bundle') }, 40_000, 1500) const rolledBack = await waitFor(async () => { v = await attach(); return (await current()) === 'e2e-staged' }, 60_000, 2000) - r.check('bundles: broken bundle rolled back automatically', !!rolledBack) + r.check('bundles: broken bundle rolled back automatically', !!rolledBack, String(await current())) await sleep(70000); await bgAndBack(); await sleep(12000); v = await attach() - r.check('bundles: no retry loop, broken version blocklisted', (await current()) === 'e2e-staged' && (await v.evaluate("localStorage.getItem('xenia.bundleFailed') || ''")).includes('e2e-broken')) + const after = { cur: await current(), failed: await v.evaluate("localStorage.getItem('xenia.bundleFailed') || ''").catch(e => String(e)) } + r.check('bundles: no retry loop, broken version blocklisted', after.cur === 'e2e-staged' && after.failed.includes('e2e-broken'), JSON.stringify(after)) serve(manifest) // ── two venues, each on its own bundle ───────────────────────────────────── @@ -366,7 +368,7 @@ server { listen 443 ssl; ssl_certificate /t/cert.pem; ssl_certificate_key /t/key v = await attach() await goTo(v, '/venues'); await sleep(1200) await typeInto(v, `http://${H}:28080/?${new URLSearchParams({ pair: 'test-site-2', k: pin2 })}`) - await tap(v, 'button', 'Σύνδεση') + await tap(v, 'button', 'Connect') v.close() let s = await waitFor(async () => { const st = await state(); return st.active === 'test-site-2' && st.current === m2.version && st }, 90_000, 2000) r.check('bundles: pairing venue 2 → venue 2 bundle', !!s) diff --git a/tests/e2e/browser.mjs b/tests/e2e/browser.mjs index 455c554..2a44c53 100644 --- a/tests/e2e/browser.mjs +++ b/tests/e2e/browser.mjs @@ -75,7 +75,7 @@ try { // ── Install-app dialog + drawer entry ───────────────────────────────────── const r2 = reporter('browser: install-app dialog') const phone = ua => browser.newContext({ userAgent: ua, viewport: { width: 393, height: 852 }, deviceScaleFactor: 2.75, isMobile: true, hasTouch: true }) - const dialog = page => page.getByRole('dialog', { name: 'Εφαρμογή Xenia' }) + const dialog = page => page.getByRole('dialog', { name: 'The Xenia app' }) const hamburger = page => page.locator('button').filter({ has: page.locator('svg') }).first() let ctx = await phone(ANDROID_UA) @@ -85,21 +85,21 @@ try { r2.check('first visit on Android: dialog opens by itself', await dialog(page).isVisible()) const box = await dialog(page).boundingBox() r2.check('dialog is taller than wide', box && box.height > box.width, box ? `${Math.round(box.width)}×${Math.round(box.height)}` : '') - r2.check('download link points at the APK', (await page.getByRole('link', { name: 'Λήψη εφαρμογής' }).getAttribute('href')) === '/downloads/xenia-waiter.apk') + r2.check('download link points at the APK', (await page.getByRole('link', { name: 'Download the app' }).getAttribute('href')) === '/downloads/xenia-waiter.apk') await page.screenshot({ path: path.join(OUT, 'install-dialog.png') }) - await page.getByRole('button', { name: 'Όχι τώρα' }).click() + await page.getByRole('button', { name: 'Not now' }).click() await sleep(400) await page.reload() await sleep(3500) - r2.check('"Όχι τώρα" → never opens by itself again', !(await dialog(page).isVisible())) + r2.check('"Not now" → never opens by itself again', !(await dialog(page).isVisible())) await page.evaluate(t => localStorage.setItem('token', t), token) await page.goto(`http://${LAN}:15173/tables`) await sleep(4000) await hamburger(page).click() await sleep(600) - const install = page.getByRole('button', { name: 'Εγκατάσταση εφαρμογής' }) + const install = page.getByRole('button', { name: 'Install the app' }) const [ib, sb] = [await install.boundingBox(), await page.getByRole('button', { name: 'Settings' }).boundingBox()] - r2.check('drawer shows "Εγκατάσταση εφαρμογής" right above Settings', !!(ib && sb && ib.y < sb.y && sb.y - ib.y < 80)) + r2.check('drawer shows "Install the app" right above Settings', !!(ib && sb && ib.y < sb.y && sb.y - ib.y < 80)) await install.click() await sleep(500) r2.check('drawer entry reopens the dialog', await dialog(page).isVisible()) @@ -115,7 +115,7 @@ try { const noDialog = !(await dialog(page).isVisible()) await hamburger(page).click() await sleep(500) - r2.check(`${label}: never offered (no dialog, no drawer entry)`, noDialog && !(await page.getByRole('button', { name: 'Εγκατάσταση εφαρμογής' }).isVisible())) + r2.check(`${label}: never offered (no dialog, no drawer entry)`, noDialog && !(await page.getByRole('button', { name: 'Install the app' }).isVisible())) await ctx.close() } ctx = await phone(ANDROID_UA) diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index 2e147e5..373413f 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -15,7 +15,7 @@ const vite = await startViteNative({ port: 5181, backendUrl: backend.url }) const APP = 'http://localhost:5181' const TOKEN_KEY = 'xenia:dev:token' const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) -const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3), server prices (4.4)') +const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3), server prices (4.4), languages (4.5)') const errors = [] let failures = 0 @@ -77,7 +77,7 @@ try { r.check('the session is a "waiter" session', sessions.some(s => s.username === 'demo_maria' && s.client === 'waiter'), JSON.stringify(sessions.map(s => [s.username, s.client]))) // start the shift on the phone (the gate after sign-in) - await a.getByRole('button', { name: /Έναρξη Βάρδιας/ }).click({ timeout: 10_000 }).catch(() => {}) + await a.getByRole('button', { name: /Start shift/ }).click({ timeout: 10_000 }).catch(() => {}) await a.waitForURL(u => u.pathname.startsWith('/tables'), { timeout: 10_000 }).catch(() => {}) await sleep(1500) @@ -94,7 +94,7 @@ try { // ── Lock from the menu, wrong PIN, right PIN (same session) ──────────────── await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 }) await a.getByTestId('menu-lock').click() - r.check('menu "Κλείδωμα" locks the phone', await shown(a, 'lock-screen', 5000)) + r.check('menu "Lock" locks the phone', await shown(a, 'lock-screen', 5000)) await a.reload() r.check('still locked after the app is reopened', await shown(a, 'lock-screen', 10_000)) await pin(a, '0000') @@ -132,9 +132,9 @@ try { await sleep(800) const sheet = await a.locator('.modal-sheet--top').innerText().catch(() => '') r.check('4.3: the actions follow the keys (transfer yes, discount hidden, cancel "with a manager\'s PIN")', - sheet.includes('Μεταφορά Τραπεζιού') && !sheet.includes('Εφαρμογή Έκπτωσης') && sheet.includes('Με έγκριση διαχειριστή'), sheet.replace(/\s+/g, ' ').slice(0, 300)) - await a.getByText('Ακύρωση Παραγγελίας', { exact: true }).click() - await a.getByRole('button', { name: 'Ακύρωση ✕' }).click() + sheet.includes('Transfer the table') && !sheet.includes('Apply a discount') && sheet.includes("With a manager's approval"), sheet.replace(/\s+/g, ' ').slice(0, 300)) + await a.getByText('Cancel order', { exact: true }).click() + await a.getByRole('button', { name: 'Cancel ✕' }).click() const dlg = a.getByRole('dialog') await dlg.waitFor({ timeout: 10_000 }).catch(() => {}) r.check('4.3: cancelling from the screen opens the approval dialog', await a.getByTestId('override-key').textContent().catch(() => '') === 'ordering.orders.cancel') @@ -192,10 +192,10 @@ try { const exact = await waitFor(async () => await total().getAttribute('data-estimated') === 'false', 10_000, 300) const shownTotal = await total().innerText().catch(() => '') r.check('4.4: the cart total is the server\'s price (a price the phone\'s menu doesn\'t know)', !!exact && shownTotal.includes('2.40'), shownTotal.replace(/\s+/g, ' ')) - await a.getByRole('button', { name: /^(ΑΠΟΣΤΟΛΗ|ΣΥΝΟΨΗ)/ }).last().click() + await a.getByRole('button', { name: /^(SEND|SUMMARY)/ }).last().click() if (await shown(a, 'summary-total', 3000)) { r.check('4.4: the summary shows the same total', (await a.getByTestId('summary-total').innerText()).includes('2.40')) - await a.getByRole('button', { name: /ΑΠΟΣΤΟΛΗ/ }).last().click() + await a.getByRole('button', { name: /SEND/ }).last().click() } const sent = await waitFor(async () => { const st = await api('GET', `/api/tables/${t4.id}/status`, { token: boss }) @@ -212,7 +212,7 @@ try { await addOn(t5.id, plain) await ctxA.setOffline(true) await a.getByTestId('cart-open').click() - const wentOffline = await waitFor(async () => (await total().innerText().catch(() => '')).includes('χωρίς σύνδεση'), 30_000, 1000) + const wentOffline = await waitFor(async () => (await total().innerText().catch(() => '')).includes('offline'), 30_000, 1000) const est = await total().getAttribute('data-estimated').catch(() => null) r.check('4.4: offline the cart total is an estimate (≈, the menu prices)', !!wentOffline && est === 'true' && (await total().innerText()).includes('≈'), `${wentOffline} ${est} ${await total().innerText().catch(() => '')}`) @@ -220,8 +220,8 @@ try { await sleep(500) await addOn(t5.id, other) await a.getByTestId('cart-open').click() - await a.getByRole('button', { name: /^(ΑΠΟΣΤΟΛΗ|ΣΥΝΟΨΗ)/ }).last().click() - if (await shown(a, 'summary-total', 3000)) await a.getByRole('button', { name: /ΑΠΟΣΤΟΛΗ/ }).last().click() + await a.getByRole('button', { name: /^(SEND|SUMMARY)/ }).last().click() + if (await shown(a, 'summary-total', 3000)) await a.getByRole('button', { name: /SEND/ }).last().click() await sleep(2000) await api('PUT', `/api/products/${other.id}`, { token: boss, body: { is_available: false } }) await ctxA.setOffline(false) @@ -244,9 +244,26 @@ try { for (const o of [sent, synced]) if (o) await api('DELETE', `/api/orders/${o.id}`, { token: boss }).catch(() => {}) await a.goto(`${APP}/tables`) + // ── 4.5: English first; the language switch in the user menu, saved to the person ── + const navText = () => a.locator('body').innerText() + await a.goto(`${APP}/tables`) + await a.locator('.table-card, [data-testid="user-menu"]').first().waitFor({ timeout: 10_000 }).catch(() => {}) + r.check('4.5: the phone runs in English (the venue language; the demo data stays Greek)', (await navText()).includes('Tables') && !(await navText()).includes('Τραπέζια'), (await navText()).replace(/\s+/g, ' ').slice(0, 300)) + await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 }) + await a.getByTestId('menu-language-el').click() + const greek = await waitFor(async () => (await navText()).includes('Τραπέζια'), 8000, 300) + const me = await api('GET', '/api/auth/me', { token: tokenA }) + r.check('4.5: menu → Ελληνικά: the screen turns Greek at once and it is saved for the person', !!greek && me.language === 'el', me.language) + await a.reload() + r.check('4.5: …still Greek after a reload', !!(await waitFor(async () => (await navText()).includes('Τραπέζια'), 15_000, 500))) + await a.screenshot({ path: path.join(OUT, 'waiter-greek.png') }) + await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 }) + await a.getByTestId('menu-language-en').click() + await waitFor(async () => (await navText()).includes('Tables'), 8000, 300) + // ── Signing out ends the session on the server: the second phone can sign in ─ await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 }) - await a.getByRole('button', { name: /Αποσύνδεση/ }).last().click() + await a.getByRole('button', { name: /Sign out/ }).last().click() await a.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).catch(() => {}) await sleep(1000) const after = await api('GET', '/api/auth/sessions', { token: boss }) diff --git a/waiter_pwa/src/components/RefusedLines.jsx b/waiter_pwa/src/components/RefusedLines.jsx index 957b17c..7c3d875 100644 --- a/waiter_pwa/src/components/RefusedLines.jsx +++ b/waiter_pwa/src/components/RefusedLines.jsx @@ -2,12 +2,14 @@ import { useEffect, useState } from 'react' import db from '../db/posdb' import { clearRefusedLines, refusedLines } from '../services/offlineOrders' import useAuthStore from '../store/authStore' +import { useTranslation } from '@xenia/i18n' // Lines of an order taken offline that the server refused when the phone came back (plan // step 4.4): a product taken off the menu meanwhile, an option deleted, a price change not // allowed. They are never dropped silently: this sheet lists them, with the reason, until the // waiter confirms they've seen them (and dealt with the table). export default function RefusedLines() { + const { t } = useTranslation('waiter') const token = useAuthStore(s => s.token) const [lines, setLines] = useState([]) @@ -30,9 +32,9 @@ export default function RefusedLines() {
e.stopPropagation()}>
-

Δεν στάλθηκαν

+

{t('refused.title')}

- Τα παρακάτω πάρθηκαν χωρίς σύνδεση και ο server δεν τα δέχτηκε. Ελέγξτε τα τραπέζια. + {t('refused.body')}

{lines.map((l, i) => ( @@ -46,7 +48,7 @@ export default function RefusedLines() { ))}
diff --git a/waiter_pwa/src/components/ServerRediscovery.jsx b/waiter_pwa/src/components/ServerRediscovery.jsx index aed632c..c8c575b 100644 --- a/waiter_pwa/src/components/ServerRediscovery.jsx +++ b/waiter_pwa/src/components/ServerRediscovery.jsx @@ -1,6 +1,7 @@ import { useEffect, useState } from 'react' import useConnectionStore from '../store/connectionStore' import { canRediscover, rediscover, upgradeToTls } from '../native/autoRediscover' +import { useTranslation } from '@xenia/i18n' const WATCHDOG_MS = 60_000 const RELOAD_DELAY_MS = 1500 @@ -20,6 +21,7 @@ const RELOAD_DELAY_MS = 1500 * IndexedDB and syncs after the reload. */ export default function ServerRediscovery() { + const { t } = useTranslation('waiter') const [movedTo, setMovedTo] = useState(null) const enabled = canRediscover() @@ -65,10 +67,10 @@ export default function ServerRediscovery() {
🔄

- Ο server άλλαξε διεύθυνση + {t('offline.moved')}

{movedTo}

-

Επανασύνδεση…

+

{t('offline.reconnecting')}

) diff --git a/waiter_pwa/src/context/NotificationContext.jsx b/waiter_pwa/src/context/NotificationContext.jsx index 2e66e76..b023fb9 100644 --- a/waiter_pwa/src/context/NotificationContext.jsx +++ b/waiter_pwa/src/context/NotificationContext.jsx @@ -2,6 +2,7 @@ import { createContext, useContext, useEffect, useState, useCallback } from 'rea import useAuthStore from '../store/authStore' import useNotificationSettingsStore from '../store/notificationSettingsStore' import client from '../api/client' +import { useTranslation } from '@xenia/i18n' const NotificationContext = createContext(null) @@ -51,22 +52,26 @@ function isManagerMessage(msg) { const HIGHLIGHT = { color: '#7dd3fc', fontWeight: 800 } // light blue bold +// the word before a table name in staff messages, English or Greek (\u escapes keep the source ASCII) +const TABLE_WORDS = 'table|\u03c4\u03c1\u03b1\u03c0\u03ad\u03b6\u03b9' + function RichBody({ text }) { if (!text) return null // Highlighted tokens: // #digits → order number - // τραπέζι → keep "τραπέζι " plain, highlight the word after it + // table → keep the word "table" (English or Greek) plain, highlight the word after it // " - " → keep " - " plain, highlight everything after const parts = [] - const re = /(#\d+|τραπέζι \S+| - .+$)/g + const re = new RegExp(`(#\\d+|(?:${TABLE_WORDS}) \\S+| - .+$)`, 'gi') let last = 0 let m while ((m = re.exec(text)) !== null) { if (m.index > last) parts.push({ t: 'plain', v: text.slice(last, m.index) }) const v = m[0] - if (v.startsWith('τραπέζι ')) { - parts.push({ t: 'plain', v: 'τραπέζι ' }) - parts.push({ t: 'hi', v: v.slice(8) }) + const word = new RegExp(`^(?:${TABLE_WORDS}) `, 'i').exec(v) + if (word) { + parts.push({ t: 'plain', v: word[0] }) + parts.push({ t: 'hi', v: v.slice(word[0].length) }) } else if (v.startsWith(' - ')) { parts.push({ t: 'plain', v: ' - ' }) parts.push({ t: 'hi', v: v.slice(3) }) @@ -91,6 +96,7 @@ function RichBody({ text }) { // ─── Persistent banner (one message at a time, stacked) ───────────────────── function NotificationBanner({ message, onAck, autoDismiss }) { + const { t } = useTranslation('waiter') const tableIds = (() => { try { return JSON.parse(message.table_ids || '[]') } catch { return [] } })() const theme = getTheme(message.message_type) @@ -120,7 +126,7 @@ function NotificationBanner({ message, onAck, autoDismiss }) { {tableIds.length > 0 && (
- Τραπέζι{tableIds.length > 1 ? 'α' : ''}: {tableIds.join(', ')} + {t('notify.tables', { count: tableIds.length, tables: tableIds.join(', ') })}
)} @@ -138,6 +144,7 @@ function NotificationBanner({ message, onAck, autoDismiss }) { } export function NotificationProvider({ children }) { + const { t } = useTranslation('waiter') const { token, user } = useAuthStore() const { popupMode, persistentPopup } = useNotificationSettingsStore() @@ -275,7 +282,7 @@ export function NotificationProvider({ children }) { textAlign: 'center', fontSize: 12, color: '#94a3b8', pointerEvents: 'all', }}> - +{popupMessages.length - 3} ακόμα μηνύματα + {t('notify.more', { count: popupMessages.length - 3 })} )} diff --git a/waiter_pwa/src/pages/ChatListPage.jsx b/waiter_pwa/src/pages/ChatListPage.jsx index 666fd60..e717eed 100644 --- a/waiter_pwa/src/pages/ChatListPage.jsx +++ b/waiter_pwa/src/pages/ChatListPage.jsx @@ -2,12 +2,13 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import client from '../api/client' import { apiError } from '../api/errors' +import { useFormat, useTranslation } from '@xenia/i18n' import useAuthStore from '../store/authStore' import useChatStore from '../store/chatStore' // ─── Relative time (Greek) ──────────────────────────────────────────────────── -function relativeTime(dateStr) { +function relativeTime(dateStr, t, formatDate) { if (!dateStr) return '' const date = new Date(dateStr) const now = new Date() @@ -15,9 +16,9 @@ function relativeTime(dateStr) { const diffMin = Math.floor(diffMs / 60_000) const diffHours = Math.floor(diffMs / 3_600_000) - if (diffMin < 1) return 'τώρα' - if (diffMin < 60) return `${diffMin}λ` - if (diffHours < 24) return `${diffHours}ω` + if (diffMin < 1) return t('chat.now') + if (diffMin < 60) return t('common.minutesShort', { m: diffMin }) + if (diffHours < 24) return t('common.hoursShort', { h: diffHours }) const yesterday = new Date(now) yesterday.setDate(yesterday.getDate() - 1) @@ -25,9 +26,9 @@ function relativeTime(dateStr) { date.getDate() === yesterday.getDate() && date.getMonth() === yesterday.getMonth() && date.getFullYear() === yesterday.getFullYear() - ) return 'χθες' + ) return t('chat.yesterday') - return date.toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit' }) + return formatDate(date, 'dateShort') } // ─── Avatar ─────────────────────────────────────────────────────────────────── @@ -53,18 +54,20 @@ function Avatar({ label, size = 44, isGroup = false }) { // ─── Conversation row ───────────────────────────────────────────────────────── function ConvRow({ conv, currentUserId, onClick }) { + const { t } = useTranslation('waiter') + const { formatDate } = useFormat() const isGroup = conv.type === 'group' const title = isGroup - ? (conv.name || 'Ομάδα') - : (conv.participants?.find(p => p.user_id !== currentUserId)?.username || 'Άγνωστος') + ? (conv.name || t('chat.group')) + : (conv.participants?.find(p => p.user_id !== currentUserId)?.username || t('chat.unknown')) const lastMsg = conv.last_message const preview = lastMsg ? lastMsg.is_deleted - ? 'Το μήνυμα διαγράφηκε' + ? t('chat.deleted') : lastMsg.body - : 'Δεν υπάρχουν μηνύματα' + : t('chat.noMessages') const timestamp = lastMsg?.sent_at || conv.created_at const hasUnread = (conv.unread_count || 0) > 0 @@ -91,7 +94,7 @@ function ConvRow({ conv, currentUserId, onClick }) { {title} - {relativeTime(timestamp)} + {relativeTime(timestamp, t, formatDate)}
{ client.get('/api/chat/users') .then(r => setStaff((r.data || []).filter(u => u.id !== currentUserId))) - .catch(() => setError('Αποτυχία φόρτωσης χρηστών')) + .catch(() => setError(t('chat.usersFailed'))) .finally(() => setLoading(false)) }, [currentUserId]) @@ -150,7 +154,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { }) onConversationCreated(res.data) } catch (e) { - setError(apiError(e, 'Σφάλμα δημιουργίας συνομιλίας')) + setError(apiError(e, t('chat.createFailed'))) setCreating(false) } } @@ -167,7 +171,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { }) onConversationCreated(res.data) } catch (e) { - setError(apiError(e, 'Σφάλμα δημιουργίας ομάδας')) + setError(apiError(e, t('chat.groupFailed'))) setCreating(false) } } @@ -185,7 +189,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { {mode === 'picker' && ( <> -

Νέα Συνομιλία

+

{t('chat.new')}

{/* New Group option */}
- Νέα Ομάδα + {t('chat.newGroup')}
{loading && (

- Φόρτωση… + {t('common.loading')}

)} {!loading && staff.length === 0 && !error && (

- Δεν υπάρχει άλλο προσωπικό + {t('chat.noStaff')}

)} {staff.map(u => ( @@ -257,14 +261,14 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { -

Όνομα Ομάδας

+

{t('chat.groupName')}

setGroupName(e.target.value)} onKeyDown={e => e.key === 'Enter' && groupName.trim() && setMode('group_pick')} - placeholder="π.χ. Βραδινή βάρδια" + placeholder={t('chat.groupNamePlaceholder')} style={{ width: '100%', padding: '12px 14px', background: 'var(--bg3)', border: '1px solid var(--border)', @@ -278,7 +282,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { disabled={!groupName.trim()} onClick={() => groupName.trim() && setMode('group_pick')} > - Επόμενο + {t('chat.next')} )} @@ -294,10 +298,10 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { -

Επιλογή Μελών

+

{t('chat.pickMembers')}

- Ομάδα: {groupName} + {t('chat.groupLabel')} {groupName}

@@ -347,7 +351,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { disabled={creating} onClick={createGroup} > - {creating ? 'Δημιουργία…' : `Δημιουργία Ομάδας${selectedIds.length > 0 ? ` (${selectedIds.length})` : ''}`} + {creating ? t('chat.creating') : selectedIds.length > 0 ? t('chat.createGroupCount', { count: selectedIds.length }) : t('chat.createGroup')} )} @@ -363,6 +367,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { // ─── Main page ──────────────────────────────────────────────────────────────── export default function ChatListPage() { + const { t } = useTranslation('waiter') const navigate = useNavigate() const { user } = useAuthStore() const { conversations, setConversations, upsertConversation } = useChatStore() @@ -414,7 +419,7 @@ export default function ChatListPage() {
- Νέα Συνομιλία + {t('chat.new')} @@ -430,7 +435,7 @@ export default function ChatListPage() { {/* ── Regular conversations ────────────────────────────────────── */} {loading && (
- Φόρτωση… + {t('common.loading')}
)} @@ -441,7 +446,7 @@ export default function ChatListPage() { }}> 💬

- Πατήστε «Νέα Συνομιλία» για να ξεκινήσετε μια συζήτηση. + {t('chat.startHint')}

)} diff --git a/waiter_pwa/src/pages/ChatThreadPage.jsx b/waiter_pwa/src/pages/ChatThreadPage.jsx index 21e7acd..bc4165d 100644 --- a/waiter_pwa/src/pages/ChatThreadPage.jsx +++ b/waiter_pwa/src/pages/ChatThreadPage.jsx @@ -1,17 +1,14 @@ import { useEffect, useRef, useState, useCallback } from 'react' import { useNavigate, useParams } from 'react-router-dom' import client from '../api/client' +import { useFormat, useTranslation } from '@xenia/i18n' import useAuthStore from '../store/authStore' import useChatStore from '../store/chatStore' // ─── Helpers ────────────────────────────────────────────────────────────────── -function formatTime(dateStr) { - if (!dateStr) return '' - return new Date(dateStr).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) -} -function formatDateLabel(dateStr) { +function formatDateLabel(dateStr, t, formatDateTime) { const date = new Date(dateStr) const now = new Date() const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()) @@ -19,9 +16,9 @@ function formatDateLabel(dateStr) { yesterday.setDate(yesterday.getDate() - 1) const d = new Date(date.getFullYear(), date.getMonth(), date.getDate()) - if (d.getTime() === today.getTime()) return 'Σήμερα' - if (d.getTime() === yesterday.getTime()) return 'Χθες' - return date.toLocaleDateString('el-GR', { weekday: 'long', day: 'numeric', month: 'long' }) + if (d.getTime() === today.getTime()) return t('chat.today') + if (d.getTime() === yesterday.getTime()) return t('chat.yesterdayCap') + return formatDateTime(date, { weekday: 'long', day: 'numeric', month: 'long' }) } function sameDay(a, b) { @@ -34,6 +31,8 @@ function sameDay(a, b) { // ─── Message bubble ─────────────────────────────────────────────────────────── function MessageBubble({ msg, isOwn, showSender, isGroup }) { + const { t } = useTranslation('waiter') + const { formatTime } = useFormat() if (msg.is_deleted) { return (
- Το μήνυμα διαγράφηκε + {t('chat.deleted')}
) @@ -142,6 +141,7 @@ function AutoTextarea({ value, onChange, onSubmit, placeholder }) { // ─── Leave confirmation modal ───────────────────────────────────────────────── function LeaveModal({ onConfirm, onCancel }) { + const { t } = useTranslation('waiter') return (
-

Αποχώρηση από ομάδα;

+

{t('chat.leaveTitle')}

- Δεν θα λαμβάνετε πλέον μηνύματα από αυτή την ομάδα. + {t('chat.leaveBody')}

- +
@@ -175,6 +175,8 @@ function LeaveModal({ onConfirm, onCancel }) { // ─── Main page ──────────────────────────────────────────────────────────────── export default function ChatThreadPage() { + const { t } = useTranslation('waiter') + const { formatDateTime } = useFormat() const { conversationId } = useParams() const navigate = useNavigate() const { user } = useAuthStore() @@ -205,8 +207,8 @@ export default function ChatThreadPage() { const isGroup = conv?.type === 'group' const title = isGroup - ? (conv?.name || 'Ομάδα') - : (conv?.participants?.find(p => p.user_id !== user?.id)?.username || 'Συνομιλία') + ? (conv?.name || t('chat.group')) + : (conv?.participants?.find(p => p.user_id !== user?.id)?.username || t('chat.conversation')) // ── Mark as read ───────────────────────────────────────────────────────────── @@ -418,7 +420,7 @@ export default function ChatThreadPage() { if (!prev || !sameDay(prev.sent_at, msg.sent_at)) { items.push( - + ) } @@ -458,7 +460,7 @@ export default function ChatThreadPage() { - Πίσω + {t('common.back')}
@@ -470,7 +472,7 @@ export default function ChatThreadPage() { {isGroup && ( - {(conv?.participants || []).length} μέλη + {t('chat.members', { count: (conv?.participants || []).length })} )}
@@ -484,7 +486,7 @@ export default function ChatThreadPage() { padding: '0 4px', minHeight: 44, borderRadius: 8, flexShrink: 0, }} > - Αποχώρηση + {t('chat.leave')} ) : (
@@ -504,13 +506,13 @@ export default function ChatThreadPage() { > {loadingMore && (
- Φόρτωση παλαιότερων… + {t('chat.loadingOlder')}
)} {initialLoad && (
- Φόρτωση… + {t('common.loading')}
)} @@ -521,7 +523,7 @@ export default function ChatThreadPage() { }}> 💬

- Δεν υπάρχουν μηνύματα ακόμα.{'\n'}Πείτε γεια! + {t('chat.emptyThread')}{'\n'}{t('chat.sayHi')}

)} @@ -542,7 +544,7 @@ export default function ChatThreadPage() { value={inputText} onChange={e => setInputText(e.target.value)} onSubmit={sendMessage} - placeholder="Γράψτε μήνυμα…" + placeholder={t('chat.placeholder')} /> {canRediscover() && ( )} {search === 'not-found' && (

- Ο server δεν βρέθηκε στο δίκτυο. Ελέγξτε ότι είναι αναμμένος, ή σαρώστε ξανά το QR από τον διαχειριστή. + {t('offline.notFound')}

)} {deliveryMode() === 'native' && ( @@ -66,7 +68,7 @@ export default function OfflinePage() { onClick={() => { window.location.href = '/venues' }} disabled={searching} > - Αλλαγή καταστήματος + {t('offline.changeVenue')} )}
diff --git a/waiter_pwa/src/pages/OrderLogPage.jsx b/waiter_pwa/src/pages/OrderLogPage.jsx index c33035f..7424f7c 100644 --- a/waiter_pwa/src/pages/OrderLogPage.jsx +++ b/waiter_pwa/src/pages/OrderLogPage.jsx @@ -2,25 +2,12 @@ import { useState, useEffect, useCallback, useRef } from 'react' import { useSearchParams } from 'react-router-dom' import AppShell from '../components/AppShell' import client from '../api/client' +import { useFormat, useTranslation } from '@xenia/i18n' +import { money as fmtPrice } from '../i18n' // ── helpers ─────────────────────────────────────────────────────────────────── -function fmtTime(iso) { - if (!iso) return '—' - return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) -} - -function fmtDateTime(iso) { - if (!iso) return '—' - return new Date(iso).toLocaleString('el-GR', { - day: '2-digit', month: '2-digit', - hour: '2-digit', minute: '2-digit', - }) -} - -function fmtPrice(n) { - return '€' + parseFloat(n || 0).toFixed(2) -} +// times in the venue's clock and the language's format: useFormat() in each component (4.5) // ── icons ───────────────────────────────────────────────────────────────────── @@ -86,6 +73,8 @@ function FilterIcon() { // ── action sheet — long-press on detailed cards ─────────────────────────────── function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) { + const { t } = useTranslation('waiter') + const { formatTime: fmtTime } = useFormat() return (
- Πρόβλημα Εκτύπωσης + {t('log.printProblem')}
- Παραγγελία #{order.id} · {order.table_name} · {fmtTime(order.opened_at)} + {t('log.orderLine', { id: order.id, table: order.table_name, time: fmtTime(order.opened_at) })} {order.print_retry_count > 0 && ( - {order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'} + {t('log.retries', { count: order.print_retry_count })} )}
@@ -127,7 +116,7 @@ function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) { opacity: busy ? 0.6 : 1, }} > - {busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'} + {busy ? t('add.sending') : t('log.printNow')}
@@ -161,6 +150,7 @@ function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) { // ── filter sheet ────────────────────────────────────────────────────────────── function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) { + const { t } = useTranslation('waiter') const [localFilter, setLocalFilter] = useState(filter) const [localFrom, setLocalFrom] = useState(dateFrom) const [localTo, setLocalTo] = useState(dateTo) @@ -184,18 +174,18 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) { }} >
-
Φίλτρα
+
{t('tables.filter.title')}
{/* Status filter */}
- Κατάσταση + {t('tables.filter.status')}
{[ - { value: 'all', label: 'Όλες' }, - { value: 'success', label: 'Επιτυχής' }, - { value: 'failed', label: 'Αποτυχημένη' }, + { value: 'all', label: t('orders.chips.all') }, + { value: 'success', label: t('log.ok') }, + { value: 'failed', label: t('log.failedF') }, ].map(opt => ( )}
@@ -271,7 +261,7 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) { fontSize: 15, fontWeight: 700, cursor: 'pointer', }} > - Εφαρμογή + {t('common.apply')}
@@ -281,6 +271,7 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) { // ── compact card (click = expand inline, expanded shows action buttons) ──────── function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) { + const { t } = useTranslation('waiter') const isPending = order.print_status === 'pending' return ( @@ -315,7 +306,7 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) { {/* Row 2: item count | total */}
- {order.items.length} αντ. + {t('log.itemsShort', { count: order.items.length })} {fmtPrice(order.total)} @@ -343,11 +334,11 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
- Σύνολο + {t('common.total')}
{isPending && order.print_retry_count > 0 && ( - {order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'} + {t('log.retries', { count: order.print_retry_count })} )} {fmtPrice(order.total)} @@ -355,9 +346,9 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
{order.fiscal_status && (
- Φορολογική εκτύπωση + {t('log.fiscal')} - {order.fiscal_status === 'success' ? 'Επιτυχής' : order.fiscal_status === 'pending' ? 'Εκκρεμεί…' : 'Αποτυχία'} + {order.fiscal_status === 'success' ? t('log.ok') : order.fiscal_status === 'pending' ? t('log.pending') : t('log.failed')}
)} @@ -376,7 +367,7 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) { opacity: busy ? 0.6 : 1, }} > - {busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'} + {busy ? t('add.sending') : t('log.printNow')}
@@ -403,6 +394,9 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) { // ── detailed card (long-press = action sheet) ───────────────────────────────── function DetailedCard({ order, onLongPress }) { + const { t } = useTranslation('waiter') + const { formatDateTime: fmtDateTime } = useFormat() + const { formatTime: fmtTime } = useFormat() const isPending = order.print_status === 'pending' const pressTimer = useRef(null) @@ -450,22 +444,22 @@ function DetailedCard({ order, onLongPress }) { {/* Meta rows */}
- Παραγγέλθηκε + {t('summary.ordered')} {fmtDateTime(order.opened_at)}
- Εκτύπωση + {t('log.print')} {isPending - ? `Εκκρεμεί (${order.print_retry_count} επαν.)` + ? t('log.pendingRetries', { count: order.print_retry_count }) : `OK ${fmtTime(order.print_attempted_at)}`}
{order.fiscal_status && (
- Φορολογική εκτύπωση + {t('log.fiscal')} - {order.fiscal_status === 'success' ? 'Επιτυχής' : order.fiscal_status === 'pending' ? 'Εκκρεμεί…' : 'Αποτυχία'} + {order.fiscal_status === 'success' ? t('log.ok') : order.fiscal_status === 'pending' ? t('log.pending') : t('log.failed')}
)} @@ -493,13 +487,13 @@ function DetailedCard({ order, onLongPress }) { {/* Total */}
- Σύνολο + {t('common.total')} {fmtPrice(order.total)}
{isPending && (
- Κρατήστε πατημένο για επιλογές + {t('log.holdForOptions')}
)}
@@ -509,6 +503,8 @@ function DetailedCard({ order, onLongPress }) { // ── main page ───────────────────────────────────────────────────────────────── export default function OrderLogPage() { + const { t } = useTranslation('waiter') + const { formatDateTime } = useFormat() const [searchParams] = useSearchParams() const initialFilter = searchParams.get('filter') === 'failed' ? 'failed' : 'all' @@ -605,7 +601,7 @@ export default function OrderLogPage() { const hasActiveFilters = filter !== 'all' || !!dateFrom || !!dateTo return ( - +
{/* Toolbar */} @@ -617,7 +613,7 @@ export default function OrderLogPage() { }}> setSearch(e.target.value)} style={{ @@ -636,7 +632,7 @@ export default function OrderLogPage() { display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', }} - title={view === 'compact' ? 'Λεπτομερής προβολή' : 'Συμπαγής προβολή'} + title={view === 'compact' ? t('log.detailedView') : t('log.compactView')} > {view === 'compact' ? : } @@ -656,7 +652,7 @@ export default function OrderLogPage() { - {pendingCount} παραγγελί{pendingCount !== 1 ? 'ες' : 'α'} με πρόβλημα εκτύπωσης + {t('log.printProblems', { count: pendingCount })}
)} @@ -676,24 +672,24 @@ export default function OrderLogPage() { color: filter === 'failed' ? '#ef4444' : '#22c55e', fontWeight: 600, }}> - {filter === 'failed' ? 'Αποτυχημένη εκτύπωση' : 'Επιτυχής εκτύπωση'} + {filter === 'failed' ? t('log.printFailed') : t('log.printOk')} )} {dateFrom && ( - Από {new Date(dateFrom).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })} + {t('log.from')} {formatDateTime(new Date(dateFrom), 'datetimeShort')} )} {dateTo && ( - Έως {new Date(dateTo).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })} + {t('log.to')} {formatDateTime(new Date(dateTo), 'datetimeShort')} )}
)} @@ -701,11 +697,11 @@ export default function OrderLogPage() { {/* List */}
{loading && ( -

Φόρτωση…

+

{t('common.loading')}

)} {!loading && filtered.length === 0 && (

- {search || hasActiveFilters ? 'Δεν βρέθηκαν παραγγελίες' : 'Δεν υπάρχουν παραγγελίες σε αυτή τη βάρδια'} + {search || hasActiveFilters ? t('log.noneFound') : t('log.noneThisShift')}

)} {filtered.map(order => @@ -744,7 +740,7 @@ export default function OrderLogPage() { display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 10, }} - title="Φίλτρα" + title={t('tables.filter.title')} > {hasActiveFilters && ( diff --git a/waiter_pwa/src/pages/ShiftOverviewPage.jsx b/waiter_pwa/src/pages/ShiftOverviewPage.jsx index 64e388b..78eef13 100644 --- a/waiter_pwa/src/pages/ShiftOverviewPage.jsx +++ b/waiter_pwa/src/pages/ShiftOverviewPage.jsx @@ -1,27 +1,22 @@ import { useQuery } from '@tanstack/react-query' import AppShell from '../components/AppShell' import client from '../api/client' +import { useFormat, useTranslation } from '@xenia/i18n' +import { money as fmtEuro, tw } from '../i18n' import { getVenueSettings } from '../api/venueSettings' // ── helpers ─────────────────────────────────────────────────────────────────── -function fmtTime(iso) { - if (!iso) return '—' - return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) -} function fmtDuration(seconds) { if (seconds == null || seconds < 0) return '—' const h = Math.floor(seconds / 3600) const m = Math.floor((seconds % 3600) / 60) - if (h === 0) return `${m}λ` - if (m === 0) return `${h}ω` - return `${h}ω ${m}λ` + if (h === 0) return tw('common.minutesShort', { m }) + if (m === 0) return tw('common.hoursShort', { h }) + return tw('common.hoursMinutesShort', { h, m }) } -function fmtEuro(n) { - return '€' + parseFloat(n || 0).toFixed(2) -} function sinceSeconds(isoStart) { if (!isoStart) return 0 @@ -101,6 +96,8 @@ function PerHourChart({ title, data, accent = 'var(--accent)' }) { // ── breaks timeline ─────────────────────────────────────────────────────────── function BreakRow({ brk, index }) { + const { t } = useTranslation('waiter') + const { formatTime: fmtTime } = useFormat() const dur = breakDurationSeconds(brk) const active = !brk.ended_at return ( @@ -118,7 +115,7 @@ function BreakRow({ brk, index }) { }}>{index + 1}
- {fmtTime(brk.started_at)} – {active ? 'Τώρα' : fmtTime(brk.ended_at)} + {fmtTime(brk.started_at)} – {active ? t('shiftPage.now') : fmtTime(brk.ended_at)}
{fmtDuration(dur)} @@ -128,7 +125,7 @@ function BreakRow({ brk, index }) { ΕΝΕΡΓΟ + }}>{t('venues.active')} )}
) @@ -137,6 +134,8 @@ function BreakRow({ brk, index }) { // ── main page ───────────────────────────────────────────────────────────────── export default function ShiftOverviewPage() { + const { t } = useTranslation('waiter') + const { formatTime: fmtTime } = useFormat() const { data: shift, isLoading: shiftLoading } = useQuery({ queryKey: ['my-shift'], queryFn: () => client.get('/api/shifts/my').then(r => r.data), @@ -164,7 +163,7 @@ export default function ShiftOverviewPage() { return (
- Φόρτωση… + {t('common.loading')}
) @@ -175,8 +174,8 @@ export default function ShiftOverviewPage() {
⏸
-
Δεν υπάρχει ενεργή βάρδια
-
Ξεκινήστε βάρδια για να δείτε στατιστικά.
+
{t('shiftPage.none')}
+
{t('shiftPage.noneSub')}
) @@ -219,9 +218,9 @@ export default function ShiftOverviewPage() { }}> ☕
-
Σε διάλειμμα
+
{t('shiftPage.onBreak')}
- από {fmtTime(activeBreak.started_at)} · {fmtDuration(breakDurationSeconds(activeBreak))} μέχρι τώρα + {t('shiftPage.breakSince', { time: fmtTime(activeBreak.started_at), duration: fmtDuration(breakDurationSeconds(activeBreak)) })}
@@ -229,18 +228,18 @@ export default function ShiftOverviewPage() { {/* Hero stats grid */}
- - - + + + {!hideRevenue && ( - + )} {!hideRevenue && ( - + )} - - - + + +
{/* Per-hour charts */} @@ -249,9 +248,9 @@ export default function ShiftOverviewPage() { background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 16, padding: '16px 18px', marginBottom: 20, }}> -
Ανά Ώρα
- - +
{t('shiftPage.perHour')}
+ +
)} @@ -259,7 +258,7 @@ export default function ShiftOverviewPage() { {(shift.breaks || []).length > 0 && (
- Διαλείμματα ({shift.breaks.length}) + {t('shiftPage.breaksCount', { count: shift.breaks.length })}
{shift.breaks.map((b, i) => )} diff --git a/waiter_pwa/src/services/offlineOrders.js b/waiter_pwa/src/services/offlineOrders.js index 0674dc7..c9b8e10 100644 --- a/waiter_pwa/src/services/offlineOrders.js +++ b/waiter_pwa/src/services/offlineOrders.js @@ -1,6 +1,7 @@ import db from '../db/posdb' import client from '../api/client' import { apiError } from '../api/errors' +import { tw } from '../i18n' // Orders taken offline (plan step 4.4): the cart lines are queued by id (`_wire`, built when // the order was taken: @xenia/api wireLine) and priced by the server when they reach it; the @@ -248,7 +249,7 @@ async function _flushLegacyOfflineOrders() { } // True legacy record (before v0.6.4): it can't be priced by the server (no lines by id) if (!entry.items.some(i => i._wire)) { - await keepRefused(entry.items.map(i => refusedEntry(i, entry.tableId, entry.uuid, OLD_FORMAT))) + await keepRefused(entry.items.map(i => refusedEntry(i, entry.tableId, entry.uuid, OLD_FORMAT()))) await db.offline_orders.update(entry.localId, { synced: 1 }) await db.pos_orders.delete(`offline_${entry.uuid}`) continue @@ -296,7 +297,7 @@ async function _flushCreateOrder(op, idMap) { const synthetic = await db.pos_orders.get(op.localOrderId) // queued before 4.4: nothing the server can price → all refused, no empty order opened if (!op.items.some(i => i._wire)) { - await keepRefused(op.items.map(i => refusedEntry(i, op.tableId, op.uuid, OLD_FORMAT))) + await keepRefused(op.items.map(i => refusedEntry(i, op.tableId, op.uuid, OLD_FORMAT()))) for (const it of synthetic?.items ?? []) idMap[it.id] = REFUSED await db.offline_orders.where('uuid').equals(op.uuid).modify({ synced: 1 }) await db.offline_ops.update(op.localId, { synced: 1 }) @@ -412,7 +413,7 @@ async function _flushPay(op, idMap) { const REFUSED_KEY = 'refused_lines' const REFUSED = 'refused' -const OLD_FORMAT = 'Παλιά μορφή παραγγελίας: προσθέστε το ξανά' +const OLD_FORMAT = () => tw('refused.oldFormat') /** Lines the server refused when an offline order was sent: [{ at, tableId, product, quantity, reason }]. */ export async function refusedLines() { @@ -449,7 +450,7 @@ async function postLines(pending, refused, ctx, post) { const n = refusedLine(err, pending.length) if (n == null) throw err const [{ item }] = pending.splice(n - 1, 1) - refused.push(refusedEntry(item, ctx.tableId, ctx.uuid, apiError(err, 'Ο server δεν το δέχτηκε'))) + refused.push(refusedEntry(item, ctx.tableId, ctx.uuid, apiError(err, tw('refused.notAccepted')))) } } return pending @@ -463,7 +464,7 @@ async function postLines(pending, refused, ctx, post) { * refusals are found again next time). Returns { orderId (null: all refused), sent: [indexes] }. */ async function sendLines(items, ctx, getOrderId) { - const refused = items.filter(item => !item._wire).map(item => refusedEntry(item, ctx.tableId, ctx.uuid, OLD_FORMAT)) + const refused = items.filter(item => !item._wire).map(item => refusedEntry(item, ctx.tableId, ctx.uuid, OLD_FORMAT())) const opts = { noOverride: true } let pending = items.map((item, index) => ({ item, index })).filter(({ item }) => item._wire) pending = await postLines(pending, refused, ctx, lines => client.post('/api/orders/quote', { lines }, opts)) diff --git a/waiter_pwa/tests/no-greek.test.mjs b/waiter_pwa/tests/no-greek.test.mjs new file mode 100644 index 0000000..645669d --- /dev/null +++ b/waiter_pwa/tests/no-greek.test.mjs @@ -0,0 +1,31 @@ +// Plan step 4.5: the waiter app's texts live in @xenia/i18n (namespace `waiter`, English first, +// Greek as a translation). No Greek letter may appear in the app's source: a new text is a key +// in packages/i18n/locales/{en,el}/waiter.json. (A Greek word the code must recognise, e.g. in +// a server message, is written with \u escapes.) +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readdirSync, readFileSync, statSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const SRC = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src') +const GREEK = /[Ͱ-Ͽἀ-῿]/ + +function walk(dir, out = []) { + for (const name of readdirSync(dir)) { + const p = path.join(dir, name) + if (statSync(p).isDirectory()) walk(p, out) + else if (/\.(jsx?|mjs|css|html)$/.test(name)) out.push(p) + } + return out +} + +test('no Greek text in the waiter app source (texts are i18n keys)', () => { + const hits = [] + for (const file of walk(SRC)) { + readFileSync(file, 'utf8').split('\n').forEach((line, i) => { + if (GREEK.test(line)) hits.push(`${path.relative(SRC, file)}:${i + 1}: ${line.trim().slice(0, 80)}`) + }) + } + assert.deepEqual(hits, [], `Greek text found — make it a key in the waiter namespace:\n${hits.join('\n')}`) +})