feat(waiter): English-first texts, part c: shift, log, chat, offline, notifications; language switch; guard (platform-v2 step 4.5c)

- Shift overview, order log, chat list / thread, offline + server search +
  rediscovery screens, notifications, the refused-lines sheet and the offline queue's
  reasons become keys; times and dates through useFormat() in the venue's clock.
- User menu: the other language(s) (data-testid menu-language-<lng>), saved to the
  person's profile (PATCH /api/auth/me) and the bootstrap reloaded (D-12).
- tests/no-greek.test.mjs: no Greek letter in waiter_pwa/src (the one Greek word the
  app recognises in staff messages is a \u escape).
- e2e: the test venue is English: waiter / browser / android use the English texts;
  waiter.mjs +3 (English by default, switch to Greek at once and saved, after reload);
  android bundle checks print what they saw when they fail.
- Pack README: the waiter texts rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 04:31:48 +02:00
co-authored by Claude Opus 5.5
parent 2c4f78af47
commit f8d91e7fae
16 changed files with 493 additions and 201 deletions
+2
View File
@@ -178,6 +178,8 @@ Routers are mounted from the module manifests (`local_backend/modules/<key>/mani
Use `core.access.deps.require("<module>.<area>.<action>")` (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). Use `core.access.deps.require("<module>.<area>.<action>")` (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). **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: <token>` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.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:<app>.config.<key>.label` (+ `.choices.<value>`), never free JSON. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header. Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.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:<app>.config.<key>.label` (+ `.choices.<value>`), never free JSON. Device-only endpoints use `require_device("<app>")`; 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). 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).
+112
View File
@@ -657,5 +657,117 @@
"summaryModal": { "summaryModal": {
"edit": "Επεξεργασία", "edit": "Επεξεργασία",
"title": "Επισκόπηση Παραγγελίας" "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}} ακόμα μηνύματα"
} }
} }
+112
View File
@@ -657,5 +657,117 @@
"summaryModal": { "summaryModal": {
"edit": "Edit", "edit": "Edit",
"title": "Order summary" "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"
} }
} }
+25 -23
View File
@@ -54,28 +54,28 @@ async function basics() {
let v = await freshApp() let v = await freshApp()
await typeInto(v, `${H}:9999`) await typeInto(v, `${H}:9999`)
await tap(v, 'button', 'Σύνδεση') await tap(v, 'button', 'Connect')
await sleep(6500) 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 typeInto(v, `http://${H}:8055/?pair=some-other-site`)
await tap(v, 'button', 'Σύνδεση') await tap(v, 'button', 'Connect')
await sleep(3000) 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 typeInto(v, `${H}:8055`)
await tap(v, 'button', 'Σύνδεση') await tap(v, 'button', 'Connect')
await sleep(5000) await sleep(5000)
v = await attach() v = await attach()
const st = await venuesState(v) 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('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 // 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 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"]', 'Κωνσταντίνου') await tap(v, '[data-testid="waiter-card"]', 'Κωνσταντίνου')
for (const d of '3302') await tap(v, 'button.pin-btn', d) 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 waitFor(() => v.evaluate("location.pathname === '/tables'"), 15_000, 500)
await sleep(3000) await sleep(3000)
r.check('signed in with name + PIN on the pad: /tables', (await v.evaluate('location.pathname')) === '/tables' 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) // 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')") 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"]') await tap(v, '[data-testid="menu-lock"]')
const lockedOk = await waitFor(() => v.evaluate("!!document.querySelector('[data-testid=lock-screen]')"), 5000, 300) 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) 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') r.check('restart: still paired and logged in', (await v.evaluate('location.pathname')) === '/tables')
// venues // venues
await tap(v, 'button[title="Μενού χρήστη"]') await tap(v, '[data-testid="user-menu"]')
await sleep(600) await sleep(600)
await tap(v, 'button.user-menu-item', 'Κατάστημα') await tap(v, 'button.user-menu-item', 'Venue')
await sleep(1200) await sleep(1200)
r.check('user menu → /venues', (await v.evaluate('location.pathname')) === '/venues') r.check('user menu → /venues', (await v.evaluate('location.pathname')) === '/venues')
back() back()
@@ -113,14 +113,14 @@ async function basics() {
await goTo(v, '/venues') await goTo(v, '/venues')
await sleep(1000) await sleep(1000)
await typeInto(v, `${H}:8056`) await typeInto(v, `${H}:8056`)
await tap(v, 'button', 'Σύνδεση') await tap(v, 'button', 'Connect')
await sleep(5000) await sleep(5000)
v = await attach() v = await attach()
let vs = await venuesState(v) let vs = await venuesState(v)
r.check('second venue paired and active', vs.active === 'test-site-2' && Object.keys(vs.venues).length === 2) 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') const path2 = await v.evaluate('location.pathname')
r.check('second venue starts logged out (own session)', path2 === '/login', `${path2} ${JSON.stringify(vs)}`) 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 sleep(1200)
await tap(v, 'button', `${H}:8055`) await tap(v, 'button', `${H}:8055`)
await sleep(5000) await sleep(5000)
@@ -139,14 +139,14 @@ async function basics() {
v = await relaunch() v = await relaunch()
await goTo(v, '/venues') await goTo(v, '/venues')
await sleep(1000) await sleep(1000)
await tap(v, 'button', 'Σάρωση QR') await tap(v, 'button', 'Scan QR')
await sleep(2500) await sleep(2500)
r.check(`camera ${label}: permission prompt shown`, /GrantPermissions/.test(focusedWindow())) r.check(`camera ${label}: permission prompt shown`, /GrantPermissions/.test(focusedWindow()))
tapDialogButton(button) tapDialogButton(button)
await sleep(label === 'deny' ? 2000 : 4000) await sleep(label === 'deny' ? 2000 : 4000)
if (label === 'deny') { if (label === 'deny') {
r.check('camera deny: asked only once', !/GrantPermissions/.test(focusedWindow())) 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 { } else {
const video = await v.evaluate("(() => { const x = document.querySelector('video'); return { ready: x.readyState, w: x.videoWidth, paused: x.paused } })()") 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)) 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) 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: 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))) 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()") 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('Ο server δεν βρέθηκε'), 60_000) 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) r.check('manual search ends with "not found" guidance', !!notFound)
// cold start while the server is down keeps the login // 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 ─────────────────────────────────────────────────────────────────── // ── TLS ───────────────────────────────────────────────────────────────────
let v = await freshApp() let v = await freshApp()
await typeInto(v, qr('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=')) await typeInto(v, qr('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='))
await tap(v, 'button', 'Σύνδεση') await tap(v, 'button', 'Connect')
await sleep(4000) 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 typeInto(v, qr(pin))
await tap(v, 'button', 'Σύνδεση') await tap(v, 'button', 'Connect')
await sleep(6000) await sleep(6000)
v = await attach() v = await attach()
let ven = (await venuesState(v)).venues['test-site-1'] 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 }) serve({ ...manifest, version: 'e2e-new-apk', min_shell_build: 99 })
await bgAndBack(); await sleep(8000); v = await attach() 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('<!doctype html><html><body><h1>broken bundle</h1></body></html>') }) const broken = zipSync({ 'index.html': strToU8('<!doctype html><html><body><h1>broken bundle</h1></body></html>') })
execFileSync('docker', ['exec', '-i', WAITER1, 'sh', '-c', `cat > ${DL}/waiter-bundle-broken.zip`], { input: Buffer.from(broken) }) 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 bgAndBack()
await waitFor(async () => { v = await attach(); return (await v.evaluate('document.body.innerText')).includes('broken bundle') }, 40_000, 1500) 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) 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() 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) serve(manifest)
// ── two venues, each on its own bundle ───────────────────────────────────── // ── 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() v = await attach()
await goTo(v, '/venues'); await sleep(1200) await goTo(v, '/venues'); await sleep(1200)
await typeInto(v, `http://${H}:28080/?${new URLSearchParams({ pair: 'test-site-2', k: pin2 })}`) 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() 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) 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) r.check('bundles: pairing venue 2 → venue 2 bundle', !!s)
+7 -7
View File
@@ -75,7 +75,7 @@ try {
// ── Install-app dialog + drawer entry ───────────────────────────────────── // ── Install-app dialog + drawer entry ─────────────────────────────────────
const r2 = reporter('browser: install-app dialog') 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 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() const hamburger = page => page.locator('button').filter({ has: page.locator('svg') }).first()
let ctx = await phone(ANDROID_UA) 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()) r2.check('first visit on Android: dialog opens by itself', await dialog(page).isVisible())
const box = await dialog(page).boundingBox() 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('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.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 sleep(400)
await page.reload() await page.reload()
await sleep(3500) 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.evaluate(t => localStorage.setItem('token', t), token)
await page.goto(`http://${LAN}:15173/tables`) await page.goto(`http://${LAN}:15173/tables`)
await sleep(4000) await sleep(4000)
await hamburger(page).click() await hamburger(page).click()
await sleep(600) 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()] 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 install.click()
await sleep(500) await sleep(500)
r2.check('drawer entry reopens the dialog', await dialog(page).isVisible()) r2.check('drawer entry reopens the dialog', await dialog(page).isVisible())
@@ -115,7 +115,7 @@ try {
const noDialog = !(await dialog(page).isVisible()) const noDialog = !(await dialog(page).isVisible())
await hamburger(page).click() await hamburger(page).click()
await sleep(500) 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() await ctx.close()
} }
ctx = await phone(ANDROID_UA) ctx = await phone(ANDROID_UA)
+29 -12
View File
@@ -15,7 +15,7 @@ const vite = await startViteNative({ port: 5181, backendUrl: backend.url })
const APP = 'http://localhost:5181' const APP = 'http://localhost:5181'
const TOKEN_KEY = 'xenia:dev:token' const TOKEN_KEY = 'xenia:dev:token'
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) 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 = [] const errors = []
let failures = 0 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]))) 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) // 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 a.waitForURL(u => u.pathname.startsWith('/tables'), { timeout: 10_000 }).catch(() => {})
await sleep(1500) await sleep(1500)
@@ -94,7 +94,7 @@ try {
// ── Lock from the menu, wrong PIN, right PIN (same session) ──────────────── // ── Lock from the menu, wrong PIN, right PIN (same session) ────────────────
await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 }) await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 })
await a.getByTestId('menu-lock').click() 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() await a.reload()
r.check('still locked after the app is reopened', await shown(a, 'lock-screen', 10_000)) r.check('still locked after the app is reopened', await shown(a, 'lock-screen', 10_000))
await pin(a, '0000') await pin(a, '0000')
@@ -132,9 +132,9 @@ try {
await sleep(800) await sleep(800)
const sheet = await a.locator('.modal-sheet--top').innerText().catch(() => '') 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")', 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)) 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('Ακύρωση Παραγγελίας', { exact: true }).click() await a.getByText('Cancel order', { exact: true }).click()
await a.getByRole('button', { name: 'Ακύρωση ✕' }).click() await a.getByRole('button', { name: 'Cancel ✕' }).click()
const dlg = a.getByRole('dialog') const dlg = a.getByRole('dialog')
await dlg.waitFor({ timeout: 10_000 }).catch(() => {}) 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') 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 exact = await waitFor(async () => await total().getAttribute('data-estimated') === 'false', 10_000, 300)
const shownTotal = await total().innerText().catch(() => '') 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, ' ')) 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)) { 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')) 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 sent = await waitFor(async () => {
const st = await api('GET', `/api/tables/${t4.id}/status`, { token: boss }) const st = await api('GET', `/api/tables/${t4.id}/status`, { token: boss })
@@ -212,7 +212,7 @@ try {
await addOn(t5.id, plain) await addOn(t5.id, plain)
await ctxA.setOffline(true) await ctxA.setOffline(true)
await a.getByTestId('cart-open').click() 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) 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' 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(() => '')}`) && (await total().innerText()).includes('≈'), `${wentOffline} ${est} ${await total().innerText().catch(() => '')}`)
@@ -220,8 +220,8 @@ try {
await sleep(500) await sleep(500)
await addOn(t5.id, other) await addOn(t5.id, other)
await a.getByTestId('cart-open').click() await a.getByTestId('cart-open').click()
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: /ΑΠΟΣΤΟΛΗ/ }).last().click() if (await shown(a, 'summary-total', 3000)) await a.getByRole('button', { name: /SEND/ }).last().click()
await sleep(2000) await sleep(2000)
await api('PUT', `/api/products/${other.id}`, { token: boss, body: { is_available: false } }) await api('PUT', `/api/products/${other.id}`, { token: boss, body: { is_available: false } })
await ctxA.setOffline(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(() => {}) for (const o of [sent, synced]) if (o) await api('DELETE', `/api/orders/${o.id}`, { token: boss }).catch(() => {})
await a.goto(`${APP}/tables`) 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 ─ // ── 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: '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 a.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).catch(() => {})
await sleep(1000) await sleep(1000)
const after = await api('GET', '/api/auth/sessions', { token: boss }) const after = await api('GET', '/api/auth/sessions', { token: boss })
+5 -3
View File
@@ -2,12 +2,14 @@ import { useEffect, useState } from 'react'
import db from '../db/posdb' import db from '../db/posdb'
import { clearRefusedLines, refusedLines } from '../services/offlineOrders' import { clearRefusedLines, refusedLines } from '../services/offlineOrders'
import useAuthStore from '../store/authStore' 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 // 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 // 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 // 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). // waiter confirms they've seen them (and dealt with the table).
export default function RefusedLines() { export default function RefusedLines() {
const { t } = useTranslation('waiter')
const token = useAuthStore(s => s.token) const token = useAuthStore(s => s.token)
const [lines, setLines] = useState([]) const [lines, setLines] = useState([])
@@ -30,9 +32,9 @@ export default function RefusedLines() {
<div className="modal-overlay" data-testid="refused-lines"> <div className="modal-overlay" data-testid="refused-lines">
<div className="modal-sheet" onClick={e => e.stopPropagation()}> <div className="modal-sheet" onClick={e => e.stopPropagation()}>
<div className="modal-handle" /> <div className="modal-handle" />
<h2 className="modal-title">Δεν στάλθηκαν</h2> <h2 className="modal-title">{t('refused.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}> <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>
Τα παρακάτω πάρθηκαν χωρίς σύνδεση και ο server δεν τα δέχτηκε. Ελέγξτε τα τραπέζια. {t('refused.body')}
</p> </p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16, maxHeight: '45vh', overflowY: 'auto' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16, maxHeight: '45vh', overflowY: 'auto' }}>
{lines.map((l, i) => ( {lines.map((l, i) => (
@@ -46,7 +48,7 @@ export default function RefusedLines() {
))} ))}
</div> </div>
<button className="btn btn--primary" style={{ width: '100%' }} data-testid="refused-lines-ok" onClick={() => clearRefusedLines()}> <button className="btn btn--primary" style={{ width: '100%' }} data-testid="refused-lines-ok" onClick={() => clearRefusedLines()}>
Το είδα {t('refused.ok')}
</button> </button>
</div> </div>
</div> </div>
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import useConnectionStore from '../store/connectionStore' import useConnectionStore from '../store/connectionStore'
import { canRediscover, rediscover, upgradeToTls } from '../native/autoRediscover' import { canRediscover, rediscover, upgradeToTls } from '../native/autoRediscover'
import { useTranslation } from '@xenia/i18n'
const WATCHDOG_MS = 60_000 const WATCHDOG_MS = 60_000
const RELOAD_DELAY_MS = 1500 const RELOAD_DELAY_MS = 1500
@@ -20,6 +21,7 @@ const RELOAD_DELAY_MS = 1500
* IndexedDB and syncs after the reload. * IndexedDB and syncs after the reload.
*/ */
export default function ServerRediscovery() { export default function ServerRediscovery() {
const { t } = useTranslation('waiter')
const [movedTo, setMovedTo] = useState(null) const [movedTo, setMovedTo] = useState(null)
const enabled = canRediscover() const enabled = canRediscover()
@@ -65,10 +67,10 @@ export default function ServerRediscovery() {
<div> <div>
<div style={{ fontSize: 44, marginBottom: 12 }}>🔄</div> <div style={{ fontSize: 44, marginBottom: 12 }}>🔄</div>
<p style={{ color: '#e2e8f0', fontSize: 17, fontWeight: 600, marginBottom: 6 }}> <p style={{ color: '#e2e8f0', fontSize: 17, fontWeight: 600, marginBottom: 6 }}>
Ο server άλλαξε διεύθυνση {t('offline.moved')}
</p> </p>
<p style={{ color: '#94a3b8', fontSize: 14, fontFamily: 'monospace' }}>{movedTo}</p> <p style={{ color: '#94a3b8', fontSize: 14, fontFamily: 'monospace' }}>{movedTo}</p>
<p style={{ color: '#94a3b8', fontSize: 14, marginTop: 10 }}>Επανασύνδεση…</p> <p style={{ color: '#94a3b8', fontSize: 14, marginTop: 10 }}>{t('offline.reconnecting')}</p>
</div> </div>
</div> </div>
) )
+14 -7
View File
@@ -2,6 +2,7 @@ import { createContext, useContext, useEffect, useState, useCallback } from 'rea
import useAuthStore from '../store/authStore' import useAuthStore from '../store/authStore'
import useNotificationSettingsStore from '../store/notificationSettingsStore' import useNotificationSettingsStore from '../store/notificationSettingsStore'
import client from '../api/client' import client from '../api/client'
import { useTranslation } from '@xenia/i18n'
const NotificationContext = createContext(null) const NotificationContext = createContext(null)
@@ -51,22 +52,26 @@ function isManagerMessage(msg) {
const HIGHLIGHT = { color: '#7dd3fc', fontWeight: 800 } // light blue bold 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 }) { function RichBody({ text }) {
if (!text) return null if (!text) return null
// Highlighted tokens: // Highlighted tokens:
// #digits → order number // #digits → order number
// τραπέζι <word> → keep "τραπέζι " plain, highlight the word after it // table <word> → keep the word "table" (English or Greek) plain, highlight the word after it
// " - " <rest> → keep " - " plain, highlight everything after // " - " <rest> → keep " - " plain, highlight everything after
const parts = [] const parts = []
const re = /(#\d+|τραπέζι \S+| - .+$)/g const re = new RegExp(`(#\\d+|(?:${TABLE_WORDS}) \\S+| - .+$)`, 'gi')
let last = 0 let last = 0
let m let m
while ((m = re.exec(text)) !== null) { while ((m = re.exec(text)) !== null) {
if (m.index > last) parts.push({ t: 'plain', v: text.slice(last, m.index) }) if (m.index > last) parts.push({ t: 'plain', v: text.slice(last, m.index) })
const v = m[0] const v = m[0]
if (v.startsWith('τραπέζι ')) { const word = new RegExp(`^(?:${TABLE_WORDS}) `, 'i').exec(v)
parts.push({ t: 'plain', v: 'τραπέζι ' }) if (word) {
parts.push({ t: 'hi', v: v.slice(8) }) parts.push({ t: 'plain', v: word[0] })
parts.push({ t: 'hi', v: v.slice(word[0].length) })
} else if (v.startsWith(' - ')) { } else if (v.startsWith(' - ')) {
parts.push({ t: 'plain', v: ' - ' }) parts.push({ t: 'plain', v: ' - ' })
parts.push({ t: 'hi', v: v.slice(3) }) parts.push({ t: 'hi', v: v.slice(3) })
@@ -91,6 +96,7 @@ function RichBody({ text }) {
// ─── Persistent banner (one message at a time, stacked) ───────────────────── // ─── Persistent banner (one message at a time, stacked) ─────────────────────
function NotificationBanner({ message, onAck, autoDismiss }) { function NotificationBanner({ message, onAck, autoDismiss }) {
const { t } = useTranslation('waiter')
const tableIds = (() => { try { return JSON.parse(message.table_ids || '[]') } catch { return [] } })() const tableIds = (() => { try { return JSON.parse(message.table_ids || '[]') } catch { return [] } })()
const theme = getTheme(message.message_type) const theme = getTheme(message.message_type)
@@ -120,7 +126,7 @@ function NotificationBanner({ message, onAck, autoDismiss }) {
</div> </div>
{tableIds.length > 0 && ( {tableIds.length > 0 && (
<div style={{ fontSize: 12, color: '#94a3b8', marginTop: 4 }}> <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 4 }}>
Τραπέζι{tableIds.length > 1 ? 'α' : ''}: {tableIds.join(', ')} {t('notify.tables', { count: tableIds.length, tables: tableIds.join(', ') })}
</div> </div>
)} )}
</div> </div>
@@ -138,6 +144,7 @@ function NotificationBanner({ message, onAck, autoDismiss }) {
} }
export function NotificationProvider({ children }) { export function NotificationProvider({ children }) {
const { t } = useTranslation('waiter')
const { token, user } = useAuthStore() const { token, user } = useAuthStore()
const { popupMode, persistentPopup } = useNotificationSettingsStore() const { popupMode, persistentPopup } = useNotificationSettingsStore()
@@ -275,7 +282,7 @@ export function NotificationProvider({ children }) {
textAlign: 'center', fontSize: 12, color: '#94a3b8', textAlign: 'center', fontSize: 12, color: '#94a3b8',
pointerEvents: 'all', pointerEvents: 'all',
}}> }}>
+{popupMessages.length - 3} ακόμα μηνύματα {t('notify.more', { count: popupMessages.length - 3 })}
</div> </div>
)} )}
</div> </div>
+32 -27
View File
@@ -2,12 +2,13 @@ import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors' import { apiError } from '../api/errors'
import { useFormat, useTranslation } from '@xenia/i18n'
import useAuthStore from '../store/authStore' import useAuthStore from '../store/authStore'
import useChatStore from '../store/chatStore' import useChatStore from '../store/chatStore'
// ─── Relative time (Greek) ──────────────────────────────────────────────────── // ─── Relative time (Greek) ────────────────────────────────────────────────────
function relativeTime(dateStr) { function relativeTime(dateStr, t, formatDate) {
if (!dateStr) return '' if (!dateStr) return ''
const date = new Date(dateStr) const date = new Date(dateStr)
const now = new Date() const now = new Date()
@@ -15,9 +16,9 @@ function relativeTime(dateStr) {
const diffMin = Math.floor(diffMs / 60_000) const diffMin = Math.floor(diffMs / 60_000)
const diffHours = Math.floor(diffMs / 3_600_000) const diffHours = Math.floor(diffMs / 3_600_000)
if (diffMin < 1) return 'τώρα' if (diffMin < 1) return t('chat.now')
if (diffMin < 60) return `${diffMin}λ` if (diffMin < 60) return t('common.minutesShort', { m: diffMin })
if (diffHours < 24) return `${diffHours}ω` if (diffHours < 24) return t('common.hoursShort', { h: diffHours })
const yesterday = new Date(now) const yesterday = new Date(now)
yesterday.setDate(yesterday.getDate() - 1) yesterday.setDate(yesterday.getDate() - 1)
@@ -25,9 +26,9 @@ function relativeTime(dateStr) {
date.getDate() === yesterday.getDate() && date.getDate() === yesterday.getDate() &&
date.getMonth() === yesterday.getMonth() && date.getMonth() === yesterday.getMonth() &&
date.getFullYear() === yesterday.getFullYear() 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 ─────────────────────────────────────────────────────────────────── // ─── Avatar ───────────────────────────────────────────────────────────────────
@@ -53,18 +54,20 @@ function Avatar({ label, size = 44, isGroup = false }) {
// ─── Conversation row ───────────────────────────────────────────────────────── // ─── Conversation row ─────────────────────────────────────────────────────────
function ConvRow({ conv, currentUserId, onClick }) { function ConvRow({ conv, currentUserId, onClick }) {
const { t } = useTranslation('waiter')
const { formatDate } = useFormat()
const isGroup = conv.type === 'group' const isGroup = conv.type === 'group'
const title = isGroup const title = isGroup
? (conv.name || 'Ομάδα') ? (conv.name || t('chat.group'))
: (conv.participants?.find(p => p.user_id !== currentUserId)?.username || 'Άγνωστος') : (conv.participants?.find(p => p.user_id !== currentUserId)?.username || t('chat.unknown'))
const lastMsg = conv.last_message const lastMsg = conv.last_message
const preview = lastMsg const preview = lastMsg
? lastMsg.is_deleted ? lastMsg.is_deleted
? 'Το μήνυμα διαγράφηκε' ? t('chat.deleted')
: lastMsg.body : lastMsg.body
: 'Δεν υπάρχουν μηνύματα' : t('chat.noMessages')
const timestamp = lastMsg?.sent_at || conv.created_at const timestamp = lastMsg?.sent_at || conv.created_at
const hasUnread = (conv.unread_count || 0) > 0 const hasUnread = (conv.unread_count || 0) > 0
@@ -91,7 +94,7 @@ function ConvRow({ conv, currentUserId, onClick }) {
{title} {title}
</span> </span>
<span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}> <span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>
{relativeTime(timestamp)} {relativeTime(timestamp, t, formatDate)}
</span> </span>
</div> </div>
<div style={{ <div style={{
@@ -125,6 +128,7 @@ function ConvRow({ conv, currentUserId, onClick }) {
// ─── New Chat bottom drawer ─────────────────────────────────────────────────── // ─── New Chat bottom drawer ───────────────────────────────────────────────────
function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) { function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
const { t } = useTranslation('waiter')
const [staff, setStaff] = useState([]) const [staff, setStaff] = useState([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [mode, setMode] = useState('picker') // 'picker' | 'group_name' | 'group_pick' const [mode, setMode] = useState('picker') // 'picker' | 'group_name' | 'group_pick'
@@ -136,7 +140,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
useEffect(() => { useEffect(() => {
client.get('/api/chat/users') client.get('/api/chat/users')
.then(r => setStaff((r.data || []).filter(u => u.id !== currentUserId))) .then(r => setStaff((r.data || []).filter(u => u.id !== currentUserId)))
.catch(() => setError('Αποτυχία φόρτωσης χρηστών')) .catch(() => setError(t('chat.usersFailed')))
.finally(() => setLoading(false)) .finally(() => setLoading(false))
}, [currentUserId]) }, [currentUserId])
@@ -150,7 +154,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
}) })
onConversationCreated(res.data) onConversationCreated(res.data)
} catch (e) { } catch (e) {
setError(apiError(e, 'Σφάλμα δημιουργίας συνομιλίας')) setError(apiError(e, t('chat.createFailed')))
setCreating(false) setCreating(false)
} }
} }
@@ -167,7 +171,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
}) })
onConversationCreated(res.data) onConversationCreated(res.data)
} catch (e) { } catch (e) {
setError(apiError(e, 'Σφάλμα δημιουργίας ομάδας')) setError(apiError(e, t('chat.groupFailed')))
setCreating(false) setCreating(false)
} }
} }
@@ -185,7 +189,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
{mode === 'picker' && ( {mode === 'picker' && (
<> <>
<h2 className="modal-title" style={{ marginBottom: 16 }}>Νέα Συνομιλία</h2> <h2 className="modal-title" style={{ marginBottom: 16 }}>{t('chat.new')}</h2>
{/* New Group option */} {/* New Group option */}
<button <button
@@ -204,18 +208,18 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
}}> }}>
👥 👥
</div> </div>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}>Νέα Ομάδα</span> <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}>{t('chat.newGroup')}</span>
</button> </button>
<div style={{ flex: 1, overflowY: 'auto', marginTop: 4 }}> <div style={{ flex: 1, overflowY: 'auto', marginTop: 4 }}>
{loading && ( {loading && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}> <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}>
Φόρτωση… {t('common.loading')}
</p> </p>
)} )}
{!loading && staff.length === 0 && !error && ( {!loading && staff.length === 0 && !error && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}> <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}>
Δεν υπάρχει άλλο προσωπικό {t('chat.noStaff')}
</p> </p>
)} )}
{staff.map(u => ( {staff.map(u => (
@@ -257,14 +261,14 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
<path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/> <path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg> </svg>
</button> </button>
<h2 className="modal-title" style={{ margin: 0 }}>Όνομα Ομάδας</h2> <h2 className="modal-title" style={{ margin: 0 }}>{t('chat.groupName')}</h2>
</div> </div>
<input <input
autoFocus autoFocus
value={groupName} value={groupName}
onChange={e => setGroupName(e.target.value)} onChange={e => setGroupName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && groupName.trim() && setMode('group_pick')} onKeyDown={e => e.key === 'Enter' && groupName.trim() && setMode('group_pick')}
placeholder="π.χ. Βραδινή βάρδια" placeholder={t('chat.groupNamePlaceholder')}
style={{ style={{
width: '100%', padding: '12px 14px', width: '100%', padding: '12px 14px',
background: 'var(--bg3)', border: '1px solid var(--border)', background: 'var(--bg3)', border: '1px solid var(--border)',
@@ -278,7 +282,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
disabled={!groupName.trim()} disabled={!groupName.trim()}
onClick={() => groupName.trim() && setMode('group_pick')} onClick={() => groupName.trim() && setMode('group_pick')}
> >
Επόμενο {t('chat.next')}
</button> </button>
</> </>
)} )}
@@ -294,10 +298,10 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
<path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/> <path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg> </svg>
</button> </button>
<h2 className="modal-title" style={{ margin: 0 }}>Επιλογή Μελών</h2> <h2 className="modal-title" style={{ margin: 0 }}>{t('chat.pickMembers')}</h2>
</div> </div>
<p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 12 }}> <p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 12 }}>
Ομάδα: <strong style={{ color: 'var(--text)' }}>{groupName}</strong> {t('chat.groupLabel')} <strong style={{ color: 'var(--text)' }}>{groupName}</strong>
</p> </p>
<div style={{ flex: 1, overflowY: 'auto', marginBottom: 12 }}> <div style={{ flex: 1, overflowY: 'auto', marginBottom: 12 }}>
@@ -347,7 +351,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
disabled={creating} disabled={creating}
onClick={createGroup} onClick={createGroup}
> >
{creating ? 'Δημιουργία…' : `Δημιουργία Ομάδας${selectedIds.length > 0 ? ` (${selectedIds.length})` : ''}`} {creating ? t('chat.creating') : selectedIds.length > 0 ? t('chat.createGroupCount', { count: selectedIds.length }) : t('chat.createGroup')}
</button> </button>
</> </>
)} )}
@@ -363,6 +367,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
// ─── Main page ──────────────────────────────────────────────────────────────── // ─── Main page ────────────────────────────────────────────────────────────────
export default function ChatListPage() { export default function ChatListPage() {
const { t } = useTranslation('waiter')
const navigate = useNavigate() const navigate = useNavigate()
const { user } = useAuthStore() const { user } = useAuthStore()
const { conversations, setConversations, upsertConversation } = useChatStore() const { conversations, setConversations, upsertConversation } = useChatStore()
@@ -414,7 +419,7 @@ export default function ChatListPage() {
</svg> </svg>
</div> </div>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}> <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}>
Νέα Συνομιλία {t('chat.new')}
</span> </span>
</button> </button>
@@ -430,7 +435,7 @@ export default function ChatListPage() {
{/* ── Regular conversations ────────────────────────────────────── */} {/* ── Regular conversations ────────────────────────────────────── */}
{loading && ( {loading && (
<div style={{ textAlign: 'center', padding: 40, color: 'var(--muted)', fontSize: 14 }}> <div style={{ textAlign: 'center', padding: 40, color: 'var(--muted)', fontSize: 14 }}>
Φόρτωση… {t('common.loading')}
</div> </div>
)} )}
@@ -441,7 +446,7 @@ export default function ChatListPage() {
}}> }}>
<span style={{ fontSize: 40 }}>💬</span> <span style={{ fontSize: 40 }}>💬</span>
<p style={{ fontSize: 15, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5, margin: 0 }}> <p style={{ fontSize: 15, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5, margin: 0 }}>
Πατήστε «Νέα Συνομιλία» για να ξεκινήσετε μια συζήτηση. {t('chat.startHint')}
</p> </p>
</div> </div>
)} )}
+25 -23
View File
@@ -1,17 +1,14 @@
import { useEffect, useRef, useState, useCallback } from 'react' import { useEffect, useRef, useState, useCallback } from 'react'
import { useNavigate, useParams } from 'react-router-dom' import { useNavigate, useParams } from 'react-router-dom'
import client from '../api/client' import client from '../api/client'
import { useFormat, useTranslation } from '@xenia/i18n'
import useAuthStore from '../store/authStore' import useAuthStore from '../store/authStore'
import useChatStore from '../store/chatStore' import useChatStore from '../store/chatStore'
// ─── Helpers ────────────────────────────────────────────────────────────────── // ─── 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 date = new Date(dateStr)
const now = new Date() const now = new Date()
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()) const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
@@ -19,9 +16,9 @@ function formatDateLabel(dateStr) {
yesterday.setDate(yesterday.getDate() - 1) yesterday.setDate(yesterday.getDate() - 1)
const d = new Date(date.getFullYear(), date.getMonth(), date.getDate()) const d = new Date(date.getFullYear(), date.getMonth(), date.getDate())
if (d.getTime() === today.getTime()) return 'Σήμερα' if (d.getTime() === today.getTime()) return t('chat.today')
if (d.getTime() === yesterday.getTime()) return 'Χθες' if (d.getTime() === yesterday.getTime()) return t('chat.yesterdayCap')
return date.toLocaleDateString('el-GR', { weekday: 'long', day: 'numeric', month: 'long' }) return formatDateTime(date, { weekday: 'long', day: 'numeric', month: 'long' })
} }
function sameDay(a, b) { function sameDay(a, b) {
@@ -34,6 +31,8 @@ function sameDay(a, b) {
// ─── Message bubble ─────────────────────────────────────────────────────────── // ─── Message bubble ───────────────────────────────────────────────────────────
function MessageBubble({ msg, isOwn, showSender, isGroup }) { function MessageBubble({ msg, isOwn, showSender, isGroup }) {
const { t } = useTranslation('waiter')
const { formatTime } = useFormat()
if (msg.is_deleted) { if (msg.is_deleted) {
return ( return (
<div style={{ <div style={{
@@ -44,7 +43,7 @@ function MessageBubble({ msg, isOwn, showSender, isGroup }) {
background: 'var(--bg3)', background: 'var(--bg3)',
}}> }}>
<span style={{ fontSize: 13, color: 'var(--muted)', fontStyle: 'italic' }}> <span style={{ fontSize: 13, color: 'var(--muted)', fontStyle: 'italic' }}>
Το μήνυμα διαγράφηκε {t('chat.deleted')}
</span> </span>
</div> </div>
) )
@@ -142,6 +141,7 @@ function AutoTextarea({ value, onChange, onSubmit, placeholder }) {
// ─── Leave confirmation modal ───────────────────────────────────────────────── // ─── Leave confirmation modal ─────────────────────────────────────────────────
function LeaveModal({ onConfirm, onCancel }) { function LeaveModal({ onConfirm, onCancel }) {
const { t } = useTranslation('waiter')
return ( return (
<div className="modal-overlay" onClick={onCancel}> <div className="modal-overlay" onClick={onCancel}>
<div <div
@@ -150,12 +150,12 @@ function LeaveModal({ onConfirm, onCancel }) {
style={{ maxHeight: 'auto' }} style={{ maxHeight: 'auto' }}
> >
<div className="modal-handle" /> <div className="modal-handle" />
<h2 className="modal-title" style={{ marginBottom: 8 }}>Αποχώρηση από ομάδα;</h2> <h2 className="modal-title" style={{ marginBottom: 8 }}>{t('chat.leaveTitle')}</h2>
<p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 20 }}> <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 20 }}>
Δεν θα λαμβάνετε πλέον μηνύματα από αυτή την ομάδα. {t('chat.leaveBody')}
</p> </p>
<div style={{ display: 'flex', gap: 10 }}> <div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onCancel}>Ακύρωση</button> <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onCancel}>{t('common.cancel')}</button>
<button <button
style={{ style={{
flex: 1, height: 44, borderRadius: 12, border: 'none', flex: 1, height: 44, borderRadius: 12, border: 'none',
@@ -164,7 +164,7 @@ function LeaveModal({ onConfirm, onCancel }) {
}} }}
onClick={onConfirm} onClick={onConfirm}
> >
Αποχώρηση {t('chat.leave')}
</button> </button>
</div> </div>
</div> </div>
@@ -175,6 +175,8 @@ function LeaveModal({ onConfirm, onCancel }) {
// ─── Main page ──────────────────────────────────────────────────────────────── // ─── Main page ────────────────────────────────────────────────────────────────
export default function ChatThreadPage() { export default function ChatThreadPage() {
const { t } = useTranslation('waiter')
const { formatDateTime } = useFormat()
const { conversationId } = useParams() const { conversationId } = useParams()
const navigate = useNavigate() const navigate = useNavigate()
const { user } = useAuthStore() const { user } = useAuthStore()
@@ -205,8 +207,8 @@ export default function ChatThreadPage() {
const isGroup = conv?.type === 'group' const isGroup = conv?.type === 'group'
const title = isGroup const title = isGroup
? (conv?.name || 'Ομάδα') ? (conv?.name || t('chat.group'))
: (conv?.participants?.find(p => p.user_id !== user?.id)?.username || 'Συνομιλία') : (conv?.participants?.find(p => p.user_id !== user?.id)?.username || t('chat.conversation'))
// ── Mark as read ───────────────────────────────────────────────────────────── // ── Mark as read ─────────────────────────────────────────────────────────────
@@ -418,7 +420,7 @@ export default function ChatThreadPage() {
if (!prev || !sameDay(prev.sent_at, msg.sent_at)) { if (!prev || !sameDay(prev.sent_at, msg.sent_at)) {
items.push( items.push(
<DateSeparator key={`date-${msg.id}`} label={formatDateLabel(msg.sent_at)} /> <DateSeparator key={`date-${msg.id}`} label={formatDateLabel(msg.sent_at, t, formatDateTime)} />
) )
} }
@@ -458,7 +460,7 @@ export default function ChatThreadPage() {
<svg width="20" height="20" viewBox="0 0 20 20" fill="none"> <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/> <path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg> </svg>
Πίσω {t('common.back')}
</button> </button>
<div style={{ flex: 1, textAlign: 'center', minWidth: 0 }}> <div style={{ flex: 1, textAlign: 'center', minWidth: 0 }}>
@@ -470,7 +472,7 @@ export default function ChatThreadPage() {
</span> </span>
{isGroup && ( {isGroup && (
<span style={{ fontSize: 11, color: 'var(--muted)', display: 'block', marginTop: -2 }}> <span style={{ fontSize: 11, color: 'var(--muted)', display: 'block', marginTop: -2 }}>
{(conv?.participants || []).length} μέλη {t('chat.members', { count: (conv?.participants || []).length })}
</span> </span>
)} )}
</div> </div>
@@ -484,7 +486,7 @@ export default function ChatThreadPage() {
padding: '0 4px', minHeight: 44, borderRadius: 8, flexShrink: 0, padding: '0 4px', minHeight: 44, borderRadius: 8, flexShrink: 0,
}} }}
> >
Αποχώρηση {t('chat.leave')}
</button> </button>
) : ( ) : (
<div style={{ width: 72, flexShrink: 0 }} /> <div style={{ width: 72, flexShrink: 0 }} />
@@ -504,13 +506,13 @@ export default function ChatThreadPage() {
> >
{loadingMore && ( {loadingMore && (
<div style={{ textAlign: 'center', padding: '8px 0', color: 'var(--muted)', fontSize: 13 }}> <div style={{ textAlign: 'center', padding: '8px 0', color: 'var(--muted)', fontSize: 13 }}>
Φόρτωση παλαιότερων… {t('chat.loadingOlder')}
</div> </div>
)} )}
{initialLoad && ( {initialLoad && (
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}> <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<span style={{ color: 'var(--muted)', fontSize: 14 }}>Φόρτωση…</span> <span style={{ color: 'var(--muted)', fontSize: 14 }}>{t('common.loading')}</span>
</div> </div>
)} )}
@@ -521,7 +523,7 @@ export default function ChatThreadPage() {
}}> }}>
<span style={{ fontSize: 40 }}>💬</span> <span style={{ fontSize: 40 }}>💬</span>
<p style={{ fontSize: 15, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5 }}> <p style={{ fontSize: 15, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5 }}>
Δεν υπάρχουν μηνύματα ακόμα.{'\n'}Πείτε γεια! {t('chat.emptyThread')}{'\n'}{t('chat.sayHi')}
</p> </p>
</div> </div>
)} )}
@@ -542,7 +544,7 @@ export default function ChatThreadPage() {
value={inputText} value={inputText}
onChange={e => setInputText(e.target.value)} onChange={e => setInputText(e.target.value)}
onSubmit={sendMessage} onSubmit={sendMessage}
placeholder="Γράψτε μήνυμα…" placeholder={t('chat.placeholder')}
/> />
<button <button
+8 -6
View File
@@ -2,11 +2,13 @@ import client from '../api/client'
import { deliveryMode } from '../config/server' import { deliveryMode } from '../config/server'
import { canRediscover, rediscover } from '../native/autoRediscover' import { canRediscover, rediscover } from '../native/autoRediscover'
import { useState } from 'react' import { useState } from 'react'
import { useTranslation } from '@xenia/i18n'
// Shown at /offline, and (plan step 4.1) instead of the whole app when the server can't be // Shown at /offline, and (plan step 4.1) instead of the whole app when the server can't be
// reached on a start with no cached bootstrap (the app retries by itself and then opens the // reached on a start with no cached bootstrap (the app retries by itself and then opens the
// screen the address asks for). // screen the address asks for).
export default function OfflinePage() { export default function OfflinePage() {
const { t } = useTranslation('waiter')
const [checking, setChecking] = useState(false) const [checking, setChecking] = useState(false)
const [search, setSearch] = useState(null) // null | { done, total } | 'not-found' const [search, setSearch] = useState(null) // null | { done, total } | 'not-found'
@@ -37,12 +39,12 @@ export default function OfflinePage() {
<div className="page page--centered"> <div className="page page--centered">
<div style={{ textAlign: 'center', maxWidth: 300 }}> <div style={{ textAlign: 'center', maxWidth: 300 }}>
<p style={{ fontSize: 48, marginBottom: 16 }}>📡</p> <p style={{ fontSize: 48, marginBottom: 16 }}>📡</p>
<h2 style={{ color: '#e2e8f0', marginBottom: 8 }}>Δεν υπάρχει σύνδεση</h2> <h2 style={{ color: '#e2e8f0', marginBottom: 8 }}>{t('offline.title')}</h2>
<p style={{ color: '#64748b', marginBottom: 32 }}> <p style={{ color: '#64748b', marginBottom: 32 }}>
Δεν είναι δυνατή η επικοινωνία με το σύστημα. Ελέγξτε τη σύνδεση WiFi. {t('offline.body')}
</p> </p>
<button className="btn btn--primary btn--lg" onClick={retry} disabled={checking || searching}> <button className="btn btn--primary btn--lg" onClick={retry} disabled={checking || searching}>
{checking ? 'Έλεγχος…' : 'Επανάληψη'} {checking ? t('venues.checking') : t('common.retry')}
</button> </button>
{canRediscover() && ( {canRediscover() && (
<button <button
@@ -51,12 +53,12 @@ export default function OfflinePage() {
onClick={searchNetwork} onClick={searchNetwork}
disabled={searching} disabled={searching}
> >
{searching ? `Αναζήτηση… ${search.done}/${search.total}` : 'Αναζήτηση server στο δίκτυο'} {searching ? t('offline.searching', { done: search.done, total: search.total }) : t('offline.search')}
</button> </button>
)} )}
{search === 'not-found' && ( {search === 'not-found' && (
<p style={{ color: '#94a3b8', fontSize: 13, marginTop: 12, lineHeight: 1.45 }}> <p style={{ color: '#94a3b8', fontSize: 13, marginTop: 12, lineHeight: 1.45 }}>
Ο server δεν βρέθηκε στο δίκτυο. Ελέγξτε ότι είναι αναμμένος, ή σαρώστε ξανά το QR από τον διαχειριστή. {t('offline.notFound')}
</p> </p>
)} )}
{deliveryMode() === 'native' && ( {deliveryMode() === 'native' && (
@@ -66,7 +68,7 @@ export default function OfflinePage() {
onClick={() => { window.location.href = '/venues' }} onClick={() => { window.location.href = '/venues' }}
disabled={searching} disabled={searching}
> >
Αλλαγή καταστήματος {t('offline.changeVenue')}
</button> </button>
)} )}
</div> </div>
+53 -57
View File
@@ -2,25 +2,12 @@ import { useState, useEffect, useCallback, useRef } from 'react'
import { useSearchParams } from 'react-router-dom' import { useSearchParams } from 'react-router-dom'
import AppShell from '../components/AppShell' import AppShell from '../components/AppShell'
import client from '../api/client' import client from '../api/client'
import { useFormat, useTranslation } from '@xenia/i18n'
import { money as fmtPrice } from '../i18n'
// ── helpers ─────────────────────────────────────────────────────────────────── // ── helpers ───────────────────────────────────────────────────────────────────
function fmtTime(iso) { // times in the venue's clock and the language's format: useFormat() in each component (4.5)
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)
}
// ── icons ───────────────────────────────────────────────────────────────────── // ── icons ─────────────────────────────────────────────────────────────────────
@@ -86,6 +73,8 @@ function FilterIcon() {
// ── action sheet — long-press on detailed cards ─────────────────────────────── // ── action sheet — long-press on detailed cards ───────────────────────────────
function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) { function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
const { t } = useTranslation('waiter')
const { formatTime: fmtTime } = useFormat()
return ( return (
<div <div
onClick={onClose} onClick={onClose}
@@ -106,13 +95,13 @@ function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
> >
<div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 16px' }} /> <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 16px' }} />
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 4 }}> <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 4 }}>
Πρόβλημα Εκτύπωσης {t('log.printProblem')}
</div> </div>
<div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 20 }}> <div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 20 }}>
Παραγγελία #{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 > 0 && (
<span style={{ marginLeft: 8, color: '#f59e0b' }}> <span style={{ marginLeft: 8, color: '#f59e0b' }}>
{order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'} {t('log.retries', { count: order.print_retry_count })}
</span> </span>
)} )}
</div> </div>
@@ -127,7 +116,7 @@ function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
opacity: busy ? 0.6 : 1, opacity: busy ? 0.6 : 1,
}} }}
> >
{busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'} {busy ? t('add.sending') : t('log.printNow')}
</button> </button>
<button <button
onClick={onCancel} onClick={onCancel}
@@ -140,7 +129,7 @@ function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
opacity: busy ? 0.6 : 1, opacity: busy ? 0.6 : 1,
}} }}
> >
Ακύρωση Εκτύπωσης {t('log.cancelPrint')}
</button> </button>
<button <button
onClick={onClose} onClick={onClose}
@@ -150,7 +139,7 @@ function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
fontSize: 15, color: 'var(--muted)', cursor: 'pointer', fontSize: 15, color: 'var(--muted)', cursor: 'pointer',
}} }}
> >
Κλείσιμο {t('common.close')}
</button> </button>
</div> </div>
</div> </div>
@@ -161,6 +150,7 @@ function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
// ── filter sheet ────────────────────────────────────────────────────────────── // ── filter sheet ──────────────────────────────────────────────────────────────
function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) { function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
const { t } = useTranslation('waiter')
const [localFilter, setLocalFilter] = useState(filter) const [localFilter, setLocalFilter] = useState(filter)
const [localFrom, setLocalFrom] = useState(dateFrom) const [localFrom, setLocalFrom] = useState(dateFrom)
const [localTo, setLocalTo] = useState(dateTo) const [localTo, setLocalTo] = useState(dateTo)
@@ -184,18 +174,18 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
}} }}
> >
<div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 20px' }} /> <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 20px' }} />
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>Φίλτρα</div> <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>{t('tables.filter.title')}</div>
{/* Status filter */} {/* Status filter */}
<div style={{ marginBottom: 20 }}> <div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}> <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
Κατάσταση {t('tables.filter.status')}
</div> </div>
<div style={{ display: 'flex', gap: 8 }}> <div style={{ display: 'flex', gap: 8 }}>
{[ {[
{ value: 'all', label: 'Όλες' }, { value: 'all', label: t('orders.chips.all') },
{ value: 'success', label: 'Επιτυχής' }, { value: 'success', label: t('log.ok') },
{ value: 'failed', label: 'Αποτυχημένη' }, { value: 'failed', label: t('log.failedF') },
].map(opt => ( ].map(opt => (
<button <button
key={opt.value} key={opt.value}
@@ -218,11 +208,11 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
{/* Date range */} {/* Date range */}
<div style={{ marginBottom: 24 }}> <div style={{ marginBottom: 24 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}> <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
Εύρος ημερομηνίας/ώρας {t('log.range')}
</div> </div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>Από</span> <span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>{t('log.from')}</span>
<input <input
type="datetime-local" type="datetime-local"
value={localFrom} value={localFrom}
@@ -236,7 +226,7 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
/> />
</div> </div>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>Έως</span> <span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>{t('log.to')}</span>
<input <input
type="datetime-local" type="datetime-local"
value={localTo} value={localTo}
@@ -257,7 +247,7 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0', background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0',
}} }}
> >
Καθαρισμός ημερομηνίας {t('log.clearDates')}
</button> </button>
)} )}
</div> </div>
@@ -271,7 +261,7 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
fontSize: 15, fontWeight: 700, cursor: 'pointer', fontSize: 15, fontWeight: 700, cursor: 'pointer',
}} }}
> >
Εφαρμογή {t('common.apply')}
</button> </button>
</div> </div>
</div> </div>
@@ -281,6 +271,7 @@ function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
// ── compact card (click = expand inline, expanded shows action buttons) ──────── // ── compact card (click = expand inline, expanded shows action buttons) ────────
function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) { function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
const { t } = useTranslation('waiter')
const isPending = order.print_status === 'pending' const isPending = order.print_status === 'pending'
return ( return (
@@ -315,7 +306,7 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
{/* Row 2: item count | total */} {/* Row 2: item count | total */}
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 5 }}> <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 5 }}>
<span style={{ fontSize: 12, color: 'var(--muted)' }}> <span style={{ fontSize: 12, color: 'var(--muted)' }}>
{order.items.length} αντ. {t('log.itemsShort', { count: order.items.length })}
</span> </span>
<span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)' }}> <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)' }}>
{fmtPrice(order.total)} {fmtPrice(order.total)}
@@ -343,11 +334,11 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
<div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} /> <div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />
<div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 4 }}> <div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 4 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontSize: 14, fontWeight: 600, color: 'var(--muted)' }}>Σύνολο</span> <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--muted)' }}>{t('common.total')}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
{isPending && order.print_retry_count > 0 && ( {isPending && order.print_retry_count > 0 && (
<span style={{ fontSize: 11, color: '#f59e0b' }}> <span style={{ fontSize: 11, color: '#f59e0b' }}>
{order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'} {t('log.retries', { count: order.print_retry_count })}
</span> </span>
)} )}
<span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{fmtPrice(order.total)}</span> <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{fmtPrice(order.total)}</span>
@@ -355,9 +346,9 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
</div> </div>
{order.fiscal_status && ( {order.fiscal_status && (
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}> <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Φορολογική εκτύπωση</span> <span style={{ color: 'var(--muted)' }}>{t('log.fiscal')}</span>
<span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}> <span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}>
{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')}
</span> </span>
</div> </div>
)} )}
@@ -376,7 +367,7 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
opacity: busy ? 0.6 : 1, opacity: busy ? 0.6 : 1,
}} }}
> >
{busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'} {busy ? t('add.sending') : t('log.printNow')}
</button> </button>
<button <button
onClick={() => onCancel(order)} onClick={() => onCancel(order)}
@@ -389,7 +380,7 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
opacity: busy ? 0.6 : 1, opacity: busy ? 0.6 : 1,
}} }}
> >
Ακύρωση {t('log.cancel')}
</button> </button>
</div> </div>
</> </>
@@ -403,6 +394,9 @@ function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
// ── detailed card (long-press = action sheet) ───────────────────────────────── // ── detailed card (long-press = action sheet) ─────────────────────────────────
function DetailedCard({ order, onLongPress }) { function DetailedCard({ order, onLongPress }) {
const { t } = useTranslation('waiter')
const { formatDateTime: fmtDateTime } = useFormat()
const { formatTime: fmtTime } = useFormat()
const isPending = order.print_status === 'pending' const isPending = order.print_status === 'pending'
const pressTimer = useRef(null) const pressTimer = useRef(null)
@@ -450,22 +444,22 @@ function DetailedCard({ order, onLongPress }) {
{/* Meta rows */} {/* Meta rows */}
<div style={{ padding: '10px 14px', display: 'flex', flexDirection: 'column', gap: 5 }}> <div style={{ padding: '10px 14px', display: 'flex', flexDirection: 'column', gap: 5 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}> <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Παραγγέλθηκε</span> <span style={{ color: 'var(--muted)' }}>{t('summary.ordered')}</span>
<span style={{ color: 'var(--text)', fontWeight: 500 }}>{fmtDateTime(order.opened_at)}</span> <span style={{ color: 'var(--text)', fontWeight: 500 }}>{fmtDateTime(order.opened_at)}</span>
</div> </div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}> <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Εκτύπωση</span> <span style={{ color: 'var(--muted)' }}>{t('log.print')}</span>
<span style={{ fontWeight: 600, color: isPending ? '#ef4444' : '#22c55e' }}> <span style={{ fontWeight: 600, color: isPending ? '#ef4444' : '#22c55e' }}>
{isPending {isPending
? `Εκκρεμεί (${order.print_retry_count} επαν.)` ? t('log.pendingRetries', { count: order.print_retry_count })
: `OK ${fmtTime(order.print_attempted_at)}`} : `OK ${fmtTime(order.print_attempted_at)}`}
</span> </span>
</div> </div>
{order.fiscal_status && ( {order.fiscal_status && (
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}> <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Φορολογική εκτύπωση</span> <span style={{ color: 'var(--muted)' }}>{t('log.fiscal')}</span>
<span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}> <span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}>
{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')}
</span> </span>
</div> </div>
)} )}
@@ -493,13 +487,13 @@ function DetailedCard({ order, onLongPress }) {
{/* Total */} {/* Total */}
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 14px', fontSize: 14 }}> <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 14px', fontSize: 14 }}>
<span style={{ color: 'var(--muted)', fontWeight: 600 }}>Σύνολο</span> <span style={{ color: 'var(--muted)', fontWeight: 600 }}>{t('common.total')}</span>
<span style={{ color: 'var(--text)', fontWeight: 700 }}>{fmtPrice(order.total)}</span> <span style={{ color: 'var(--text)', fontWeight: 700 }}>{fmtPrice(order.total)}</span>
</div> </div>
{isPending && ( {isPending && (
<div style={{ padding: '0 14px 10px', textAlign: 'center' }}> <div style={{ padding: '0 14px 10px', textAlign: 'center' }}>
<span style={{ fontSize: 11, color: 'var(--muted)' }}>Κρατήστε πατημένο για επιλογές</span> <span style={{ fontSize: 11, color: 'var(--muted)' }}>{t('log.holdForOptions')}</span>
</div> </div>
)} )}
</div> </div>
@@ -509,6 +503,8 @@ function DetailedCard({ order, onLongPress }) {
// ── main page ───────────────────────────────────────────────────────────────── // ── main page ─────────────────────────────────────────────────────────────────
export default function OrderLogPage() { export default function OrderLogPage() {
const { t } = useTranslation('waiter')
const { formatDateTime } = useFormat()
const [searchParams] = useSearchParams() const [searchParams] = useSearchParams()
const initialFilter = searchParams.get('filter') === 'failed' ? 'failed' : 'all' const initialFilter = searchParams.get('filter') === 'failed' ? 'failed' : 'all'
@@ -605,7 +601,7 @@ export default function OrderLogPage() {
const hasActiveFilters = filter !== 'all' || !!dateFrom || !!dateTo const hasActiveFilters = filter !== 'all' || !!dateFrom || !!dateTo
return ( return (
<AppShell title="Αρχ. Παραγγ."> <AppShell title={t('log.titleShort')}>
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}> <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>
{/* Toolbar */} {/* Toolbar */}
@@ -617,7 +613,7 @@ export default function OrderLogPage() {
}}> }}>
<input <input
type="search" type="search"
placeholder="Τραπέζι, #παραγγελία, αντικείμενο…" placeholder={t('log.searchPlaceholder')}
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
style={{ style={{
@@ -636,7 +632,7 @@ export default function OrderLogPage() {
display: 'flex', alignItems: 'center', justifyContent: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer', cursor: 'pointer',
}} }}
title={view === 'compact' ? 'Λεπτομερής προβολή' : 'Συμπαγής προβολή'} title={view === 'compact' ? t('log.detailedView') : t('log.compactView')}
> >
{view === 'compact' ? <DetailedIcon active={false} /> : <CompactIcon active={false} />} {view === 'compact' ? <DetailedIcon active={false} /> : <CompactIcon active={false} />}
</button> </button>
@@ -656,7 +652,7 @@ export default function OrderLogPage() {
<path d="M12 8v4M12 16h.01" stroke="#ef4444" strokeWidth="2" strokeLinecap="round"/> <path d="M12 8v4M12 16h.01" stroke="#ef4444" strokeWidth="2" strokeLinecap="round"/>
</svg> </svg>
<span style={{ fontSize: 13, color: '#ef4444', fontWeight: 600 }}> <span style={{ fontSize: 13, color: '#ef4444', fontWeight: 600 }}>
{pendingCount} παραγγελί{pendingCount !== 1 ? 'ες' : 'α'} με πρόβλημα εκτύπωσης {t('log.printProblems', { count: pendingCount })}
</span> </span>
</div> </div>
)} )}
@@ -676,24 +672,24 @@ export default function OrderLogPage() {
color: filter === 'failed' ? '#ef4444' : '#22c55e', color: filter === 'failed' ? '#ef4444' : '#22c55e',
fontWeight: 600, fontWeight: 600,
}}> }}>
{filter === 'failed' ? 'Αποτυχημένη εκτύπωση' : 'Επιτυχής εκτύπωση'} {filter === 'failed' ? t('log.printFailed') : t('log.printOk')}
</span> </span>
)} )}
{dateFrom && ( {dateFrom && (
<span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}> <span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}>
Από {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')}
</span> </span>
)} )}
{dateTo && ( {dateTo && (
<span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}> <span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}>
Έως {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')}
</span> </span>
)} )}
<button <button
onClick={() => { setFilter('all'); setDateFrom(''); setDateTo('') }} onClick={() => { setFilter('all'); setDateFrom(''); setDateTo('') }}
style={{ fontSize: 12, color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer', padding: '3px 6px' }} style={{ fontSize: 12, color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer', padding: '3px 6px' }}
> >
✕ Καθαρισμός ✕ {t('common.clear')}
</button> </button>
</div> </div>
)} )}
@@ -701,11 +697,11 @@ export default function OrderLogPage() {
{/* List */} {/* List */}
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px 80px', display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px 80px', display: 'flex', flexDirection: 'column', gap: 8 }}>
{loading && ( {loading && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}>Φόρτωση…</p> <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}>{t('common.loading')}</p>
)} )}
{!loading && filtered.length === 0 && ( {!loading && filtered.length === 0 && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}> <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}>
{search || hasActiveFilters ? 'Δεν βρέθηκαν παραγγελίες' : 'Δεν υπάρχουν παραγγελίες σε αυτή τη βάρδια'} {search || hasActiveFilters ? t('log.noneFound') : t('log.noneThisShift')}
</p> </p>
)} )}
{filtered.map(order => {filtered.map(order =>
@@ -744,7 +740,7 @@ export default function OrderLogPage() {
display: 'flex', alignItems: 'center', justifyContent: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center',
zIndex: 10, zIndex: 10,
}} }}
title="Φίλτρα" title={t('tables.filter.title')}
> >
<FilterIcon /> <FilterIcon />
{hasActiveFilters && ( {hasActiveFilters && (
+28 -29
View File
@@ -1,27 +1,22 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import AppShell from '../components/AppShell' import AppShell from '../components/AppShell'
import client from '../api/client' import client from '../api/client'
import { useFormat, useTranslation } from '@xenia/i18n'
import { money as fmtEuro, tw } from '../i18n'
import { getVenueSettings } from '../api/venueSettings' import { getVenueSettings } from '../api/venueSettings'
// ── helpers ─────────────────────────────────────────────────────────────────── // ── helpers ───────────────────────────────────────────────────────────────────
function fmtTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}
function fmtDuration(seconds) { function fmtDuration(seconds) {
if (seconds == null || seconds < 0) return '—' if (seconds == null || seconds < 0) return '—'
const h = Math.floor(seconds / 3600) const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60) const m = Math.floor((seconds % 3600) / 60)
if (h === 0) return `${m}λ` if (h === 0) return tw('common.minutesShort', { m })
if (m === 0) return `${h}ω` if (m === 0) return tw('common.hoursShort', { h })
return `${h}ω ${m}λ` return tw('common.hoursMinutesShort', { h, m })
} }
function fmtEuro(n) {
return '€' + parseFloat(n || 0).toFixed(2)
}
function sinceSeconds(isoStart) { function sinceSeconds(isoStart) {
if (!isoStart) return 0 if (!isoStart) return 0
@@ -101,6 +96,8 @@ function PerHourChart({ title, data, accent = 'var(--accent)' }) {
// ── breaks timeline ─────────────────────────────────────────────────────────── // ── breaks timeline ───────────────────────────────────────────────────────────
function BreakRow({ brk, index }) { function BreakRow({ brk, index }) {
const { t } = useTranslation('waiter')
const { formatTime: fmtTime } = useFormat()
const dur = breakDurationSeconds(brk) const dur = breakDurationSeconds(brk)
const active = !brk.ended_at const active = !brk.ended_at
return ( return (
@@ -118,7 +115,7 @@ function BreakRow({ brk, index }) {
}}>{index + 1}</div> }}>{index + 1}</div>
<div style={{ flex: 1 }}> <div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}> <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
{fmtTime(brk.started_at)} – {active ? 'Τώρα' : fmtTime(brk.ended_at)} {fmtTime(brk.started_at)} – {active ? t('shiftPage.now') : fmtTime(brk.ended_at)}
</div> </div>
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}> <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>
{fmtDuration(dur)} {fmtDuration(dur)}
@@ -128,7 +125,7 @@ function BreakRow({ brk, index }) {
<span style={{ <span style={{
fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999,
background: '#f97316', color: 'white', background: '#f97316', color: 'white',
}}>ΕΝΕΡΓΟ</span> }}>{t('venues.active')}</span>
)} )}
</div> </div>
) )
@@ -137,6 +134,8 @@ function BreakRow({ brk, index }) {
// ── main page ───────────────────────────────────────────────────────────────── // ── main page ─────────────────────────────────────────────────────────────────
export default function ShiftOverviewPage() { export default function ShiftOverviewPage() {
const { t } = useTranslation('waiter')
const { formatTime: fmtTime } = useFormat()
const { data: shift, isLoading: shiftLoading } = useQuery({ const { data: shift, isLoading: shiftLoading } = useQuery({
queryKey: ['my-shift'], queryKey: ['my-shift'],
queryFn: () => client.get('/api/shifts/my').then(r => r.data), queryFn: () => client.get('/api/shifts/my').then(r => r.data),
@@ -164,7 +163,7 @@ export default function ShiftOverviewPage() {
return ( return (
<AppShell title="Shift Overview"> <AppShell title="Shift Overview">
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 14 }}> <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 14 }}>
Φόρτωση… {t('common.loading')}
</div> </div>
</AppShell> </AppShell>
) )
@@ -175,8 +174,8 @@ export default function ShiftOverviewPage() {
<AppShell title="Shift Overview"> <AppShell title="Shift Overview">
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, padding: 24, textAlign: 'center' }}> <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, padding: 24, textAlign: 'center' }}>
<div style={{ fontSize: 40 }}>⏸</div> <div style={{ fontSize: 40 }}>⏸</div>
<div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>Δεν υπάρχει ενεργή βάρδια</div> <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>{t('shiftPage.none')}</div>
<div style={{ fontSize: 13, color: 'var(--muted)' }}>Ξεκινήστε βάρδια για να δείτε στατιστικά.</div> <div style={{ fontSize: 13, color: 'var(--muted)' }}>{t('shiftPage.noneSub')}</div>
</div> </div>
</AppShell> </AppShell>
) )
@@ -219,9 +218,9 @@ export default function ShiftOverviewPage() {
}}> }}>
<span style={{ fontSize: 20 }}>☕</span> <span style={{ fontSize: 20 }}>☕</span>
<div> <div>
<div style={{ fontSize: 14, fontWeight: 700, color: '#f97316' }}>Σε διάλειμμα</div> <div style={{ fontSize: 14, fontWeight: 700, color: '#f97316' }}>{t('shiftPage.onBreak')}</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}> <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>
από {fmtTime(activeBreak.started_at)} · {fmtDuration(breakDurationSeconds(activeBreak))} μέχρι τώρα {t('shiftPage.breakSince', { time: fmtTime(activeBreak.started_at), duration: fmtDuration(breakDurationSeconds(activeBreak)) })}
</div> </div>
</div> </div>
</div> </div>
@@ -229,18 +228,18 @@ export default function ShiftOverviewPage() {
{/* Hero stats grid */} {/* Hero stats grid */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 20 }}> <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 20 }}>
<StatCard label="Έναρξη" value={fmtTime(shift.started_at)} /> <StatCard label={t('shiftPage.start')} value={fmtTime(shift.started_at)} />
<StatCard label="Ώρες Εργασίας" value={fmtDuration(workedSec)} sub={`${fmtDuration(totalBreakSec)} διαλείμματα`} /> <StatCard label={t('shiftPage.worked')} value={fmtDuration(workedSec)} sub={t('shiftPage.breaksSub', { duration: fmtDuration(totalBreakSec) })} />
<StatCard label="Αρχ. Μετρητά" value={fmtEuro(shift.starting_cash)} /> <StatCard label={t('shiftPage.startCash')} value={fmtEuro(shift.starting_cash)} />
{!hideRevenue && ( {!hideRevenue && (
<StatCard label="Είσπραξη" value={fmtEuro(shift.total_collected)} accent="var(--success, #22c55e)" /> <StatCard label={t('shiftPage.collected')} value={fmtEuro(shift.total_collected)} accent="var(--success, #22c55e)" />
)} )}
{!hideRevenue && ( {!hideRevenue && (
<StatCard label="Παραδ. Ποσό" value={fmtEuro(shift.net_to_deliver)} sub="Αρχ. + Είσπραξη" accent="var(--accent)" /> <StatCard label={t('shiftPage.toHandIn')} value={fmtEuro(shift.net_to_deliver)} sub={t('shiftPage.toHandInSub')} accent="var(--accent)" />
)} )}
<StatCard label="Ανοιχτά Τραπέζια" value={String(openOrders.length)} sub="τρέχουσες παραγγελίες" /> <StatCard label={t('shiftPage.openTables')} value={String(openOrders.length)} sub={t('shiftPage.openTablesSub')} />
<StatCard label="Είδη (ανοιχτά)" value={String(totalItems)} /> <StatCard label={t('shiftPage.items')} value={String(totalItems)} />
<StatCard label="Διαλείμματα" value={String((shift.breaks || []).length)} sub={`${fmtDuration(totalBreakSec)} σύνολο`} /> <StatCard label={t('shiftPage.breaks')} value={String((shift.breaks || []).length)} sub={t('shiftPage.totalSub', { duration: fmtDuration(totalBreakSec) })} />
</div> </div>
{/* Per-hour charts */} {/* Per-hour charts */}
@@ -249,9 +248,9 @@ export default function ShiftOverviewPage() {
background: 'var(--bg2)', border: '1px solid var(--border)', background: 'var(--bg2)', border: '1px solid var(--border)',
borderRadius: 16, padding: '16px 18px', marginBottom: 20, borderRadius: 16, padding: '16px 18px', marginBottom: 20,
}}> }}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>Ανά Ώρα</div> <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>{t('shiftPage.perHour')}</div>
<PerHourChart title="Παραγγελίες" data={ordersByHour} /> <PerHourChart title={t('nav.orders')} data={ordersByHour} />
<PerHourChart title="Είδη" data={itemsByHour} /> <PerHourChart title={t('shiftPage.itemsShort')} data={itemsByHour} />
</div> </div>
)} )}
@@ -259,7 +258,7 @@ export default function ShiftOverviewPage() {
{(shift.breaks || []).length > 0 && ( {(shift.breaks || []).length > 0 && (
<div> <div>
<div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}> <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>
Διαλείμματα ({shift.breaks.length}) {t('shiftPage.breaksCount', { count: shift.breaks.length })}
</div> </div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{shift.breaks.map((b, i) => <BreakRow key={b.id} brk={b} index={i} />)} {shift.breaks.map((b, i) => <BreakRow key={b.id} brk={b} index={i} />)}
+6 -5
View File
@@ -1,6 +1,7 @@
import db from '../db/posdb' import db from '../db/posdb'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors' 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 // 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 // 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) // 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)) { 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.offline_orders.update(entry.localId, { synced: 1 })
await db.pos_orders.delete(`offline_${entry.uuid}`) await db.pos_orders.delete(`offline_${entry.uuid}`)
continue continue
@@ -296,7 +297,7 @@ async function _flushCreateOrder(op, idMap) {
const synthetic = await db.pos_orders.get(op.localOrderId) const synthetic = await db.pos_orders.get(op.localOrderId)
// queued before 4.4: nothing the server can price → all refused, no empty order opened // queued before 4.4: nothing the server can price → all refused, no empty order opened
if (!op.items.some(i => i._wire)) { 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 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_orders.where('uuid').equals(op.uuid).modify({ synced: 1 })
await db.offline_ops.update(op.localId, { 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_KEY = 'refused_lines'
const REFUSED = 'refused' 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 }]. */ /** Lines the server refused when an offline order was sent: [{ at, tableId, product, quantity, reason }]. */
export async function refusedLines() { export async function refusedLines() {
@@ -449,7 +450,7 @@ async function postLines(pending, refused, ctx, post) {
const n = refusedLine(err, pending.length) const n = refusedLine(err, pending.length)
if (n == null) throw err if (n == null) throw err
const [{ item }] = pending.splice(n - 1, 1) 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 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] }. * refusals are found again next time). Returns { orderId (null: all refused), sent: [indexes] }.
*/ */
async function sendLines(items, ctx, getOrderId) { 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 } const opts = { noOverride: true }
let pending = items.map((item, index) => ({ item, index })).filter(({ item }) => item._wire) 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)) pending = await postLines(pending, refused, ctx, lines => client.post('/api/orders/quote', { lines }, opts))
+31
View File
@@ -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')}`)
})