feat(cloud): table bookings online, with food ordered ahead
Plan phase 3S, step S.6.
- New order types "reservation" (a table only, no items) and "preorder" (a table with food,
priced at the online_preorder sales point); online_orders.party_size (migration 0005).
- services/ordering.py: the venue's booking settings (ordering.reservations in the snapshot):
hours (none = any time), time grid, notice, days ahead (≤ 90), party size; res_slots per
venue day, res_days, res_check (order.service_unavailable, order.party_invalid,
order.time_invalid). The public menu's ordering summary gains `reservations`
{enabled, with_food, party_max, days}; GET /api/orders/{site}/reservation-slots?day=.
- Bookings need a phone; a plain booking refuses items (order.items_not_allowed).
- Status steps for bookings: pending_acceptance → accepted | rejected; accepted → delivered
(arrived) | cancelled (by the venue); ordinary orders unchanged.
- Order app: "Book a table" (people, day, time, optional food at the pre-order prices),
booking summary at checkout, a booking tracking page (waiting, confirmed, welcome;
declined / cancelled with the reason). en/el.
- Tests: tests/test_reservations.py (3), order-app logic test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,3 +11,5 @@ export const quote = async (site, body) => (await api.post(`/api/orders/${encode
|
||||
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}`)
|
||||
/** One venue day's table booking times (S.6): {day, slots: [iso]}. */
|
||||
export const fetchBookingSlots = async (site, day) => (await api.get(`/api/orders/${encodeURIComponent(site)}/reservation-slots`, { params: { day } })).data
|
||||
|
||||
@@ -6,6 +6,13 @@ const STORE = 'xenia-order-lang'
|
||||
|
||||
export const TEXTS = {
|
||||
en: {
|
||||
service: 'How', bookTable: 'Book a table',
|
||||
book: {
|
||||
party: 'People', day: 'Day', time: 'Time', none: 'No tables can be booked online right now.', noTimes: 'No free times this day. Try another day.',
|
||||
food: 'Order food for when you arrive', foodHint: 'Pick dishes now: the kitchen prepares them for your arrival. You pay at the venue.',
|
||||
continue: 'Continue', title: 'Book a table', tableFor_one: 'Table for {{count}}', tableFor_other: 'Table for {{count}}',
|
||||
send: 'Request booking', note: 'The venue confirms your booking. You pay at the venue.', foodReady: 'Ready for when you arrive.',
|
||||
},
|
||||
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.',
|
||||
@@ -19,6 +26,7 @@ export const TEXTS = {
|
||||
placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back',
|
||||
payNote: 'You pay at the venue or on delivery.',
|
||||
problem: {
|
||||
party: 'Pick how many people.',
|
||||
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.',
|
||||
},
|
||||
@@ -28,9 +36,15 @@ export const TEXTS = {
|
||||
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.',
|
||||
party_invalid: 'We take online bookings for up to {{max}} people. Call us for larger groups.',
|
||||
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: {
|
||||
booking: {
|
||||
title: 'Booking {{ref}}', placed: 'Thank you! We got your booking request.',
|
||||
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', delivered: 'Welcome, you\'re here',
|
||||
rejected: 'The venue could not take this booking', cancelled: 'Cancelled by the venue',
|
||||
},
|
||||
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: {
|
||||
@@ -41,6 +55,13 @@ export const TEXTS = {
|
||||
},
|
||||
},
|
||||
el: {
|
||||
service: 'Τρόπος', bookTable: 'Κράτηση τραπεζιού',
|
||||
book: {
|
||||
party: 'Άτομα', day: 'Ημέρα', time: 'Ώρα', none: 'Δεν γίνονται online κρατήσεις αυτή τη στιγμή.', noTimes: 'Δεν υπάρχουν ελεύθερες ώρες αυτή τη μέρα. Δοκιμάστε άλλη.',
|
||||
food: 'Παραγγείλετε φαγητό για την άφιξή σας', foodHint: 'Διαλέξτε πιάτα τώρα: η κουζίνα τα ετοιμάζει για την ώρα που έρχεστε. Πληρώνετε στο κατάστημα.',
|
||||
continue: 'Συνέχεια', title: 'Κράτηση τραπεζιού', tableFor_one: 'Τραπέζι για {{count}}', tableFor_other: 'Τραπέζι για {{count}}',
|
||||
send: 'Αίτημα κράτησης', note: 'Το κατάστημα επιβεβαιώνει την κράτηση. Πληρώνετε στο κατάστημα.', foodReady: 'Έτοιμα για την άφιξή σας.',
|
||||
},
|
||||
takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα',
|
||||
closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.',
|
||||
loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.',
|
||||
@@ -54,6 +75,7 @@ export const TEXTS = {
|
||||
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
|
||||
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
|
||||
problem: {
|
||||
party: 'Επιλέξτε πόσα άτομα.',
|
||||
name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.',
|
||||
area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.',
|
||||
},
|
||||
@@ -63,9 +85,15 @@ export const TEXTS = {
|
||||
item_unavailable: 'Κάτι στην παραγγελία σας δεν είναι πλέον διαθέσιμο. Αφαιρέστε το.', option_unavailable: 'Ένα έξτρα που επιλέξατε δεν είναι πλέον διαθέσιμο.',
|
||||
service_unavailable: 'Αυτή η υπηρεσία δεν είναι διαθέσιμη τώρα.', closed: 'Είμαστε κλειστά τώρα. Επιλέξτε αργότερη ώρα.',
|
||||
time_invalid: 'Η ώρα αυτή δεν είναι πλέον διαθέσιμη. Επιλέξτε άλλη.', details_missing: 'Συμπληρώστε τα στοιχεία σας.',
|
||||
party_invalid: 'Online κρατήσεις έως {{max}} άτομα. Για μεγαλύτερες παρέες τηλεφωνήστε μας.',
|
||||
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.',
|
||||
},
|
||||
track: {
|
||||
booking: {
|
||||
title: 'Κράτηση {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε το αίτημα κράτησης.',
|
||||
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', delivered: 'Καλώς ήρθατε',
|
||||
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την κράτηση', cancelled: 'Ακυρώθηκε από το κατάστημα',
|
||||
},
|
||||
title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο',
|
||||
keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.',
|
||||
status: {
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
// 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' }
|
||||
// 'preorder': food ordered with a table booking, ready on arrival (S.6)
|
||||
export const POINT = { takeaway: 'online_takeaway', delivery: 'online_delivery', preorder: 'online_preorder' }
|
||||
export const BOOKING_TYPES = ['reservation', 'preorder']
|
||||
|
||||
const round2 = n => Math.round(n * 100) / 100
|
||||
|
||||
@@ -109,8 +111,38 @@ export function slotDays(slots, timeZone) {
|
||||
return out
|
||||
}
|
||||
|
||||
/** What a table booking still needs (S.6): field keys (empty = can send). */
|
||||
export function bookingProblems(form, booking, partyMax = 99) {
|
||||
const out = []
|
||||
if (!form.name.trim()) out.push('name')
|
||||
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
|
||||
if (!(booking.party >= 1 && booking.party <= partyMax)) out.push('party')
|
||||
if (!booking.when) out.push('when')
|
||||
return out
|
||||
}
|
||||
|
||||
/** The booking request (POST /api/orders/{site}): a table only, or with food (a preorder). */
|
||||
export function bookingBody(form, booking, lines, quote) {
|
||||
const food = lines.length > 0
|
||||
return {
|
||||
order_type: food ? 'preorder' : 'reservation',
|
||||
customer_name: form.name.trim(),
|
||||
customer_phone: form.phone.trim(),
|
||||
customer_notes: form.notes.trim() || null,
|
||||
party_size: booking.party,
|
||||
requested_for: booking.when,
|
||||
items: food ? itemsBody(lines) : [],
|
||||
total: food ? (quote?.total ?? undefined) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** The tracking page's steps for an order type, and how far it got. */
|
||||
export function trackSteps(orderType, status) {
|
||||
if (BOOKING_TYPES.includes(orderType)) {
|
||||
const steps = ['pending_acceptance', 'accepted', 'delivered']
|
||||
const over = ['rejected', 'cancelled'].includes(status)
|
||||
return { steps, at: over ? -1 : steps.indexOf(status), done: status === 'delivered' || over }
|
||||
}
|
||||
const steps = orderType === 'delivery'
|
||||
? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered']
|
||||
: ['pending_acceptance', 'accepted', 'preparing', 'ready', 'delivered']
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Booking a table (plan phase 3S, step S.6): how many people, which day, what time, and
|
||||
// (when the venue allows it) food ordered ahead to be ready on arrival. The days come with the
|
||||
// menu (ordering.reservations.days); the times of a day from the cloud, in venue time.
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Minus, Plus, Users } from 'lucide-react'
|
||||
import { fetchBookingSlots } from '../api'
|
||||
import { useT } from '../i18n'
|
||||
import { slotDays } from '../logic'
|
||||
|
||||
export default function BookingPicker({ site, res, timeZone, booking, setBooking }) {
|
||||
const { t, lang } = useT()
|
||||
const [slots, setSlots] = useState(null)
|
||||
const set = patch => setBooking(b => ({ ...b, ...patch }))
|
||||
const day = booking.day ?? res.days[0] ?? null
|
||||
|
||||
useEffect(() => {
|
||||
if (!day) return undefined
|
||||
let alive = true
|
||||
setSlots(null)
|
||||
fetchBookingSlots(site, day).then(d => alive && setSlots(d.slots)).catch(() => alive && setSlots([]))
|
||||
return () => { alive = false }
|
||||
}, [site, day])
|
||||
|
||||
const times = useMemo(() => slotDays(slots ?? [], timeZone)[0]?.times ?? [], [slots, timeZone])
|
||||
const today = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date())
|
||||
const dayLabel = iso => {
|
||||
const d = new Date(`${iso}T12:00:00Z`)
|
||||
const diff = Math.round((d - new Date(`${today}T12:00:00Z`)) / 86_400_000)
|
||||
if (diff === 0) return t('today')
|
||||
if (diff === 1) return t('tomorrow')
|
||||
return new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }).format(d)
|
||||
}
|
||||
const chip = on => `shrink-0 px-3.5 h-10 rounded-full text-sm font-semibold ${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`
|
||||
|
||||
if (!res.days.length) return <p className="p-3 rounded-control bg-warning-soft text-warning-ink text-sm" data-testid="no-booking">{t('book.none')}</p>
|
||||
|
||||
return (
|
||||
<div className="grid gap-3" data-testid="booking">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex-1 flex items-center gap-2 font-medium text-ink"><Users size={18} aria-hidden="true" />{t('book.party')}</span>
|
||||
<button type="button" aria-label="−" onClick={() => set({ party: Math.max(1, booking.party - 1) })}
|
||||
className="w-10 h-10 rounded-full bg-surface-2 flex items-center justify-center"><Minus size={16} /></button>
|
||||
<span className="w-8 text-center text-lg font-semibold" data-testid="party">{booking.party}</span>
|
||||
<button type="button" aria-label="+" onClick={() => set({ party: Math.min(res.party_max, booking.party + 1) })}
|
||||
className="w-10 h-10 rounded-full bg-accent text-accent-fg flex items-center justify-center"><Plus size={16} /></button>
|
||||
</div>
|
||||
<div className="flex gap-2 overflow-x-auto pb-1" role="radiogroup" aria-label={t('book.day')}>
|
||||
{res.days.map(d => (
|
||||
<button key={d} type="button" role="radio" aria-checked={d === day} className={chip(d === day)} data-testid="book-day" data-day={d}
|
||||
onClick={() => set({ day: d, when: null })}>{dayLabel(d)}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-4 gap-2" role="radiogroup" aria-label={t('book.time')} data-testid="book-times">
|
||||
{slots === null && <p className="col-span-4 text-sm text-ink-2" role="status">{t('loading')}</p>}
|
||||
{slots !== null && times.length === 0 && <p className="col-span-4 text-sm text-ink-2">{t('book.noTimes')}</p>}
|
||||
{times.map(s => (
|
||||
<button key={s.iso} type="button" role="radio" aria-checked={booking.when === s.iso} data-testid="book-time"
|
||||
onClick={() => set({ day, when: s.iso })}
|
||||
className={`h-10 rounded-control text-sm font-semibold ${booking.when === s.iso ? 'bg-accent text-accent-fg' : 'bg-surface border border-line text-ink'}`}>{s.label}</button>
|
||||
))}
|
||||
</div>
|
||||
{res.with_food && (
|
||||
<label className="flex items-start gap-3 p-3 rounded-control bg-surface-2 cursor-pointer">
|
||||
<input type="checkbox" checked={booking.food} onChange={e => set({ food: e.target.checked })} data-testid="book-food"
|
||||
className="mt-0.5 w-5 h-5 accent-[rgb(var(--o-accent))]" />
|
||||
<span className="grid gap-0.5">
|
||||
<span className="font-semibold text-ink">{t('book.food')}</span>
|
||||
<span className="text-sm text-ink-2">{t('book.foodHint')}</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,11 +2,13 @@
|
||||
// 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.
|
||||
// S.6: service 'book' = a table booking (`booking` {party, when}), with food ordered ahead
|
||||
// when there are lines (priced as a pre-order); no address, no time picker here.
|
||||
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'
|
||||
import { bookingBody, bookingProblems, checkoutProblems, itemsBody, orderBody, refusal, setQty, slotDays } from '../logic'
|
||||
|
||||
const QUOTE_DELAY = 250
|
||||
const SLOTS_EVERY = 60_000
|
||||
@@ -16,8 +18,10 @@ 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()
|
||||
export default function Checkout({ site, service, booking, menu, lines, setCart, onBack, onPlaced }) {
|
||||
const { t, money, lang } = useT()
|
||||
const book = service === 'book'
|
||||
const quoteType = book ? 'preorder' : service
|
||||
const areas = menu.delivery_areas ?? []
|
||||
const [form, setForm] = useState(() => ({
|
||||
name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(),
|
||||
@@ -40,8 +44,8 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
return () => { alive = false; clearInterval(id) }
|
||||
}, [site])
|
||||
useEffect(() => {
|
||||
if (form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0])
|
||||
}, [slots, form.when])
|
||||
if (!book && form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0])
|
||||
}, [slots, form.when, book])
|
||||
|
||||
// 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,
|
||||
@@ -53,7 +57,7 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
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 })
|
||||
const q = await quote(site, { order_type: quoteType, 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 })
|
||||
@@ -63,9 +67,15 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
}, [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 problems = book
|
||||
? bookingProblems(form, booking, menu.ordering?.reservations?.party_max)
|
||||
: checkoutProblems(form, service, { areas, asap: !!slots.asap, slots: slots.slots ?? [] })
|
||||
const q = priced.quote
|
||||
const canSend = q && !priced.pending && !priced.problem && !sending
|
||||
const canSend = book && !lines.length ? !sending : (q && !priced.pending && !priced.problem && !sending)
|
||||
const tz = menu.ordering?.timezone || 'Europe/Athens'
|
||||
const bookedFor = book && booking.when
|
||||
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: tz }).format(new Date(booking.when))
|
||||
: null
|
||||
|
||||
const submit = async () => {
|
||||
setTried(true)
|
||||
@@ -73,7 +83,7 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
if (problems.length || !canSend) return
|
||||
setSending(true)
|
||||
try {
|
||||
const body = orderBody(form, service, lines, q)
|
||||
const body = book ? bookingBody(form, booking, lines, q) : 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)
|
||||
@@ -93,11 +103,18 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
<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>
|
||||
<h1 className="font-display text-xl font-semibold">{book ? t('book.title') : `${t('yourOrder')} · ${t(service)}`}</h1>
|
||||
</header>
|
||||
|
||||
{book && (
|
||||
<section className="mx-4 mt-4 p-4 rounded-card bg-accent-soft text-accent-ink grid gap-0.5" data-testid="booking-summary">
|
||||
<p className="font-semibold">{t('book.tableFor', { count: booking.party })}</p>
|
||||
<p>{bookedFor}</p>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="p-4 grid gap-2" aria-label={t('yourOrder')}>
|
||||
{lines.length === 0 && <p className="text-ink-2">{t('empty')}</p>}
|
||||
{lines.length === 0 && !book && <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 (
|
||||
@@ -157,7 +174,7 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
<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')}>
|
||||
{!book && <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>}
|
||||
@@ -167,10 +184,10 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</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"
|
||||
{(!book || lines.length > 0) && <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>}
|
||||
@@ -181,15 +198,15 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
|
||||
<Row label={t('total')} value={money(q.total)} strong />
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</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"
|
||||
<button type="button" onClick={submit} disabled={sending || (!book && !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) : '…' })}
|
||||
{sending ? t('sending') : book ? t('book.send') : t('placeOrder', { total: q ? money(q.total) : '…' })}
|
||||
</button>
|
||||
<p className="text-sm text-ink-2 text-center">{t('payNote')}</p>
|
||||
<p className="text-sm text-ink-2 text-center">{book ? t('book.note') : t('payNote')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
// 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.
|
||||
// S.6: "Book a table" (when the venue takes bookings): party, day, time, and maybe food ordered
|
||||
// ahead at the pre-order prices; the details and the request on the next screen.
|
||||
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 { Bike, CalendarDays, 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 BookingPicker from './BookingPicker'
|
||||
import Checkout from './Checkout'
|
||||
|
||||
const CART_KEY = site => `xenia-order-cart:${site}`
|
||||
@@ -25,13 +28,14 @@ export default function OrderPage() {
|
||||
const [picking, setPicking] = useState(null) // a product whose extras are being chosen
|
||||
const [checkout, setCheckout] = useState(false)
|
||||
const [category, setCategory] = useState(null)
|
||||
const [booking, setBooking] = useState({ party: 2, day: null, when: null, food: false })
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(null)
|
||||
try {
|
||||
const data = await fetchMenu(site)
|
||||
setMenu(data)
|
||||
setService(s => s ?? data.ordering?.services?.[0] ?? null)
|
||||
setService(s => s ?? data.ordering?.services?.[0] ?? (data.ordering?.reservations?.enabled ? 'book' : null))
|
||||
} catch (err) {
|
||||
setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed')
|
||||
}
|
||||
@@ -41,9 +45,12 @@ export default function OrderPage() {
|
||||
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 book = service === 'book'
|
||||
// the prices: the service's; a booking's food at the pre-order prices (only when food is on)
|
||||
const priceService = book ? (booking.food ? 'preorder' : null) : service
|
||||
const sections = useMemo(() => (menu && priceService ? menuFor(menu.categories, priceService) : []), [menu, priceService])
|
||||
const products = useMemo(() => sections.flatMap(c => c.products), [sections])
|
||||
const lines = useMemo(() => (service ? cartLines(cart, products, service) : []), [cart, products, service])
|
||||
const lines = useMemo(() => (priceService ? cartLines(cart, products, priceService) : []), [cart, products, priceService])
|
||||
const count = cartCount(lines)
|
||||
const subtotal = lines.reduce((s, l) => s + l.total, 0)
|
||||
|
||||
@@ -60,13 +67,16 @@ export default function OrderPage() {
|
||||
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 res = ordering.reservations ?? { enabled: false, days: [] }
|
||||
const offered = [...SERVICES.filter(s => ordering.services.includes(s)), ...(res.enabled ? ['book'] : [])]
|
||||
const ICON = { delivery: Bike, takeaway: Store, book: CalendarDays }
|
||||
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}
|
||||
<Checkout site={site} service={book ? 'book' : service} booking={book ? booking : null} menu={menu} lines={lines} setCart={setCart}
|
||||
onBack={() => setCheckout(false)}
|
||||
onPlaced={(result) => {
|
||||
// cleared here too: the page unmounts before its storage effect would run
|
||||
@@ -95,26 +105,31 @@ export default function OrderPage() {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{ordering.services.length === 0 ? (
|
||||
{offered.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
|
||||
<div className={`grid gap-2 ${offered.length === 3 ? 'grid-cols-3' : offered.length === 2 ? 'grid-cols-2' : 'grid-cols-1'}`} role="radiogroup" aria-label={t('service')}>
|
||||
{offered.map(s => {
|
||||
const Icon = ICON[s]
|
||||
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
|
||||
${offered.length === 3 ? 'gap-1.5 px-1.5 text-sm leading-tight' : ''}
|
||||
${service === s ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
|
||||
<Icon size={18} aria-hidden="true" />{t(s)}
|
||||
<Icon size={18} aria-hidden="true" />{t(s === 'book' ? 'bookTable' : 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>
|
||||
{book ? (
|
||||
<BookingPicker site={site} res={res} timeZone={ordering.timezone || 'Europe/Athens'} booking={booking} setBooking={setBooking} />
|
||||
) : (
|
||||
<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>
|
||||
@@ -145,7 +160,18 @@ export default function OrderPage() {
|
||||
))}
|
||||
</main>
|
||||
|
||||
{count > 0 && service && (
|
||||
{book && booking.when && (
|
||||
<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="book-continue"
|
||||
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">
|
||||
<CalendarDays size={20} aria-hidden="true" />
|
||||
<span className="flex-1 text-left">{t('book.continue')}{count > 0 ? ` · ${t('items', { count })}` : ''}</span>
|
||||
{count > 0 && <span>{money(subtotal)}</span>}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!book && 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">
|
||||
|
||||
@@ -6,7 +6,7 @@ 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'
|
||||
import { BOOKING_TYPES, trackSteps } from '../logic'
|
||||
|
||||
const POLL_MS = 8000
|
||||
|
||||
@@ -40,27 +40,34 @@ export default function TrackPage() {
|
||||
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 rejected = order.status === 'rejected' || order.status === 'cancelled'
|
||||
const booked = BOOKING_TYPES.includes(order.order_type) // a table booking (S.6)
|
||||
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))
|
||||
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', booked
|
||||
? { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit', hour12: false }
|
||||
: { weekday: 'long', hour: '2-digit', minute: '2-digit' }).format(new Date(order.requested_for))
|
||||
: null
|
||||
const st = s => t(booked ? `track.booking.${s}` : `track.status.${s}`)
|
||||
|
||||
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>}
|
||||
{placed && <p className="p-3 rounded-control bg-success-soft text-success-ink font-medium">{t(booked ? 'track.booking.placed' : '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>
|
||||
<h1 className="font-display text-2xl font-semibold" data-testid="track-ref">{t(booked ? 'track.booking.title' : 'track.title', { ref: order.public_ref })}</h1>
|
||||
<p className="text-ink-2">
|
||||
{booked ? `${t('book.tableFor', { count: order.party_size ?? 1 })} · ${when}`
|
||||
: `${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>
|
||||
<p className="font-semibold flex items-center gap-2"><X size={18} aria-hidden="true" />{booked ? st(order.status) : 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)}>
|
||||
<ol className="grid gap-0" aria-label={st(order.status)}>
|
||||
{steps.map((s, i) => {
|
||||
const done = i < at || order.status === 'delivered'
|
||||
const now = i === at && order.status !== 'delivered'
|
||||
@@ -70,14 +77,14 @@ export default function TrackPage() {
|
||||
${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>
|
||||
<span className={done || now ? 'text-ink font-medium' : 'text-ink-3'}>{st(s)}</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
<section className="p-4 rounded-card bg-surface border border-line grid gap-1.5">
|
||||
{(!booked || (order.lines ?? []).length > 0) && <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>
|
||||
@@ -86,7 +93,8 @@ export default function TrackPage() {
|
||||
))}
|
||||
{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>
|
||||
{booked && <p className="text-sm text-ink-2">{t('book.foodReady')}</p>}
|
||||
</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>
|
||||
|
||||
@@ -61,3 +61,23 @@ test('slots by day in the venue time zone, tracking steps, refusals', () => {
|
||||
assert.deepEqual(refusal({ response: { status: 429, data: {} } }), ['rate', {}])
|
||||
assert.deepEqual(refusal(new Error('x')), ['failed', {}])
|
||||
})
|
||||
|
||||
test('booking a table, with or without food (S.6)', async () => {
|
||||
const { bookingBody, bookingProblems } = await import('../src/logic.js')
|
||||
const form = { name: 'Eleni', phone: '6977777777', notes: '' }
|
||||
const booking = { party: 4, when: '2026-11-16T18:00:00+00:00' }
|
||||
assert.deepEqual(bookingProblems(form, booking, 8), [])
|
||||
assert.deepEqual(bookingProblems({ ...form, name: ' ' }, { party: 9, when: null }, 8), ['name', 'party', 'when'])
|
||||
assert.deepEqual(bookingBody(form, booking, [], null), {
|
||||
order_type: 'reservation', customer_name: 'Eleni', customer_phone: '6977777777', customer_notes: null,
|
||||
party_size: 4, requested_for: booking.when, items: [], total: undefined,
|
||||
})
|
||||
const food = bookingBody(form, booking, [{ productId: 1, qty: 2, options: [], unit: 2.6 }], { total: 5.2 })
|
||||
assert.equal(food.order_type, 'preorder')
|
||||
assert.deepEqual(food.items, [{ product_id: 1, quantity: 2, options: [], unit_price: 2.6 }])
|
||||
assert.equal(food.total, 5.2)
|
||||
assert.deepEqual(trackSteps('reservation', 'accepted'), { steps: ['pending_acceptance', 'accepted', 'delivered'], at: 1, done: false })
|
||||
assert.equal(trackSteps('preorder', 'cancelled').done, true)
|
||||
assert.equal(trackSteps('preorder', 'cancelled').at, -1)
|
||||
assert.equal(priceFor({ sold_at: ['online_preorder'], prices: { online_preorder: 2.6 } }, 'preorder'), 2.6)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user