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 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 11:27:05 +02:00
co-authored by Claude Opus 5.5
parent 9f9b882806
commit e55157fa86
19 changed files with 746 additions and 1448 deletions
+2 -1
View File
@@ -2,7 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#1f3a34" />
<title>Menu</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-33
View File
@@ -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",
+2 -2
View File
@@ -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": {
-13
View File
@@ -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 (
<Routes>
<Route path="/:siteSlug" element={<MenuPage />} />
<Route path="/:siteSlug/confirm/:ref" element={<OrderConfirm />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
)
}
+12 -21
View File
@@ -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}`)
@@ -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 (
<div
className={`relative flex ${sizeClass} shrink-0 items-center justify-center overflow-hidden rounded-[13px]`}
style={{ background: `linear-gradient(135deg, ${c1}, ${c2})` }}
>
<span
className="absolute -right-2 -top-3 font-display text-[56px] leading-none opacity-[0.14] select-none"
style={{ color: glyphColor }}
>
{letter}
</span>
{GlyphIcon && (
<GlyphIcon
className={iconClass}
style={{ color: glyphColor, opacity: 0.62 }}
strokeWidth={1.4}
/>
)}
</div>
)
}
// ── Badge (Popular / Chef's pick) ────────────────────────────────────────────
export function Badge({ kind, t }) {
if (kind === 'popular') {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-[#f4ecd8] px-2 py-[3px] text-[10px] font-semibold uppercase tracking-[0.08em] text-[#a9842f] ring-1 ring-inset ring-[#e4d4a8]">
<Flame className="h-3 w-3" strokeWidth={2.2} />
{t?.popular ?? 'Popular'}
</span>
)
}
if (kind === 'chefs') {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-[#2d3b2d] px-2 py-[3px] text-[10px] font-semibold uppercase tracking-[0.08em] text-[#f0e9d6]">
<ChefHat className="h-3 w-3" strokeWidth={2} />
{t?.chefs ?? "Chef's pick"}
</span>
)
}
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 (
<span
className="inline-flex items-center gap-1 rounded-full px-[7px] py-[2px] text-[10px] font-medium ring-1 ring-inset"
style={{ color: s.fg, background: s.bg, borderColor: s.ring }}
>
<Icon className="h-[11px] w-[11px]" strokeWidth={2} />
{label}
</span>
)
}
// ── 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 (
<div className="flex shrink-0 items-center gap-1 pt-[3px]">
{shown.map((s, i) => {
const { Icon } = s
return (
<span
key={i}
className="flex h-[19px] w-[19px] items-center justify-center rounded-full ring-1 ring-inset"
style={{ color: s.fg, background: s.bg, borderColor: s.ring }}
>
<Icon className="h-[11px] w-[11px]" strokeWidth={2.2} />
</span>
)
})}
</div>
)
}
// ── Price display ─────────────────────────────────────────────────────────────
export function Price({ product, large }) {
const base = basePrice(product)
const now = discountedPrice(product)
const discounted = hasDiscount(product)
return (
<div className="flex items-baseline gap-1.5">
{discounted && (
<span className="font-display text-[13px] text-[#b3aa97] line-through">{eur(base)}</span>
)}
<span
className={`font-display ${large ? 'text-[18px]' : 'text-[16px]'} font-semibold ${discounted ? 'text-[#c2602f]' : 'text-[#2d3b2d]'}`}
>
{eur(now)}
</span>
</div>
)
}
// ── Discount flag ─────────────────────────────────────────────────────────────
export function DiscountFlag({ product, t }) {
const pct = discountPct(product)
if (!pct) return null
return (
<span className="inline-flex items-center rounded-md bg-[#c2602f] px-1.5 py-[2px] font-sans text-[10px] font-bold tracking-[0.05em] text-white">
−{pct}% {t?.off ?? 'OFF'}
</span>
)
}
// ── Quantity stepper ─────────────────────────────────────────────────────────
export function Stepper({ qty, onInc, onDec }) {
return (
<div className="flex items-center gap-3 rounded-full bg-[#f3efe5] p-1 ring-1 ring-inset ring-[#e8e1d1]">
<button
onClick={onDec}
className="flex h-7 w-7 items-center justify-center rounded-full bg-white text-[#2d3b2d] shadow-sm ring-1 ring-[#e8e1d1] transition active:scale-90"
>
<Minus className="h-3.5 w-3.5" strokeWidth={2.5} />
</button>
<span className="min-w-[16px] text-center font-display text-[16px] font-semibold tabular-nums text-[#2d3b2d]">
{qty}
</span>
<button
onClick={onInc}
className="flex h-7 w-7 items-center justify-center rounded-full bg-[#2d3b2d] text-white shadow-sm transition active:scale-90"
>
<Plus className="h-3.5 w-3.5" strokeWidth={2.5} />
</button>
</div>
)
}
+97
View File
@@ -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 }
}
+28 -11
View File
@@ -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; }
}
+107
View File
@@ -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'
}
+25 -13
View File
@@ -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(
<React.StrictMode>
<BrowserRouter basename="/menu">
<App />
<Toaster position="top-center" />
</BrowserRouter>
</React.StrictMode>
)
function App() {
const [lang, setLangState] = useState(initialLang)
const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l }
document.documentElement.lang = lang
return (
<LangContext.Provider value={{ lang, setLang }}>
<BrowserRouter basename="/menu">
<Routes>
<Route path="/:site" element={<MenuPage />} />
<Route path="/:site/confirm/:ref" element={<ConfirmPage />} />
<Route path="*" element={<p className="p-6 text-ink-2">Xenia</p>} />
</Routes>
</BrowserRouter>
</LangContext.Provider>
)
}
createRoot(document.getElementById('root')).render(<StrictMode><App /></StrictMode>)
@@ -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 (
<div className="mx-auto max-w-lg min-h-dvh bg-canvas flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
<div className={`w-20 h-20 rounded-full flex items-center justify-center ${tone}`}><Icon size={38} strokeWidth={2.2} aria-hidden="true" /></div>
{order?.public_ref && <p className="text-xs font-semibold uppercase tracking-[0.2em] text-ink-3">{order.public_ref}</p>}
<h1 data-testid="confirm-status" data-status={status ?? ''} className="font-display text-2xl font-semibold text-ink leading-tight">
{failed ? t('track.failed') : t(`track.${state}`)}
</h1>
{order?.rejection_reason && <p className="text-ink-2">{t('track.reason', { reason: order.rejection_reason })}</p>}
{state === 'accepted' && <p className="max-w-xs text-ink-2">{t('track.acceptedBody')}</p>}
{state === 'rejected' && <p className="max-w-xs text-ink-2">{t('track.rejectedBody')}</p>}
{state === 'pending_acceptance' && !failed && (<>
<p className="text-sm text-ink-3">{t('track.waiting')}</p>
<div className="w-5 h-5 rounded-full border-2 border-accent border-t-transparent animate-spin" role="status" aria-label={t('track.waiting')} />
</>)}
<Link to={`/${site}`} className="mt-4 px-5 h-11 rounded-full bg-surface border border-line text-ink font-semibold flex items-center">{t('track.back')}</Link>
</div>
)
}
File diff suppressed because it is too large Load Diff
@@ -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 (
<div className="relative mx-auto min-h-dvh max-w-[480px] bg-[#faf7f0] shadow-[0_0_60px_-20px_rgba(45,42,31,0.3)] flex flex-col items-center justify-center px-6 py-12">
{/* Ornament top */}
<div className="mb-8 flex w-32 items-center gap-2">
<span className="h-px flex-1 bg-gradient-to-r from-transparent to-[#d8cfb6]" />
<Leaf className="h-3.5 w-3.5 text-[#c9a24b]" strokeWidth={1.6} />
<span className="h-px flex-1 bg-gradient-to-l from-transparent to-[#d8cfb6]" />
</div>
{/* Status icon */}
<div
className="flex h-20 w-20 items-center justify-center rounded-full"
style={{ background: bg }}
>
<Icon size={38} style={{ color }} strokeWidth={2.2} />
</div>
{/* Ref number */}
<p className="mt-5 font-sans text-[11px] font-semibold uppercase tracking-[0.22em] text-[#b3aa90]">
{publicRef ?? ''}
</p>
{/* Status label */}
<h1 data-testid="confirm-status" data-status={orderStatus ?? ''} className="mt-2 font-display text-[28px] font-semibold leading-tight text-center text-[#2d3b2d]">
{error ? 'Could not load status' : label}
</h1>
{/* Rejection reason */}
{rejectionReason && (
<p className="mt-2 text-[14px] text-center text-[#7d7660]">
Reason: {rejectionReason}
</p>
)}
{/* Subtext */}
{TERMINAL.has(orderStatus) && orderStatus !== 'rejected' && (
<p className="mt-3 max-w-[280px] text-center text-[14px] leading-relaxed text-[#7d7660]">
Thank you! Your waiter will bring it to your table. Enjoy your meal.
</p>
)}
{orderStatus === 'rejected' && (
<p className="mt-3 max-w-[280px] text-center text-[14px] leading-relaxed text-[#7d7660]">
We're sorry we couldn't take your order this time. Please try again or speak to staff.
</p>
)}
{!TERMINAL.has(orderStatus) && !error && (
<p className="mt-3 text-[13px] text-[#9a917a]">
We'll update this page automatically. Keep it open.
</p>
)}
{/* Spinner */}
{!TERMINAL.has(orderStatus) && !error && (
<div className="mt-6 flex justify-center">
<div className="h-5 w-5 rounded-full border-2 border-[#2d3b2d] border-t-transparent animate-spin" />
</div>
)}
{/* Ornament bottom */}
<div className="mt-10 flex w-32 items-center gap-2">
<span className="h-px flex-1 bg-gradient-to-r from-transparent to-[#d8cfb6]" />
<Leaf className="h-3 w-3 text-[#c9a24b]" strokeWidth={1.6} />
<span className="h-px flex-1 bg-gradient-to-l from-transparent to-[#d8cfb6]" />
</div>
</div>
)
}
+16 -38
View File
@@ -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}) / <alpha-value>)`
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: [],
@@ -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')
})
+10
View File
@@ -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: 'Σύνολο',
+9
View File
@@ -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
@@ -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 }) {
<div className="flex-1 min-w-0 grid gap-1 content-start">
<h3 className="font-semibold text-ink leading-snug">{productName(product)}</h3>
{text && <p className="text-sm text-ink-2 line-clamp-2">{text}</p>}
<AllergenLine product={product} />
<div className="flex items-center justify-between gap-2 mt-1">
<span className="font-semibold text-ink" data-testid="price">{money(product.price)}</span>
{!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 (
<p className="text-xs" data-testid="allergens">
{a.contains.length > 0 && <span className="text-warning-ink">{t('contains')}: {a.contains.map(k => t(`allergen.${k}`)).join(', ')}</span>}
{a.contains.length > 0 && a.may_contain.length > 0 && ' · '}
{a.may_contain.length > 0 && <span className="text-ink-3">{t('mayContain')}: {a.may_contain.map(k => t(`allergen.${k}`)).join(', ')}</span>}
</p>
)
}
function ExtrasSheet({ product, onClose, onAdd }) {
const { t, money } = useT()
const [chosen, setChosen] = useState([])
@@ -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: [] })
})