feat(cloud): the online ordering app (takeaway, delivery) with hours, time slots and rate limits (platform-v2 3S, S.4)

- connect_frontend/order-app at /order/{site}: menu per service at that service's prices,
  extras, basket (kept per tab), checkout priced by the cloud (fee, area by list or
  postcode, minimum), name/phone/address/notes (remembered), as soon as possible or a time
  slot, tracking page with steps, lines and totals; en/el; tokens in index.css. Logic in
  src/logic.js, unit-tested; built and served by the connect image (npm test in the build).
- services/ordering.py: the venue's services, hours (past midnight), preparation, slot grid,
  days ahead, ASAP; takeaway/delivery orders checked (order.service_unavailable,
  order.closed, order.time_invalid) and need a phone; GET /api/orders/{site}/slots; the
  public menu carries the ordering summary.
- services/ratelimit.py: per-caller limits on quote, order and track (429 rate.limited).
- online_orders.requested_for (0003, unreleased) stored as UTC; every datetime sent with its
  offset (the database keeps no zone: a 12:00 Athens slot came back as 12:00 unzoned).
- Tracking returns what was ordered, the totals, the type and the time.
- Tests: test_ordering.py (5), checkout/fees updated; order-app unit (4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 13:39:00 +02:00
co-authored by Claude Opus 5.5
parent 9e8ec4c4e6
commit b25bfcda3e
30 changed files with 4424 additions and 15 deletions
+12 -1
View File
@@ -8,6 +8,16 @@ ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
# Build order-app (online ordering: takeaway and delivery, plan phase 3S S.4)
FROM node:20-alpine AS order-builder
WORKDIR /app/order-app
COPY order-app/package.json order-app/package-lock.json ./
RUN npm ci
COPY order-app/ .
ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm test && npm run build
# Build manager-app
FROM node:20-alpine AS manager-builder
WORKDIR /app/manager-app
@@ -18,8 +28,9 @@ ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
# Serve both with nginx
# Serve them with nginx
FROM nginx:alpine
COPY --from=menu-builder /app/menu-app/dist /usr/share/nginx/html/menu
COPY --from=manager-builder /app/manager-app/dist /usr/share/nginx/html/manage
COPY --from=order-builder /app/order-app/dist /usr/share/nginx/html/order
COPY nginx-connect.conf /etc/nginx/conf.d/default.conf
+6
View File
@@ -7,6 +7,12 @@ server {
try_files $uri $uri/ /menu/index.html;
}
# Online ordering SPA (takeaway, delivery)
location /order/ {
alias /usr/share/nginx/html/order/;
try_files $uri $uri/ /order/index.html;
}
# Remote manager SPA
location /manage/ {
alias /usr/share/nginx/html/manage/;
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#1f3a34" />
<title>Order online</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Hanken+Grotesk:wght@400;500;600;700&family=Noto+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "order-app",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"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-router-dom": "^6.28.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"vite": "^6.0.5"
}
}
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
+13
View File
@@ -0,0 +1,13 @@
// The cloud's public endpoints for online ordering (cloud_backend/routers/orders.py, menu.py).
import axios from 'axios'
export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || ''
const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 })
/** The venue's menu, areas and ordering summary (services, open now, slots). */
export const fetchMenu = async site => (await api.get(`/api/menu/${encodeURIComponent(site)}`)).data
export const fetchSlots = async site => (await api.get(`/api/orders/${encodeURIComponent(site)}/slots`)).data
export const quote = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}/quote`, body)).data
export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data
export const track = async token => (await api.get(`/api/orders/track/${encodeURIComponent(token)}`)).data
export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`)
+108
View File
@@ -0,0 +1,108 @@
// The ordering app's texts (en, el). The customer's choice is remembered on this device; the
// first visit follows the browser's language.
import { createContext, useContext } from 'react'
const STORE = 'xenia-order-lang'
export const TEXTS = {
en: {
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.',
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',
pricing: 'Working out the price…', details: 'Your details', name: 'Name', phone: 'Phone',
address: 'Street and number', area: 'Area', areaPick: 'Pick your area', byPostcode: 'Or enter your postcode',
byArea: 'Pick from the list', postcode: 'Postcode', notes: 'Notes for the venue (optional)',
when: 'When', asap: 'As soon as possible', pickTime: 'Pick a time', today: 'Today', tomorrow: 'Tomorrow',
placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back',
payNote: 'You pay at the venue or on delivery.',
problem: {
name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.',
area: 'Pick your area.', postcode: 'Enter your postcode.', when: 'Pick a time.',
},
refused: {
minimum_not_met: 'The minimum order for delivery is {{minimum}}.', area_not_served: 'Sorry, we don\'t deliver to this address.',
price_changed: 'Prices changed since you opened the menu. Check your order: it now shows the current prices.',
item_unavailable: 'Something in your order is no longer available. Please remove it.', option_unavailable: 'An extra you chose is no longer available.',
service_unavailable: 'This service is not available right now.', closed: 'We\'re closed right now. Pick a later time.',
time_invalid: 'That time is no longer available. Pick another.', details_missing: 'Please fill in your details.',
rate: 'Too many attempts. Please wait a few minutes.', no_menu: 'The menu is not available right now.', failed: 'Something went wrong. Please try again.',
},
track: {
title: 'Order {{ref}}', placed: 'Thank you! We got your order.', for: 'For {{when}}', asap: 'As soon as possible',
keep: 'Keep this page open, or save its address, to follow your order.',
status: {
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', preparing: 'Being prepared',
ready: 'Ready to collect', out_for_delivery: 'On its way', delivered: 'Done', rejected: 'Not accepted',
},
rejected: 'The venue could not take this order.', reason: 'Reason: {{reason}}', newOrder: 'Order again', notFound: 'This order was not found.',
},
},
el: {
takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα',
closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.',
loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.',
retry: 'Δοκιμάστε ξανά', add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', options: 'Έξτρα', addToOrder: 'Στην παραγγελία', cancel: 'Ακύρωση',
viewOrder: 'Η παραγγελία', items_one: '{{count}} τεμάχιο', items_other: '{{count}} τεμάχια',
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', products: 'Προϊόντα', fee: 'Χρέωση διανομής', total: 'Σύνολο',
pricing: 'Υπολογισμός τιμής…', details: 'Τα στοιχεία σας', name: 'Όνομα', phone: 'Τηλέφωνο',
address: 'Οδός και αριθμός', area: 'Περιοχή', areaPick: 'Επιλέξτε περιοχή', byPostcode: 'Ή γράψτε τον Τ.Κ.',
byArea: 'Επιλογή από τη λίστα', postcode: 'Τ.Κ.', notes: 'Σημειώσεις για το κατάστημα (προαιρετικά)',
when: 'Πότε', asap: 'Το συντομότερο', pickTime: 'Επιλέξτε ώρα', today: 'Σήμερα', tomorrow: 'Αύριο',
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
problem: {
name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.',
area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.',
},
refused: {
minimum_not_met: 'Η ελάχιστη παραγγελία για διανομή είναι {{minimum}}.', area_not_served: 'Δυστυχώς δεν κάνουμε διανομή σε αυτή τη διεύθυνση.',
price_changed: 'Οι τιμές άλλαξαν από τότε που ανοίξατε το μενού. Ελέγξτε την παραγγελία: δείχνει πλέον τις τρέχουσες τιμές.',
item_unavailable: 'Κάτι στην παραγγελία σας δεν είναι πλέον διαθέσιμο. Αφαιρέστε το.', option_unavailable: 'Ένα έξτρα που επιλέξατε δεν είναι πλέον διαθέσιμο.',
service_unavailable: 'Αυτή η υπηρεσία δεν είναι διαθέσιμη τώρα.', closed: 'Είμαστε κλειστά τώρα. Επιλέξτε αργότερη ώρα.',
time_invalid: 'Η ώρα αυτή δεν είναι πλέον διαθέσιμη. Επιλέξτε άλλη.', details_missing: 'Συμπληρώστε τα στοιχεία σας.',
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.',
},
track: {
title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο',
keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.',
status: {
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', preparing: 'Ετοιμάζεται',
ready: 'Έτοιμη για παραλαβή', out_for_delivery: 'Καθ\' οδόν', delivered: 'Ολοκληρώθηκε', rejected: 'Δεν έγινε δεκτή',
},
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την παραγγελία.', reason: 'Λόγος: {{reason}}', newOrder: 'Νέα παραγγελία', notFound: 'Η παραγγελία δεν βρέθηκε.',
},
},
}
export function initialLang() {
try {
const saved = localStorage.getItem(STORE)
if (saved && TEXTS[saved]) return saved
} 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 }
}
+35
View File
@@ -0,0 +1,35 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* 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;
}
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; }
}
+126
View File
@@ -0,0 +1,126 @@
// The online ordering app's logic (plan phase 3S, step S.4). Pure: unit-tested in Node
// (tests/logic.test.mjs). Prices shown come from the venue's menu for the chosen service;
// what is charged is the cloud's answer (POST /api/orders/{site}/quote and the order itself).
export const SERVICES = ['takeaway', 'delivery']
export const POINT = { takeaway: 'online_takeaway', delivery: 'online_delivery' }
const round2 = n => Math.round(n * 100) / 100
/** A product's price for a service, or null when it isn't sold that way. */
export function priceFor(product, service) {
const point = POINT[service]
if (product.sold_at && !product.sold_at.includes(point)) return null
if (product.prices) return product.prices[point] ?? null
return product.digital_price ?? product.base_price ?? null // menus from before S.2
}
/** The menu for a service: categories with the products sold that way (once each, priced). */
export function menuFor(categories, service) {
const seen = new Set()
return (categories ?? []).map(c => ({
...c,
products: (c.products ?? []).filter(p => {
const price = priceFor(p, service)
return price != null
}).map(p => ({ ...p, price: priceFor(p, service), available: p.digital_available !== false, repeat: seen.has(p.id) || !seen.add(p.id) })),
})).filter(c => c.products.length > 0)
}
export const productName = p => p.digital_name || p.name
export const productText = p => p.digital_description || ''
/** A cart line's key: the product and its chosen options. */
export const lineKey = (productId, options = []) => [productId, ...[...options].sort((a, b) => a - b)].join(':')
/** Add one (or `qty`) of a product with options. */
export function addToCart(cart, product, options = [], qty = 1) {
const key = lineKey(product.id, options)
const found = cart.find(l => l.key === key)
if (found) return cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, l.qty + qty) } : l))
return [...cart, { key, productId: product.id, options: [...options].sort((a, b) => a - b), qty }]
}
export function setQty(cart, key, qty) {
return qty <= 0 ? cart.filter(l => l.key !== key) : cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, qty) } : l))
}
export const cartCount = cart => cart.reduce((s, l) => s + l.qty, 0)
/** The cart priced from the menu (what's shown before the cloud answers); lines whose product
* isn't sold for this service any more are dropped. */
export function cartLines(cart, products, service) {
const byId = new Map(products.map(p => [p.id, p]))
return cart.flatMap(l => {
const p = byId.get(l.productId)
const price = p ? priceFor(p, service) : null
if (price == null) return []
const opts = (p.quick_options ?? []).filter(o => l.options.includes(o.id))
const unit = round2(price + opts.reduce((s, o) => s + (o.price || 0), 0))
return [{ ...l, name: productName(p), unit, total: round2(unit * l.qty), optionNames: opts.map(o => o.name) }]
})
}
/** Items as the cloud takes them. */
export const itemsBody = lines => lines.map(l => ({ product_id: l.productId, quantity: l.qty, options: l.options, unit_price: l.unit }))
/** What checkout still needs: a list of field keys (empty = can order). */
export function checkoutProblems(form, service, { areas = [], asap = true, slots = [] } = {}) {
const out = []
if (!form.name.trim()) out.push('name')
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
if (service === 'delivery') {
if (!form.address.trim()) out.push('address')
if (areas.length && form.where === 'area' && !form.areaId) out.push('area')
if (form.where === 'postcode' && !form.postcode.trim()) out.push('postcode')
}
if (form.when === 'asap' ? !asap : !slots.includes(form.when)) out.push('when')
return out
}
/** The order request (POST /api/orders/{site}). `quote` is the cloud's last answer. */
export function orderBody(form, service, lines, quote) {
return {
order_type: service,
customer_name: form.name.trim(),
customer_phone: form.phone.trim(),
customer_address: service === 'delivery' ? form.address.trim() : null,
customer_notes: form.notes.trim() || null,
area_id: service === 'delivery' && form.where === 'area' && form.areaId ? Number(form.areaId) : null,
postcode: service === 'delivery' && form.where === 'postcode' ? form.postcode.trim() || null : null,
requested_for: form.when === 'asap' ? null : form.when,
items: itemsBody(lines),
total: quote?.total ?? undefined,
}
}
/** Slots grouped by local day for the picker: [{ day: 'YYYY-MM-DD', times: [{ iso, label }] }]. */
export function slotDays(slots, timeZone) {
const dayFmt = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
const timeFmt = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hour12: false })
const out = []
for (const iso of slots ?? []) {
const d = new Date(iso)
const day = dayFmt.format(d)
let g = out.find(x => x.day === day)
if (!g) out.push(g = { day, times: [] })
g.times.push({ iso, label: timeFmt.format(d) })
}
return out
}
/** The tracking page's steps for an order type, and how far it got. */
export function trackSteps(orderType, status) {
const steps = orderType === 'delivery'
? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered']
: ['pending_acceptance', 'accepted', 'preparing', 'ready', 'delivered']
return { steps, at: status === 'rejected' ? -1 : steps.indexOf(status), done: status === 'delivered' || status === 'rejected' }
}
/** A refusal from the cloud → a message key and its params. */
export function refusal(err) {
const d = err?.response?.data?.detail
if (err?.response?.status === 429) return ['rate', {}]
if (d && typeof d === 'object' && d.code) return [d.code.replace(/^order\./, ''), d.params ?? {}]
return ['failed', {}]
}
+26
View File
@@ -0,0 +1,26 @@
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 OrderPage from './pages/OrderPage'
import TrackPage from './pages/TrackPage'
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="/order">
<Routes>
<Route path="/:site" element={<OrderPage />} />
<Route path="/:site/track/:token" element={<TrackPage />} />
<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,218 @@
// Checkout (plan phase 3S, step S.4): the order priced by the cloud (products at this service's
// prices, the delivery fee from the venue's rules, the minimum), the customer's details, when
// (as soon as possible while open, or a time slot) and "Place order". Every price shown here is
// the cloud's answer; the order is refused if it changed meanwhile and the new prices show.
import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowLeft, Minus, Plus } from 'lucide-react'
import { fetchSlots, placeOrder, quote } from '../api'
import { useT } from '../i18n'
import { checkoutProblems, itemsBody, orderBody, refusal, setQty, slotDays } from '../logic'
const QUOTE_DELAY = 250
const SLOTS_EVERY = 60_000
const FORM_KEY = 'xenia-order-details'
function savedDetails() {
try { return JSON.parse(localStorage.getItem(FORM_KEY) || '{}') } catch { return {} }
}
export default function Checkout({ site, service, menu, lines, setCart, onBack, onPlaced }) {
const { t, money } = useT()
const areas = menu.delivery_areas ?? []
const [form, setForm] = useState(() => ({
name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(),
where: areas.length ? 'area' : 'postcode', areaId: '', when: 'asap',
}))
const [slots, setSlots] = useState(menu.ordering ?? { slots: [], asap: false, timezone: 'Europe/Athens' })
const [priced, setPriced] = useState({ quote: null, problem: null, pending: true })
const [tried, setTried] = useState(false)
const [sending, setSending] = useState(false)
const [sendProblem, setSendProblem] = useState(null)
const seq = useRef(0)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
// the slots move on with the clock
useEffect(() => {
let alive = true
const load = () => fetchSlots(site).then(s => alive && setSlots(s)).catch(() => {})
load()
const id = setInterval(load, SLOTS_EVERY)
return () => { alive = false; clearInterval(id) }
}, [site])
useEffect(() => {
if (form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0])
}, [slots, form.when])
// the cloud prices the order whenever what affects the price changes
const quoteKey = JSON.stringify([itemsBody(lines).map(i => [i.product_id, i.quantity, i.options]), service,
service === 'delivery' ? [form.where, form.areaId, form.postcode.trim()] : null])
useEffect(() => {
const mine = ++seq.current
if (!lines.length) { setPriced({ quote: null, problem: null, pending: false }); return undefined }
setPriced(p => ({ ...p, pending: true }))
const id = setTimeout(async () => {
const body = orderBody(form, service, lines, null)
try {
const q = await quote(site, { order_type: service, items: body.items, area_id: body.area_id, postcode: body.postcode })
if (mine === seq.current) setPriced({ quote: q, problem: null, pending: false })
} catch (err) {
if (mine === seq.current) setPriced({ quote: null, problem: refusal(err), pending: false })
}
}, QUOTE_DELAY)
return () => clearTimeout(id)
}, [quoteKey]) // eslint-disable-line react-hooks/exhaustive-deps -- quoteKey is what changes the price
const days = useMemo(() => slotDays(slots.slots ?? [], slots.timezone || 'Europe/Athens'), [slots])
const problems = checkoutProblems(form, service, { areas, asap: !!slots.asap, slots: slots.slots ?? [] })
const q = priced.quote
const canSend = q && !priced.pending && !priced.problem && !sending
const submit = async () => {
setTried(true)
setSendProblem(null)
if (problems.length || !canSend) return
setSending(true)
try {
const body = orderBody(form, service, lines, q)
const result = await placeOrder(site, body)
try { localStorage.setItem(FORM_KEY, JSON.stringify({ name: form.name, phone: form.phone, address: form.address, postcode: form.postcode })) } catch { /* private mode */ }
onPlaced(result)
} catch (err) {
const [code, params] = refusal(err)
setSendProblem([code, params])
// the refusal carries the current prices: show them; "Place order" again sends the new total
if (code === 'price_changed' && params.lines) setPriced({ quote: params, problem: null, pending: false })
setSending(false)
}
}
const fieldErr = k => (tried && problems.includes(k) ? t(`problem.${k}`) : null)
const input = 'w-full h-12 px-3.5 rounded-control bg-surface border border-line text-ink placeholder:text-ink-3'
return (
<div className="pb-10" data-testid="checkout">
<header className="px-4 py-3 flex items-center gap-2 bg-surface border-b border-line sticky top-0 z-10">
<button type="button" onClick={onBack} aria-label={t('back')} className="w-10 h-10 rounded-full bg-surface-2 flex items-center justify-center"><ArrowLeft size={18} /></button>
<h1 className="font-display text-xl font-semibold">{t('yourOrder')} · {t(service)}</h1>
</header>
<section className="p-4 grid gap-2" aria-label={t('yourOrder')}>
{lines.length === 0 && <p className="text-ink-2">{t('empty')}</p>}
{lines.map(l => {
const cloudLine = q?.lines?.find(x => x.product_id === l.productId && JSON.stringify((x.options ?? []).map(o => o.id).sort()) === JSON.stringify(l.options))
return (
<div key={l.key} className="p-3 rounded-card bg-surface border border-line flex items-center gap-3" data-testid="line">
<div className="flex-1 min-w-0">
<p className="font-medium text-ink">{l.name}</p>
{l.optionNames.length > 0 && <p className="text-sm text-ink-2">{l.optionNames.join(', ')}</p>}
<p className="text-sm text-ink-2">{money(cloudLine?.unit_price ?? l.unit)}</p>
</div>
<div className="flex items-center gap-1">
<button type="button" onClick={() => setCart(c => setQty(c, l.key, l.qty - 1))} aria-label="−" className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><Minus size={16} /></button>
<span className="w-7 text-center font-semibold">{l.qty}</span>
<button type="button" onClick={() => setCart(c => setQty(c, l.key, l.qty + 1))} aria-label="+" className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><Plus size={16} /></button>
</div>
</div>
)
})}
</section>
<section className="px-4 grid gap-3" aria-labelledby="details-h">
<h2 id="details-h" className="font-display text-lg font-semibold">{t('details')}</h2>
<Field label={t('name')} error={fieldErr('name')}>
<input className={input} value={form.name} onChange={e => set('name', e.target.value)} autoComplete="name" maxLength={100} data-testid="f-name" />
</Field>
<Field label={t('phone')} error={fieldErr('phone')}>
<input className={input} value={form.phone} onChange={e => set('phone', e.target.value)} autoComplete="tel" inputMode="tel" maxLength={40} data-testid="f-phone" />
</Field>
{service === 'delivery' && (
<>
{areas.length > 0 && (
<div className="flex gap-2 text-sm" role="radiogroup" aria-label={t('area')}>
{['area', 'postcode'].map(w => (
<button key={w} type="button" role="radio" aria-checked={form.where === w} onClick={() => set('where', w)}
className={`px-3 h-9 rounded-full font-medium ${form.where === w ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{w === 'area' ? t('byArea') : t('byPostcode')}
</button>
))}
</div>
)}
{form.where === 'area' && areas.length > 0 ? (
<Field label={t('area')} error={fieldErr('area')}>
<select className={input} value={form.areaId} onChange={e => set('areaId', e.target.value)} data-testid="f-area">
<option value="">{t('areaPick')}</option>
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
</select>
</Field>
) : (
<Field label={t('postcode')} error={fieldErr('postcode')}>
<input className={input} value={form.postcode} onChange={e => set('postcode', e.target.value)} autoComplete="postal-code" maxLength={20} data-testid="f-postcode" />
</Field>
)}
<Field label={t('address')} error={fieldErr('address')}>
<input className={input} value={form.address} onChange={e => set('address', e.target.value)} autoComplete="street-address" maxLength={300} data-testid="f-address" />
</Field>
</>
)}
<Field label={t('notes')}>
<textarea className={`${input} h-20 py-2.5`} value={form.notes} onChange={e => set('notes', e.target.value)} maxLength={500} />
</Field>
<Field label={t('when')} error={fieldErr('when')}>
<select className={input} value={form.when} onChange={e => set('when', e.target.value)} data-testid="f-when">
{slots.asap && <option value="asap">{t('asap')}</option>}
{!slots.asap && <option value="asap" disabled>{t('pickTime')}</option>}
{days.map((d, i) => (
<optgroup key={d.day} label={i === 0 ? t('today') : i === 1 ? t('tomorrow') : d.day}>
{d.times.map(s => <option key={s.iso} value={s.iso}>{s.label}</option>)}
</optgroup>
))}
</select>
</Field>
</section>
<section className="m-4 p-4 rounded-card bg-surface border border-line grid gap-1.5" aria-live="polite" data-testid="totals"
data-total={q?.total ?? ''} data-fee={q?.delivery_fee ?? ''}>
{priced.pending && <p className="text-sm text-ink-2">{t('pricing')}</p>}
{priced.problem && <p className="text-sm font-medium text-danger-ink" role="alert" data-testid="quote-problem" data-code={priced.problem[0]}>{refusedText(t, money, priced.problem)}</p>}
{q && (
<>
<Row label={t('products')} value={money(q.subtotal)} />
{service === 'delivery' && <Row label={t('fee') + (q.area_name ? ` · ${q.area_name}` : '')} value={money(q.delivery_fee)} testId="fee" />}
<Row label={t('total')} value={money(q.total)} strong />
</>
)}
</section>
<div className="px-4 grid gap-2">
{sendProblem && <p className="text-sm font-medium text-danger-ink" role="alert" data-testid="send-problem" data-code={sendProblem[0]}>{refusedText(t, money, sendProblem)}</p>}
<button type="button" onClick={submit} disabled={sending || !lines.length} data-testid="place-order"
className={`h-14 rounded-full font-semibold ${canSend ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-3'}`}>
{sending ? t('sending') : t('placeOrder', { total: q ? money(q.total) : '…' })}
</button>
<p className="text-sm text-ink-2 text-center">{t('payNote')}</p>
</div>
</div>
)
}
function refusedText(t, money, [code, params]) {
return t(`refused.${code}`, { ...params, minimum: params.minimum != null ? money(params.minimum) : '' })
}
function Field({ label, error, children }) {
return (
<label className="grid gap-1">
<span className="text-sm font-medium text-ink-2">{label}</span>
{children}
{error && <span className="text-sm text-danger-ink" role="alert">{error}</span>}
</label>
)
}
function Row({ label, value, strong, testId }) {
return (
<div className={`flex items-baseline justify-between ${strong ? 'text-lg font-semibold text-ink pt-1 border-t border-line' : 'text-ink-2'}`} data-testid={testId}>
<span>{label}</span><span>{value}</span>
</div>
)
}
@@ -0,0 +1,225 @@
// Online ordering (plan phase 3S, step S.4): /order/{site}. The customer picks takeaway or
// delivery (what the venue offers), adds products at that service's prices, and checks out:
// the cart is priced by the cloud (with the delivery fee and minimum), then the order is
// placed for "as soon as possible" or a time slot, and the tracking page opens.
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Bike, Clock, Minus, Plus, ShoppingBag, Store, X } from 'lucide-react'
import { fetchMenu, imageUrl } from '../api'
import { useT } from '../i18n'
import { addToCart, cartCount, cartLines, menuFor, productName, productText, SERVICES } from '../logic'
import Checkout from './Checkout'
const CART_KEY = site => `xenia-order-cart:${site}`
export default function OrderPage() {
const { site } = useParams()
const { t, lang, setLang, money } = useT()
const navigate = useNavigate()
const [menu, setMenu] = useState(null)
const [error, setError] = useState(null)
const [service, setService] = useState(null)
const [cart, setCart] = useState(() => {
try { return JSON.parse(sessionStorage.getItem(CART_KEY(site)) || '[]') } catch { return [] }
})
const [picking, setPicking] = useState(null) // a product whose extras are being chosen
const [checkout, setCheckout] = useState(false)
const [category, setCategory] = useState(null)
const load = useCallback(async () => {
setError(null)
try {
const data = await fetchMenu(site)
setMenu(data)
setService(s => s ?? data.ordering?.services?.[0] ?? null)
} catch (err) {
setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed')
}
}, [site])
useEffect(() => { load() }, [load])
useEffect(() => {
try { sessionStorage.setItem(CART_KEY(site), JSON.stringify(cart)) } catch { /* private mode */ }
}, [cart, site])
const sections = useMemo(() => (menu && service ? menuFor(menu.categories, service) : []), [menu, service])
const products = useMemo(() => sections.flatMap(c => c.products), [sections])
const lines = useMemo(() => (service ? cartLines(cart, products, service) : []), [cart, products, service])
const count = cartCount(lines)
const subtotal = lines.reduce((s, l) => s + l.total, 0)
if (error) {
return (
<Shell>
<div className="p-6 grid gap-4 text-center">
<p className="text-body text-ink-2">{t(error)}</p>
{error === 'loadFailed' && <button className="mx-auto px-5 h-11 rounded-full bg-accent text-accent-fg font-semibold" onClick={load}>{t('retry')}</button>}
</div>
</Shell>
)
}
if (!menu) return <Shell><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Shell>
const ordering = menu.ordering ?? { services: [] }
const name = menu.restaurant?.name || site
const add = (product, options = []) => setCart(c => addToCart(c, product, options))
if (checkout && service) {
return (
<Shell>
<Checkout site={site} service={service} menu={menu} lines={lines} setCart={setCart}
onBack={() => setCheckout(false)}
onPlaced={(result) => {
// cleared here too: the page unmounts before its storage effect would run
try { sessionStorage.removeItem(CART_KEY(site)) } catch { /* private mode */ }
setCart([])
navigate(`/${site}/track/${result.tracking_token}`, { state: { placed: true } })
}} />
</Shell>
)
}
return (
<Shell>
<header className="px-4 pt-5 pb-3 grid gap-3 bg-surface border-b border-line">
<div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<h1 className="font-display text-2xl font-semibold text-ink leading-tight" data-testid="venue-name">{name}</h1>
{menu.restaurant?.tagline?.[lang === 'el' ? 'gr' : 'en'] && (
<p className="text-sm text-ink-2 mt-0.5">{menu.restaurant.tagline[lang === 'el' ? 'gr' : 'en']}</p>
)}
</div>
<div className="flex rounded-full bg-surface-2 p-0.5 text-sm font-semibold" role="group" aria-label="Language">
{['el', 'en'].map(l => (
<button key={l} type="button" onClick={() => setLang(l)} aria-pressed={lang === l}
className={`px-2.5 h-8 rounded-full ${lang === l ? 'bg-surface text-ink shadow-card' : 'text-ink-2'}`}>{l.toUpperCase()}</button>
))}
</div>
</div>
{ordering.services.length === 0 ? (
<p className="p-3 rounded-control bg-warning-soft text-warning-ink text-sm" data-testid="no-ordering">{t('noOrdering')}</p>
) : (
<>
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label={t('takeaway') + ' / ' + t('delivery')}>
{SERVICES.filter(s => ordering.services.includes(s)).map(s => {
const Icon = s === 'delivery' ? Bike : Store
return (
<button key={s} type="button" role="radio" aria-checked={service === s} onClick={() => setService(s)} data-testid={`service-${s}`}
className={`h-12 rounded-control flex items-center justify-center gap-2 font-semibold transition-colors
${service === s ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
<Icon size={18} aria-hidden="true" />{t(s)}
</button>
)
})}
</div>
<p className={`text-sm flex items-center gap-1.5 ${ordering.open_now ? 'text-success-ink' : 'text-warning-ink'}`} data-testid="open-state">
<Clock size={15} aria-hidden="true" />
{ordering.open_now ? t('open') : `${t('closed')} · ${t('closedBody')}`}
</p>
</>
)}
</header>
{sections.length > 1 && (
<nav className="sticky top-0 z-10 bg-canvas/95 backdrop-blur px-4 py-2 flex gap-2 overflow-x-auto border-b border-line" aria-label="Categories">
{sections.filter(c => c.products.some(p => !p.repeat)).map(c => (
<a key={c.id} href={`#cat-${c.id}`} onClick={() => setCategory(c.id)}
className={`shrink-0 px-3.5 h-9 rounded-full flex items-center text-sm font-medium ${category === c.id ? 'bg-accent text-accent-fg' : 'bg-surface text-ink-2 border border-line'}`}>{c.name}</a>
))}
</nav>
)}
<main className="px-4 pb-32 pt-3 grid gap-6">
{sections.map(c => (
<section key={c.id} id={`cat-${c.id}`} className="grid gap-2 scroll-mt-16" aria-labelledby={`h-${c.id}`}>
<h2 id={`h-${c.id}`} className="font-display text-lg font-semibold text-ink">{c.name}</h2>
{c.products.map(p => (
<ProductCard key={`${c.id}-${p.id}`} product={p} qty={lines.filter(l => l.productId === p.id).reduce((s, l) => s + l.qty, 0)}
onAdd={() => (p.quick_options?.length ? setPicking(p) : add(p))}
onRemove={() => setCart(cc => {
const i = cc.map(l => l.productId).lastIndexOf(p.id)
if (i < 0) return cc
return cc[i].qty > 1 ? cc.map((l, j) => (j === i ? { ...l, qty: l.qty - 1 } : l)) : cc.filter((_, j) => j !== i)
})} />
))}
</section>
))}
</main>
{count > 0 && service && (
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<button type="button" onClick={() => setCheckout(true)} data-testid="view-order"
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
<ShoppingBag size={20} aria-hidden="true" />
<span className="flex-1 text-left">{t('viewOrder')} · {t('items', { count })}</span>
<span>{money(subtotal)}</span>
</button>
</div>
)}
{picking && <ExtrasSheet product={picking} onClose={() => setPicking(null)} onAdd={opts => { add(picking, opts); setPicking(null) }} />}
</Shell>
)
}
function Shell({ children }) {
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
}
function ProductCard({ product, qty, onAdd, onRemove }) {
const { t, money } = useT()
const img = imageUrl(product.digital_image_url || product.image_url)
const text = productText(product)
return (
<article className="p-3 rounded-card bg-surface border border-line shadow-card flex gap-3" data-testid="product" data-product={product.id}>
{img && <img src={img} alt="" loading="lazy" className="w-20 h-20 rounded-control object-cover bg-surface-2 shrink-0" />}
<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>}
<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 ? (
<span className="text-sm font-medium text-ink-3">{t('soldOut')}</span>
) : qty > 0 ? (
<div className="flex items-center gap-1">
<button type="button" onClick={onRemove} aria-label="−" className="w-9 h-9 rounded-full bg-surface-2 text-ink flex items-center justify-center"><Minus size={16} /></button>
<span className="w-7 text-center font-semibold" data-testid="qty">{qty}</span>
<button type="button" onClick={onAdd} aria-label="+" className="w-9 h-9 rounded-full bg-accent text-accent-fg flex items-center justify-center"><Plus size={16} /></button>
</div>
) : (
<button type="button" onClick={onAdd} data-testid="add"
className="h-9 px-4 rounded-full bg-accent text-accent-fg text-sm font-semibold flex items-center gap-1"><Plus size={15} aria-hidden="true" />{t('add')}</button>
)}
</div>
</div>
</article>
)
}
function ExtrasSheet({ product, onClose, onAdd }) {
const { t, money } = useT()
const [chosen, setChosen] = useState([])
const toggle = id => setChosen(c => (c.includes(id) ? c.filter(x => x !== id) : [...c, id]))
const total = product.price + (product.quick_options ?? []).filter(o => chosen.includes(o.id)).reduce((s, o) => s + (o.price || 0), 0)
return (
<div className="fixed inset-0 z-20 flex items-end justify-center bg-ink/40" role="dialog" aria-modal="true" aria-labelledby="extras-title" onClick={onClose}>
<div className="w-full max-w-lg bg-surface rounded-t-[22px] p-4 pb-[max(1rem,env(safe-area-inset-bottom))] grid gap-3" onClick={e => e.stopPropagation()}>
<div className="flex items-center gap-2">
<h2 id="extras-title" className="flex-1 font-display text-lg font-semibold">{productName(product)}</h2>
<button type="button" onClick={onClose} aria-label={t('cancel')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><X size={18} /></button>
</div>
<p className="text-sm font-semibold text-ink-2">{t('options')}</p>
<div className="grid gap-1">
{product.quick_options.map(o => (
<label key={o.id} className="flex items-center gap-3 p-2.5 rounded-control bg-surface-2 cursor-pointer">
<input type="checkbox" checked={chosen.includes(o.id)} onChange={() => toggle(o.id)} className="w-5 h-5 accent-[rgb(var(--o-accent))]" />
<span className="flex-1">{o.name}</span>
{o.price ? <span className="text-sm text-ink-2">+{money(o.price)}</span> : null}
</label>
))}
</div>
<button type="button" onClick={() => onAdd(chosen)} data-testid="extras-add"
className="h-12 rounded-full bg-accent text-accent-fg font-semibold">{t('addToOrder')} · {money(total)}</button>
</div>
</div>
)
}
@@ -0,0 +1,99 @@
// The customer's order tracking (plan phase 3S, step S.4): /order/{site}/track/{token}. The
// token is the order's private code (the address is the customer's to keep). Polls the cloud
// until the order is done or not accepted; shows the steps, what was ordered and for when.
import { useEffect, useState } from 'react'
import { Link, useLocation, useParams } from 'react-router-dom'
import { Check, X } from 'lucide-react'
import { track } from '../api'
import { useT } from '../i18n'
import { trackSteps } from '../logic'
const POLL_MS = 8000
export default function TrackPage() {
const { site, token } = useParams()
const { t, money, lang } = useT()
const placed = useLocation().state?.placed
const [order, setOrder] = useState(null)
const [missing, setMissing] = useState(false)
useEffect(() => {
let timer
let alive = true
const poll = async () => {
try {
const o = await track(token)
if (!alive) return
setOrder(o)
if (!trackSteps(o.order_type, o.status).done) timer = setTimeout(poll, POLL_MS)
} catch (err) {
if (!alive) return
if (err?.response?.status === 404) setMissing(true)
else timer = setTimeout(poll, POLL_MS) // offline for a moment: try again
}
}
poll()
return () => { alive = false; clearTimeout(timer) }
}, [token])
if (missing) return <Page><p className="p-6 text-center text-ink-2">{t('track.notFound')}</p></Page>
if (!order) return <Page><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Page>
const { steps, at } = trackSteps(order.order_type, order.status)
const rejected = order.status === 'rejected'
const when = order.requested_for
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', { weekday: 'long', hour: '2-digit', minute: '2-digit' }).format(new Date(order.requested_for))
: null
return (
<Page>
<div className="p-4 grid gap-4" data-testid="track" data-status={order.status}>
{placed && <p className="p-3 rounded-control bg-success-soft text-success-ink font-medium">{t('track.placed')}</p>}
<header className="grid gap-1">
<h1 className="font-display text-2xl font-semibold" data-testid="track-ref">{t('track.title', { ref: order.public_ref })}</h1>
<p className="text-ink-2">{t(order.order_type === 'delivery' ? 'delivery' : 'takeaway')} · {order.requested_for ? t('track.for', { when }) : t('track.asap')}</p>
</header>
{rejected ? (
<div className="p-4 rounded-card bg-danger-soft text-danger-ink grid gap-1" role="status">
<p className="font-semibold flex items-center gap-2"><X size={18} aria-hidden="true" />{t('track.rejected')}</p>
{order.rejection_reason && <p>{t('track.reason', { reason: order.rejection_reason })}</p>}
</div>
) : (
<ol className="grid gap-0" aria-label={t('track.status.' + order.status)}>
{steps.map((s, i) => {
const done = i < at || order.status === 'delivered'
const now = i === at && order.status !== 'delivered'
return (
<li key={s} className="flex items-center gap-3 py-2" aria-current={now ? 'step' : undefined}>
<span className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 text-sm font-semibold
${done ? 'bg-accent text-accent-fg' : now ? 'bg-accent-soft text-accent-ink ring-2 ring-accent' : 'bg-surface-2 text-ink-3'}`}>
{done ? <Check size={15} aria-hidden="true" /> : i + 1}
</span>
<span className={done || now ? 'text-ink font-medium' : 'text-ink-3'}>{t(`track.status.${s}`)}</span>
</li>
)
})}
</ol>
)}
<section className="p-4 rounded-card bg-surface border border-line grid gap-1.5">
{(order.lines ?? []).map((l, i) => (
<div key={i} className="flex justify-between gap-3 text-ink-2">
<span>{l.quantity}× {l.name}{l.options?.length ? ` (${l.options.join(', ')})` : ''}</span>
<span>{money(l.unit_price * l.quantity)}</span>
</div>
))}
{order.delivery_fee > 0 && <div className="flex justify-between text-ink-2"><span>{t('fee')}</span><span>{money(order.delivery_fee)}</span></div>}
<div className="flex justify-between text-lg font-semibold pt-1 border-t border-line"><span>{t('total')}</span><span data-testid="track-total">{money(order.total)}</span></div>
</section>
{!trackSteps(order.order_type, order.status).done && <p className="text-sm text-ink-2">{t('track.keep')}</p>}
<Link to={`/${site}`} className="text-center text-accent-ink font-semibold">{t('track.newOrder')}</Link>
</div>
</Page>
)
}
function Page({ children }) {
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
}
@@ -0,0 +1,29 @@
/** @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: {
sans: ['Hanken Grotesk', 'Noto Sans', 'system-ui', 'sans-serif'],
display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'],
},
colors: {
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,63 @@
// The online ordering app's logic (plan phase 3S, step S.4).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
addToCart, cartCount, cartLines, checkoutProblems, menuFor, orderBody, priceFor, refusal, setQty, slotDays, trackSteps,
} from '../src/logic.js'
const cola = { id: 1, name: 'Cola', sold_at: ['qr_table', 'online_takeaway', 'online_delivery'], prices: { qr_table: 3.5, online_takeaway: 2.5, online_delivery: 2.8 },
quick_options: [{ id: 7, name: 'Ice', price: 0.2 }] }
const pie = { id: 2, name: 'Pie', digital_name: 'Spinach pie', sold_at: ['online_takeaway'], prices: { online_takeaway: 4 }, digital_available: false }
const old = { id: 3, name: 'Old', digital_price: 5 }
const cats = [{ id: 10, name: 'Drinks', products: [cola] }, { id: 11, name: 'Food', products: [pie, old] }, { id: 12, name: 'Also', products: [cola] }]
test('the menu and prices per service', () => {
assert.equal(priceFor(cola, 'takeaway'), 2.5)
assert.equal(priceFor(cola, 'delivery'), 2.8)
assert.equal(priceFor(pie, 'delivery'), null)
assert.equal(priceFor(old, 'delivery'), 5)
const m = menuFor(cats, 'delivery')
assert.deepEqual(m.map(c => [c.name, c.products.map(p => [p.id, p.price, p.repeat])]), [['Drinks', [[1, 2.8, false]]], ['Food', [[3, 5, false]]], ['Also', [[1, 2.8, true]]]])
assert.equal(menuFor(cats, 'takeaway')[1].products[0].available, false)
})
test('the cart', () => {
let cart = addToCart([], cola)
cart = addToCart(cart, cola)
cart = addToCart(cart, cola, [7])
assert.deepEqual(cart.map(l => [l.key, l.qty]), [['1', 2], ['1:7', 1]])
assert.equal(cartCount(cart), 3)
const lines = cartLines(cart, [cola, pie], 'takeaway')
assert.deepEqual(lines.map(l => [l.unit, l.total, l.optionNames]), [[2.5, 5, []], [2.7, 2.7, ['Ice']]])
assert.deepEqual(cartLines(addToCart(cart, pie), [cola, pie], 'delivery').length, 2) // the pie isn't delivered
assert.deepEqual(setQty(cart, '1', 0).map(l => l.key), ['1:7'])
assert.equal(setQty(cart, '1', 500)[0].qty, 99)
})
test('checkout checks and the order body', () => {
const form = { name: ' Maria ', phone: '690 000 0000', address: '', notes: '', where: 'area', areaId: '', postcode: '', when: 'asap' }
assert.deepEqual(checkoutProblems(form, 'takeaway'), [])
assert.deepEqual(checkoutProblems(form, 'delivery', { areas: [{ id: 1 }] }), ['address', 'area'])
assert.deepEqual(checkoutProblems({ ...form, name: '', phone: 'abc' }, 'takeaway'), ['name', 'phone'])
assert.deepEqual(checkoutProblems(form, 'takeaway', { asap: false }), ['when'])
assert.deepEqual(checkoutProblems({ ...form, when: 'X' }, 'takeaway', { slots: ['X'] }), [])
const lines = cartLines(addToCart([], cola), [cola], 'delivery')
const body = orderBody({ ...form, address: 'Main sq 3', areaId: '2', notes: ' bell ' }, 'delivery', lines, { total: 4.8 })
assert.deepEqual(body, {
order_type: 'delivery', customer_name: 'Maria', customer_phone: '690 000 0000', customer_address: 'Main sq 3', customer_notes: 'bell',
area_id: 2, postcode: null, requested_for: null, items: [{ product_id: 1, quantity: 1, options: [], unit_price: 2.8 }], total: 4.8,
})
assert.equal(orderBody({ ...form, when: '2026-11-16T10:00:00+00:00' }, 'takeaway', lines, null).requested_for, '2026-11-16T10:00:00+00:00')
})
test('slots by day in the venue time zone, tracking steps, refusals', () => {
const days = slotDays(['2026-11-15T19:45:00+00:00', '2026-11-15T22:00:00+00:00'], 'Europe/Athens')
assert.deepEqual(days, [{ day: '2026-11-15', times: [{ iso: '2026-11-15T19:45:00+00:00', label: '21:45' }] },
{ day: '2026-11-16', times: [{ iso: '2026-11-15T22:00:00+00:00', label: '00:00' }] }])
assert.deepEqual(trackSteps('delivery', 'preparing'), { steps: ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered'], at: 2, done: false })
assert.equal(trackSteps('takeaway', 'ready').at, 3)
assert.deepEqual(trackSteps('takeaway', 'rejected'), { ...trackSteps('takeaway', 'rejected'), at: -1, done: true })
assert.deepEqual(refusal({ response: { status: 409, data: { detail: { code: 'order.minimum_not_met', params: { minimum: 10 } } } } }), ['minimum_not_met', { minimum: 10 }])
assert.deepEqual(refusal({ response: { status: 429, data: {} } }), ['rate', {}])
assert.deepEqual(refusal(new Error('x')), ['failed', {}])
})
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// The online ordering app (plan phase 3S, step S.4), served at /order/ next to the QR menu.
export default defineConfig({
plugins: [react()],
base: '/order/',
server: { host: '0.0.0.0', port: 5210 },
preview: { port: 5211 },
build: { outDir: 'dist' },
})