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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 13:39:00 +02:00
co-authored by Claude Opus 5.5
parent 9e8ec4c4e6
commit b25bfcda3e
30 changed files with 4424 additions and 15 deletions
@@ -1,4 +1,4 @@
"""online orders: sales_point, table_label, delivery_area, tracking_token; public_ref unique per site (plan phase 3S, S.2/S.3)
"""online orders: sales_point, table_label, delivery_area, requested_for, tracking_token; public_ref unique per site (plan phase 3S, S.2/S.3)
- sales_point / table_label: the cloud prices orders per sales point; the QR menu's table
- public_ref ("ORD-0001") counts per site but was unique across all sites, so a second
@@ -60,6 +60,7 @@ def upgrade() -> None:
with op.batch_alter_table('online_orders', copy_from=_base(), recreate='always') as batch_op:
batch_op.add_column(sa.Column('table_label', sa.String(), nullable=True))
batch_op.add_column(sa.Column('delivery_area', sa.String(), nullable=True))
batch_op.add_column(sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True))
batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=True))
batch_op.add_column(sa.Column('tracking_token', sa.String(), nullable=True))
batch_op.create_unique_constraint('uq_online_orders_site_ref', ['site_id', 'public_ref'])
@@ -73,11 +74,13 @@ def upgrade() -> None:
def downgrade() -> None:
current = _base(sa.Column('table_label', sa.String(), nullable=True),
sa.Column('delivery_area', sa.String(), nullable=True),
sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True),
sa.Column('sales_point', sa.String(), nullable=True),
sa.Column('tracking_token', sa.String(), nullable=True))
with op.batch_alter_table('online_orders', copy_from=current, recreate='always') as batch_op:
batch_op.drop_column('tracking_token')
batch_op.drop_column('sales_point')
batch_op.drop_column('requested_for')
batch_op.drop_column('delivery_area')
batch_op.drop_column('table_label')
batch_op.create_unique_constraint('uq_online_orders_public_ref', ['public_ref'])
+1
View File
@@ -26,6 +26,7 @@ class OnlineOrder(Base):
customer_notes = Column(Text, nullable=True)
table_label = Column(String, nullable=True) # the QR menu's table, as the customer gave it
delivery_area = Column(String, nullable=True) # the delivery area's name (S.3)
requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
# Order content — JSON array of ordered items
+2
View File
@@ -45,6 +45,8 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)):
from services.checkout import delivery_areas
data["delivery_areas"] = delivery_areas(data) # S.3: what the customer picks from
data.pop("fees", None) # the rules and postcodes stay on the cloud
from services.ordering import summary
data["ordering"] = summary(data) # S.4: services, open now, slots
data["menu_mode"] = site.menu_mode
data["restaurant"] = {
"name": site.menu_display_name,
+46 -6
View File
@@ -1,6 +1,7 @@
import json
import secrets
from fastapi import APIRouter, Depends, HTTPException, Header, status
from datetime import timezone
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
@@ -13,6 +14,17 @@ from schemas.online_order import (
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest,
)
from services.checkout import CheckoutError, check_sent, price_cart
from services import ordering, ratelimit
# public endpoints, per caller address (CL-4)
QUOTE_LIMIT = (120, 60) # 120 quotes a minute
ORDER_LIMIT = (10, 600) # 10 orders in 10 minutes
TRACK_LIMIT = (240, 60)
def _limit(request, bucket, rule):
if not ratelimit.hit(bucket, ratelimit.client_ip(request), *rule):
raise HTTPException(status_code=429, detail={"code": "rate.limited", "params": {"seconds": rule[1]}})
from auth_utils import get_current_admin # manager JWT checked separately in manager_auth
router = APIRouter()
@@ -58,22 +70,37 @@ def _priced(menu, order_type, items, area_id=None, postcode=None):
raise HTTPException(status_code=e.status, detail=e.detail())
@router.get("/{site_slug}/slots")
def order_slots(site_slug: str, db: Session = Depends(get_db)):
"""When online orders can be placed (S.4): services, open now, ASAP offered, time slots."""
_site, menu = _site_and_menu(db, site_slug)
return ordering.summary(menu)
@router.post("/{site_slug}/quote")
def quote_order(site_slug: str, body: QuoteRequest, 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)."""
_limit(request, "quote", QUOTE_LIMIT)
_site, menu = _site_and_menu(db, site_slug)
return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode).out()
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(get_db)):
def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db: Session = Depends(get_db)):
"""Customer submits an order from a customer app. The cloud prices it from the venue's menu
for the order's sales point (services/checkout.py); a price or total the app sent that
differs → 409 order.price_changed with the current prices; nothing the browser says about
money is stored (phase 3S, S.2)."""
_limit(request, "order", ORDER_LIMIT)
site, menu = _site_and_menu(db, site_slug)
items = [i.model_dump() for i in body.items]
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode)
if body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
problem = ordering.check(menu, body.order_type, body.requested_for)
if problem:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
if not (body.customer_phone or "").strip():
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
try:
check_sent(priced, items, body.total)
except CheckoutError as e:
@@ -95,6 +122,9 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(
customer_notes=body.customer_notes,
table_label=(body.customer_table or "").strip() or None,
delivery_area=priced.area_name,
# 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)
if body.order_type in ("takeaway", "delivery") and body.requested_for else None),
sales_point=priced.sales_point,
items_json=json.dumps([line.out() for line in priced.lines]),
subtotal=priced.subtotal,
@@ -111,12 +141,22 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(
@router.get("/track/{token}", response_model=OrderStatusOut)
def track_order(token: str, db: Session = Depends(get_db)):
"""The customer's tracking page (S.2): by the order's random token."""
def track_order(token: str, request: Request, db: Session = Depends(get_db)):
"""The customer's tracking page (S.2): by the order's random token. Since S.4 also what
was ordered and when it's wanted (the token is the customer's own secret)."""
_limit(request, "track", TRACK_LIMIT)
order = db.query(OnlineOrder).filter(OnlineOrder.tracking_token == token).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason)
try:
lines = json.loads(order.items_json or "[]")
except ValueError:
lines = []
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,
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],
subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total)
@router.get("/status/{public_ref}", response_model=OrderStatusOut)
+28 -1
View File
@@ -1,7 +1,16 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from datetime import timezone
from pydantic import BaseModel, Field, field_serializer
def _utc(value):
"""The cloud's database keeps no time zone: a naive datetime is UTC. Sent with its offset."""
if value is None:
return None
return (value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value).isoformat()
class OrderItemIn(BaseModel):
@@ -30,6 +39,7 @@ class OnlineOrderCreate(BaseModel):
customer_table: Optional[str] = Field(default=None, max_length=40)
area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20)
requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible
items: list[OrderItemIn] = Field(max_length=100)
# what the customer was shown: compared, never stored as sent
subtotal: Optional[float] = None
@@ -49,6 +59,18 @@ class OrderStatusOut(BaseModel):
public_ref: str
status: str
rejection_reason: Optional[str] = None
# S.4: what the tracking page shows (all optional: older clients ignore them)
order_type: Optional[str] = None
requested_for: Optional[datetime] = None
created_at: Optional[datetime] = None
lines: Optional[list] = None
subtotal: Optional[float] = None
delivery_fee: Optional[float] = None
total: Optional[float] = None
@field_serializer('requested_for', 'created_at')
def _times(self, value):
return _utc(value)
class PendingOrderOut(BaseModel):
@@ -61,6 +83,7 @@ class PendingOrderOut(BaseModel):
customer_notes: Optional[str] = None
table_label: Optional[str] = None # the QR menu's table (S.2)
delivery_area: Optional[str] = None # the delivery area's name (S.3)
requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible
sales_point: Optional[str] = None # the site's sales point (S.2)
items_json: str
subtotal: float
@@ -71,6 +94,10 @@ class PendingOrderOut(BaseModel):
model_config = {"from_attributes": True}
@field_serializer('requested_for', 'created_at')
def _times(self, value):
return _utc(value)
class OrderSyncedRequest(BaseModel):
local_order_id: int
+111
View File
@@ -0,0 +1,111 @@
"""When online orders are taken (plan phase 3S, step S.4).
The venue's settings travel with the menu snapshot (`ordering`, site routers/fees.py
OrderingBody) and are enforced here at checkout:
{services: ["takeaway", "delivery"], hours: {"0".."6": [["HH:MM", "HH:MM"], ...]},
prep_minutes, slot_minutes, days_ahead, asap}
- a service not in `services` → order.service_unavailable
- hours: none at all = any time; otherwise a day without ranges is closed; a range whose end
is before its start runs past midnight into the next day
- "as soon as possible" (no requested time): only while open now, and only if `asap`
- a requested time: one of slots() — on the slot grid (every slot_minutes from local
midnight), at least prep_minutes from now, within today + days_ahead, while open
Times are the venue's local time (the snapshot's `timezone`).
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
DEFAULTS = {"services": [], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
MAX_SLOTS = 300
def config(snapshot: dict) -> dict:
cfg = {**DEFAULTS, **(snapshot.get("ordering") or {})}
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 15))
cfg["prep_minutes"] = max(0, int(cfg.get("prep_minutes") or 0))
cfg["days_ahead"] = max(0, min(7, int(cfg.get("days_ahead") or 0)))
return cfg
def venue_tz(snapshot: dict) -> ZoneInfo:
try:
return ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
except Exception:
return ZoneInfo("Europe/Athens")
def _mins(hhmm: str) -> int:
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def is_open(cfg: dict, local: datetime) -> bool:
hours = cfg.get("hours") or {}
if not hours:
return True
t = local.hour * 60 + local.minute
today, yesterday = str(local.weekday()), str((local.weekday() - 1) % 7)
for start, end in hours.get(today, []):
s, e = _mins(start), _mins(end)
if (s < e and s <= t < e) or (s > e and t >= s):
return True
for start, end in hours.get(yesterday, []):
s, e = _mins(start), _mins(end)
if s > e and t < e: # yesterday's range running past midnight
return True
return False
def _first_slot(cfg: dict, local_now: datetime) -> datetime:
earliest = local_now + timedelta(minutes=cfg["prep_minutes"])
step = cfg["slot_minutes"]
midnight = earliest.replace(hour=0, minute=0, second=0, microsecond=0)
mins = (earliest - midnight).total_seconds() / 60
n = int(-(-mins // step)) # round up to the grid
return midnight + timedelta(minutes=n * step)
def slots(snapshot: dict, now: datetime | None = None) -> list[datetime]:
"""The times a customer can pick (aware, venue local), in order."""
cfg, tz = config(snapshot), venue_tz(snapshot)
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
last_day = (local_now + timedelta(days=cfg["days_ahead"])).date()
out, t = [], _first_slot(cfg, local_now)
while t.date() <= last_day and len(out) < MAX_SLOTS:
if is_open(cfg, t):
out.append(t)
t = (t + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
return out
def summary(snapshot: dict, now: datetime | None = None) -> dict:
"""What the ordering app needs: services, open now, ASAP offered, the slots."""
cfg, tz = config(snapshot), venue_tz(snapshot)
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
open_now = is_open(cfg, local_now)
return {"services": cfg["services"], "open_now": open_now, "asap": bool(cfg["asap"]) and open_now,
"prep_minutes": cfg["prep_minutes"], "timezone": tz.key,
"slots": [t.isoformat() for t in slots(snapshot, now)]}
def check(snapshot: dict, service: str, requested_for: datetime | None, now: datetime | None = None):
"""None if the order may be placed for that time, else (code, params)."""
cfg = config(snapshot)
if service not in cfg["services"]:
return "order.service_unavailable", {"service": service}
tz = venue_tz(snapshot)
now = now or datetime.now(timezone.utc)
if requested_for is None:
if cfg["asap"] and is_open(cfg, now.astimezone(tz)):
return None
return "order.closed", {}
if requested_for.tzinfo is None:
return "order.time_invalid", {}
wanted = requested_for.astimezone(tz)
if any(abs((wanted - t).total_seconds()) < 1 for t in slots(snapshot, now)):
return None
return "order.time_invalid", {}
+44
View File
@@ -0,0 +1,44 @@
"""A small in-memory rate limit for the public endpoints (CL-4, plan phase 3S S.4).
hit(bucket, key, limit, per_seconds) -> bool True = allowed (and counted)
client_ip(request) the caller's address behind the proxy
Per process (the cloud runs one); a restart forgets. Enough to stop a script hammering the
order endpoint; not a defence against a distributed attack (that's the proxy's job).
"""
from __future__ import annotations
import threading
import time
from collections import deque
_lock = threading.Lock()
_hits: dict[tuple[str, str], deque] = {}
_MAX_KEYS = 50_000
def hit(bucket: str, key: str, limit: int, per_seconds: float, now: float | None = None) -> bool:
now = time.monotonic() if now is None else now
with _lock:
if len(_hits) > _MAX_KEYS: # never grow without bound
_hits.clear()
q = _hits.setdefault((bucket, key), deque())
while q and now - q[0] >= per_seconds:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
return True
def reset() -> None:
with _lock:
_hits.clear()
def client_ip(request) -> str:
"""The first X-Forwarded-For address (the VPS proxy sets it), else the socket's."""
fwd = request.headers.get("x-forwarded-for", "")
if fwd:
return fwd.split(",")[0].strip() or "?"
return getattr(request.client, "host", None) or "?"
+8
View File
@@ -41,3 +41,11 @@ def admin_h(client):
r = client.post("/api/auth/login", json={"username": "sysadmin", "password": "test-admin-pw"})
assert r.status_code == 200, r.text
return {"Authorization": f"Bearer {r.json()['access_token']}"}
@pytest.fixture(autouse=True)
def _fresh_rate_limits():
"""Every test starts with empty rate-limit counters (services/ratelimit.py, S.4)."""
from services import ratelimit
ratelimit.reset()
yield
+6 -2
View File
@@ -7,6 +7,8 @@ import json
from test_licensing_v2 import _heartbeat, _new_site
COLA, PIE, SOUP = 11, 12, 13
# online ordering on, any time (no hours), as soon as possible (S.4)
ORDERING = {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
def _h(site):
@@ -24,7 +26,7 @@ def _menu(client, site, numeric):
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": []},
{"id": SOUP, "name": "Soup", "base_price": 6.0, "digital_price": 6.0, "digital_available": False,
"sold_at": ["qr_table", "online_delivery"], "prices": {"qr_table": 6.0, "online_delivery": 6.0}, "quick_options": []},
]}]}
]}], "ordering": ORDERING, "timezone": "Europe/Athens"}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200, r.text
@@ -124,6 +126,8 @@ def test_order_numbers_per_site_and_tracking_by_token(client, admin_h):
assert ra["public_ref"] == rb["public_ref"] == "ORD-0001"
assert ra["tracking_token"] != rb["tracking_token"] and ra["total"] == 5.0
t = client.get(f"/api/orders/track/{ra['tracking_token']}")
assert t.status_code == 200 and t.json() == {"public_ref": "ORD-0001", "status": "pending_acceptance", "rejection_reason": None}
tj = t.json()
assert t.status_code == 200 and (tj["public_ref"], tj["status"], tj["rejection_reason"], tj["total"]) == ("ORD-0001", "pending_acceptance", None, 5.0)
assert tj["lines"] == [{"name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}] and tj["order_type"] == "takeaway"
assert client.get("/api/orders/status/ORD-0001").status_code == 404 # ambiguous now
assert client.get("/api/orders/track/nope").status_code == 404
+2 -2
View File
@@ -9,7 +9,7 @@ from pathlib import Path
import pytest
from test_checkout import COLA, _code, _h, _menu, _order
from test_checkout import COLA, ORDERING, _code, _h, _menu, _order
from test_licensing_v2 import _heartbeat, _new_site
CASES = json.loads((Path(__file__).resolve().parent / "fixtures" / "fee_cases.json").read_text(encoding="utf-8"))
@@ -36,7 +36,7 @@ def _venue_with_fees(client, admin_h):
_menu(client, site, numeric)
# the same menu plus the venue's fees, as the site pushes them since S.3
menu = client.get(f"/api/menu/{site['site_id']}").json()
snap = {"categories": menu["categories"], "fees": FEES, "timezone": "Europe/Athens"}
snap = {"categories": menu["categories"], "fees": FEES, "ordering": ORDERING, "timezone": "Europe/Athens"}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200
return site, numeric
+95
View File
@@ -0,0 +1,95 @@
"""When online orders are taken: services, hours, time slots, rate limits (plan phase 3S, S.4)."""
import json
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from services import ordering
from test_checkout import COLA, _code, _h, _menu, _order, _venue
ATH = ZoneInfo("Europe/Athens")
def snap(**cfg):
return {"timezone": "Europe/Athens", "ordering": {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20,
"slot_minutes": 15, "days_ahead": 0, "asap": True, **cfg}}
def at(y, mo, d, h, mi):
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
# Sunday 15 Nov 2026 is weekday 6; Monday 16 Nov is 0
EVENINGS = {"6": [["18:00", "23:00"]], "5": [["20:00", "02:00"]]}
def test_open_hours_including_past_midnight():
cfg = ordering.config(snap(hours=EVENINGS))
local = lambda *a: datetime(*a, tzinfo=ATH) # noqa: E731
assert ordering.is_open(cfg, local(2026, 11, 15, 18, 0))
assert not ordering.is_open(cfg, local(2026, 11, 15, 23, 0))
assert not ordering.is_open(cfg, local(2026, 11, 15, 12, 0))
assert ordering.is_open(cfg, local(2026, 11, 15, 1, 30)) # Saturday's 20:00–02:00, after midnight
assert not ordering.is_open(cfg, local(2026, 11, 16, 19, 0)) # Monday has no hours: closed
assert ordering.is_open(ordering.config(snap()), local(2026, 11, 16, 4, 0)) # no hours = any time
def test_slots_start_after_preparation_on_the_grid_and_stay_in_hours():
s = snap(hours=EVENINGS)
got = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 21, 7))]
assert got == ["21:30", "21:45", "22:00", "22:15", "22:30", "22:45"] # 21:07 + 20 → 21:27 → 21:30
assert ordering.slots(s, at(2026, 11, 15, 22, 50)) == [] # nothing left today
ahead = ordering.slots(snap(hours=EVENINGS, days_ahead=1, slot_minutes=30), at(2026, 11, 15, 22, 50))
assert ahead == [] # Monday closed
morning = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 10, 0))]
assert morning[0] == "18:00" and morning[-1] == "22:45"
def test_check_asap_and_requested_times():
s = snap(hours=EVENINGS)
evening, noon = at(2026, 11, 15, 21, 7), at(2026, 11, 15, 12, 0)
assert ordering.check(s, "delivery", None, evening) is None
assert ordering.check(s, "delivery", None, noon) == ("order.closed", {}) # closed now: no ASAP
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 30), noon) is None # but a later slot is fine
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 31), noon)[0] == "order.time_invalid" # off the grid
assert ordering.check(s, "takeaway", at(2026, 11, 15, 21, 15), evening)[0] == "order.time_invalid" # too soon
assert ordering.check(snap(asap=False), "delivery", None, evening) == ("order.closed", {})
assert ordering.check(snap(services=["takeaway"]), "delivery", None, evening) == ("order.service_unavailable", {"service": "delivery"})
assert ordering.check(s, "takeaway", datetime(2026, 11, 15, 18, 30), noon)[0] == "order.time_invalid" # no zone
def test_the_endpoints_enforce_it(client, admin_h):
site, numeric = _venue(client, admin_h)
# the venue turns delivery off and opens only on Mondays 12:00–13:00
menu = client.get(f"/api/menu/{site['site_id']}").json()
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
"ordering": {"services": ["takeaway"], "hours": {"0": [["12:00", "13:00"]]}, "prep_minutes": 0,
"slot_minutes": 15, "days_ahead": 7, "asap": True}}
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
s = client.get(f"/api/orders/{site['site_id']}/slots").json()
assert s["services"] == ["takeaway"] and len(s["slots"]) >= 4
first = datetime.fromisoformat(s["slots"][0])
assert first.astimezone(ATH).weekday() == 0 and first.astimezone(ATH).strftime("%H:%M") >= "12:00"
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["services"] == ["takeaway"]
assert _code(_order(client, site, "delivery", customer_address="x")) == "order.service_unavailable"
r = _order(client, site, "takeaway", requested_for=s["slots"][0])
assert r.status_code == 201, r.text
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == r.json()["public_ref"])
assert datetime.fromisoformat(stored["requested_for"].replace("Z", "+00:00")) == first
track = client.get(f"/api/orders/track/{r.json()['tracking_token']}").json()
assert track["requested_for"] and track["order_type"] == "takeaway"
# a takeaway or delivery order needs a phone number
assert _code(_order(client, site, "takeaway", customer_phone="", requested_for=s["slots"][0])) == "order.details_missing"
def test_rate_limits(client, admin_h):
from services import ratelimit
site, _ = _venue(client, admin_h)
statuses = [_order(client, site).status_code for _ in range(11)]
assert statuses[:10] == [201] * 10 and statuses[10] == 429
assert _code(_order(client, site)) == "rate.limited"
# another address is counted apart (behind the proxy)
ok = client.post(f"/api/orders/{site['site_id']}", headers={"X-Forwarded-For": "203.0.113.9"},
json={"order_type": "takeaway", "customer_name": "A", "customer_phone": "1", "items": [{"product_id": COLA, "quantity": 1}]})
assert ok.status_code == 201
assert ratelimit.hit("t", "k", 2, 60, now=0) and ratelimit.hit("t", "k", 2, 60, now=1) and not ratelimit.hit("t", "k", 2, 60, now=2)
assert ratelimit.hit("t", "k", 2, 60, now=61) # the window moves on
+12 -1
View File
@@ -8,6 +8,16 @@ ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
# Build order-app (online ordering: takeaway and delivery, plan phase 3S S.4)
FROM node:20-alpine AS order-builder
WORKDIR /app/order-app
COPY order-app/package.json order-app/package-lock.json ./
RUN npm ci
COPY order-app/ .
ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm test && npm run build
# Build manager-app
FROM node:20-alpine AS manager-builder
WORKDIR /app/manager-app
@@ -18,8 +28,9 @@ ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
# Serve both with nginx
# Serve them with nginx
FROM nginx:alpine
COPY --from=menu-builder /app/menu-app/dist /usr/share/nginx/html/menu
COPY --from=manager-builder /app/manager-app/dist /usr/share/nginx/html/manage
COPY --from=order-builder /app/order-app/dist /usr/share/nginx/html/order
COPY nginx-connect.conf /etc/nginx/conf.d/default.conf
+6
View File
@@ -7,6 +7,12 @@ server {
try_files $uri $uri/ /menu/index.html;
}
# Online ordering SPA (takeaway, delivery)
location /order/ {
alias /usr/share/nginx/html/order/;
try_files $uri $uri/ /order/index.html;
}
# Remote manager SPA
location /manage/ {
alias /usr/share/nginx/html/manage/;
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#1f3a34" />
<title>Order online</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Hanken+Grotesk:wght@400;500;600;700&family=Noto+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "order-app",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "node --test \"tests/*.test.mjs\""
},
"dependencies": {
"axios": "^1.7.9",
"lucide-react": "^1.14.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"vite": "^6.0.5"
}
}
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
+13
View File
@@ -0,0 +1,13 @@
// The cloud's public endpoints for online ordering (cloud_backend/routers/orders.py, menu.py).
import axios from 'axios'
export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || ''
const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 })
/** The venue's menu, areas and ordering summary (services, open now, slots). */
export const fetchMenu = async site => (await api.get(`/api/menu/${encodeURIComponent(site)}`)).data
export const fetchSlots = async site => (await api.get(`/api/orders/${encodeURIComponent(site)}/slots`)).data
export const quote = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}/quote`, body)).data
export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data
export const track = async token => (await api.get(`/api/orders/track/${encodeURIComponent(token)}`)).data
export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`)
+108
View File
@@ -0,0 +1,108 @@
// The ordering app's texts (en, el). The customer's choice is remembered on this device; the
// first visit follows the browser's language.
import { createContext, useContext } from 'react'
const STORE = 'xenia-order-lang'
export const TEXTS = {
en: {
takeaway: 'Takeaway', delivery: 'Delivery', open: 'Open now', closed: 'Closed now',
closedBody: 'You can still order for a later time.', noOrdering: 'Online ordering is not available right now.',
loading: 'Loading the menu…', notFound: 'This venue was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.',
retry: 'Try again', add: 'Add', soldOut: 'Sold out', options: 'Extras', addToOrder: 'Add to order', cancel: 'Cancel',
viewOrder: 'View order', items_one: '{{count}} item', items_other: '{{count}} items',
yourOrder: 'Your order', empty: 'Your order is empty.', products: 'Products', fee: 'Delivery fee', total: 'Total',
pricing: 'Working out the price…', details: 'Your details', name: 'Name', phone: 'Phone',
address: 'Street and number', area: 'Area', areaPick: 'Pick your area', byPostcode: 'Or enter your postcode',
byArea: 'Pick from the list', postcode: 'Postcode', notes: 'Notes for the venue (optional)',
when: 'When', asap: 'As soon as possible', pickTime: 'Pick a time', today: 'Today', tomorrow: 'Tomorrow',
placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back',
payNote: 'You pay at the venue or on delivery.',
problem: {
name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.',
area: 'Pick your area.', postcode: 'Enter your postcode.', when: 'Pick a time.',
},
refused: {
minimum_not_met: 'The minimum order for delivery is {{minimum}}.', area_not_served: 'Sorry, we don\'t deliver to this address.',
price_changed: 'Prices changed since you opened the menu. Check your order: it now shows the current prices.',
item_unavailable: 'Something in your order is no longer available. Please remove it.', option_unavailable: 'An extra you chose is no longer available.',
service_unavailable: 'This service is not available right now.', closed: 'We\'re closed right now. Pick a later time.',
time_invalid: 'That time is no longer available. Pick another.', details_missing: 'Please fill in your details.',
rate: 'Too many attempts. Please wait a few minutes.', no_menu: 'The menu is not available right now.', failed: 'Something went wrong. Please try again.',
},
track: {
title: 'Order {{ref}}', placed: 'Thank you! We got your order.', for: 'For {{when}}', asap: 'As soon as possible',
keep: 'Keep this page open, or save its address, to follow your order.',
status: {
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', preparing: 'Being prepared',
ready: 'Ready to collect', out_for_delivery: 'On its way', delivered: 'Done', rejected: 'Not accepted',
},
rejected: 'The venue could not take this order.', reason: 'Reason: {{reason}}', newOrder: 'Order again', notFound: 'This order was not found.',
},
},
el: {
takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα',
closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.',
loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.',
retry: 'Δοκιμάστε ξανά', add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', options: 'Έξτρα', addToOrder: 'Στην παραγγελία', cancel: 'Ακύρωση',
viewOrder: 'Η παραγγελία', items_one: '{{count}} τεμάχιο', items_other: '{{count}} τεμάχια',
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', products: 'Προϊόντα', fee: 'Χρέωση διανομής', total: 'Σύνολο',
pricing: 'Υπολογισμός τιμής…', details: 'Τα στοιχεία σας', name: 'Όνομα', phone: 'Τηλέφωνο',
address: 'Οδός και αριθμός', area: 'Περιοχή', areaPick: 'Επιλέξτε περιοχή', byPostcode: 'Ή γράψτε τον Τ.Κ.',
byArea: 'Επιλογή από τη λίστα', postcode: 'Τ.Κ.', notes: 'Σημειώσεις για το κατάστημα (προαιρετικά)',
when: 'Πότε', asap: 'Το συντομότερο', pickTime: 'Επιλέξτε ώρα', today: 'Σήμερα', tomorrow: 'Αύριο',
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
problem: {
name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.',
area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.',
},
refused: {
minimum_not_met: 'Η ελάχιστη παραγγελία για διανομή είναι {{minimum}}.', area_not_served: 'Δυστυχώς δεν κάνουμε διανομή σε αυτή τη διεύθυνση.',
price_changed: 'Οι τιμές άλλαξαν από τότε που ανοίξατε το μενού. Ελέγξτε την παραγγελία: δείχνει πλέον τις τρέχουσες τιμές.',
item_unavailable: 'Κάτι στην παραγγελία σας δεν είναι πλέον διαθέσιμο. Αφαιρέστε το.', option_unavailable: 'Ένα έξτρα που επιλέξατε δεν είναι πλέον διαθέσιμο.',
service_unavailable: 'Αυτή η υπηρεσία δεν είναι διαθέσιμη τώρα.', closed: 'Είμαστε κλειστά τώρα. Επιλέξτε αργότερη ώρα.',
time_invalid: 'Η ώρα αυτή δεν είναι πλέον διαθέσιμη. Επιλέξτε άλλη.', details_missing: 'Συμπληρώστε τα στοιχεία σας.',
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.',
},
track: {
title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο',
keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.',
status: {
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', preparing: 'Ετοιμάζεται',
ready: 'Έτοιμη για παραλαβή', out_for_delivery: 'Καθ\' οδόν', delivered: 'Ολοκληρώθηκε', rejected: 'Δεν έγινε δεκτή',
},
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την παραγγελία.', reason: 'Λόγος: {{reason}}', newOrder: 'Νέα παραγγελία', notFound: 'Η παραγγελία δεν βρέθηκε.',
},
},
}
export function initialLang() {
try {
const saved = localStorage.getItem(STORE)
if (saved && TEXTS[saved]) return saved
} catch { /* private mode */ }
return (navigator.language || 'en').toLowerCase().startsWith('el') ? 'el' : 'en'
}
export function saveLang(lang) {
try { localStorage.setItem(STORE, lang) } catch { /* private mode */ }
}
/** t('a.b', {x}) with {{x}} and _one/_other plurals by `count`. */
export function translate(lang, key, params = {}) {
const dict = TEXTS[lang] ?? TEXTS.en
const find = k => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), dict)
let s = params.count != null ? find(`${key}_${params.count === 1 ? 'one' : 'other'}`) : undefined
if (s === undefined) s = find(key)
if (typeof s !== 'string') return key
return s.replace(/\{\{(\w+)\}\}/g, (_, k) => (params[k] ?? ''))
}
export const LangContext = createContext({ lang: 'en', setLang: () => {} })
export function useT() {
const { lang, setLang } = useContext(LangContext)
const money = n => new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-IE', { style: 'currency', currency: 'EUR' }).format(n ?? 0)
return { lang, setLang, t: (key, params) => translate(lang, key, params), money }
}
+35
View File
@@ -0,0 +1,35 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* The app's tokens (RGB triples, used through tailwind.config.js). Light only for now. */
:root {
--o-canvas: 246 244 239;
--o-surface: 255 255 255;
--o-surface-2: 239 236 228;
--o-line: 226 221 209;
--o-ink: 28 36 33;
--o-ink-2: 88 96 92;
--o-ink-3: 140 145 140;
--o-accent: 31 58 52;
--o-accent-fg: 247 244 236;
--o-accent-soft: 222 234 228;
--o-accent-ink: 24 66 56;
--o-success: 48 120 78;
--o-success-soft: 225 242 231;
--o-success-ink: 30 92 56;
--o-warning-soft: 252 240 214;
--o-warning-ink: 124 82 10;
--o-danger-soft: 251 228 222;
--o-danger-ink: 160 50 30;
--o-shadow: 28 36 33;
color-scheme: light;
}
html, body { background: rgb(var(--o-canvas)); color: rgb(var(--o-ink)); }
body { font-family: theme('fontFamily.sans'); -webkit-font-smoothing: antialiased; }
button { -webkit-tap-highlight-color: transparent; }
:focus-visible { outline: 3px solid rgb(var(--o-accent) / 0.45); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
+126
View File
@@ -0,0 +1,126 @@
// The online ordering app's logic (plan phase 3S, step S.4). Pure: unit-tested in Node
// (tests/logic.test.mjs). Prices shown come from the venue's menu for the chosen service;
// what is charged is the cloud's answer (POST /api/orders/{site}/quote and the order itself).
export const SERVICES = ['takeaway', 'delivery']
export const POINT = { takeaway: 'online_takeaway', delivery: 'online_delivery' }
const round2 = n => Math.round(n * 100) / 100
/** A product's price for a service, or null when it isn't sold that way. */
export function priceFor(product, service) {
const point = POINT[service]
if (product.sold_at && !product.sold_at.includes(point)) return null
if (product.prices) return product.prices[point] ?? null
return product.digital_price ?? product.base_price ?? null // menus from before S.2
}
/** The menu for a service: categories with the products sold that way (once each, priced). */
export function menuFor(categories, service) {
const seen = new Set()
return (categories ?? []).map(c => ({
...c,
products: (c.products ?? []).filter(p => {
const price = priceFor(p, service)
return price != null
}).map(p => ({ ...p, price: priceFor(p, service), available: p.digital_available !== false, repeat: seen.has(p.id) || !seen.add(p.id) })),
})).filter(c => c.products.length > 0)
}
export const productName = p => p.digital_name || p.name
export const productText = p => p.digital_description || ''
/** A cart line's key: the product and its chosen options. */
export const lineKey = (productId, options = []) => [productId, ...[...options].sort((a, b) => a - b)].join(':')
/** Add one (or `qty`) of a product with options. */
export function addToCart(cart, product, options = [], qty = 1) {
const key = lineKey(product.id, options)
const found = cart.find(l => l.key === key)
if (found) return cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, l.qty + qty) } : l))
return [...cart, { key, productId: product.id, options: [...options].sort((a, b) => a - b), qty }]
}
export function setQty(cart, key, qty) {
return qty <= 0 ? cart.filter(l => l.key !== key) : cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, qty) } : l))
}
export const cartCount = cart => cart.reduce((s, l) => s + l.qty, 0)
/** The cart priced from the menu (what's shown before the cloud answers); lines whose product
* isn't sold for this service any more are dropped. */
export function cartLines(cart, products, service) {
const byId = new Map(products.map(p => [p.id, p]))
return cart.flatMap(l => {
const p = byId.get(l.productId)
const price = p ? priceFor(p, service) : null
if (price == null) return []
const opts = (p.quick_options ?? []).filter(o => l.options.includes(o.id))
const unit = round2(price + opts.reduce((s, o) => s + (o.price || 0), 0))
return [{ ...l, name: productName(p), unit, total: round2(unit * l.qty), optionNames: opts.map(o => o.name) }]
})
}
/** Items as the cloud takes them. */
export const itemsBody = lines => lines.map(l => ({ product_id: l.productId, quantity: l.qty, options: l.options, unit_price: l.unit }))
/** What checkout still needs: a list of field keys (empty = can order). */
export function checkoutProblems(form, service, { areas = [], asap = true, slots = [] } = {}) {
const out = []
if (!form.name.trim()) out.push('name')
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
if (service === 'delivery') {
if (!form.address.trim()) out.push('address')
if (areas.length && form.where === 'area' && !form.areaId) out.push('area')
if (form.where === 'postcode' && !form.postcode.trim()) out.push('postcode')
}
if (form.when === 'asap' ? !asap : !slots.includes(form.when)) out.push('when')
return out
}
/** The order request (POST /api/orders/{site}). `quote` is the cloud's last answer. */
export function orderBody(form, service, lines, quote) {
return {
order_type: service,
customer_name: form.name.trim(),
customer_phone: form.phone.trim(),
customer_address: service === 'delivery' ? form.address.trim() : null,
customer_notes: form.notes.trim() || null,
area_id: service === 'delivery' && form.where === 'area' && form.areaId ? Number(form.areaId) : null,
postcode: service === 'delivery' && form.where === 'postcode' ? form.postcode.trim() || null : null,
requested_for: form.when === 'asap' ? null : form.when,
items: itemsBody(lines),
total: quote?.total ?? undefined,
}
}
/** Slots grouped by local day for the picker: [{ day: 'YYYY-MM-DD', times: [{ iso, label }] }]. */
export function slotDays(slots, timeZone) {
const dayFmt = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
const timeFmt = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hour12: false })
const out = []
for (const iso of slots ?? []) {
const d = new Date(iso)
const day = dayFmt.format(d)
let g = out.find(x => x.day === day)
if (!g) out.push(g = { day, times: [] })
g.times.push({ iso, label: timeFmt.format(d) })
}
return out
}
/** The tracking page's steps for an order type, and how far it got. */
export function trackSteps(orderType, status) {
const steps = orderType === 'delivery'
? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered']
: ['pending_acceptance', 'accepted', 'preparing', 'ready', 'delivered']
return { steps, at: status === 'rejected' ? -1 : steps.indexOf(status), done: status === 'delivered' || status === 'rejected' }
}
/** A refusal from the cloud → a message key and its params. */
export function refusal(err) {
const d = err?.response?.data?.detail
if (err?.response?.status === 429) return ['rate', {}]
if (d && typeof d === 'object' && d.code) return [d.code.replace(/^order\./, ''), d.params ?? {}]
return ['failed', {}]
}
+26
View File
@@ -0,0 +1,26 @@
import { StrictMode, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
import './index.css'
import { initialLang, LangContext, saveLang } from './i18n'
import OrderPage from './pages/OrderPage'
import TrackPage from './pages/TrackPage'
function App() {
const [lang, setLangState] = useState(initialLang)
const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l }
document.documentElement.lang = lang
return (
<LangContext.Provider value={{ lang, setLang }}>
<BrowserRouter basename="/order">
<Routes>
<Route path="/:site" element={<OrderPage />} />
<Route path="/:site/track/:token" element={<TrackPage />} />
<Route path="*" element={<p className="p-6 text-ink-2">Xenia</p>} />
</Routes>
</BrowserRouter>
</LangContext.Provider>
)
}
createRoot(document.getElementById('root')).render(<StrictMode><App /></StrictMode>)
@@ -0,0 +1,218 @@
// Checkout (plan phase 3S, step S.4): the order priced by the cloud (products at this service's
// prices, the delivery fee from the venue's rules, the minimum), the customer's details, when
// (as soon as possible while open, or a time slot) and "Place order". Every price shown here is
// the cloud's answer; the order is refused if it changed meanwhile and the new prices show.
import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowLeft, Minus, Plus } from 'lucide-react'
import { fetchSlots, placeOrder, quote } from '../api'
import { useT } from '../i18n'
import { checkoutProblems, itemsBody, orderBody, refusal, setQty, slotDays } from '../logic'
const QUOTE_DELAY = 250
const SLOTS_EVERY = 60_000
const FORM_KEY = 'xenia-order-details'
function savedDetails() {
try { return JSON.parse(localStorage.getItem(FORM_KEY) || '{}') } catch { return {} }
}
export default function Checkout({ site, service, menu, lines, setCart, onBack, onPlaced }) {
const { t, money } = useT()
const areas = menu.delivery_areas ?? []
const [form, setForm] = useState(() => ({
name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(),
where: areas.length ? 'area' : 'postcode', areaId: '', when: 'asap',
}))
const [slots, setSlots] = useState(menu.ordering ?? { slots: [], asap: false, timezone: 'Europe/Athens' })
const [priced, setPriced] = useState({ quote: null, problem: null, pending: true })
const [tried, setTried] = useState(false)
const [sending, setSending] = useState(false)
const [sendProblem, setSendProblem] = useState(null)
const seq = useRef(0)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
// the slots move on with the clock
useEffect(() => {
let alive = true
const load = () => fetchSlots(site).then(s => alive && setSlots(s)).catch(() => {})
load()
const id = setInterval(load, SLOTS_EVERY)
return () => { alive = false; clearInterval(id) }
}, [site])
useEffect(() => {
if (form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0])
}, [slots, form.when])
// the cloud prices the order whenever what affects the price changes
const quoteKey = JSON.stringify([itemsBody(lines).map(i => [i.product_id, i.quantity, i.options]), service,
service === 'delivery' ? [form.where, form.areaId, form.postcode.trim()] : null])
useEffect(() => {
const mine = ++seq.current
if (!lines.length) { setPriced({ quote: null, problem: null, pending: false }); return undefined }
setPriced(p => ({ ...p, pending: true }))
const id = setTimeout(async () => {
const body = orderBody(form, service, lines, null)
try {
const q = await quote(site, { order_type: service, items: body.items, area_id: body.area_id, postcode: body.postcode })
if (mine === seq.current) setPriced({ quote: q, problem: null, pending: false })
} catch (err) {
if (mine === seq.current) setPriced({ quote: null, problem: refusal(err), pending: false })
}
}, QUOTE_DELAY)
return () => clearTimeout(id)
}, [quoteKey]) // eslint-disable-line react-hooks/exhaustive-deps -- quoteKey is what changes the price
const days = useMemo(() => slotDays(slots.slots ?? [], slots.timezone || 'Europe/Athens'), [slots])
const problems = checkoutProblems(form, service, { areas, asap: !!slots.asap, slots: slots.slots ?? [] })
const q = priced.quote
const canSend = q && !priced.pending && !priced.problem && !sending
const submit = async () => {
setTried(true)
setSendProblem(null)
if (problems.length || !canSend) return
setSending(true)
try {
const body = orderBody(form, service, lines, q)
const result = await placeOrder(site, body)
try { localStorage.setItem(FORM_KEY, JSON.stringify({ name: form.name, phone: form.phone, address: form.address, postcode: form.postcode })) } catch { /* private mode */ }
onPlaced(result)
} catch (err) {
const [code, params] = refusal(err)
setSendProblem([code, params])
// the refusal carries the current prices: show them; "Place order" again sends the new total
if (code === 'price_changed' && params.lines) setPriced({ quote: params, problem: null, pending: false })
setSending(false)
}
}
const fieldErr = k => (tried && problems.includes(k) ? t(`problem.${k}`) : null)
const input = 'w-full h-12 px-3.5 rounded-control bg-surface border border-line text-ink placeholder:text-ink-3'
return (
<div className="pb-10" data-testid="checkout">
<header className="px-4 py-3 flex items-center gap-2 bg-surface border-b border-line sticky top-0 z-10">
<button type="button" onClick={onBack} aria-label={t('back')} className="w-10 h-10 rounded-full bg-surface-2 flex items-center justify-center"><ArrowLeft size={18} /></button>
<h1 className="font-display text-xl font-semibold">{t('yourOrder')} · {t(service)}</h1>
</header>
<section className="p-4 grid gap-2" aria-label={t('yourOrder')}>
{lines.length === 0 && <p className="text-ink-2">{t('empty')}</p>}
{lines.map(l => {
const cloudLine = q?.lines?.find(x => x.product_id === l.productId && JSON.stringify((x.options ?? []).map(o => o.id).sort()) === JSON.stringify(l.options))
return (
<div key={l.key} className="p-3 rounded-card bg-surface border border-line flex items-center gap-3" data-testid="line">
<div className="flex-1 min-w-0">
<p className="font-medium text-ink">{l.name}</p>
{l.optionNames.length > 0 && <p className="text-sm text-ink-2">{l.optionNames.join(', ')}</p>}
<p className="text-sm text-ink-2">{money(cloudLine?.unit_price ?? l.unit)}</p>
</div>
<div className="flex items-center gap-1">
<button type="button" onClick={() => setCart(c => setQty(c, l.key, l.qty - 1))} aria-label="−" className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><Minus size={16} /></button>
<span className="w-7 text-center font-semibold">{l.qty}</span>
<button type="button" onClick={() => setCart(c => setQty(c, l.key, l.qty + 1))} aria-label="+" className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><Plus size={16} /></button>
</div>
</div>
)
})}
</section>
<section className="px-4 grid gap-3" aria-labelledby="details-h">
<h2 id="details-h" className="font-display text-lg font-semibold">{t('details')}</h2>
<Field label={t('name')} error={fieldErr('name')}>
<input className={input} value={form.name} onChange={e => set('name', e.target.value)} autoComplete="name" maxLength={100} data-testid="f-name" />
</Field>
<Field label={t('phone')} error={fieldErr('phone')}>
<input className={input} value={form.phone} onChange={e => set('phone', e.target.value)} autoComplete="tel" inputMode="tel" maxLength={40} data-testid="f-phone" />
</Field>
{service === 'delivery' && (
<>
{areas.length > 0 && (
<div className="flex gap-2 text-sm" role="radiogroup" aria-label={t('area')}>
{['area', 'postcode'].map(w => (
<button key={w} type="button" role="radio" aria-checked={form.where === w} onClick={() => set('where', w)}
className={`px-3 h-9 rounded-full font-medium ${form.where === w ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{w === 'area' ? t('byArea') : t('byPostcode')}
</button>
))}
</div>
)}
{form.where === 'area' && areas.length > 0 ? (
<Field label={t('area')} error={fieldErr('area')}>
<select className={input} value={form.areaId} onChange={e => set('areaId', e.target.value)} data-testid="f-area">
<option value="">{t('areaPick')}</option>
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
</select>
</Field>
) : (
<Field label={t('postcode')} error={fieldErr('postcode')}>
<input className={input} value={form.postcode} onChange={e => set('postcode', e.target.value)} autoComplete="postal-code" maxLength={20} data-testid="f-postcode" />
</Field>
)}
<Field label={t('address')} error={fieldErr('address')}>
<input className={input} value={form.address} onChange={e => set('address', e.target.value)} autoComplete="street-address" maxLength={300} data-testid="f-address" />
</Field>
</>
)}
<Field label={t('notes')}>
<textarea className={`${input} h-20 py-2.5`} value={form.notes} onChange={e => set('notes', e.target.value)} maxLength={500} />
</Field>
<Field label={t('when')} error={fieldErr('when')}>
<select className={input} value={form.when} onChange={e => set('when', e.target.value)} data-testid="f-when">
{slots.asap && <option value="asap">{t('asap')}</option>}
{!slots.asap && <option value="asap" disabled>{t('pickTime')}</option>}
{days.map((d, i) => (
<optgroup key={d.day} label={i === 0 ? t('today') : i === 1 ? t('tomorrow') : d.day}>
{d.times.map(s => <option key={s.iso} value={s.iso}>{s.label}</option>)}
</optgroup>
))}
</select>
</Field>
</section>
<section className="m-4 p-4 rounded-card bg-surface border border-line grid gap-1.5" aria-live="polite" data-testid="totals"
data-total={q?.total ?? ''} data-fee={q?.delivery_fee ?? ''}>
{priced.pending && <p className="text-sm text-ink-2">{t('pricing')}</p>}
{priced.problem && <p className="text-sm font-medium text-danger-ink" role="alert" data-testid="quote-problem" data-code={priced.problem[0]}>{refusedText(t, money, priced.problem)}</p>}
{q && (
<>
<Row label={t('products')} value={money(q.subtotal)} />
{service === 'delivery' && <Row label={t('fee') + (q.area_name ? ` · ${q.area_name}` : '')} value={money(q.delivery_fee)} testId="fee" />}
<Row label={t('total')} value={money(q.total)} strong />
</>
)}
</section>
<div className="px-4 grid gap-2">
{sendProblem && <p className="text-sm font-medium text-danger-ink" role="alert" data-testid="send-problem" data-code={sendProblem[0]}>{refusedText(t, money, sendProblem)}</p>}
<button type="button" onClick={submit} disabled={sending || !lines.length} data-testid="place-order"
className={`h-14 rounded-full font-semibold ${canSend ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-3'}`}>
{sending ? t('sending') : t('placeOrder', { total: q ? money(q.total) : '…' })}
</button>
<p className="text-sm text-ink-2 text-center">{t('payNote')}</p>
</div>
</div>
)
}
function refusedText(t, money, [code, params]) {
return t(`refused.${code}`, { ...params, minimum: params.minimum != null ? money(params.minimum) : '' })
}
function Field({ label, error, children }) {
return (
<label className="grid gap-1">
<span className="text-sm font-medium text-ink-2">{label}</span>
{children}
{error && <span className="text-sm text-danger-ink" role="alert">{error}</span>}
</label>
)
}
function Row({ label, value, strong, testId }) {
return (
<div className={`flex items-baseline justify-between ${strong ? 'text-lg font-semibold text-ink pt-1 border-t border-line' : 'text-ink-2'}`} data-testid={testId}>
<span>{label}</span><span>{value}</span>
</div>
)
}
@@ -0,0 +1,225 @@
// Online ordering (plan phase 3S, step S.4): /order/{site}. The customer picks takeaway or
// delivery (what the venue offers), adds products at that service's prices, and checks out:
// the cart is priced by the cloud (with the delivery fee and minimum), then the order is
// placed for "as soon as possible" or a time slot, and the tracking page opens.
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Bike, Clock, Minus, Plus, ShoppingBag, Store, X } from 'lucide-react'
import { fetchMenu, imageUrl } from '../api'
import { useT } from '../i18n'
import { addToCart, cartCount, cartLines, menuFor, productName, productText, SERVICES } from '../logic'
import Checkout from './Checkout'
const CART_KEY = site => `xenia-order-cart:${site}`
export default function OrderPage() {
const { site } = useParams()
const { t, lang, setLang, money } = useT()
const navigate = useNavigate()
const [menu, setMenu] = useState(null)
const [error, setError] = useState(null)
const [service, setService] = useState(null)
const [cart, setCart] = useState(() => {
try { return JSON.parse(sessionStorage.getItem(CART_KEY(site)) || '[]') } catch { return [] }
})
const [picking, setPicking] = useState(null) // a product whose extras are being chosen
const [checkout, setCheckout] = useState(false)
const [category, setCategory] = useState(null)
const load = useCallback(async () => {
setError(null)
try {
const data = await fetchMenu(site)
setMenu(data)
setService(s => s ?? data.ordering?.services?.[0] ?? null)
} catch (err) {
setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed')
}
}, [site])
useEffect(() => { load() }, [load])
useEffect(() => {
try { sessionStorage.setItem(CART_KEY(site), JSON.stringify(cart)) } catch { /* private mode */ }
}, [cart, site])
const sections = useMemo(() => (menu && service ? menuFor(menu.categories, service) : []), [menu, service])
const products = useMemo(() => sections.flatMap(c => c.products), [sections])
const lines = useMemo(() => (service ? cartLines(cart, products, service) : []), [cart, products, service])
const count = cartCount(lines)
const subtotal = lines.reduce((s, l) => s + l.total, 0)
if (error) {
return (
<Shell>
<div className="p-6 grid gap-4 text-center">
<p className="text-body text-ink-2">{t(error)}</p>
{error === 'loadFailed' && <button className="mx-auto px-5 h-11 rounded-full bg-accent text-accent-fg font-semibold" onClick={load}>{t('retry')}</button>}
</div>
</Shell>
)
}
if (!menu) return <Shell><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Shell>
const ordering = menu.ordering ?? { services: [] }
const name = menu.restaurant?.name || site
const add = (product, options = []) => setCart(c => addToCart(c, product, options))
if (checkout && service) {
return (
<Shell>
<Checkout site={site} service={service} menu={menu} lines={lines} setCart={setCart}
onBack={() => setCheckout(false)}
onPlaced={(result) => {
// cleared here too: the page unmounts before its storage effect would run
try { sessionStorage.removeItem(CART_KEY(site)) } catch { /* private mode */ }
setCart([])
navigate(`/${site}/track/${result.tracking_token}`, { state: { placed: true } })
}} />
</Shell>
)
}
return (
<Shell>
<header className="px-4 pt-5 pb-3 grid gap-3 bg-surface border-b border-line">
<div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<h1 className="font-display text-2xl font-semibold text-ink leading-tight" data-testid="venue-name">{name}</h1>
{menu.restaurant?.tagline?.[lang === 'el' ? 'gr' : 'en'] && (
<p className="text-sm text-ink-2 mt-0.5">{menu.restaurant.tagline[lang === 'el' ? 'gr' : 'en']}</p>
)}
</div>
<div className="flex rounded-full bg-surface-2 p-0.5 text-sm font-semibold" role="group" aria-label="Language">
{['el', 'en'].map(l => (
<button key={l} type="button" onClick={() => setLang(l)} aria-pressed={lang === l}
className={`px-2.5 h-8 rounded-full ${lang === l ? 'bg-surface text-ink shadow-card' : 'text-ink-2'}`}>{l.toUpperCase()}</button>
))}
</div>
</div>
{ordering.services.length === 0 ? (
<p className="p-3 rounded-control bg-warning-soft text-warning-ink text-sm" data-testid="no-ordering">{t('noOrdering')}</p>
) : (
<>
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label={t('takeaway') + ' / ' + t('delivery')}>
{SERVICES.filter(s => ordering.services.includes(s)).map(s => {
const Icon = s === 'delivery' ? Bike : Store
return (
<button key={s} type="button" role="radio" aria-checked={service === s} onClick={() => setService(s)} data-testid={`service-${s}`}
className={`h-12 rounded-control flex items-center justify-center gap-2 font-semibold transition-colors
${service === s ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
<Icon size={18} aria-hidden="true" />{t(s)}
</button>
)
})}
</div>
<p className={`text-sm flex items-center gap-1.5 ${ordering.open_now ? 'text-success-ink' : 'text-warning-ink'}`} data-testid="open-state">
<Clock size={15} aria-hidden="true" />
{ordering.open_now ? t('open') : `${t('closed')} · ${t('closedBody')}`}
</p>
</>
)}
</header>
{sections.length > 1 && (
<nav className="sticky top-0 z-10 bg-canvas/95 backdrop-blur px-4 py-2 flex gap-2 overflow-x-auto border-b border-line" aria-label="Categories">
{sections.filter(c => c.products.some(p => !p.repeat)).map(c => (
<a key={c.id} href={`#cat-${c.id}`} onClick={() => setCategory(c.id)}
className={`shrink-0 px-3.5 h-9 rounded-full flex items-center text-sm font-medium ${category === c.id ? 'bg-accent text-accent-fg' : 'bg-surface text-ink-2 border border-line'}`}>{c.name}</a>
))}
</nav>
)}
<main className="px-4 pb-32 pt-3 grid gap-6">
{sections.map(c => (
<section key={c.id} id={`cat-${c.id}`} className="grid gap-2 scroll-mt-16" aria-labelledby={`h-${c.id}`}>
<h2 id={`h-${c.id}`} className="font-display text-lg font-semibold text-ink">{c.name}</h2>
{c.products.map(p => (
<ProductCard key={`${c.id}-${p.id}`} product={p} qty={lines.filter(l => l.productId === p.id).reduce((s, l) => s + l.qty, 0)}
onAdd={() => (p.quick_options?.length ? setPicking(p) : add(p))}
onRemove={() => setCart(cc => {
const i = cc.map(l => l.productId).lastIndexOf(p.id)
if (i < 0) return cc
return cc[i].qty > 1 ? cc.map((l, j) => (j === i ? { ...l, qty: l.qty - 1 } : l)) : cc.filter((_, j) => j !== i)
})} />
))}
</section>
))}
</main>
{count > 0 && service && (
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<button type="button" onClick={() => setCheckout(true)} data-testid="view-order"
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
<ShoppingBag size={20} aria-hidden="true" />
<span className="flex-1 text-left">{t('viewOrder')} · {t('items', { count })}</span>
<span>{money(subtotal)}</span>
</button>
</div>
)}
{picking && <ExtrasSheet product={picking} onClose={() => setPicking(null)} onAdd={opts => { add(picking, opts); setPicking(null) }} />}
</Shell>
)
}
function Shell({ children }) {
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
}
function ProductCard({ product, qty, onAdd, onRemove }) {
const { t, money } = useT()
const img = imageUrl(product.digital_image_url || product.image_url)
const text = productText(product)
return (
<article className="p-3 rounded-card bg-surface border border-line shadow-card flex gap-3" data-testid="product" data-product={product.id}>
{img && <img src={img} alt="" loading="lazy" className="w-20 h-20 rounded-control object-cover bg-surface-2 shrink-0" />}
<div className="flex-1 min-w-0 grid gap-1 content-start">
<h3 className="font-semibold text-ink leading-snug">{productName(product)}</h3>
{text && <p className="text-sm text-ink-2 line-clamp-2">{text}</p>}
<div className="flex items-center justify-between gap-2 mt-1">
<span className="font-semibold text-ink" data-testid="price">{money(product.price)}</span>
{!product.available ? (
<span className="text-sm font-medium text-ink-3">{t('soldOut')}</span>
) : qty > 0 ? (
<div className="flex items-center gap-1">
<button type="button" onClick={onRemove} aria-label="−" className="w-9 h-9 rounded-full bg-surface-2 text-ink flex items-center justify-center"><Minus size={16} /></button>
<span className="w-7 text-center font-semibold" data-testid="qty">{qty}</span>
<button type="button" onClick={onAdd} aria-label="+" className="w-9 h-9 rounded-full bg-accent text-accent-fg flex items-center justify-center"><Plus size={16} /></button>
</div>
) : (
<button type="button" onClick={onAdd} data-testid="add"
className="h-9 px-4 rounded-full bg-accent text-accent-fg text-sm font-semibold flex items-center gap-1"><Plus size={15} aria-hidden="true" />{t('add')}</button>
)}
</div>
</div>
</article>
)
}
function ExtrasSheet({ product, onClose, onAdd }) {
const { t, money } = useT()
const [chosen, setChosen] = useState([])
const toggle = id => setChosen(c => (c.includes(id) ? c.filter(x => x !== id) : [...c, id]))
const total = product.price + (product.quick_options ?? []).filter(o => chosen.includes(o.id)).reduce((s, o) => s + (o.price || 0), 0)
return (
<div className="fixed inset-0 z-20 flex items-end justify-center bg-ink/40" role="dialog" aria-modal="true" aria-labelledby="extras-title" onClick={onClose}>
<div className="w-full max-w-lg bg-surface rounded-t-[22px] p-4 pb-[max(1rem,env(safe-area-inset-bottom))] grid gap-3" onClick={e => e.stopPropagation()}>
<div className="flex items-center gap-2">
<h2 id="extras-title" className="flex-1 font-display text-lg font-semibold">{productName(product)}</h2>
<button type="button" onClick={onClose} aria-label={t('cancel')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><X size={18} /></button>
</div>
<p className="text-sm font-semibold text-ink-2">{t('options')}</p>
<div className="grid gap-1">
{product.quick_options.map(o => (
<label key={o.id} className="flex items-center gap-3 p-2.5 rounded-control bg-surface-2 cursor-pointer">
<input type="checkbox" checked={chosen.includes(o.id)} onChange={() => toggle(o.id)} className="w-5 h-5 accent-[rgb(var(--o-accent))]" />
<span className="flex-1">{o.name}</span>
{o.price ? <span className="text-sm text-ink-2">+{money(o.price)}</span> : null}
</label>
))}
</div>
<button type="button" onClick={() => onAdd(chosen)} data-testid="extras-add"
className="h-12 rounded-full bg-accent text-accent-fg font-semibold">{t('addToOrder')} · {money(total)}</button>
</div>
</div>
)
}
@@ -0,0 +1,99 @@
// The customer's order tracking (plan phase 3S, step S.4): /order/{site}/track/{token}. The
// token is the order's private code (the address is the customer's to keep). Polls the cloud
// until the order is done or not accepted; shows the steps, what was ordered and for when.
import { useEffect, useState } from 'react'
import { Link, useLocation, useParams } from 'react-router-dom'
import { Check, X } from 'lucide-react'
import { track } from '../api'
import { useT } from '../i18n'
import { trackSteps } from '../logic'
const POLL_MS = 8000
export default function TrackPage() {
const { site, token } = useParams()
const { t, money, lang } = useT()
const placed = useLocation().state?.placed
const [order, setOrder] = useState(null)
const [missing, setMissing] = useState(false)
useEffect(() => {
let timer
let alive = true
const poll = async () => {
try {
const o = await track(token)
if (!alive) return
setOrder(o)
if (!trackSteps(o.order_type, o.status).done) timer = setTimeout(poll, POLL_MS)
} catch (err) {
if (!alive) return
if (err?.response?.status === 404) setMissing(true)
else timer = setTimeout(poll, POLL_MS) // offline for a moment: try again
}
}
poll()
return () => { alive = false; clearTimeout(timer) }
}, [token])
if (missing) return <Page><p className="p-6 text-center text-ink-2">{t('track.notFound')}</p></Page>
if (!order) return <Page><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Page>
const { steps, at } = trackSteps(order.order_type, order.status)
const rejected = order.status === 'rejected'
const when = order.requested_for
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', { weekday: 'long', hour: '2-digit', minute: '2-digit' }).format(new Date(order.requested_for))
: null
return (
<Page>
<div className="p-4 grid gap-4" data-testid="track" data-status={order.status}>
{placed && <p className="p-3 rounded-control bg-success-soft text-success-ink font-medium">{t('track.placed')}</p>}
<header className="grid gap-1">
<h1 className="font-display text-2xl font-semibold" data-testid="track-ref">{t('track.title', { ref: order.public_ref })}</h1>
<p className="text-ink-2">{t(order.order_type === 'delivery' ? 'delivery' : 'takeaway')} · {order.requested_for ? t('track.for', { when }) : t('track.asap')}</p>
</header>
{rejected ? (
<div className="p-4 rounded-card bg-danger-soft text-danger-ink grid gap-1" role="status">
<p className="font-semibold flex items-center gap-2"><X size={18} aria-hidden="true" />{t('track.rejected')}</p>
{order.rejection_reason && <p>{t('track.reason', { reason: order.rejection_reason })}</p>}
</div>
) : (
<ol className="grid gap-0" aria-label={t('track.status.' + order.status)}>
{steps.map((s, i) => {
const done = i < at || order.status === 'delivered'
const now = i === at && order.status !== 'delivered'
return (
<li key={s} className="flex items-center gap-3 py-2" aria-current={now ? 'step' : undefined}>
<span className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 text-sm font-semibold
${done ? 'bg-accent text-accent-fg' : now ? 'bg-accent-soft text-accent-ink ring-2 ring-accent' : 'bg-surface-2 text-ink-3'}`}>
{done ? <Check size={15} aria-hidden="true" /> : i + 1}
</span>
<span className={done || now ? 'text-ink font-medium' : 'text-ink-3'}>{t(`track.status.${s}`)}</span>
</li>
)
})}
</ol>
)}
<section className="p-4 rounded-card bg-surface border border-line grid gap-1.5">
{(order.lines ?? []).map((l, i) => (
<div key={i} className="flex justify-between gap-3 text-ink-2">
<span>{l.quantity}× {l.name}{l.options?.length ? ` (${l.options.join(', ')})` : ''}</span>
<span>{money(l.unit_price * l.quantity)}</span>
</div>
))}
{order.delivery_fee > 0 && <div className="flex justify-between text-ink-2"><span>{t('fee')}</span><span>{money(order.delivery_fee)}</span></div>}
<div className="flex justify-between text-lg font-semibold pt-1 border-t border-line"><span>{t('total')}</span><span data-testid="track-total">{money(order.total)}</span></div>
</section>
{!trackSteps(order.order_type, order.status).done && <p className="text-sm text-ink-2">{t('track.keep')}</p>}
<Link to={`/${site}`} className="text-center text-accent-ink font-semibold">{t('track.newOrder')}</Link>
</div>
</Page>
)
}
function Page({ children }) {
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
}
@@ -0,0 +1,29 @@
/** @type {import('tailwindcss').Config} */
// Colours are tokens (CSS variables in src/index.css), never literals in components: one
// place to restyle the app, the same token names as the venue apps' @xenia/ui.
const c = name => `rgb(var(--o-${name}) / <alpha-value>)`
export default {
content: ['./index.html', './src/**/*.{js,jsx}'],
theme: {
extend: {
fontFamily: {
sans: ['Hanken Grotesk', 'Noto Sans', 'system-ui', 'sans-serif'],
display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'],
},
colors: {
canvas: c('canvas'),
surface: { DEFAULT: c('surface'), 2: c('surface-2') },
line: c('line'),
ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') },
accent: { DEFAULT: c('accent'), fg: c('accent-fg'), soft: c('accent-soft'), ink: c('accent-ink') },
success: { DEFAULT: c('success'), soft: c('success-soft'), ink: c('success-ink') },
warning: { soft: c('warning-soft'), ink: c('warning-ink') },
danger: { soft: c('danger-soft'), ink: c('danger-ink') },
},
borderRadius: { card: '18px', control: '12px' },
boxShadow: { card: '0 6px 18px -12px rgb(var(--o-shadow) / 0.45)', bar: '0 12px 28px -10px rgb(var(--o-shadow) / 0.6)' },
},
},
plugins: [],
}
@@ -0,0 +1,63 @@
// The online ordering app's logic (plan phase 3S, step S.4).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
addToCart, cartCount, cartLines, checkoutProblems, menuFor, orderBody, priceFor, refusal, setQty, slotDays, trackSteps,
} from '../src/logic.js'
const cola = { id: 1, name: 'Cola', sold_at: ['qr_table', 'online_takeaway', 'online_delivery'], prices: { qr_table: 3.5, online_takeaway: 2.5, online_delivery: 2.8 },
quick_options: [{ id: 7, name: 'Ice', price: 0.2 }] }
const pie = { id: 2, name: 'Pie', digital_name: 'Spinach pie', sold_at: ['online_takeaway'], prices: { online_takeaway: 4 }, digital_available: false }
const old = { id: 3, name: 'Old', digital_price: 5 }
const cats = [{ id: 10, name: 'Drinks', products: [cola] }, { id: 11, name: 'Food', products: [pie, old] }, { id: 12, name: 'Also', products: [cola] }]
test('the menu and prices per service', () => {
assert.equal(priceFor(cola, 'takeaway'), 2.5)
assert.equal(priceFor(cola, 'delivery'), 2.8)
assert.equal(priceFor(pie, 'delivery'), null)
assert.equal(priceFor(old, 'delivery'), 5)
const m = menuFor(cats, 'delivery')
assert.deepEqual(m.map(c => [c.name, c.products.map(p => [p.id, p.price, p.repeat])]), [['Drinks', [[1, 2.8, false]]], ['Food', [[3, 5, false]]], ['Also', [[1, 2.8, true]]]])
assert.equal(menuFor(cats, 'takeaway')[1].products[0].available, false)
})
test('the cart', () => {
let cart = addToCart([], cola)
cart = addToCart(cart, cola)
cart = addToCart(cart, cola, [7])
assert.deepEqual(cart.map(l => [l.key, l.qty]), [['1', 2], ['1:7', 1]])
assert.equal(cartCount(cart), 3)
const lines = cartLines(cart, [cola, pie], 'takeaway')
assert.deepEqual(lines.map(l => [l.unit, l.total, l.optionNames]), [[2.5, 5, []], [2.7, 2.7, ['Ice']]])
assert.deepEqual(cartLines(addToCart(cart, pie), [cola, pie], 'delivery').length, 2) // the pie isn't delivered
assert.deepEqual(setQty(cart, '1', 0).map(l => l.key), ['1:7'])
assert.equal(setQty(cart, '1', 500)[0].qty, 99)
})
test('checkout checks and the order body', () => {
const form = { name: ' Maria ', phone: '690 000 0000', address: '', notes: '', where: 'area', areaId: '', postcode: '', when: 'asap' }
assert.deepEqual(checkoutProblems(form, 'takeaway'), [])
assert.deepEqual(checkoutProblems(form, 'delivery', { areas: [{ id: 1 }] }), ['address', 'area'])
assert.deepEqual(checkoutProblems({ ...form, name: '', phone: 'abc' }, 'takeaway'), ['name', 'phone'])
assert.deepEqual(checkoutProblems(form, 'takeaway', { asap: false }), ['when'])
assert.deepEqual(checkoutProblems({ ...form, when: 'X' }, 'takeaway', { slots: ['X'] }), [])
const lines = cartLines(addToCart([], cola), [cola], 'delivery')
const body = orderBody({ ...form, address: 'Main sq 3', areaId: '2', notes: ' bell ' }, 'delivery', lines, { total: 4.8 })
assert.deepEqual(body, {
order_type: 'delivery', customer_name: 'Maria', customer_phone: '690 000 0000', customer_address: 'Main sq 3', customer_notes: 'bell',
area_id: 2, postcode: null, requested_for: null, items: [{ product_id: 1, quantity: 1, options: [], unit_price: 2.8 }], total: 4.8,
})
assert.equal(orderBody({ ...form, when: '2026-11-16T10:00:00+00:00' }, 'takeaway', lines, null).requested_for, '2026-11-16T10:00:00+00:00')
})
test('slots by day in the venue time zone, tracking steps, refusals', () => {
const days = slotDays(['2026-11-15T19:45:00+00:00', '2026-11-15T22:00:00+00:00'], 'Europe/Athens')
assert.deepEqual(days, [{ day: '2026-11-15', times: [{ iso: '2026-11-15T19:45:00+00:00', label: '21:45' }] },
{ day: '2026-11-16', times: [{ iso: '2026-11-15T22:00:00+00:00', label: '00:00' }] }])
assert.deepEqual(trackSteps('delivery', 'preparing'), { steps: ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered'], at: 2, done: false })
assert.equal(trackSteps('takeaway', 'ready').at, 3)
assert.deepEqual(trackSteps('takeaway', 'rejected'), { ...trackSteps('takeaway', 'rejected'), at: -1, done: true })
assert.deepEqual(refusal({ response: { status: 409, data: { detail: { code: 'order.minimum_not_met', params: { minimum: 10 } } } } }), ['minimum_not_met', { minimum: 10 }])
assert.deepEqual(refusal({ response: { status: 429, data: {} } }), ['rate', {}])
assert.deepEqual(refusal(new Error('x')), ['failed', {}])
})
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// The online ordering app (plan phase 3S, step S.4), served at /order/ next to the QR menu.
export default defineConfig({
plugins: [react()],
base: '/order/',
server: { host: '0.0.0.0', port: 5210 },
preview: { port: 5211 },
build: { outDir: 'dist' },
})
+3 -2
View File
@@ -14,7 +14,7 @@ This folder is its **own git repo**, nested inside the `xenia-pos` parent repo.
|---|---|---|---|
| `cloud_backend` | FastAPI + SQLAlchemy + SQLite (`${BACKEND_DATA}`) | 8001 | local sites (heartbeat/sync), sysadmin, connect apps |
| `sysadmin_panel` | React + Vite (`VITE_CLOUD_URL` baked in at build) | 5175 | the developer only |
| `connect_frontend` | nginx serving two SPAs: `menu-app` at `/menu/`, `manager-app` at `/manage/` | 3100 | restaurant customers (QR menu), remote managers |
| `connect_frontend` | nginx serving three SPAs: `menu-app` at `/menu/` (QR menu), `order-app` at `/order/` (online ordering: takeaway, delivery; phase 3S), `manager-app` at `/manage/` | 3100 | restaurant customers, remote managers |
TLS and domains are handled in front of these ports on the VPS (`xenia-api.bonamin.net` → cloud_backend, `xenia-admin.bonamin.net` → sysadmin panel, `registry.bonamin.net` → image registry).
@@ -26,7 +26,7 @@ TLS and domains are handled in front of these ports on the VPS (`xenia-api.bonam
| `/api/sites` | `sites.py` | admin bearer | sysadmin panel |
| `/api/heartbeat` | `heartbeat.py` | `X-Site-ID` + `X-Site-Key` | local sites |
| `/api/menu` | `menu.py` | public GET; site headers for sync | menu-app, local sites |
| `/api/orders` | `orders.py` | public create/quote/track (priced by `services/checkout.py` from the site's snapshot, never the browser's numbers); site headers for pending/synced/status (own site only) | menu-app, local sites |
| `/api/orders` | `orders.py` | public create/quote/slots/track (priced by `services/checkout.py`, fees `services/fees.py`, hours and slots `services/ordering.py`, rate-limited `services/ratelimit.py`; never the browser's numbers); site headers for pending/synced/status (own site only) | menu-app, order-app, local sites |
| `/api/manager` | `manager_auth.py` | manager bearer | manager-app, sysadmin |
| `/api/remote` | `remote_dashboard.py` | manager bearer; site headers for `POST /snapshot` | manager-app, local sites |
@@ -74,6 +74,7 @@ cd cloud_backend && uvicorn main:app --reload --port 8001
cd cloud_backend && python -m pytest tests -q # schema guards, licensing v2 (pip install -r requirements-dev.txt)
cd sysadmin_panel && npm run dev
cd connect_frontend/menu-app && npm run dev
cd connect_frontend/order-app && npm run dev && npm test # VITE_CLOUD_URL=http://localhost:8001; e2e: client-services/tests/e2e/order_app.mjs
cd connect_frontend/manager-app && npm run dev
```
+6
View File
@@ -7,6 +7,12 @@ server {
try_files $uri $uri/ /menu/index.html;
}
# Online ordering SPA (takeaway, delivery)
location /order/ {
alias /usr/share/nginx/html/order/;
try_files $uri $uri/ /order/index.html;
}
# Remote manager SPA
location /manage/ {
alias /usr/share/nginx/html/manage/;