From e55157fa866bb37ff880f2b8b55562b777dabacd Mon Sep 17 00:00:00 2001 From: bonamin Date: Wed, 18 Nov 2026 11:27:05 +0200 Subject: [PATCH] feat(menu-app): the QR menu on the customer apps' look, two languages, allergens (platform-v2 step 6.5) - connect_frontend/menu-app rebuilt like the order app: the same tokens (index.css, tailwind.config.js), texts in i18n.js (en, el; the old 'ot_lang' choice carries over), pure logic in src/logic.js with tests (menuFor in the guest's language, QR prices, search in either language, cart, order body, refusals). MenuPage (menu, search, dish sheet, cart, checkout at the table) and ConfirmPage; App.jsx, components/primitives and OrderConfirm removed; react-hot-toast dropped. - Allergens on every dish (contains on the card; contains / may contain on the dish sheet) and in the order app's cards too. Co-Authored-By: Claude Opus 5.5 --- connect_frontend/menu-app/index.html | 3 +- connect_frontend/menu-app/package-lock.json | 33 - connect_frontend/menu-app/package.json | 4 +- connect_frontend/menu-app/src/App.jsx | 13 - connect_frontend/menu-app/src/api.js | 33 +- .../menu-app/src/components/primitives.jsx | 207 --- connect_frontend/menu-app/src/i18n.js | 97 ++ connect_frontend/menu-app/src/index.css | 39 +- connect_frontend/menu-app/src/logic.js | 107 ++ connect_frontend/menu-app/src/main.jsx | 38 +- .../menu-app/src/pages/ConfirmPage.jsx | 55 + .../menu-app/src/pages/MenuPage.jsx | 1292 ++++------------- .../menu-app/src/pages/OrderConfirm.jsx | 115 -- connect_frontend/menu-app/tailwind.config.js | 54 +- .../menu-app/tests/logic.test.mjs | 61 + connect_frontend/order-app/src/i18n.js | 10 + connect_frontend/order-app/src/logic.js | 9 + .../order-app/src/pages/OrderPage.jsx | 17 +- .../order-app/tests/logic.test.mjs | 7 +- 19 files changed, 746 insertions(+), 1448 deletions(-) delete mode 100644 connect_frontend/menu-app/src/App.jsx delete mode 100644 connect_frontend/menu-app/src/components/primitives.jsx create mode 100644 connect_frontend/menu-app/src/i18n.js create mode 100644 connect_frontend/menu-app/src/logic.js create mode 100644 connect_frontend/menu-app/src/pages/ConfirmPage.jsx delete mode 100644 connect_frontend/menu-app/src/pages/OrderConfirm.jsx create mode 100644 connect_frontend/menu-app/tests/logic.test.mjs diff --git a/connect_frontend/menu-app/index.html b/connect_frontend/menu-app/index.html index f554d8e..9279c80 100644 --- a/connect_frontend/menu-app/index.html +++ b/connect_frontend/menu-app/index.html @@ -2,7 +2,8 @@ - + + Menu diff --git a/connect_frontend/menu-app/package-lock.json b/connect_frontend/menu-app/package-lock.json index f8eefb3..13a71c9 100644 --- a/connect_frontend/menu-app/package-lock.json +++ b/connect_frontend/menu-app/package-lock.json @@ -12,7 +12,6 @@ "lucide-react": "^1.14.0", "react": "^18.3.1", "react-dom": "^18.3.1", - "react-hot-toast": "^2.4.1", "react-router-dom": "^6.28.0" }, "devDependencies": { @@ -1579,12 +1578,6 @@ "node": ">=4" } }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "license": "MIT" - }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1930,15 +1923,6 @@ "node": ">=10.13.0" } }, - "node_modules/goober": { - "version": "2.1.19", - "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.19.tgz", - "integrity": "sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg==", - "license": "MIT", - "peerDependencies": { - "csstype": "^3.0.10" - } - }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -2554,23 +2538,6 @@ "react": "^18.3.1" } }, - "node_modules/react-hot-toast": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz", - "integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==", - "license": "MIT", - "dependencies": { - "csstype": "^3.1.3", - "goober": "^2.1.16" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "react": ">=16", - "react-dom": ">=16" - } - }, "node_modules/react-refresh": { "version": "0.17.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", diff --git a/connect_frontend/menu-app/package.json b/connect_frontend/menu-app/package.json index 5678ab6..2502c2d 100644 --- a/connect_frontend/menu-app/package.json +++ b/connect_frontend/menu-app/package.json @@ -6,14 +6,14 @@ "scripts": { "dev": "vite", "build": "vite build", - "preview": "vite preview" + "preview": "vite preview", + "test": "node --test \"tests/*.test.mjs\"" }, "dependencies": { "axios": "^1.7.9", "lucide-react": "^1.14.0", "react": "^18.3.1", "react-dom": "^18.3.1", - "react-hot-toast": "^2.4.1", "react-router-dom": "^6.28.0" }, "devDependencies": { diff --git a/connect_frontend/menu-app/src/App.jsx b/connect_frontend/menu-app/src/App.jsx deleted file mode 100644 index acfce2e..0000000 --- a/connect_frontend/menu-app/src/App.jsx +++ /dev/null @@ -1,13 +0,0 @@ -import { Routes, Route, Navigate } from 'react-router-dom' -import MenuPage from './pages/MenuPage' -import OrderConfirm from './pages/OrderConfirm' - -export default function App() { - return ( - - } /> - } /> - } /> - - ) -} diff --git a/connect_frontend/menu-app/src/api.js b/connect_frontend/menu-app/src/api.js index 0a1280b..a726a70 100644 --- a/connect_frontend/menu-app/src/api.js +++ b/connect_frontend/menu-app/src/api.js @@ -1,30 +1,21 @@ +// The cloud's public endpoints for the QR menu (cloud_backend/routers/menu.py, orders.py). import axios from 'axios' export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || '' +const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 }) -const api = axios.create({ baseURL: CLOUD_URL }) - -/** The menu; with a table's QR token (phase 3S, S.7) it also says which table it is - * (`table`, or `table_invalid`) and whether ordering at the table is on (`table_ordering`). */ -export async function fetchMenu(siteSlug, tableToken) { - const { data } = await api.get(`/api/menu/${siteSlug}`, { params: tableToken ? { t: tableToken } : {} }) - return data -} - -export async function submitOrder(siteSlug, body) { - const { data } = await api.post(`/api/orders/${siteSlug}`, body) - return data // { order_id, public_ref, status } -} - -// The tracking link carries the order's random token (phase 3S, S.2); links from before that -// carry the public ref and use the old endpoint. -export async function fetchOrderStatus(ref) { +/** The menu; with a table's QR token (phase 3S, S.7) also which table it is (`table`, or + * `table_invalid`) and whether ordering at the table is on (`table_ordering`). */ +export const fetchMenu = async (site, tableToken) => + (await api.get(`/api/menu/${encodeURIComponent(site)}`, { params: tableToken ? { t: tableToken } : {} })).data +export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data +/** The tracking link carries the order's random token (S.2); older links carry the public ref. */ +export async function track(ref) { try { - const { data } = await api.get(`/api/orders/track/${ref}`) - return data // { public_ref, status, rejection_reason } + return (await api.get(`/api/orders/track/${encodeURIComponent(ref)}`)).data } catch (err) { if (err?.response?.status !== 404 || !/^ORD-\d+$/.test(ref)) throw err - const { data } = await api.get(`/api/orders/status/${ref}`) - return data + return (await api.get(`/api/orders/status/${encodeURIComponent(ref)}`)).data } } +export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`) diff --git a/connect_frontend/menu-app/src/components/primitives.jsx b/connect_frontend/menu-app/src/components/primitives.jsx deleted file mode 100644 index 17dc6b2..0000000 --- a/connect_frontend/menu-app/src/components/primitives.jsx +++ /dev/null @@ -1,207 +0,0 @@ -import { - Leaf, Sprout, Wheat, Flame, Star, ChefHat, - Minus, Plus, -} from 'lucide-react' - -// ── Money helpers ──────────────────────────────────────────────────────────── -export function eur(n) { - return '€' + Number(n).toFixed(2) -} - -// The price is the QR menu's (sales point qr_table, set in normaliseProduct): since phase 3S -// discounts are price rules already in it, so there is no separate discount to show. -export function discountedPrice(product) { - return product.price ?? 0 -} - -export function basePrice(product) { - return product.price ?? 0 -} - -export function hasDiscount() { - return false -} - -export function discountPct() { - return 0 -} - -// ── Placeholder gradient art ───────────────────────────────────────────────── -export function DishArt({ product, category, size = 'card' }) { - const hue = category?.hue ?? 40 - const GlyphIcon = category?.GlyphIcon ?? null - const id = product?.id ?? 'x' - let seed = 0 - for (let i = 0; i < id.length; i++) seed += id.charCodeAt(i) - const lift = (seed % 5) - 2 - const c1 = `hsl(${hue} 34% ${90 + lift}%)` - const c2 = `hsl(${hue} 30% ${80 + lift}%)` - const glyphColor = `hsl(${hue} 32% 42%)` - const firstName = product?.digital_name || product?.name || '?' - const letter = typeof firstName === 'object' ? (firstName.en?.[0] ?? '?') : (firstName[0] ?? '?') - - const sizeClass = - size === 'hero' - ? 'self-stretch min-h-[100px] w-[100px]' - : size === 'sm' - ? 'h-16 w-16' - : 'h-[92px] w-[92px]' - const iconClass = size === 'sm' ? 'h-7 w-7' : 'h-9 w-9' - - return ( -
- - {letter} - - {GlyphIcon && ( - - )} -
- ) -} - -// ── Badge (Popular / Chef's pick) ──────────────────────────────────────────── -export function Badge({ kind, t }) { - if (kind === 'popular') { - return ( - - - {t?.popular ?? 'Popular'} - - ) - } - if (kind === 'chefs') { - return ( - - - {t?.chefs ?? "Chef's pick"} - - ) - } - return null -} - -// ── Dietary chips (with text labels) ──────────────────────────────────────── -const DIET_STYLE = { - vegan: { Icon: Leaf, fg: '#3f7d4e', bg: '#e7f1e7', ring: '#c9e2cb' }, - vegetarian: { Icon: Sprout, fg: '#5d7a37', bg: '#eef2e0', ring: '#d8e2bd' }, - 'gluten-free': { Icon: Wheat, fg: '#a9842f', bg: '#f5edd8', ring: '#e6d6a6' }, - spicy: { Icon: Flame, fg: '#c2602f', bg: '#f7e6dc', ring: '#eccab3' }, -} - -export function DietChip({ tag, t }) { - const s = DIET_STYLE[tag] - if (!s) return null - const { Icon } = s - const label = t?.dietary?.[tag] ?? tag - return ( - - - {label} - - ) -} - -// ── Compact tag icon badges (card title row) ───────────────────────────────── -const TAG_BADGE = { - vegan: { Icon: Leaf, fg: '#3f7d4e', bg: '#e7f1e7', ring: '#bcdcc0' }, - vegetarian: { Icon: Sprout, fg: '#5d7a37', bg: '#eef2e0', ring: '#cfe0b0' }, - 'gluten-free': { Icon: Wheat, fg: '#9a7726', bg: '#f6edd6', ring: '#e6d49e' }, - spicy: { Icon: Flame, fg: '#c2602f', bg: '#f8e6da', ring: '#eec4ac' }, -} -const PRIORITY_BADGE = { - popular: { Icon: Star, fg: '#a9842f', bg: '#f6edd6', ring: '#e6d49e' }, - chefs: { Icon: ChefHat, fg: '#f0e9d6', bg: '#2d3b2d', ring: '#2d3b2d' }, -} - -export function TagIcons({ product }) { - const items = [] - const badge = product.badge ?? product.digital_badge - if (badge && PRIORITY_BADGE[badge]) items.push(PRIORITY_BADGE[badge]) - const tags = product.tags ?? product.digital_tags ?? [] - tags.forEach(tag => { if (TAG_BADGE[tag]) items.push(TAG_BADGE[tag]) }) - const shown = items.slice(0, 3) - if (!shown.length) return null - return ( -
- {shown.map((s, i) => { - const { Icon } = s - return ( - - - - ) - })} -
- ) -} - -// ── Price display ───────────────────────────────────────────────────────────── -export function Price({ product, large }) { - const base = basePrice(product) - const now = discountedPrice(product) - const discounted = hasDiscount(product) - return ( -
- {discounted && ( - {eur(base)} - )} - - {eur(now)} - -
- ) -} - -// ── Discount flag ───────────────────────────────────────────────────────────── -export function DiscountFlag({ product, t }) { - const pct = discountPct(product) - if (!pct) return null - return ( - - −{pct}% {t?.off ?? 'OFF'} - - ) -} - -// ── Quantity stepper ───────────────────────────────────────────────────────── -export function Stepper({ qty, onInc, onDec }) { - return ( -
- - - {qty} - - -
- ) -} diff --git a/connect_frontend/menu-app/src/i18n.js b/connect_frontend/menu-app/src/i18n.js new file mode 100644 index 0000000..bc7da41 --- /dev/null +++ b/connect_frontend/menu-app/src/i18n.js @@ -0,0 +1,97 @@ +// The QR menu's texts (en, el; plan step 6.5, same shape as the order app's). The guest's choice +// is remembered on this device; the first visit follows the browser's language. +import { createContext, useContext } from 'react' + +const STORE = 'xenia-menu-lang' +const OLD_STORE = 'ot_lang' // the menu app before 6.5 kept 'en' / 'gr' here + +export const TEXTS = { + en: { + menu: 'Menu', loading: 'Loading the menu…', notFound: 'This menu was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.', + retry: 'Try again', language: 'Language', categories: 'Categories', search: 'Search the menu…', searchOpen: 'Search', close: 'Close', + noResults: 'No dishes found', noResultsBody: 'Try a different word.', + add: 'Add', soldOut: 'Sold out', more: 'More', less: 'Less', + allergens: 'Allergens', contains: 'Contains', mayContain: 'May contain', noAllergens: 'No allergens declared. Ask the staff if you have an allergy.', + allergenNote: 'Ask the staff if you have an allergy.', + atTable: 'Table {{table}}: order from your phone', tableInvalid: 'This QR code is no longer valid. Please ask the staff.', + orderingOff: 'Ordering from the table is not available right now. Please ask the staff.', + viewOrder: 'Your order', items_one: '{{count}} item', items_other: '{{count}} items', + yourOrder: 'Your order', empty: 'Your order is empty.', emptyBody: 'Add a few dishes to get started.', total: 'Total', continue: 'Continue', back: 'Back', + table: 'Table', checkout: 'Send to the kitchen', name: 'Your name (optional)', namePlaceholder: 'e.g. Alex', summary: 'Your order', + placeOrder: 'Place order · {{total}}', sending: 'Sending…', payNote: 'You pay at the table.', + refused: { + changed: 'Something on the menu changed since you opened it. Please reload the page and check your order.', + rate: 'Too many attempts. Please wait a few minutes.', failed: 'The order could not be sent. Please try again.', + }, + track: { + pending_acceptance: 'Sending your order to the kitchen…', accepted: 'Your order is in the kitchen', rejected: 'Order not taken', + acceptedBody: 'Thank you! Your waiter will bring it to your table. Enjoy your meal.', + rejectedBody: 'We\'re sorry we couldn\'t take your order this time. Please speak to the staff.', + waiting: 'This page updates by itself. Keep it open.', reason: 'Reason: {{reason}}', failed: 'Could not load the order\'s status.', back: 'Back to the menu', + }, + allergen: { + gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk', + nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs', + }, + }, + el: { + menu: 'Μενού', loading: 'Φόρτωση μενού…', notFound: 'Το μενού δεν βρέθηκε.', loadFailed: 'Το μενού δεν φορτώθηκε. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά.', + retry: 'Δοκιμάστε ξανά', language: 'Γλώσσα', categories: 'Κατηγορίες', search: 'Αναζήτηση στο μενού…', searchOpen: 'Αναζήτηση', close: 'Κλείσιμο', + noResults: 'Δεν βρέθηκαν πιάτα', noResultsBody: 'Δοκιμάστε άλλη λέξη.', + add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', more: 'Περισσότερο', less: 'Λιγότερο', + allergens: 'Αλλεργιογόνα', contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει', noAllergens: 'Δεν έχουν δηλωθεί αλλεργιογόνα. Ρωτήστε το προσωπικό αν έχετε αλλεργία.', + allergenNote: 'Ρωτήστε το προσωπικό αν έχετε αλλεργία.', + atTable: 'Τραπέζι {{table}}: παραγγείλτε από το κινητό σας', tableInvalid: 'Αυτό το QR δεν ισχύει πλέον. Ρωτήστε το προσωπικό.', + orderingOff: 'Η παραγγελία από το τραπέζι δεν είναι διαθέσιμη τώρα. Ρωτήστε το προσωπικό.', + viewOrder: 'Η παραγγελία σας', items_one: '{{count}} πιάτο', items_other: '{{count}} πιάτα', + yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', emptyBody: 'Προσθέστε μερικά πιάτα για να ξεκινήσετε.', total: 'Σύνολο', continue: 'Συνέχεια', back: 'Πίσω', + table: 'Τραπέζι', checkout: 'Αποστολή στην κουζίνα', name: 'Το όνομά σας (προαιρετικά)', namePlaceholder: 'π.χ. Αλέξης', summary: 'Η παραγγελία σας', + placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', payNote: 'Πληρώνετε στο τραπέζι.', + refused: { + changed: 'Κάτι άλλαξε στο μενού από τότε που το ανοίξατε. Ανανεώστε τη σελίδα και ελέγξτε την παραγγελία σας.', + rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', failed: 'Η παραγγελία δεν στάλθηκε. Δοκιμάστε ξανά.', + }, + track: { + pending_acceptance: 'Η παραγγελία σας στέλνεται στην κουζίνα…', accepted: 'Η παραγγελία σας είναι στην κουζίνα', rejected: 'Η παραγγελία δεν έγινε δεκτή', + acceptedBody: 'Ευχαριστούμε! Ο σερβιτόρος θα τη φέρει στο τραπέζι σας. Καλή όρεξη.', + rejectedBody: 'Λυπούμαστε, δεν μπορέσαμε να δεχτούμε την παραγγελία. Μιλήστε με το προσωπικό.', + waiting: 'Η σελίδα ενημερώνεται μόνη της. Κρατήστε την ανοιχτή.', reason: 'Λόγος: {{reason}}', failed: 'Δεν φορτώθηκε η κατάσταση της παραγγελίας.', back: 'Πίσω στο μενού', + }, + allergen: { + gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα', + nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια', + }, + }, +} + +export function initialLang() { + try { + const saved = localStorage.getItem(STORE) + if (saved && TEXTS[saved]) return saved + const old = localStorage.getItem(OLD_STORE) + if (old) return old === 'gr' ? 'el' : 'en' + } catch { /* private mode */ } + return (navigator.language || 'en').toLowerCase().startsWith('el') ? 'el' : 'en' +} + +export function saveLang(lang) { + try { localStorage.setItem(STORE, lang) } catch { /* private mode */ } +} + +/** t('a.b', {x}) with {{x}} and _one/_other plurals by `count`. */ +export function translate(lang, key, params = {}) { + const dict = TEXTS[lang] ?? TEXTS.en + const find = k => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), dict) + let s = params.count != null ? find(`${key}_${params.count === 1 ? 'one' : 'other'}`) : undefined + if (s === undefined) s = find(key) + if (typeof s !== 'string') return key + return s.replace(/\{\{(\w+)\}\}/g, (_, k) => (params[k] ?? '')) +} + +export const LangContext = createContext({ lang: 'en', setLang: () => {} }) + +export function useT() { + const { lang, setLang } = useContext(LangContext) + const money = n => new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-IE', { style: 'currency', currency: 'EUR' }).format(n ?? 0) + return { lang, setLang, t: (key, params) => translate(lang, key, params), money } +} diff --git a/connect_frontend/menu-app/src/index.css b/connect_frontend/menu-app/src/index.css index 83f370b..f641a0f 100644 --- a/connect_frontend/menu-app/src/index.css +++ b/connect_frontend/menu-app/src/index.css @@ -2,17 +2,34 @@ @tailwind components; @tailwind utilities; -* { box-sizing: border-box; } - -body { - margin: 0; - font-family: 'Hanken Grotesk', system-ui, sans-serif; - background: radial-gradient(ellipse at top, #f3eedf 0%, #ece4d2 50%, #e6ddc8 100%); - min-height: 100dvh; +/* The app's tokens (RGB triples, used through tailwind.config.js). Light only for now. */ +:root { + --o-canvas: 246 244 239; + --o-surface: 255 255 255; + --o-surface-2: 239 236 228; + --o-line: 226 221 209; + --o-ink: 28 36 33; + --o-ink-2: 88 96 92; + --o-ink-3: 140 145 140; + --o-accent: 31 58 52; + --o-accent-fg: 247 244 236; + --o-accent-soft: 222 234 228; + --o-accent-ink: 24 66 56; + --o-success: 48 120 78; + --o-success-soft: 225 242 231; + --o-success-ink: 30 92 56; + --o-warning-soft: 252 240 214; + --o-warning-ink: 124 82 10; + --o-danger-soft: 251 228 222; + --o-danger-ink: 160 50 30; + --o-shadow: 28 36 33; + color-scheme: light; } -@layer utilities { - .no-scrollbar::-webkit-scrollbar { display: none; } - .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } - .font-display { font-family: 'Bricolage Grotesque', serif; } +html, body { background: rgb(var(--o-canvas)); color: rgb(var(--o-ink)); } +body { font-family: theme('fontFamily.sans'); -webkit-font-smoothing: antialiased; } +button { -webkit-tap-highlight-color: transparent; } +:focus-visible { outline: 3px solid rgb(var(--o-accent) / 0.45); outline-offset: 2px; } +@media (prefers-reduced-motion: reduce) { + * { transition: none !important; animation: none !important; } } diff --git a/connect_frontend/menu-app/src/logic.js b/connect_frontend/menu-app/src/logic.js new file mode 100644 index 0000000..60218e6 --- /dev/null +++ b/connect_frontend/menu-app/src/logic.js @@ -0,0 +1,107 @@ +// The QR menu's logic (plan step 6.5). Pure: unit-tested in Node (tests/logic.test.mjs). +// +// The venue's menu comes from GET /api/menu/{site}: categories with products, each with the +// prices per sales point (this app sells at `qr_table`), its texts per language (`names`, +// `descriptions`, 6.4) and allergens (6.3). The cloud prices the order itself; the numbers here +// are what the guest sees before sending. + +export const QR_POINT = 'qr_table' +export const LANGS = ['el', 'en'] + +/** The 14 EU allergens, in the order the venue's apps list them (the site's core/allergens.py). */ +export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs'] + +const round2 = n => Math.round(n * 100) / 100 + +/** A product's allergens to show: what it contains, then what it may contain (traces). */ +export function allergenList(map) { + const m = map && typeof map === 'object' && !Array.isArray(map) ? map : {} + const list = Array.isArray(map) ? map.filter(k => ALLERGENS.includes(k)).map(key => ({ key, level: 'contains' })) : [] + for (const level of ['contains', 'may_contain']) for (const key of ALLERGENS) if (m[key] === level) list.push({ key, level }) + return list +} + +/** A text in the guest's language: `texts` {el, en} from the venue (already falling back), else the base. */ +const pick = (texts, lang, base) => (texts && texts[lang]) || base || '' + +/** + * The menu as this app shows it: the categories with the products sold on the QR menu, each + * product's text in `lang`, its price, availability and allergens. A product listed in several + * categories shows in each (`repeat` marks the later ones, so search shows it once). + */ +export function menuFor(data, lang) { + const seen = new Set() + return (data?.categories ?? []).map(c => ({ + id: String(c.id), + name: pick(c.names, lang, c.name), + products: (c.products ?? []) + .filter(p => !p.sold_at || p.sold_at.includes(QR_POINT)) + .map(p => ({ + id: String(p.id), + name: pick(p.names, lang, p.digital_name || p.name), + names: p.names ?? null, + baseName: p.digital_name || p.name || '', + description: pick(p.descriptions, lang, p.digital_description || p.description || ''), + price: p.prices ? (p.prices[QR_POINT] ?? 0) : (p.digital_price ?? p.base_price ?? 0), + available: p.digital_available !== false, + image: p.digital_image_url || p.image_url || null, + tags: p.tags ?? [], + allergens: allergenList(p.allergens), + repeat: seen.has(String(p.id)) || !seen.add(String(p.id)), + })), + })).filter(c => c.products.length > 0) +} + +/** Lowercase, no accents: "Σουβλάκι" and "σουβλακι" match. */ +export function fold(text) { + return String(text ?? '').normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim() +} + +/** What a search finds, once each: by its name in either language (or as typed) or description. */ +export function search(categories, query) { + const q = fold(query) + if (!q) return [] + return categories.flatMap(c => c.products.filter(p => !p.repeat)) + .filter(p => [p.name, p.baseName, ...Object.values(p.names ?? {}), p.description].some(s => fold(s).includes(q))) +} + +/** The cart is {productId: quantity}. */ +export function setQty(cart, id, qty) { + const next = { ...cart } + if (qty <= 0) delete next[id] + else next[id] = Math.min(99, qty) + return next +} + +/** The cart's lines priced from the menu; products no longer on it (or sold out) are left out. */ +export function cartLines(cart, categories) { + const byId = new Map(categories.flatMap(c => c.products).map(p => [p.id, p])) + return Object.entries(cart ?? {}).flatMap(([id, qty]) => { + const p = byId.get(id) + if (!p || !p.available || qty <= 0) return [] + return [{ product: p, qty, total: round2(p.price * qty) }] + }) +} + +export const cartTotal = lines => round2(lines.reduce((s, l) => s + l.total, 0)) +export const cartCount = lines => lines.reduce((s, l) => s + l.qty, 0) + +/** The order as the cloud takes it: at the table its QR code names (the cloud checks the token). */ +export function orderBody(lines, { tableToken, name, tableLabel, tableWord }) { + return { + order_type: 'dine_in', + table_token: tableToken, + customer_name: (name ?? '').trim() || `${tableWord} ${tableLabel ?? ''}`.trim(), + items: lines.map(l => ({ product_id: Number(l.product.id), quantity: l.qty, unit_price: l.product.price })), + total: cartTotal(lines), + } +} + +/** The text key for a refused order (the cloud's error code). */ +export function refusalKey(code) { + if (['order.price_changed', 'order.item_unavailable', 'order.option_unavailable'].includes(code)) return 'refused.changed' + if (code === 'order.table_invalid') return 'tableInvalid' + if (code === 'order.service_unavailable') return 'orderingOff' + if (code === 'rate.limited') return 'refused.rate' + return 'refused.failed' +} diff --git a/connect_frontend/menu-app/src/main.jsx b/connect_frontend/menu-app/src/main.jsx index 1cb2b6b..13e0b78 100644 --- a/connect_frontend/menu-app/src/main.jsx +++ b/connect_frontend/menu-app/src/main.jsx @@ -1,15 +1,27 @@ -import React from 'react' -import ReactDOM from 'react-dom/client' -import { BrowserRouter } from 'react-router-dom' -import { Toaster } from 'react-hot-toast' -import App from './App' +// The QR menu (plan step 6.5): read the venue's menu, or order at a table with its QR code. +import { StrictMode, useState } from 'react' +import { createRoot } from 'react-dom/client' +import { BrowserRouter, Route, Routes } from 'react-router-dom' import './index.css' +import { initialLang, LangContext, saveLang } from './i18n' +import ConfirmPage from './pages/ConfirmPage' +import MenuPage from './pages/MenuPage' -ReactDOM.createRoot(document.getElementById('root')).render( - - - - - - -) +function App() { + const [lang, setLangState] = useState(initialLang) + const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l } + document.documentElement.lang = lang + return ( + + + + } /> + } /> + Xenia

} /> +
+
+
+ ) +} + +createRoot(document.getElementById('root')).render() diff --git a/connect_frontend/menu-app/src/pages/ConfirmPage.jsx b/connect_frontend/menu-app/src/pages/ConfirmPage.jsx new file mode 100644 index 0000000..3f9fbd6 --- /dev/null +++ b/connect_frontend/menu-app/src/pages/ConfirmPage.jsx @@ -0,0 +1,55 @@ +// After a table order (plan step 6.5): sending → in the kitchen, or not taken (with the +// venue's reason). Polls every 10 s until it's settled. +import { useEffect, useState } from 'react' +import { Link, useParams } from 'react-router-dom' +import { Check, Clock, X } from 'lucide-react' +import { track } from '../api' +import { useT } from '../i18n' + +const SETTLED = new Set(['accepted', 'rejected', 'delivered', 'preparing', 'ready']) +const POLL_MS = 10_000 + +export default function ConfirmPage() { + const { site, ref } = useParams() + const { t } = useT() + const [order, setOrder] = useState(null) + const [failed, setFailed] = useState(false) + + useEffect(() => { + let timer + let stop = false + const poll = async () => { + try { + const data = await track(ref) + if (stop) return + setOrder(data) + if (!SETTLED.has(data.status)) timer = setTimeout(poll, POLL_MS) + } catch { if (!stop) setFailed(true) } + } + poll() + return () => { stop = true; clearTimeout(timer) } + }, [ref]) + + const status = order?.status + const state = status === 'rejected' ? 'rejected' : SETTLED.has(status) ? 'accepted' : 'pending_acceptance' + const Icon = { pending_acceptance: Clock, accepted: Check, rejected: X }[state] + const tone = { pending_acceptance: 'bg-warning-soft text-warning-ink', accepted: 'bg-success-soft text-success-ink', rejected: 'bg-danger-soft text-danger-ink' }[state] + + return ( +
+
+ {order?.public_ref &&

{order.public_ref}

} +

+ {failed ? t('track.failed') : t(`track.${state}`)} +

+ {order?.rejection_reason &&

{t('track.reason', { reason: order.rejection_reason })}

} + {state === 'accepted' &&

{t('track.acceptedBody')}

} + {state === 'rejected' &&

{t('track.rejectedBody')}

} + {state === 'pending_acceptance' && !failed && (<> +

{t('track.waiting')}

+
+ )} + {t('track.back')} +
+ ) +} diff --git a/connect_frontend/menu-app/src/pages/MenuPage.jsx b/connect_frontend/menu-app/src/pages/MenuPage.jsx index d9a3853..fd6a04a 100644 --- a/connect_frontend/menu-app/src/pages/MenuPage.jsx +++ b/connect_frontend/menu-app/src/pages/MenuPage.jsx @@ -1,1029 +1,337 @@ -import { useState, useEffect, useRef, useMemo } from 'react' -import { useParams, useNavigate, useSearchParams } from 'react-router-dom' -import { - Search, Leaf, X, Plus, ShoppingBag, - ChevronLeft, ArrowRight, Send, Loader2, Info, - Armchair, Check, SearchX, UtensilsCrossed, AlertCircle, - Soup, Salad, Wheat, IceCream2, Wine, Globe, -} from 'lucide-react' -import { fetchMenu, submitOrder, CLOUD_URL } from '../api' -import { - DishArt, Badge, DietChip, TagIcons, Price, DiscountFlag, Stepper, - eur, discountedPrice, discountPct, -} from '../components/primitives' +// The QR menu (plan step 6.5, rebuilt on the customer apps' look). Without a table it's a menu to +// read; scanned at a table whose venue allows it (phase 3S, S.7) the guest orders from their +// phone: the order goes to the table's order and the kitchen, and the cloud prices it itself. +// Texts in the guest's language (the venue's translations, 6.4), each dish's allergens (6.3). +import { useEffect, useMemo, useState } from 'react' +import { useNavigate, useParams, useSearchParams } from 'react-router-dom' +import { Armchair, ChevronLeft, Minus, Plus, Search, Send, ShoppingBag, TriangleAlert, X } from 'lucide-react' +import { fetchMenu, imageUrl, placeOrder } from '../api' +import { useT } from '../i18n' +import { cartCount, cartLines, cartTotal, menuFor, orderBody, refusalKey, search, setQty } from '../logic' -// Shown only when a site has never been configured at all (brand-new site, restaurant === null) -const RESTAURANT_FALLBACK = { name: 'Our Menu' } +const TABLE_KEY = site => `xenia-qr-table:${site}` +const CART_KEY = site => `xenia-qr-cart:${site}` -// Category glyph icons — mapped by category id or index -const GLYPH_BY_ID = { starters: Soup, salads: Salad, mains: UtensilsCrossed, sides: Wheat, desserts: IceCream2, drinks: Wine } -const GLYPH_FALLBACK = [Soup, Salad, UtensilsCrossed, Wheat, IceCream2, Wine] -const CATEGORY_HUES = [96, 78, 18, 40, 340, 176] +export default function MenuPage() { + const { site } = useParams() + const navigate = useNavigate() + const [params] = useSearchParams() + const { t, lang } = useT() + // the table's QR code carries its token (?t=…); kept for this visit so a reload keeps the table + const [tableToken] = useState(() => { + const fromUrl = params.get('t') + try { + if (fromUrl) sessionStorage.setItem(TABLE_KEY(site), fromUrl) + return fromUrl || sessionStorage.getItem(TABLE_KEY(site)) || null + } catch { return fromUrl } + }) + const [data, setData] = useState(null) + const [error, setError] = useState(null) + const [cart, setCart] = useState(() => { try { return JSON.parse(sessionStorage.getItem(CART_KEY(site))) || {} } catch { return {} } }) + const [open, setOpen] = useState(null) // a product shown big + const [searching, setSearching] = useState(false) + const [stage, setStage] = useState(null) // 'cart' | 'checkout' -// Allergen label fallbacks -const ALLERGEN_EN = { gluten: 'gluten', dairy: 'dairy', egg: 'egg', fish: 'fish', shellfish: 'shellfish', nuts: 'nuts', soy: 'soy', sesame: 'sesame', sulphites: 'sulphites' } - -const I18N = { - en: { - searchPlaceholder: 'Search the menu…', - add: 'Add', back: 'Back', total: 'Total', - yourOrder: 'Your order', emptyCart: 'Your cart is empty', - emptyCartSub: 'Add a few dishes to get started.', - continue: 'Continue', placeOrder: 'Place order', sending: 'Sending…', - orderChanged: 'Something on the menu changed since you opened it. Please reload the page and check your order.', - orderFailed: 'The order could not be sent. Please try again.', - orderPlaced: 'Order placed!', orderPlacedSub: 'Your order has been sent to the kitchen.', - newOrder: 'Back to menu', table: 'Table', name: 'Your name (optional)', - namePh: 'e.g. Alex', orderSummary: 'Order summary', - atTable: 'Table {table}: order from your phone', tableInvalid: 'This QR code is no longer valid. Please ask the staff.', - orderingOff: 'Ordering from the table is not available right now. Please ask the staff.', - contains: 'Contains', ingredients: 'Ingredients', noResults: 'No dishes found', - noResultsSub: 'Try a different search.', - popular: 'Popular', chefs: "Chef's pick", off: 'OFF', - dietary: { vegan: 'Vegan', vegetarian: 'Vegetarian', 'gluten-free': 'Gluten-free', spicy: 'Spicy' }, - }, - gr: { - searchPlaceholder: 'Αναζήτηση στο μενού…', - add: 'Προσθήκη', back: 'Πίσω', total: 'Σύνολο', - yourOrder: 'Η παραγγελία σου', emptyCart: 'Το καλάθι σου είναι άδειο', - emptyCartSub: 'Πρόσθεσε μερικά πιάτα για να ξεκινήσεις.', - continue: 'Συνέχεια', placeOrder: 'Αποστολή παραγγελίας', sending: 'Αποστολή…', - orderChanged: 'Κάτι άλλαξε στο μενού από τότε που το άνοιξες. Ανανέωσε τη σελίδα και έλεγξε την παραγγελία σου.', - orderFailed: 'Η παραγγελία δεν στάλθηκε. Δοκίμασε ξανά.', - orderPlaced: 'Η παραγγελία στάλθηκε!', orderPlacedSub: 'Η παραγγελία σου εστάλη στην κουζίνα.', - newOrder: 'Πίσω στο μενού', table: 'Τραπέζι', name: 'Το όνομά σου (προαιρετικά)', - namePh: 'π.χ. Αλέξης', orderSummary: 'Σύνοψη παραγγελίας', - atTable: 'Τραπέζι {table}: παραγγείλτε από το κινητό σας', tableInvalid: 'Αυτό το QR δεν ισχύει πλέον. Ρωτήστε το προσωπικό.', - orderingOff: 'Η παραγγελία από το τραπέζι δεν είναι διαθέσιμη τώρα. Ρωτήστε το προσωπικό.', - contains: 'Περιέχει', ingredients: 'Συστατικά', noResults: 'Δεν βρέθηκαν πιάτα', - noResultsSub: 'Δοκίμασε διαφορετική αναζήτηση.', - popular: 'Δημοφιλές', chefs: 'Επιλογή Σεφ', off: 'ΕΚΠΤΩΣΗ', - dietary: { vegan: 'Vegan', vegetarian: 'Χορτοφαγικό', 'gluten-free': 'Χωρίς γλουτένη', spicy: 'Πικάντικο' }, - }, -} - -// Resolve a possibly-relative path (e.g. "/static/product_images/x.jpg") against -// the cloud API origin. Absolute URLs (manager-set external overrides) pass through untouched. -function resolveImageUrl(url) { - if (!url) return null - return /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}` -} - -// ── Normalise a backend product to the shape the UI expects ────────────────── -// The QR menu sells at the sales point qr_table (phase 3S): its price from `prices`; menus -// pushed before S.2 had digital_price. -const QR_POINT = 'qr_table' - -// The menu in the guest's language (plan step 6.4): the venue sends `names` / `descriptions` per -// menu language (el, en), already falling back to the text as typed; this app's codes are en / gr. -const byLang = (texts, base) => (texts ? { en: texts.en || base, gr: texts.el || base } : base) - -// Allergens (6.3) come as {key: "contains" | "may_contain"}; this page lists what it contains. -const allergenKeys = a => (Array.isArray(a) ? a : Object.keys(a || {}).filter(k => a[k] === 'contains')) - -function normaliseProduct(p, catId) { - return { - ...p, - digital_price: undefined, digital_discount: undefined, - id: String(p.id), - cat: catId, - name: byLang(p.names, p.digital_name || p.name || ''), - desc: byLang(p.descriptions, p.digital_description || p.description || ''), - price: p.prices ? (p.prices[QR_POINT] ?? 0) : (p.digital_price ?? p.base_price ?? 0), - badge: p.digital_badge || p.badge || null, - tags: p.digital_tags || p.tags || [], - allergens: allergenKeys(p.allergens), - ingredients: p.ingredients || null, - discountPct: 0, - image_url: resolveImageUrl(p.digital_image_url || p.image_url || null), - digital_available: p.digital_available !== false, + const load = () => { + setError(null) + fetchMenu(site, tableToken).then(setData).catch(err => setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed')) } -} + useEffect(load, [site, tableToken]) // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { try { sessionStorage.setItem(CART_KEY(site), JSON.stringify(cart)) } catch { /* private mode */ } }, [cart, site]) -function normaliseCategories(rawCats) { - return rawCats.map((cat, idx) => { - const id = cat.id ? String(cat.id) : `cat-${idx}` - return { - ...cat, - name: byLang(cat.names, cat.name), - id, - hue: cat.hue ?? CATEGORY_HUES[idx % CATEGORY_HUES.length], - GlyphIcon: GLYPH_BY_ID[id] ?? GLYPH_FALLBACK[idx % GLYPH_FALLBACK.length], - products: (cat.products || []).filter(p => !p.sold_at || p.sold_at.includes(QR_POINT)).map(p => normaliseProduct(p, id)), - } - }).filter(c => c.products.length > 0) -} + const categories = useMemo(() => menuFor(data, lang), [data, lang]) + const lines = useMemo(() => cartLines(cart, categories), [cart, categories]) + const count = cartCount(lines) + const canOrder = !!(data?.table_ordering && data?.table) + const add = p => setCart(c => setQty(c, p.id, (c[p.id] || 0) + 1)) + const remove = p => setCart(c => setQty(c, p.id, (c[p.id] || 0) - 1)) + + if (error) { + return ( + +
+

{t(error)}

+ {error === 'loadFailed' && } +
+
+ ) + } + if (!data) return

{t('loading')}

+ + const r = data.restaurant ?? {} + const tagline = r.tagline?.[lang === 'el' ? 'gr' : 'en'] + const visible = categories.filter(c => c.products.some(p => !p.repeat)) -// ── Bottom Sheet shell ──────────────────────────────────────────────────────── -function Sheet({ open, onClose, children, maxH = '88vh' }) { - if (!open) return null return ( -
-
-
+ +
+
+
+

{r.name || t('menu')}

+ {tagline &&

{tagline}

} +
+ +
+ {(data.table && canOrder) || data.table_invalid ? ( +

+ {data.table_invalid ?

+ ) : null} +
+ + + +
+ {categories.map(c => ( +
+

{c.name}

+ {c.products.map(p => ( + setOpen(p)} onAdd={() => add(p)} onRemove={() => remove(p)} /> + ))} +
+ ))} +

{t('allergenNote')}

+
+ + {canOrder && count > 0 && ( +
+ +
+ )} + + {open && setOpen(null)} onAdd={() => add(open)} onRemove={() => remove(open)} />} + {searching && setSearching(false)} + onOpen={p => { setSearching(false); setOpen(p) }} onAdd={add} onRemove={remove} />} + {stage && canOrder && ( + { + const result = await placeOrder(site, orderBody(lines, { tableToken, name, tableLabel: data.table.label, tableWord: t('table') })) + setCart({}) + try { sessionStorage.removeItem(CART_KEY(site)) } catch { /* private mode */ } + navigate(`/${site}/confirm/${result.tracking_token ?? result.public_ref}`) + }} /> + )} +
+ ) +} + +function Shell({ children }) { + return
{children}
+} + +function LangSwitch() { + const { lang, setLang, t } = useT() + return ( +
+ {['el', 'en'].map(l => ( + + ))} +
+ ) +} + +function Money({ value }) { + const { money } = useT() + return {money(value)} +} + +function Qty({ qty, onAdd, onRemove }) { + const { t } = useT() + return ( +
+ + {qty} + +
+ ) +} + +function AddButton({ product, qty, canOrder, onAdd, onRemove }) { + const { t } = useT() + if (!product.available) return {t('soldOut')} + if (!canOrder) return null + if (qty > 0) return + return ( + + ) +} + +function ProductCard({ product, qty, canOrder, onOpen, onAdd, onRemove }) { + const { t } = useT() + const img = imageUrl(product.image) + const contains = product.allergens.filter(a => a.level === 'contains') + return ( +
+ {img && } +
+ + {product.description &&

{product.description}

} + {contains.length > 0 && ( +

{t('contains')}: {contains.map(a => t(`allergen.${a.key}`)).join(', ')}

+ )} +
+ + +
+
+
+ ) +} + +/** The dish's allergens: what it contains, then what it may contain. */ +function AllergenBlock({ allergens }) { + const { t } = useT() + const contains = allergens.filter(a => a.level === 'contains') + const traces = allergens.filter(a => a.level === 'may_contain') + return ( +
+

{t('allergens')}

+ {allergens.length === 0 &&

{t('noAllergens')}

} + {[['contains', contains], ['mayContain', traces]].filter(([, list]) => list.length).map(([label, list]) => ( +
+ {t(label)}: + {list.map(a => ( + + {t(`allergen.${a.key}`)} + + ))} +
+ ))} +
+ ) +} + +function Sheet({ onClose, labelledBy, children }) { + useEffect(() => { + const esc = e => { if (e.key === 'Escape') onClose() } + document.addEventListener('keydown', esc) + return () => document.removeEventListener('keydown', esc) + }, [onClose]) + return ( +
+
e.stopPropagation()}> {children}
) } -function SheetHandle() { +function ProductSheet({ product, canOrder, qty, onClose, onAdd, onRemove }) { + const { t } = useT() + const img = imageUrl(product.image) return ( -
-
-
- ) -} - -// ── Language Switcher ──────────────────────────────────────────────────────── -const LANGS = [ - { code: 'en', label: 'English' }, - { code: 'gr', label: 'Ελληνικά' }, -] - -function LanguageSwitcher({ lang, setLang }) { - const [open, setOpen] = useState(false) - const ref = useRef(null) - - useEffect(() => { - if (!open) return - const onClickAway = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false) } - document.addEventListener('mousedown', onClickAway) - return () => document.removeEventListener('mousedown', onClickAway) - }, [open]) - - return ( -
- - - {open && ( -
- {LANGS.map(({ code, label }) => ( - - ))} + +
+ {img && } +
+

{product.name}

+
- )} -
- ) -} - -// ── Hero ────────────────────────────────────────────────────────────────────── -function Hero({ lang, setLang, restaurant }) { - const name = restaurant?.name || RESTAURANT_FALLBACK.name - const tagline = restaurant?.tagline?.[lang] - const blurb = restaurant?.blurb?.[lang] - const hours = restaurant?.hours - const headerImageUrl = restaurant?.headerImageUrl ? `${CLOUD_URL}${restaurant.headerImageUrl}` : null - - return ( -
- - - {headerImageUrl ? ( - {name} - ) : ( -

- {name} -

- )} - {tagline && ( -
- {tagline} + {product.description &&

{product.description}

} + +
+ +
- )} - - {/* Ornament */} -
- - - -
- - {blurb && ( -

- {blurb} -

- )} - - {hours && ( -
- - - - - {hours} -
- )} -
- ) -} - -// ── Category Bar ────────────────────────────────────────────────────────────── -function CategoryBar({ categories, active, onPick, onSearch, lang }) { - const [scrolled, setScrolled] = useState(false) - const railRef = useRef(null) - - useEffect(() => { - const onScroll = () => setScrolled(window.scrollY > 220) - window.addEventListener('scroll', onScroll, { passive: true }) - return () => window.removeEventListener('scroll', onScroll) - }, []) - - useEffect(() => { - const rail = railRef.current - if (!rail) return - const el = rail.querySelector(`[data-pill="${active}"]`) - if (el) { - const target = el.offsetLeft - rail.clientWidth / 2 + el.clientWidth / 2 - rail.scrollTo({ left: target, behavior: 'smooth' }) - } - }, [active]) - - return ( -
-
- -
- {categories.map(cat => { - const on = cat.id === active - const label = typeof cat.name === 'object' ? (cat.name[lang] ?? cat.name.en) : cat.name - return ( - - ) - })} -
-
-
- ) -} - -// ── Product Card ────────────────────────────────────────────────────────────── -function ProductCard({ product, category, lang, t, onOpen, onAdd, qty, viewOnly }) { - const name = typeof product.name === 'object' ? (product.name[lang] ?? product.name.en) : product.name - const desc = typeof product.desc === 'object' ? (product.desc[lang] ?? product.desc.en) : product.desc - const unavailable = product.digital_available === false - - return ( -
onOpen(product)} - data-testid="menu-product" data-product={product.id} - className={`group overflow-hidden rounded-[20px] bg-[#fcfbf7] ring-1 ring-[#e7e1d1] shadow-card transition hover:shadow-card-hover active:scale-[0.992] ${unavailable ? 'opacity-50' : 'cursor-pointer'}`} - > -
- {/* Left: photo or placeholder art */} - {product.image_url ? ( - {name} - ) : ( - - )} - - {/* Right: content column */} -
-
-

- {name} -

- -
- -

- {desc} -

- -
-
- - -
- {!viewOnly && ( - - )} -
-
-
-
- ) -} - -// ── Menu Section ────────────────────────────────────────────────────────────── -function Section({ category, lang, t, onOpen, onAdd, cart, sectionRef, viewOnly }) { - const { hue, products } = category - const label = typeof category.name === 'object' ? (category.name[lang] ?? category.name.en) : category.name - return ( -
-
-
-

{label}

- {products.length} -
-
- {products.map(p => ( - - ))} -
-
-
- ) -} - -// ── Product Detail Sheet ────────────────────────────────────────────────────── -function ProductSheet({ product, category, lang, t, onClose, onAdd, qty, onInc, onDec, viewOnly }) { - if (!product) return null - const hue = category?.hue ?? 40 - const GlyphIcon = category?.GlyphIcon ?? UtensilsCrossed - const name = typeof product.name === 'object' ? (product.name[lang] ?? product.name.en) : product.name - const desc = typeof product.desc === 'object' ? (product.desc[lang] ?? product.desc.en) : product.desc - const ingredients = product.ingredients - ? (typeof product.ingredients === 'object' && !Array.isArray(product.ingredients) - ? (product.ingredients[lang] ?? product.ingredients.en ?? []) - : product.ingredients) - : [] - const allergens = product.allergens ?? [] - const badge = product.badge ?? product.digital_badge - const tags = product.tags ?? product.digital_tags ?? [] - - return ( - - - -
- {/* Hero art */} - {product.image_url ? ( -
- {name} -
- ) : ( -
- -
- )} - -
- {badge && } - -
-

{name}

- {desc &&

{desc}

} - - {tags.length > 0 && ( -
- {tags.map(tag => )} -
- )} - - {ingredients.length > 0 && ( -
-
{t.ingredients}
-
- {ingredients.map((ing, i) => ( - {ing} - ))} -
-
- )} - - {allergens.length > 0 && ( -
- -
- {t.contains}: - {allergens.map(a => ALLERGEN_EN[a] ?? a).join(', ')} -
-
- )} -
- - {/* Sticky add bar */} -
- {!viewOnly && qty > 0 ? ( - onInc(product)} onDec={() => onDec(product)} /> - ) : ( -
- - -
- )} - {!viewOnly && ( - - )}
) } -// ── Search Overlay ──────────────────────────────────────────────────────────── -function SearchOverlay({ open, onClose, categories, lang, t, onOpen, onAdd, cart, viewOnly }) { +function SearchSheet({ categories, cart, canOrder, onClose, onOpen, onAdd, onRemove }) { + const { t } = useT() const [q, setQ] = useState('') - const inputRef = useRef(null) - useEffect(() => { if (open && inputRef.current) inputRef.current.focus() }, [open]) - useEffect(() => { if (!open) setQ('') }, [open]) - - // A product can be listed in several categories (platform v2, D-23): search shows it once, - // under the first category it appears in. - const allProducts = useMemo(() => { - const seen = new Set() - return categories.flatMap(c => c.products).filter(p => !seen.has(p.id) && seen.add(p.id)) - }, [categories]) - - const results = useMemo(() => { - const term = q.trim().toLowerCase() - if (!term) return [] - return allProducts.filter(p => { - const name = typeof p.name === 'object' ? Object.values(p.name).join(' ') : (p.name ?? '') - const desc = typeof p.desc === 'object' ? Object.values(p.desc).join(' ') : (p.desc ?? '') - const ings = p.ingredients - ? (Array.isArray(p.ingredients) ? p.ingredients : Object.values(p.ingredients).flat()).join(' ') - : '' - return (name + ' ' + desc + ' ' + ings).toLowerCase().includes(term) - }) - }, [q, allProducts]) - - if (!open) return null - + const found = useMemo(() => search(categories, q), [categories, q]) return ( -
-
-
- - setQ(e.target.value)} - placeholder={t.searchPlaceholder} - className="w-full bg-transparent text-[15px] text-[#2d3b2d] outline-none placeholder:text-[#b3aa90]" - /> - {q && ( - - )} +
+
+
+
- +
- -
- {q && results.length === 0 && ( -
- -
{t.noResults}
-
{t.noResultsSub}
-
- )} - {results.length > 0 && ( -
- {results.map(p => { - const cat = categories.find(c => c.id === p.cat) - return ( - { onClose(); onOpen(prod) }} - onAdd={onAdd} - qty={cart[p.id] || 0} - viewOnly={viewOnly} - /> - ) - })} -
- )} - {!q && ( -
- -
{t.searchPlaceholder}
-
+
+ {q.trim() && found.length === 0 && ( +

{t('noResults')}

{t('noResultsBody')}

)} + {found.map(p => onOpen(p)} onAdd={() => onAdd(p)} onRemove={() => onRemove(p)} />)}
) } -// ── Cart Flow (bottom sheet) ────────────────────────────────────────────────── -function CartFlow({ stage, setStage, cart, setCart, categories, lang, t, onOpenProduct, siteSlug, navigate, table, tableToken }) { - const [form, setForm] = useState({ name: '' }) +function CartSheet({ stage, setStage, lines, table, onAdd, onRemove, onSend }) { + const { t, money } = useT() + const [name, setName] = useState('') const [sending, setSending] = useState(false) - const [sendError, setSendError] = useState('') - - const allProducts = useMemo(() => categories.flatMap(c => c.products), [categories]) - - const lines = useMemo(() => - Object.entries(cart) - .map(([id, qty]) => ({ product: allProducts.find(p => p.id === id), qty })) - .filter(l => l.product && l.qty > 0), - [cart, allProducts] - ) - const total = lines.reduce((s, l) => s + discountedPrice(l.product) * l.qty, 0) - - const inc = p => setCart(c => ({ ...c, [p.id]: (c[p.id] || 0) + 1 })) - const dec = p => setCart(c => { - const n = (c[p.id] || 0) - 1 - const next = { ...c } - if (n <= 0) delete next[p.id]; else next[p.id] = n - return next - }) - - const submit = async () => { - setSending(true) - setSendError('') - try { - const result = await submitOrder(siteSlug, { - // the table comes from its QR code (S.7): the cloud checks the token, never a typed number - order_type: 'dine_in', - table_token: tableToken, - customer_name: form.name.trim() || `${t.table} ${table?.label ?? ''}`.trim(), - items: lines.map(l => ({ - product_id: Number(l.product.id), - quantity: l.qty, - unit_price: discountedPrice(l.product), - })), - total: Math.round(total * 100) / 100, - }) - setCart({}) - setForm({ name: '' }) - setStage(null) - // the cloud prices the order itself (phase 3S, S.2); the tracking link is the order's token - navigate(`/${siteSlug}/confirm/${result.tracking_token ?? result.public_ref}`) - } catch (err) { - const code = err?.response?.data?.detail?.code - setSendError(code === 'order.price_changed' || code === 'order.item_unavailable' || code === 'order.option_unavailable' - ? t.orderChanged : code === 'order.table_invalid' ? t.tableInvalid : code === 'order.service_unavailable' ? t.orderingOff : t.orderFailed) - setSending(false) - } - } - + const [problem, setProblem] = useState(null) + const total = cartTotal(lines) const close = () => setStage(null) - - // Cart view - if (stage === 'cart') { - return ( - - -
-

{t.yourOrder}

- -
- {lines.length === 0 ? ( -
- -
{t.emptyCart}
-
{t.emptyCartSub}
-
- ) : ( - <> -
-
- {lines.map(l => { - const cat = categories.find(c => c.id === l.product.cat) - const pname = typeof l.product.name === 'object' ? (l.product.name[lang] ?? l.product.name.en) : l.product.name - return ( -
- -
-
{ close(); onOpenProduct(l.product) }} - className="cursor-pointer font-display text-[16px] font-semibold leading-tight text-[#2d3b2d]" - > - {pname} -
-
{eur(discountedPrice(l.product))}
-
- inc(l.product)} onDec={() => dec(l.product)} /> -
- ) - })} -
-
-
-
- {t.total} - {eur(total)} -
- -
- - )} -
- ) + const send = async () => { + setSending(true) + setProblem(null) + try { await onSend(name) } catch (err) { setProblem(refusalKey(err?.response?.data?.detail?.code ?? err?.response?.data?.error?.code)); setSending(false) } } - - // Checkout view - if (stage === 'checkout') { - const valid = lines.length > 0 - return ( - - -
- -

{t.placeOrder}

-
-
-
-

{t.table} {table?.label}

- -
- -
{t.orderSummary}
-
- {lines.map((l, i) => { - const pname = typeof l.product.name === 'object' ? (l.product.name[lang] ?? l.product.name.en) : l.product.name - return ( -
0 ? 'border-t border-[#f0ebdd]' : ''}`}> - - {l.qty}× {pname} - - - {eur(discountedPrice(l.product) * l.qty)} - -
- ) - })} -
-
-
-
- {t.total} - {eur(total)} -
- {sendError &&

{sendError}

} - -
-
- ) - } - - return null -} - -// ── Floating Cart Button ────────────────────────────────────────────────────── -function CartButton({ count, total, t, onClick }) { - const [bump, setBump] = useState(false) - const prev = useRef(count) - useEffect(() => { - if (count !== prev.current && count > 0) { - setBump(true) - const tm = setTimeout(() => setBump(false), 320) - prev.current = count - return () => clearTimeout(tm) - } - prev.current = count - }, [count]) - - if (count === 0) return null return ( -
- -
- ) -} - -// ── Main MenuPage ───────────────────────────────────────────────────────────── -const TABLE_KEY = site => `xenia-qr-table:${site}` - -export default function MenuPage() { - const { siteSlug } = useParams() - const navigate = useNavigate() - const [params] = useSearchParams() - // the table's QR code carries its token (?t=…); kept for this visit so a reload keeps the table - const [tableToken] = useState(() => { - const fromUrl = params.get('t') - try { - if (fromUrl) sessionStorage.setItem(TABLE_KEY(siteSlug), fromUrl) - return fromUrl || sessionStorage.getItem(TABLE_KEY(siteSlug)) || null - } catch { return fromUrl } - }) - const [table, setTable] = useState(null) - const [tableInvalid, setTableInvalid] = useState(false) - - const [categories, setCategories] = useState([]) - const [restaurant, setRestaurant] = useState(null) - const [viewOnly, setViewOnly] = useState(false) - const [error, setError] = useState(null) - const [loading, setLoading] = useState(true) - - const [lang, setLang] = useState(() => { - try { return localStorage.getItem('ot_lang') || 'en' } catch { return 'en' } - }) - const [cart, setCart] = useState(() => { - try { return JSON.parse(localStorage.getItem('ot_cart')) || {} } catch { return {} } - }) - const [active, setActive] = useState(null) - const [activeProduct, setActiveProduct] = useState(null) - const [activeProductCat, setActiveProductCat] = useState(null) - const [searchOpen, setSearchOpen] = useState(false) - const [stage, setStage] = useState(null) - - const t = I18N[lang] ?? I18N.en - - useEffect(() => { try { localStorage.setItem('ot_lang', lang) } catch {} }, [lang]) - useEffect(() => { try { localStorage.setItem('ot_cart', JSON.stringify(cart)) } catch {} }, [cart]) - - useEffect(() => { - fetchMenu(siteSlug, tableToken) - .then(data => { - const cats = normaliseCategories(data.categories || []) - setCategories(cats) - setRestaurant(data.restaurant ?? null) - // ordering only at a real table, when the venue allows it (S.7); otherwise a menu to read - setTable(data.table ?? null) - setTableInvalid(!!data.table_invalid) - setViewOnly(!(data.table_ordering && data.table)) - if (cats.length) setActive(cats[0].id) - }) - .catch(() => setError('Menu not available. Please try again.')) - .finally(() => setLoading(false)) - }, [siteSlug, tableToken]) - - const sectionRefs = useRef({}) - const clickLock = useRef(false) - - // Scroll-spy - useEffect(() => { - const onScroll = () => { - if (clickLock.current) return - let current = categories[0]?.id - for (const c of categories) { - const el = sectionRefs.current[c.id] - if (el && el.getBoundingClientRect().top <= 90) current = c.id - } - if (current) setActive(a => a === current ? a : current) - } - window.addEventListener('scroll', onScroll, { passive: true }) - onScroll() - return () => window.removeEventListener('scroll', onScroll) - }, [categories]) - - const pick = id => { - const el = sectionRefs.current[id] - if (!el) return - setActive(id) - clickLock.current = true - const top = el.getBoundingClientRect().top + window.scrollY - 64 - window.scrollTo({ top, behavior: 'smooth' }) - setTimeout(() => { clickLock.current = false }, 700) - } - - const addToCart = p => setCart(c => ({ ...c, [p.id]: (c[p.id] || 0) + 1 })) - const incCart = p => setCart(c => ({ ...c, [p.id]: (c[p.id] || 0) + 1 })) - const decCart = p => setCart(c => { - const n = (c[p.id] || 0) - 1 - const next = { ...c } - if (n <= 0) delete next[p.id]; else next[p.id] = n - return next - }) - - const openProduct = p => { - setActiveProduct(p) - setActiveProductCat(categories.find(c => c.id === p.cat) ?? null) - } - - const count = Object.values(cart).reduce((s, q) => s + q, 0) - const total = useMemo(() => { - const allProducts = categories.flatMap(c => c.products) - return Object.entries(cart).reduce((s, [id, q]) => { - const p = allProducts.find(x => x.id === id) - return p ? s + discountedPrice(p) * q : s - }, 0) - }, [cart, categories]) - - if (loading) return ( -
-
-
- ) - - if (error) return ( -
- -

{error}

-
- ) - - return ( -
- - setSearchOpen(true)} - lang={lang} - /> - - {(table && !viewOnly) || tableInvalid ? ( -

- {tableInvalid ? t.tableInvalid : t.atTable.replace('{table}', table.label)} -

- ) : null} - -
- {categories.map(cat => ( -
{ sectionRefs.current[cat.id] = el }} - viewOnly={viewOnly} - /> - ))} - -
-
- - - -
-
-
- - {!viewOnly && setStage('cart')} />} - - setActiveProduct(null)} - onAdd={addToCart} - qty={activeProduct ? (cart[activeProduct.id] || 0) : 0} - onInc={incCart} - onDec={decCart} - viewOnly={viewOnly} - /> - - setSearchOpen(false)} - categories={categories} - lang={lang} - t={t} - onOpen={openProduct} - onAdd={addToCart} - cart={cart} - viewOnly={viewOnly} - /> - - {!viewOnly && ( - - )} -
+ +
+ {stage === 'checkout' && } +

{stage === 'cart' ? t('yourOrder') : t('checkout')}

+ +
+ {lines.length === 0 ? ( +

{t('empty')}

{t('emptyBody')}

+ ) : stage === 'cart' ? (<> +
    + {lines.map(l => ( +
  • + {l.product.name} + onAdd(l.product)} onRemove={() => onRemove(l.product)} /> +
  • + ))} +
+
{t('total')}
+ + ) : (<> +

{t('table')} {table?.label}

+ +
+

{t('summary')}

+ {lines.map(l => ( +
{l.qty}× {l.product.name}
+ ))} +
+

{t('payNote')}

+ {problem &&

{t(problem)}

} + + )} +
) } diff --git a/connect_frontend/menu-app/src/pages/OrderConfirm.jsx b/connect_frontend/menu-app/src/pages/OrderConfirm.jsx deleted file mode 100644 index a103b6c..0000000 --- a/connect_frontend/menu-app/src/pages/OrderConfirm.jsx +++ /dev/null @@ -1,115 +0,0 @@ -import { useEffect, useState } from 'react' -import { useParams } from 'react-router-dom' -import { Check, Clock, X, Leaf } from 'lucide-react' -import { fetchOrderStatus } from '../api' - -// A table order from the QR menu (phase 3S, S.7): sent → in the kitchen (or not taken). -// Takeaway and delivery have their own app since S.4 (/order/), so their steps are gone here. -const STATUS_CONFIG = { - pending_acceptance: { label: 'Sending your order to the kitchen…', Icon: Clock, color: '#c9a24b', bg: '#f6edd6' }, - accepted: { label: 'Your order is in the kitchen', Icon: Check, color: '#3f7d4e', bg: '#e7f1e7' }, - rejected: { label: 'Order not taken', Icon: X, color: '#c2602f', bg: '#f7e6dc' }, -} - -const TERMINAL = new Set(['accepted', 'rejected', 'delivered', 'preparing', 'ready']) -const POLL_MS = 10_000 - -export default function OrderConfirm() { - const { ref } = useParams() - const [orderStatus, setOrderStatus] = useState(null) - const [rejectionReason, setRejectionReason] = useState(null) - const [publicRef, setPublicRef] = useState(null) // the link carries a token (S.2); show the order number - const [error, setError] = useState(false) - - useEffect(() => { - let timer - - async function poll() { - try { - const data = await fetchOrderStatus(ref) - setOrderStatus(data.status) - setPublicRef(data.public_ref) - setRejectionReason(data.rejection_reason) - if (!TERMINAL.has(data.status)) { - timer = setTimeout(poll, POLL_MS) - } - } catch { - setError(true) - } - } - - poll() - return () => clearTimeout(timer) - }, [ref]) - - const cfg = STATUS_CONFIG[orderStatus] ?? (TERMINAL.has(orderStatus) ? STATUS_CONFIG.accepted : STATUS_CONFIG.pending_acceptance) - const { label, Icon, color, bg } = cfg - - return ( -
- - {/* Ornament top */} -
- - - -
- - {/* Status icon */} -
- -
- - {/* Ref number */} -

- {publicRef ?? ''} -

- - {/* Status label */} -

- {error ? 'Could not load status' : label} -

- - {/* Rejection reason */} - {rejectionReason && ( -

- Reason: {rejectionReason} -

- )} - - {/* Subtext */} - {TERMINAL.has(orderStatus) && orderStatus !== 'rejected' && ( -

- Thank you! Your waiter will bring it to your table. Enjoy your meal. -

- )} - {orderStatus === 'rejected' && ( -

- We're sorry we couldn't take your order this time. Please try again or speak to staff. -

- )} - {!TERMINAL.has(orderStatus) && !error && ( -

- We'll update this page automatically. Keep it open. -

- )} - - {/* Spinner */} - {!TERMINAL.has(orderStatus) && !error && ( -
-
-
- )} - - {/* Ornament bottom */} -
- - - -
-
- ) -} diff --git a/connect_frontend/menu-app/tailwind.config.js b/connect_frontend/menu-app/tailwind.config.js index 394fdab..6b3fc4c 100644 --- a/connect_frontend/menu-app/tailwind.config.js +++ b/connect_frontend/menu-app/tailwind.config.js @@ -1,51 +1,29 @@ +// The QR menu (plan step 6.5) on the customer apps' look: the same tokens as the order app. /** @type {import('tailwindcss').Config} */ +// Colours are tokens (CSS variables in src/index.css), never literals in components: one +// place to restyle the app, the same token names as the venue apps' @xenia/ui. +const c = name => `rgb(var(--o-${name}) / )` + export default { content: ['./index.html', './src/**/*.{js,jsx}'], theme: { extend: { fontFamily: { - display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'], sans: ['Hanken Grotesk', 'Noto Sans', 'system-ui', 'sans-serif'], + display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'], }, colors: { - brand: { - dark: '#2d3b2d', - hover: '#26331f', - }, - cream: '#faf7f0', - card: '#fcfbf7', - gold: '#c9a24b', - terracotta: '#c2602f', - sage: '#9caf88', - success: '#3f7d4e', - }, - borderRadius: { - card: '20px', - section: '22px', - sheet: '24px', - }, - boxShadow: { - card: '0 5px 16px -10px rgba(45,42,31,0.45)', - 'card-hover': '0 10px 24px -12px rgba(45,42,31,0.5)', - cart: '0 12px 28px -8px rgba(45,59,45,0.55)', - }, - keyframes: { - fade: { from: { opacity: 0 }, to: { opacity: 1 } }, - slideup: { - from: { transform: 'translateY(100%)' }, - to: { transform: 'translateY(0)' }, - }, - pop: { - '0%': { transform: 'scale(1)' }, - '50%': { transform: 'scale(1.06)' }, - '100%': { transform: 'scale(1)' }, - }, - }, - animation: { - fade: 'fade 0.2s ease', - slideup: 'slideup 0.28s cubic-bezier(0.22,1,0.36,1)', - pop: 'pop 0.32s ease', + canvas: c('canvas'), + surface: { DEFAULT: c('surface'), 2: c('surface-2') }, + line: c('line'), + ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') }, + accent: { DEFAULT: c('accent'), fg: c('accent-fg'), soft: c('accent-soft'), ink: c('accent-ink') }, + success: { DEFAULT: c('success'), soft: c('success-soft'), ink: c('success-ink') }, + warning: { soft: c('warning-soft'), ink: c('warning-ink') }, + danger: { soft: c('danger-soft'), ink: c('danger-ink') }, }, + borderRadius: { card: '18px', control: '12px' }, + boxShadow: { card: '0 6px 18px -12px rgb(var(--o-shadow) / 0.45)', bar: '0 12px 28px -10px rgb(var(--o-shadow) / 0.6)' }, }, }, plugins: [], diff --git a/connect_frontend/menu-app/tests/logic.test.mjs b/connect_frontend/menu-app/tests/logic.test.mjs new file mode 100644 index 0000000..1bd0ae3 --- /dev/null +++ b/connect_frontend/menu-app/tests/logic.test.mjs @@ -0,0 +1,61 @@ +// The QR menu's logic (plan step 6.5). +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { allergenList, cartCount, cartLines, cartTotal, fold, menuFor, orderBody, refusalKey, search, setQty } from '../src/logic.js' + +const data = { categories: [ + { id: 1, name: 'Ψητά', names: { el: 'Ψητά', en: 'Grill' }, products: [ + { id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, descriptions: { el: 'Με πίτα', en: 'With pitta' }, + prices: { qr_table: 3.5, online_delivery: 4 }, sold_at: ['qr_table', 'online_delivery'], allergens: { gluten: 'contains', sesame: 'may_contain' } }, + { id: 6, name: 'Μπριζόλα', prices: { qr_table: 12 }, sold_at: ['qr_table'], digital_available: false }, + { id: 7, name: 'Delivery only', prices: { online_delivery: 9 }, sold_at: ['online_delivery'] }, + ] }, + { id: 2, name: 'Ορεκτικά', products: [{ id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, prices: { qr_table: 3.5 }, sold_at: ['qr_table'] }] }, + { id: 3, name: 'Empty', products: [{ id: 7, name: 'x', prices: {}, sold_at: ['online_takeaway'] }] }, +] } + +test('the menu in the guest\'s language, the QR menu\'s prices, only what it sells', () => { + const en = menuFor(data, 'en') + assert.deepEqual(en.map(c => c.name), ['Grill', 'Ορεκτικά']) // a category without a translation: as typed + const souv = en[0].products[0] + assert.equal(souv.name, 'Pork skewer') + assert.equal(souv.description, 'With pitta') + assert.equal(souv.price, 3.5) + assert.equal(en[0].products.length, 2) // the delivery-only dish isn't here + assert.equal(en[0].products[1].available, false) + assert.equal(en[1].products[0].repeat, true) // listed twice: search shows it once + assert.equal(menuFor(data, 'el')[0].products[0].name, 'Σουβλάκι') +}) + +test('allergens: contains first, then may contain; older array data still read', () => { + assert.deepEqual(allergenList({ sesame: 'may_contain', milk: 'contains', pollen: 'contains' }), [{ key: 'milk', level: 'contains' }, { key: 'sesame', level: 'may_contain' }]) + assert.deepEqual(allergenList(['gluten', 'dairy']), [{ key: 'gluten', level: 'contains' }]) + assert.deepEqual(allergenList(null), []) +}) + +test('search: either language, no accents, each dish once', () => { + const en = menuFor(data, 'en') + assert.deepEqual(search(en, 'σουβλακι').map(p => p.id), ['5']) + assert.deepEqual(search(en, 'pork').map(p => p.id), ['5']) + assert.deepEqual(search(en, 'pitta').map(p => p.id), ['5']) + assert.deepEqual(search(en, ''), []) + assert.equal(fold('Σουβλάκι'), 'σουβλακι') +}) + +test('the cart, its total and the order the cloud takes', () => { + const en = menuFor(data, 'en') + let cart = setQty({}, '5', 2) + cart = setQty(cart, '6', 1) // sold out: left out + cart = setQty(cart, '99', 1) // not on the menu any more + const lines = cartLines(cart, en) + assert.deepEqual(lines.map(l => [l.product.id, l.qty, l.total]), [['5', 2, 7]]) + assert.equal(cartTotal(lines), 7) + assert.equal(cartCount(lines), 2) + assert.deepEqual(setQty({ 5: 1 }, '5', 0), {}) + assert.deepEqual(orderBody(lines, { tableToken: 'tok', name: ' ', tableLabel: '5', tableWord: 'Table' }), { + order_type: 'dine_in', table_token: 'tok', customer_name: 'Table 5', items: [{ product_id: 5, quantity: 2, unit_price: 3.5 }], total: 7, + }) + assert.equal(refusalKey('order.price_changed'), 'refused.changed') + assert.equal(refusalKey('order.table_invalid'), 'tableInvalid') + assert.equal(refusalKey('nope'), 'refused.failed') +}) diff --git a/connect_frontend/order-app/src/i18n.js b/connect_frontend/order-app/src/i18n.js index 76ec7a0..8c2ffe8 100644 --- a/connect_frontend/order-app/src/i18n.js +++ b/connect_frontend/order-app/src/i18n.js @@ -16,6 +16,11 @@ export const TEXTS = { takeaway: 'Takeaway', delivery: 'Delivery', open: 'Open now', closed: 'Closed now', closedBody: 'You can still order for a later time.', noOrdering: 'Online ordering is not available right now.', loading: 'Loading the menu…', notFound: 'This venue was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.', + contains: 'Contains', mayContain: 'May contain', + allergen: { + gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk', + nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs', + }, retry: 'Try again', add: 'Add', soldOut: 'Sold out', options: 'Extras', addToOrder: 'Add to order', cancel: 'Cancel', viewOrder: 'View order', items_one: '{{count}} item', items_other: '{{count}} items', yourOrder: 'Your order', empty: 'Your order is empty.', products: 'Products', fee: 'Delivery fee', total: 'Total', @@ -65,6 +70,11 @@ export const TEXTS = { takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα', closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.', loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.', + contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει', + allergen: { + gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα', + nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια', + }, retry: 'Δοκιμάστε ξανά', add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', options: 'Έξτρα', addToOrder: 'Στην παραγγελία', cancel: 'Ακύρωση', viewOrder: 'Η παραγγελία', items_one: '{{count}} τεμάχιο', items_other: '{{count}} τεμάχια', yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', products: 'Προϊόντα', fee: 'Χρέωση διανομής', total: 'Σύνολο', diff --git a/connect_frontend/order-app/src/logic.js b/connect_frontend/order-app/src/logic.js index 8b9f165..34b3b73 100644 --- a/connect_frontend/order-app/src/logic.js +++ b/connect_frontend/order-app/src/logic.js @@ -31,6 +31,15 @@ export function menuFor(categories, service) { export const productName = p => p.digital_name || p.name +/** The 14 EU allergens (plan step 6.3), in the venue's order. */ +export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs'] + +/** A product's allergens by level: {contains: [keys], may_contain: [keys]}. */ +export function allergensOf(p) { + const m = p?.allergens && typeof p.allergens === 'object' && !Array.isArray(p.allergens) ? p.allergens : {} + return { contains: ALLERGENS.filter(k => m[k] === 'contains'), may_contain: ALLERGENS.filter(k => m[k] === 'may_contain') } +} + /** * The menu in the guest's language (plan step 6.4): the venue sends each product's, quick option's * and category's `names` (and `descriptions`) per menu language, already falling back to the text diff --git a/connect_frontend/order-app/src/pages/OrderPage.jsx b/connect_frontend/order-app/src/pages/OrderPage.jsx index c735ec4..8b4257a 100644 --- a/connect_frontend/order-app/src/pages/OrderPage.jsx +++ b/connect_frontend/order-app/src/pages/OrderPage.jsx @@ -9,7 +9,7 @@ import { useNavigate, useParams } from 'react-router-dom' import { Bike, CalendarDays, Clock, Minus, Plus, ShoppingBag, Store, X } from 'lucide-react' import { fetchMenu, imageUrl } from '../api' import { useT } from '../i18n' -import { addToCart, cartCount, cartLines, localizeMenu, menuFor, productName, productText, SERVICES } from '../logic' +import { addToCart, allergensOf, cartCount, cartLines, localizeMenu, menuFor, productName, productText, SERVICES } from '../logic' import BookingPicker from './BookingPicker' import Checkout from './Checkout' @@ -201,6 +201,7 @@ function ProductCard({ product, qty, onAdd, onRemove }) {

{productName(product)}

{text &&

{text}

} +
{money(product.price)} {!product.available ? ( @@ -221,6 +222,20 @@ function ProductCard({ product, qty, onAdd, onRemove }) { ) } +/** What a dish contains and may contain (plan steps 6.3, 6.5). */ +function AllergenLine({ product }) { + const { t } = useT() + const a = allergensOf(product) + if (!a.contains.length && !a.may_contain.length) return null + return ( +

+ {a.contains.length > 0 && {t('contains')}: {a.contains.map(k => t(`allergen.${k}`)).join(', ')}} + {a.contains.length > 0 && a.may_contain.length > 0 && ' · '} + {a.may_contain.length > 0 && {t('mayContain')}: {a.may_contain.map(k => t(`allergen.${k}`)).join(', ')}} +

+ ) +} + function ExtrasSheet({ product, onClose, onAdd }) { const { t, money } = useT() const [chosen, setChosen] = useState([]) diff --git a/connect_frontend/order-app/tests/logic.test.mjs b/connect_frontend/order-app/tests/logic.test.mjs index ef56f75..802c2f5 100644 --- a/connect_frontend/order-app/tests/logic.test.mjs +++ b/connect_frontend/order-app/tests/logic.test.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import { test } from 'node:test' import { - localizeMenu, productName, + allergensOf, localizeMenu, productName, addToCart, cartCount, cartLines, checkoutProblems, menuFor, orderBody, priceFor, refusal, setQty, slotDays, trackSteps, } from '../src/logic.js' @@ -96,3 +96,8 @@ test('the menu in the guest’s language (6.4): names, descriptions, extras; old assert.equal(productName(en[0].products[1]), 'Old one') assert.equal(productName(localizeMenu(cats, 'el')[0].products[0]), 'Σουβλάκι χοιρινό') }) + +test('a dish\'s allergens by level (6.3)', () => { + assert.deepEqual(allergensOf({ allergens: { sesame: 'may_contain', milk: 'contains', gluten: 'contains' } }), { contains: ['gluten', 'milk'], may_contain: ['sesame'] }) + assert.deepEqual(allergensOf({ allergens: ['gluten'] }), { contains: [], may_contain: [] }) +})