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:
2026-11-15 19:31:21 +02:00
co-authored by Claude Opus 5.5
parent 9ccb47cfd1
commit 3459c80611
14 changed files with 527 additions and 69 deletions
@@ -0,0 +1,24 @@
"""online orders: party_size (reservations online, plan phase 3S, S.6)
Revision ID: 0005_order_party_size
Revises: 0004_order_area_id
Create Date: 2026-11-16 21:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0005_order_party_size'
down_revision = '0004_order_area_id'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('party_size', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('party_size')
+4 -1
View File
@@ -17,7 +17,7 @@ class OnlineOrder(Base):
public_ref = Column(String, nullable=False) public_ref = Column(String, nullable=False)
# the customer's tracking page: random, unguessable (S.2; the ref alone was ambiguous across sites) # the customer's tracking page: random, unguessable (S.2; the ref alone was ambiguous across sites)
tracking_token = Column(String, nullable=True) tracking_token = Column(String, nullable=True)
order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | preorder order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | reservation | preorder (S.6)
# Customer info # Customer info
customer_name = Column(String, nullable=False) customer_name = Column(String, nullable=False)
@@ -28,6 +28,7 @@ class OnlineOrder(Base):
delivery_area = Column(String, nullable=True) # the delivery area's name (S.3) delivery_area = Column(String, nullable=True) # the delivery area's name (S.3)
delivery_area_id = Column(Integer, nullable=True) # the site's area id (S.5: the site checks the fee) delivery_area_id = Column(Integer, nullable=True) # the site's area id (S.5: the site checks the fee)
requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap
party_size = Column(Integer, nullable=True) # reservations (S.6): how many guests
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2) sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
# Order content — JSON array of ordered items # Order content — JSON array of ordered items
@@ -41,6 +42,8 @@ class OnlineOrder(Base):
# Status lifecycle: # Status lifecycle:
# pending_acceptance → accepted | rejected # pending_acceptance → accepted | rejected
# accepted → preparing → ready | out_for_delivery → delivered # accepted → preparing → ready | out_for_delivery → delivered
# reservations (S.6): pending_acceptance → accepted (confirmed) | rejected;
# accepted → delivered (the guests arrived) | cancelled (by the venue)
status = Column(String, default="pending_acceptance", nullable=False, index=True) status = Column(String, default="pending_acceptance", nullable=False, index=True)
rejection_reason = Column(String, nullable=True) rejection_reason = Column(String, nullable=True)
+53 -20
View File
@@ -1,6 +1,6 @@
import json import json
import secrets import secrets
from datetime import timezone from datetime import date, timezone
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
from passlib.context import CryptContext from passlib.context import CryptContext
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -38,6 +38,15 @@ _TRANSITIONS: dict[str, set[str]] = {
"ready": {"delivered"}, "ready": {"delivered"},
"out_for_delivery": {"delivered"}, "out_for_delivery": {"delivered"},
} }
# reservations (S.6): confirmed or declined; then the guests arrive, or the venue cancels
_RES_TRANSITIONS: dict[str, set[str]] = {
"pending_acceptance": {"accepted", "rejected"},
"accepted": {"delivered", "cancelled"},
}
def _transitions(order_type: str) -> dict[str, set[str]]:
return _RES_TRANSITIONS if order_type in ordering.RES_TYPES else _TRANSITIONS
def _require_site( def _require_site(
@@ -77,6 +86,17 @@ def order_slots(site_slug: str, db: Session = Depends(get_db)):
return ordering.summary(menu) return ordering.summary(menu)
@router.get("/{site_slug}/reservation-slots")
def reservation_slots(site_slug: str, day: str, db: Session = Depends(get_db)):
"""The reservation times of one venue day (S.6): ?day=YYYY-MM-DD → {day, slots: [iso]}."""
_site, menu = _site_and_menu(db, site_slug)
try:
wanted = date.fromisoformat(day)
except ValueError:
raise HTTPException(status_code=422, detail={"code": "order.time_invalid", "params": {}})
return {"day": wanted.isoformat(), "slots": [t.isoformat() for t in ordering.res_slots(menu, wanted)]}
@router.post("/{site_slug}/quote") @router.post("/{site_slug}/quote")
def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Session = Depends(get_db)): def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Session = Depends(get_db)):
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S).""" """The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
@@ -94,17 +114,28 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db:
_limit(request, "order", ORDER_LIMIT) _limit(request, "order", ORDER_LIMIT)
site, menu = _site_and_menu(db, site_slug) site, menu = _site_and_menu(db, site_slug)
items = [i.model_dump() for i in body.items] items = [i.model_dump() for i in body.items]
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode) reservation = body.order_type in ordering.RES_TYPES # S.6: a table, maybe with food
if body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4) if body.order_type == "reservation":
if items:
raise HTTPException(status_code=422, detail={"code": "order.items_not_allowed", "params": {}})
priced = None
else:
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode)
if reservation:
problem = ordering.res_check(menu, body.order_type, body.requested_for, body.party_size)
elif body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
problem = ordering.check(menu, body.order_type, body.requested_for) problem = ordering.check(menu, body.order_type, body.requested_for)
if problem: else:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]}) problem = None
if not (body.customer_phone or "").strip(): if problem:
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}}) raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
try: if (reservation or body.order_type in ("takeaway", "delivery")) and not (body.customer_phone or "").strip():
check_sent(priced, items, body.total) raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
except CheckoutError as e: if priced is not None:
raise HTTPException(status_code=e.status, detail=e.detail()) try:
check_sent(priced, items, body.total)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
if body.order_type == "delivery" and not ((body.customer_address or "").strip() and (body.customer_phone or "").strip()): if body.order_type == "delivery" and not ((body.customer_address or "").strip() and (body.customer_phone or "").strip()):
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone", "customer_address"]}}) raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone", "customer_address"]}})
@@ -121,16 +152,17 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db:
customer_address=body.customer_address, customer_address=body.customer_address,
customer_notes=body.customer_notes, customer_notes=body.customer_notes,
table_label=(body.customer_table or "").strip() or None, table_label=(body.customer_table or "").strip() or None,
delivery_area=priced.area_name, delivery_area=priced.area_name if priced else None,
delivery_area_id=priced.area_id, delivery_area_id=priced.area_id if priced else None,
# stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it) # stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it)
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None) requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
if body.order_type in ("takeaway", "delivery") and body.requested_for else None), if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None),
sales_point=priced.sales_point, party_size=body.party_size if reservation else None,
items_json=json.dumps([line.out() for line in priced.lines]), sales_point=priced.sales_point if priced else None,
subtotal=priced.subtotal, items_json=json.dumps([line.out() for line in priced.lines] if priced else []),
delivery_fee=priced.delivery_fee, subtotal=priced.subtotal if priced else 0.0,
total=priced.total, delivery_fee=priced.delivery_fee if priced else 0.0,
total=priced.total if priced else 0.0,
status="pending_acceptance", status="pending_acceptance",
) )
order.tracking_token = secrets.token_urlsafe(12) order.tracking_token = secrets.token_urlsafe(12)
@@ -155,6 +187,7 @@ def track_order(token: str, request: Request, db: Session = Depends(get_db)):
lines = [] lines = []
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason, return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason,
order_type=order.order_type, requested_for=order.requested_for, created_at=order.created_at, order_type=order.order_type, requested_for=order.requested_for, created_at=order.created_at,
party_size=order.party_size,
lines=[{"name": x.get("name"), "quantity": x.get("quantity"), "unit_price": x.get("unit_price"), lines=[{"name": x.get("name"), "quantity": x.get("quantity"), "unit_price": x.get("unit_price"),
"options": [o.get("name") for o in x.get("options") or []]} for x in lines], "options": [o.get("name") for o in x.get("options") or []]} for x in lines],
subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total) subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total)
@@ -224,7 +257,7 @@ def update_order_status(
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise HTTPException(status_code=404, detail="Order not found")
allowed = _TRANSITIONS.get(order.status, set()) allowed = _transitions(order.order_type).get(order.status, set())
if body.status not in allowed: if body.status not in allowed:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+5 -2
View File
@@ -31,8 +31,9 @@ class QuoteRequest(BaseModel):
class OnlineOrderCreate(BaseModel): class OnlineOrderCreate(BaseModel):
order_type: str # dine_in | takeaway | delivery | preorder order_type: str # dine_in | takeaway | delivery | reservation | preorder
customer_name: str = Field(min_length=1, max_length=100) customer_name: str = Field(min_length=1, max_length=100)
party_size: Optional[int] = None # reservations (S.6)
customer_phone: Optional[str] = Field(default=None, max_length=40) customer_phone: Optional[str] = Field(default=None, max_length=40)
customer_address: Optional[str] = Field(default=None, max_length=500) customer_address: Optional[str] = Field(default=None, max_length=500)
customer_notes: Optional[str] = Field(default=None, max_length=1000) customer_notes: Optional[str] = Field(default=None, max_length=1000)
@@ -40,7 +41,7 @@ class OnlineOrderCreate(BaseModel):
area_id: Optional[int] = None # the delivery area picked (S.3) area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20) postcode: Optional[str] = Field(default=None, max_length=20)
requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible
items: list[OrderItemIn] = Field(max_length=100) items: list[OrderItemIn] = Field(default_factory=list, max_length=100)
# what the customer was shown: compared, never stored as sent # what the customer was shown: compared, never stored as sent
subtotal: Optional[float] = None subtotal: Optional[float] = None
delivery_fee: Optional[float] = None delivery_fee: Optional[float] = None
@@ -62,6 +63,7 @@ class OrderStatusOut(BaseModel):
# S.4: what the tracking page shows (all optional: older clients ignore them) # S.4: what the tracking page shows (all optional: older clients ignore them)
order_type: Optional[str] = None order_type: Optional[str] = None
requested_for: Optional[datetime] = None requested_for: Optional[datetime] = None
party_size: Optional[int] = None # reservations (S.6)
created_at: Optional[datetime] = None created_at: Optional[datetime] = None
lines: Optional[list] = None lines: Optional[list] = None
subtotal: Optional[float] = None subtotal: Optional[float] = None
@@ -85,6 +87,7 @@ class PendingOrderOut(BaseModel):
delivery_area: Optional[str] = None # the delivery area's name (S.3) delivery_area: Optional[str] = None # the delivery area's name (S.3)
delivery_area_id: Optional[int] = None # the site's area id (S.5) delivery_area_id: Optional[int] = None # the site's area id (S.5)
requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible
party_size: Optional[int] = None # reservations (S.6)
sales_point: Optional[str] = None # the site's sales point (S.2) sales_point: Optional[str] = None # the site's sales point (S.2)
items_json: str items_json: str
subtotal: float subtotal: float
+75 -1
View File
@@ -89,7 +89,8 @@ def summary(snapshot: dict, now: datetime | None = None) -> dict:
open_now = is_open(cfg, local_now) open_now = is_open(cfg, local_now)
return {"services": cfg["services"], "open_now": open_now, "asap": bool(cfg["asap"]) and open_now, return {"services": cfg["services"], "open_now": open_now, "asap": bool(cfg["asap"]) and open_now,
"prep_minutes": cfg["prep_minutes"], "timezone": tz.key, "prep_minutes": cfg["prep_minutes"], "timezone": tz.key,
"slots": [t.isoformat() for t in slots(snapshot, now)]} "slots": [t.isoformat() for t in slots(snapshot, now)],
"reservations": res_summary(snapshot, now)} # S.6
def check(snapshot: dict, service: str, requested_for: datetime | None, now: datetime | None = None): def check(snapshot: dict, service: str, requested_for: datetime | None, now: datetime | None = None):
@@ -109,3 +110,76 @@ def check(snapshot: dict, service: str, requested_for: datetime | None, now: dat
if any(abs((wanted - t).total_seconds()) < 1 for t in slots(snapshot, now)): if any(abs((wanted - t).total_seconds()) < 1 for t in slots(snapshot, now)):
return None return None
return "order.time_invalid", {} return "order.time_invalid", {}
# ── Reservations online (plan phase 3S, step S.6) ─────────────────────────────
# The snapshot's `ordering.reservations` (site routers/fees.py ReservationsBody):
# {enabled, with_food, hours: {"0".."6": [[from, to], ...]}, slot_minutes, days_ahead,
# notice_minutes, party_max, fire_minutes}
# "reservation" = a table only; "preorder" = a table with food ready on arrival (with_food).
# Times: on the slot grid of the venue's day, at least notice_minutes from now, within today +
# days_ahead, inside the hours (none = any time). fire_minutes is the site's (the kitchen).
RES_DEFAULTS = {"enabled": False, "with_food": False, "hours": {}, "slot_minutes": 30, "days_ahead": 30,
"notice_minutes": 60, "party_max": 10}
RES_TYPES = ("reservation", "preorder")
def res_config(snapshot: dict) -> dict:
cfg = {**RES_DEFAULTS, **((snapshot.get("ordering") or {}).get("reservations") or {})}
cfg["enabled"] = bool(cfg.get("enabled"))
cfg["with_food"] = cfg["enabled"] and bool(cfg.get("with_food"))
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 30))
cfg["days_ahead"] = max(0, min(90, int(cfg.get("days_ahead") or 0)))
cfg["notice_minutes"] = max(0, int(cfg.get("notice_minutes") or 0))
cfg["party_max"] = max(1, min(100, int(cfg.get("party_max") or 1)))
return cfg
def res_slots(snapshot: dict, day, now: datetime | None = None) -> list[datetime]:
"""The reservation times on one venue day (a date), aware venue local, in order."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
if day < local_now.date() or day > (local_now + timedelta(days=cfg["days_ahead"])).date():
return []
earliest = local_now + timedelta(minutes=cfg["notice_minutes"])
t = datetime(day.year, day.month, day.day, tzinfo=tz)
out = []
while t.date() == day:
if t >= earliest and is_open(cfg, t):
out.append(t)
t = (t.astimezone(timezone.utc) + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
return out
def res_days(snapshot: dict, now: datetime | None = None) -> list[str]:
"""The venue days (ISO dates) with at least one reservation time."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
today = (now or datetime.now(timezone.utc)).astimezone(tz).date()
days = (today + timedelta(days=n) for n in range(cfg["days_ahead"] + 1))
return [d.isoformat() for d in days if res_slots(snapshot, d, now)]
def res_summary(snapshot: dict, now: datetime | None = None) -> dict:
cfg = res_config(snapshot)
return {"enabled": cfg["enabled"], "with_food": cfg["with_food"], "party_max": cfg["party_max"],
"days": res_days(snapshot, now)}
def res_check(snapshot: dict, order_type: str, requested_for: datetime | None, party_size, now: datetime | None = None):
"""None if the reservation may be requested, else (code, params)."""
cfg = res_config(snapshot)
if not cfg["enabled"] or (order_type == "preorder" and not cfg["with_food"]):
return "order.service_unavailable", {"service": order_type}
if isinstance(party_size, bool) or not isinstance(party_size, int) or not 1 <= party_size <= cfg["party_max"]:
return "order.party_invalid", {"max": cfg["party_max"]}
if requested_for is None or requested_for.tzinfo is None:
return "order.time_invalid", {}
wanted = requested_for.astimezone(venue_tz(snapshot))
if any(abs((wanted - t).total_seconds()) < 1 for t in res_slots(snapshot, wanted.date(), now)):
return None
return "order.time_invalid", {}
+114
View File
@@ -0,0 +1,114 @@
"""Reservations online (plan phase 3S, step S.6): a table only, or a table with food ready on
arrival; times on the venue's grid, inside its hours, with notice, up to N days ahead; party
size; the venue confirms or declines, then the guests arrive or the venue cancels."""
import json
from datetime import date, datetime, timezone
from zoneinfo import ZoneInfo
from services import ordering
from test_checkout import COLA, ORDERING, _code, _h, _venue
ATH = ZoneInfo("Europe/Athens")
DINNER = {"0": [["19:00", "23:00"]], "6": [["13:00", "16:00"], ["19:00", "23:00"]]} # Mon, Sun
def snap(**res):
return {"timezone": "Europe/Athens", "ordering": {**ORDERING, "reservations": {
"enabled": True, "with_food": True, "hours": DINNER, "slot_minutes": 30, "days_ahead": 14,
"notice_minutes": 120, "party_max": 8, **res}}}
def at(y, mo, d, h, mi):
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
def test_times_days_and_checks():
s, now = snap(), at(2026, 11, 15, 18, 10) # Sunday 18:10
sunday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 15), now)]
assert sunday == ["20:30", "21:00", "21:30", "22:00", "22:30"] # 2 h notice; lunch is over
monday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 16), now)]
assert monday[0] == "19:00" and monday[-1] == "22:30"
assert ordering.res_slots(s, date(2026, 11, 17), now) == [] # Tuesday: no hours = closed
assert ordering.res_slots(s, date(2026, 11, 30), now) == [] # beyond 14 days
days = ordering.res_days(s, now)
assert days[:3] == ["2026-11-15", "2026-11-16", "2026-11-22"] and "2026-11-17" not in days
ok = at(2026, 11, 16, 20, 0)
assert ordering.res_check(s, "reservation", ok, 4, now) is None
assert ordering.res_check(s, "preorder", ok, 4, now) is None
assert ordering.res_check(s, "reservation", ok, 9, now) == ("order.party_invalid", {"max": 8})
assert ordering.res_check(s, "reservation", ok, 0, now)[0] == "order.party_invalid"
assert ordering.res_check(s, "reservation", ok, None, now)[0] == "order.party_invalid"
assert ordering.res_check(s, "reservation", at(2026, 11, 16, 20, 10), 2, now)[0] == "order.time_invalid" # off grid
assert ordering.res_check(s, "reservation", at(2026, 11, 15, 19, 0), 2, now)[0] == "order.time_invalid" # too soon
assert ordering.res_check(s, "reservation", None, 2, now)[0] == "order.time_invalid"
assert ordering.res_check(snap(with_food=False), "preorder", ok, 2, now) == ("order.service_unavailable", {"service": "preorder"})
assert ordering.res_check(snap(enabled=False), "reservation", ok, 2, now)[0] == "order.service_unavailable"
assert ordering.res_summary(snap(enabled=False), now) == {"enabled": False, "with_food": False, "party_max": 8, "days": []}
def _push(client, site, numeric, **res):
menu = client.get(f"/api/menu/{site['site_id']}").json()
hours = {str(d): [["00:00", "23:59"]] for d in range(7)}
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
"ordering": {**ORDERING, "reservations": {"enabled": True, "with_food": True, "hours": hours, "slot_minutes": 30,
"days_ahead": 3, "notice_minutes": 0, "party_max": 6, **res}}}
for cat in snapshot["categories"]:
for p in cat["products"]:
if p["id"] == COLA:
p["sold_at"] = [*p["sold_at"], "online_preorder"]
p["prices"] = {**p["prices"], "online_preorder": 2.6}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
assert r.status_code in (200, 204), r.text
def test_book_a_table_with_and_without_food(client, admin_h):
site, numeric = _venue(client, admin_h)
_push(client, site, numeric)
menu = client.get(f"/api/menu/{site['site_id']}").json()
res = menu["ordering"]["reservations"]
assert res["enabled"] and res["with_food"] and res["party_max"] == 6 and len(res["days"]) == 4
day = res["days"][1]
slots = client.get(f"/api/orders/{site['site_id']}/reservation-slots", params={"day": day}).json()["slots"]
assert len(slots) == 48
when = slots[40] # 20:00 tomorrow
book = lambda **x: client.post(f"/api/orders/{site['site_id']}", json={ # noqa: E731
"order_type": "reservation", "customer_name": "Eleni", "customer_phone": "6977777777", "party_size": 4,
"requested_for": when, "customer_notes": "By the window", **x})
plain = book()
assert plain.status_code == 201, plain.text
assert _code(book(party_size=7)) == "order.party_invalid"
assert _code(book(customer_phone="")) == "order.details_missing"
assert _code(book(items=[{"product_id": COLA, "quantity": 1}])) == "order.items_not_allowed"
assert _code(book(requested_for=None)) == "order.time_invalid"
food = book(order_type="preorder", items=[{"product_id": COLA, "quantity": 2}], total=5.2)
assert food.status_code == 201, food.text
assert food.json()["total"] == 5.2 # the preorder price
assert _code(book(order_type="preorder", items=[])) == "order.empty"
pending = {o["public_ref"]: o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()}
p = pending[plain.json()["public_ref"]]
assert (p["order_type"], p["party_size"], p["total"], json.loads(p["items_json"]), p["sales_point"]) == ("reservation", 4, 0.0, [], None)
assert datetime.fromisoformat(p["requested_for"].replace("Z", "+00:00")) == datetime.fromisoformat(when)
f = pending[food.json()["public_ref"]]
assert (f["order_type"], f["sales_point"], f["party_size"]) == ("preorder", "online_preorder", 4)
# the venue confirms, then the guests arrive (or it cancels); the customer's page follows
st = lambda oid, s: client.patch(f"/api/orders/{oid}/status", headers=_h(site), json={"status": s}) # noqa: E731
assert st(p["id"], "preparing").status_code == 422
assert st(p["id"], "accepted").status_code == 204
assert st(p["id"], "delivered").status_code == 204
assert st(f["id"], "accepted").status_code == 204 and st(f["id"], "cancelled").status_code == 204
track = client.get(f"/api/orders/track/{food.json()['tracking_token']}").json()
assert (track["status"], track["order_type"], track["party_size"], track["total"]) == ("cancelled", "preorder", 4, 5.2)
# an ordinary order can't be "cancelled" this way
order = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "takeaway", "customer_name": "M",
"customer_phone": "6900000000", "items": [{"product_id": COLA, "quantity": 1}]})
oid = next(o["id"] for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == order.json()["public_ref"])
st(oid, "accepted")
assert st(oid, "cancelled").status_code == 422
def test_reservations_off_by_default(client, admin_h):
site, _ = _venue(client, admin_h)
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["reservations"]["enabled"] is False
r = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "reservation", "customer_name": "E", "customer_phone": "690000000",
"party_size": 2, "requested_for": datetime.now(timezone.utc).isoformat()})
assert _code(r) == "order.service_unavailable"
+2
View File
@@ -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 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 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}`) 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
+28
View File
@@ -6,6 +6,13 @@ const STORE = 'xenia-order-lang'
export const TEXTS = { export const TEXTS = {
en: { 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', 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.', 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.', 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', placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back',
payNote: 'You pay at the venue or on delivery.', payNote: 'You pay at the venue or on delivery.',
problem: { problem: {
party: 'Pick how many people.',
name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.', 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.', 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.', 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.', 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.', 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.', 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: { 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', 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.', keep: 'Keep this page open, or save its address, to follow your order.',
status: { status: {
@@ -41,6 +55,13 @@ export const TEXTS = {
}, },
}, },
el: { 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: 'Κλειστά τώρα', takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα',
closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.', closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.',
loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.', loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.',
@@ -54,6 +75,7 @@ export const TEXTS = {
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω', placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.', payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
problem: { problem: {
party: 'Επιλέξτε πόσα άτομα.',
name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.', name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.',
area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.', area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.',
}, },
@@ -63,9 +85,15 @@ export const TEXTS = {
item_unavailable: 'Κάτι στην παραγγελία σας δεν είναι πλέον διαθέσιμο. Αφαιρέστε το.', option_unavailable: 'Ένα έξτρα που επιλέξατε δεν είναι πλέον διαθέσιμο.', item_unavailable: 'Κάτι στην παραγγελία σας δεν είναι πλέον διαθέσιμο. Αφαιρέστε το.', option_unavailable: 'Ένα έξτρα που επιλέξατε δεν είναι πλέον διαθέσιμο.',
service_unavailable: 'Αυτή η υπηρεσία δεν είναι διαθέσιμη τώρα.', closed: 'Είμαστε κλειστά τώρα. Επιλέξτε αργότερη ώρα.', service_unavailable: 'Αυτή η υπηρεσία δεν είναι διαθέσιμη τώρα.', closed: 'Είμαστε κλειστά τώρα. Επιλέξτε αργότερη ώρα.',
time_invalid: 'Η ώρα αυτή δεν είναι πλέον διαθέσιμη. Επιλέξτε άλλη.', details_missing: 'Συμπληρώστε τα στοιχεία σας.', time_invalid: 'Η ώρα αυτή δεν είναι πλέον διαθέσιμη. Επιλέξτε άλλη.', details_missing: 'Συμπληρώστε τα στοιχεία σας.',
party_invalid: 'Online κρατήσεις έως {{max}} άτομα. Για μεγαλύτερες παρέες τηλεφωνήστε μας.',
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.', rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.',
}, },
track: { track: {
booking: {
title: 'Κράτηση {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε το αίτημα κράτησης.',
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', delivered: 'Καλώς ήρθατε',
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την κράτηση', cancelled: 'Ακυρώθηκε από το κατάστημα',
},
title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο', title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο',
keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.', keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.',
status: { status: {
+33 -1
View File
@@ -3,7 +3,9 @@
// what is charged is the cloud's answer (POST /api/orders/{site}/quote and the order itself). // what is charged is the cloud's answer (POST /api/orders/{site}/quote and the order itself).
export const SERVICES = ['takeaway', 'delivery'] 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 const round2 = n => Math.round(n * 100) / 100
@@ -109,8 +111,38 @@ export function slotDays(slots, timeZone) {
return out 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. */ /** The tracking page's steps for an order type, and how far it got. */
export function trackSteps(orderType, status) { 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' const steps = orderType === 'delivery'
? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered'] ? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered']
: ['pending_acceptance', 'accepted', 'preparing', 'ready', '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 // 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 // (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. // 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 { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowLeft, Minus, Plus } from 'lucide-react' import { ArrowLeft, Minus, Plus } from 'lucide-react'
import { fetchSlots, placeOrder, quote } from '../api' import { fetchSlots, placeOrder, quote } from '../api'
import { useT } from '../i18n' 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 QUOTE_DELAY = 250
const SLOTS_EVERY = 60_000 const SLOTS_EVERY = 60_000
@@ -16,8 +18,10 @@ function savedDetails() {
try { return JSON.parse(localStorage.getItem(FORM_KEY) || '{}') } catch { return {} } try { return JSON.parse(localStorage.getItem(FORM_KEY) || '{}') } catch { return {} }
} }
export default function Checkout({ site, service, menu, lines, setCart, onBack, onPlaced }) { export default function Checkout({ site, service, booking, menu, lines, setCart, onBack, onPlaced }) {
const { t, money } = useT() const { t, money, lang } = useT()
const book = service === 'book'
const quoteType = book ? 'preorder' : service
const areas = menu.delivery_areas ?? [] const areas = menu.delivery_areas ?? []
const [form, setForm] = useState(() => ({ const [form, setForm] = useState(() => ({
name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(), 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) } return () => { alive = false; clearInterval(id) }
}, [site]) }, [site])
useEffect(() => { useEffect(() => {
if (form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0]) if (!book && form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0])
}, [slots, form.when]) }, [slots, form.when, book])
// the cloud prices the order whenever what affects the price changes // 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, 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 id = setTimeout(async () => {
const body = orderBody(form, service, lines, null) const body = orderBody(form, service, lines, null)
try { 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 }) if (mine === seq.current) setPriced({ quote: q, problem: null, pending: false })
} catch (err) { } catch (err) {
if (mine === seq.current) setPriced({ quote: null, problem: refusal(err), pending: false }) 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 }, [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 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 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 () => { const submit = async () => {
setTried(true) setTried(true)
@@ -73,7 +83,7 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
if (problems.length || !canSend) return if (problems.length || !canSend) return
setSending(true) setSending(true)
try { 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) 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 */ } try { localStorage.setItem(FORM_KEY, JSON.stringify({ name: form.name, phone: form.phone, address: form.address, postcode: form.postcode })) } catch { /* private mode */ }
onPlaced(result) onPlaced(result)
@@ -93,11 +103,18 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
<div className="pb-10" data-testid="checkout"> <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"> <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> <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> </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')}> <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 => { {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)) 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 ( return (
@@ -157,7 +174,7 @@ export default function Checkout({ site, service, menu, lines, setCart, onBack,
<Field label={t('notes')}> <Field label={t('notes')}>
<textarea className={`${input} h-20 py-2.5`} value={form.notes} onChange={e => set('notes', e.target.value)} maxLength={500} /> <textarea className={`${input} h-20 py-2.5`} value={form.notes} onChange={e => set('notes', e.target.value)} maxLength={500} />
</Field> </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"> <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">{t('asap')}</option>}
{!slots.asap && <option value="asap" disabled>{t('pickTime')}</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> </optgroup>
))} ))}
</select> </select>
</Field> </Field>}
</section> </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 ?? ''}> data-total={q?.total ?? ''} data-fee={q?.delivery_fee ?? ''}>
{priced.pending && <p className="text-sm text-ink-2">{t('pricing')}</p>} {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>} {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 /> <Row label={t('total')} value={money(q.total)} strong />
</> </>
)} )}
</section> </section>}
<div className="px-4 grid gap-2"> <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>} {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'}`}> 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> </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>
</div> </div>
) )
@@ -2,12 +2,15 @@
// delivery (what the venue offers), adds products at that service's prices, and checks out: // 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 // 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. // 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 { useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom' 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 { fetchMenu, imageUrl } from '../api'
import { useT } from '../i18n' import { useT } from '../i18n'
import { addToCart, cartCount, cartLines, menuFor, productName, productText, SERVICES } from '../logic' import { addToCart, cartCount, cartLines, menuFor, productName, productText, SERVICES } from '../logic'
import BookingPicker from './BookingPicker'
import Checkout from './Checkout' import Checkout from './Checkout'
const CART_KEY = site => `xenia-order-cart:${site}` 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 [picking, setPicking] = useState(null) // a product whose extras are being chosen
const [checkout, setCheckout] = useState(false) const [checkout, setCheckout] = useState(false)
const [category, setCategory] = useState(null) const [category, setCategory] = useState(null)
const [booking, setBooking] = useState({ party: 2, day: null, when: null, food: false })
const load = useCallback(async () => { const load = useCallback(async () => {
setError(null) setError(null)
try { try {
const data = await fetchMenu(site) const data = await fetchMenu(site)
setMenu(data) 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) { } catch (err) {
setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed') 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 */ } try { sessionStorage.setItem(CART_KEY(site), JSON.stringify(cart)) } catch { /* private mode */ }
}, [cart, site]) }, [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 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 count = cartCount(lines)
const subtotal = lines.reduce((s, l) => s + l.total, 0) 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> 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 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 name = menu.restaurant?.name || site
const add = (product, options = []) => setCart(c => addToCart(c, product, options)) const add = (product, options = []) => setCart(c => addToCart(c, product, options))
if (checkout && service) { if (checkout && service) {
return ( return (
<Shell> <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)} onBack={() => setCheckout(false)}
onPlaced={(result) => { onPlaced={(result) => {
// cleared here too: the page unmounts before its storage effect would run // cleared here too: the page unmounts before its storage effect would run
@@ -95,26 +105,31 @@ export default function OrderPage() {
))} ))}
</div> </div>
</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> <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')}> <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')}>
{SERVICES.filter(s => ordering.services.includes(s)).map(s => { {offered.map(s => {
const Icon = s === 'delivery' ? Bike : Store const Icon = ICON[s]
return ( return (
<button key={s} type="button" role="radio" aria-checked={service === s} onClick={() => setService(s)} data-testid={`service-${s}`} <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 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'}`}> ${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> </button>
) )
})} })}
</div> </div>
<p className={`text-sm flex items-center gap-1.5 ${ordering.open_now ? 'text-success-ink' : 'text-warning-ink'}`} data-testid="open-state"> {book ? (
<Clock size={15} aria-hidden="true" /> <BookingPicker site={site} res={res} timeZone={ordering.timezone || 'Europe/Athens'} booking={booking} setBooking={setBooking} />
{ordering.open_now ? t('open') : `${t('closed')} · ${t('closedBody')}`} ) : (
</p> <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> </header>
@@ -145,7 +160,18 @@ export default function OrderPage() {
))} ))}
</main> </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))]"> <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" <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"> 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 { Check, X } from 'lucide-react'
import { track } from '../api' import { track } from '../api'
import { useT } from '../i18n' import { useT } from '../i18n'
import { trackSteps } from '../logic' import { BOOKING_TYPES, trackSteps } from '../logic'
const POLL_MS = 8000 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> 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 { 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 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 : null
const st = s => t(booked ? `track.booking.${s}` : `track.status.${s}`)
return ( return (
<Page> <Page>
<div className="p-4 grid gap-4" data-testid="track" data-status={order.status}> <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"> <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> <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">{t(order.order_type === 'delivery' ? 'delivery' : 'takeaway')} · {order.requested_for ? t('track.for', { when }) : t('track.asap')}</p> <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> </header>
{rejected ? ( {rejected ? (
<div className="p-4 rounded-card bg-danger-soft text-danger-ink grid gap-1" role="status"> <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>} {order.rejection_reason && <p>{t('track.reason', { reason: order.rejection_reason })}</p>}
</div> </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) => { {steps.map((s, i) => {
const done = i < at || order.status === 'delivered' const done = i < at || order.status === 'delivered'
const now = 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 ? '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} {done ? <Check size={15} aria-hidden="true" /> : i + 1}
</span> </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> </li>
) )
})} })}
</ol> </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) => ( {(order.lines ?? []).map((l, i) => (
<div key={i} className="flex justify-between gap-3 text-ink-2"> <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>{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>} {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> <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>} {!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> <Link to={`/${site}`} className="text-center text-accent-ink font-semibold">{t('track.newOrder')}</Link>
</div> </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({ response: { status: 429, data: {} } }), ['rate', {}])
assert.deepEqual(refusal(new Error('x')), ['failed', {}]) 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)
})