Compare commits

..
11 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 e55157fa86 feat(menu-app): the QR menu on the customer apps' look, two languages, allergens (platform-v2 step 6.5)
- connect_frontend/menu-app rebuilt like the order app: the same tokens (index.css,
  tailwind.config.js), texts in i18n.js (en, el; the old 'ot_lang' choice carries over), pure
  logic in src/logic.js with tests (menuFor in the guest's language, QR prices, search in either
  language, cart, order body, refusals). MenuPage (menu, search, dish sheet, cart, checkout at
  the table) and ConfirmPage; App.jsx, components/primitives and OrderConfirm removed;
  react-hot-toast dropped.
- Allergens on every dish (contains on the card; contains / may contain on the dish sheet) and
  in the order app's cards too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:27:05 +02:00
bonaminandClaude Opus 5.5 9f9b882806 feat(menu-app): the QR menu and the order app in the guest's language (contract C-2 names, platform-v2 step 6.4)
The site now sends names / descriptions {el, en} per product, quick option and category
(falling back to the text as typed). The menu app maps them onto its en / gr switch (byLang);
the order app localises its menu by the guest's language (localizeMenu, tested). The menu app
also reads 6.3's allergens object (what a product contains).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:46:59 +02:00
bonaminandClaude Opus 5.5 e0158b2c72 test(cloud): the public menu carries each product's allergens (contract C-2, platform-v2 step 6.3)
The snapshot is stored as the site sends it, so `allergens` {key: contains | may_contain}
reaches GET /api/menu/{site} for the QR menu and the order app without a cloud change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:04:20 +02:00
bonaminandClaude Opus 5.5 7ee059d834 feat(sysadmin): the venue's menu and ordering links from PUBLIC_APPS_URL; 3S pack notes
Plan phase 3S, step S.99.
- SiteOut.apps_url (the cloud's PUBLIC_APPS_URL; a Site property, not stored per site).
- Sysadmin site page: the QR menu and online ordering links/QR codes are built from it
  (were a hard-coded IP and a "/menu/<site>/order" route that never existed); a note when
  PUBLIC_APPS_URL isn't set, and that table codes are printed by the venue.
- Pack README: connect_frontend and /api/menu rows for phase 3S, CL-9 (rate limits are per
  process), CL-10 (table QR tokens: hashes only).
- Test: the sysadmin gets the apps address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 01:35:50 +02:00
bonaminandClaude Opus 5.5 2835b5dc68 feat(cloud): the QR menu at the table, ordering only with a table's QR code
Plan phase 3S, step S.7.
- services/qr.py: the snapshot's `qr` {ordering, tables: [{id, label, token_hash}]} (sha256
  of each table's token; the cloud never holds the tokens). A table order (dine_in) needs
  the venue's ordering on, the site's menu_mode "order" and a valid table token: otherwise
  order.service_unavailable / 403 order.table_invalid (a forged, old or typed-in table is
  refused). The order keeps the table's id and label (online_orders.table_id, migration 0006).
- Public menu: ?t=<token> → `table` {id, label} or `table_invalid`; `table_ordering`; `qr`
  never leaves the cloud.
- Heartbeat returns `apps_url` (new setting PUBLIC_APPS_URL: where /menu/ and /order/ are
  served) so sites can print table QR codes that open the right address.
- Menu app: the table from its QR code (kept for the visit), a "Table 5" banner, ordering
  only at a real table (otherwise read-only, with a notice for an invalid code); checkout
  without a typed table number; prices are the QR menu's (sales point qr_table — it showed
  in-store prices since S.1 removed digital_price) and only products sold there; the
  confirmation page for table orders (in the kitchen); the delivery/takeaway leftovers
  removed (they have their own app since S.4); test ids for e2e.
- Tests: tests/test_qr.py (3); test_checkout's typed-table case moved there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 01:26:33 +02:00
bonaminandClaude Opus 5.5 3459c80611 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>
2026-11-15 19:31:21 +02:00
bonaminandClaude Opus 5.5 9ccb47cfd1 feat(cloud): online orders keep the delivery area's id for the site's fee check
The site checks the cloud's delivery fee with its own engine when it pulls an order (plan
phase 3S, step S.5) and needs the area by id: a name can change between a menu push and
the order. New column online_orders.delivery_area_id (migration 0004), set from the priced
cart, and in the pending-orders payload (C-4, additive).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:38:00 +02:00
bonaminandClaude Opus 5.5 b25bfcda3e 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>
2026-11-15 13:39:00 +02:00
bonaminandClaude Opus 5.5 9e8ec4c4e6 docs: CL-8 the fee engine has two copies (pack README)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:29:43 +02:00
bonaminandClaude Opus 5.5 96f16e948d feat(cloud): delivery fees and minimum orders at checkout (platform-v2 3S, S.3)
- services/fees.py: the site's fee engine, byte-identical (the site's tests check it);
  tests/fixtures/fee_cases.json: the shared cases, run here too.
- checkout: the snapshot's fees (areas, rules) at the venue's time zone; refused
  order.area_not_served / order.minimum_not_met {minimum, subtotal}; quote and order take
  area_id / postcode and return area_name, fee_rules; the order stores delivery_area.
- GET /api/menu/{site}: delivery_areas [{id, name}] for the customer; the rules and
  postcodes are never sent to the browser.
- Alembic 0003 (unreleased) gains online_orders.delivery_area.
- Tests: test_fees.py (22 shared cases + checkout fees, refusals, public menu, clock).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:28:15 +02:00
bonaminandClaude Opus 5.5 5bdd19d9fb feat(cloud): the cloud prices online orders itself; sites only touch their own data (platform-v2 3S, S.2)
- services/checkout.py: orders and quotes priced from the site's snapshot per sales point
  (prices map; older snapshots: digital_price less discount); refused: unavailable or
  not sold there, bad quantity/option/type, empty, order.price_changed when the browser's
  unit price or total differs. Nothing the browser says about money is stored.
- POST /api/orders/{site}/quote; delivery needs phone + address.
- Fixes: pending orders, menu sync and stats snapshot acted on the site_id given, not the
  authenticated site (a site could read another's orders or overwrite its menu/stats).
- Order refs are unique per site (a second site's first order failed); tracking by a
  random token GET /api/orders/track/{token}; old /status/{ref} only while unambiguous.
- Alembic 0003: online_orders sales_point, table_label, tracking_token; table rebuilt.
- menu-app: tracking link uses the token, shows the order number; tells the customer when
  the menu changed or the order failed.
- Tests: test_checkout.py (6), 0003 data migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:38:37 +02:00
64 changed files with 6769 additions and 1445 deletions
+5
View File
@@ -20,3 +20,8 @@ LATEST_VERSION=0.0.0
# Generate with: python -c "import secrets; print(secrets.token_hex(32))"
MANAGER_JWT_SECRET=change-me-manager-secret
MANAGER_JWT_EXPIRE_HOURS=72
# Where customers open the apps (connect_frontend: /menu/ QR menu, /order/ online ordering),
# e.g. https://menu.example.com. Sent to sites with the heartbeat: their table QR codes and
# ordering link point here. Empty = sites use their CLOUD_URL.
PUBLIC_APPS_URL=
+4
View File
@@ -26,6 +26,10 @@ class Settings(BaseSettings):
# Manager JWT (separate secret from admin JWT)
MANAGER_JWT_SECRET: str = "change-me-manager-secret"
MANAGER_JWT_EXPIRE_HOURS: int = 72
# Where customers open the apps (connect_frontend: /menu/, /order/), e.g. https://menu.example.com.
# Sent to sites with the heartbeat so they can print table QR codes and show their ordering
# link (phase 3S, S.7). Empty = the sites use their CLOUD_URL.
PUBLIC_APPS_URL: str = ""
model_config = {"env_file": str(_HERE / ".env")}
@@ -0,0 +1,86 @@
"""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
site's first online order failed → unique per (site_id, public_ref)
- tracking_token: the customer's tracking page used the public ref alone (ambiguous across
sites and guessable) → a random token per order (existing orders get one)
The table is rebuilt from an explicit definition (SQLite can't drop the unnamed
UNIQUE(public_ref) in place; copy_from leaves it out, the indexes are kept).
Revision ID: 0003_order_sales_point
Revises: 0002_v2_licensing
Create Date: 2026-11-15 23:00:00
"""
import secrets
from alembic import op
import sqlalchemy as sa
revision = '0003_order_sales_point'
down_revision = '0002_v2_licensing'
branch_labels = None
depends_on = None
def _base(*extra):
"""online_orders as 0001 created it, without UNIQUE(public_ref), plus `extra`."""
return sa.Table(
'online_orders', sa.MetaData(),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('public_ref', sa.String(), nullable=False),
sa.Column('order_type', sa.String(), nullable=False),
sa.Column('customer_name', sa.String(), nullable=False),
sa.Column('customer_phone', sa.String(), nullable=True),
sa.Column('customer_address', sa.Text(), nullable=True),
sa.Column('customer_notes', sa.Text(), nullable=True),
sa.Column('items_json', sa.Text(), nullable=False),
sa.Column('subtotal', sa.Float(), nullable=False),
sa.Column('delivery_fee', sa.Float(), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('rejection_reason', sa.String(), nullable=True),
sa.Column('synced_to_local', sa.Integer(), nullable=False),
sa.Column('local_order_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
*extra,
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.Index('ix_online_orders_id', 'id'),
sa.Index('ix_online_orders_site_id', 'site_id'),
sa.Index('ix_online_orders_status', 'status'),
)
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'])
batch_op.create_unique_constraint('uq_online_orders_tracking_token', ['tracking_token'])
conn = op.get_bind()
for (oid,) in conn.execute(sa.text("select id from online_orders where tracking_token is null")).fetchall():
conn.execute(sa.text("update online_orders set tracking_token = :t where id = :i"),
{"t": secrets.token_urlsafe(12), "i": oid})
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'])
@@ -0,0 +1,27 @@
"""online orders: delivery_area_id (plan phase 3S, S.5)
The site checks the cloud's delivery fee with its own engine when it pulls an order, and
needs the area by id (a name can change between a menu push and the order).
Revision ID: 0004_order_area_id
Revises: 0003_order_sales_point
Create Date: 2026-11-16 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0004_order_area_id'
down_revision = '0003_order_sales_point'
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('delivery_area_id', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('delivery_area_id')
@@ -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')
@@ -0,0 +1,24 @@
"""online orders: table_id (the QR menu at the table, plan phase 3S, S.7)
Revision ID: 0006_order_table_id
Revises: 0005_order_party_size
Create Date: 2026-11-16 23:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0006_order_table_id'
down_revision = '0005_order_party_size'
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('table_id', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('table_id')
+18 -3
View File
@@ -1,23 +1,36 @@
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.sql import func
from database import Base
class OnlineOrder(Base):
__tablename__ = "online_orders"
__table_args__ = (
UniqueConstraint("site_id", "public_ref", name="uq_online_orders_site_ref"), # S.2: per site
UniqueConstraint("tracking_token", name="uq_online_orders_tracking_token"),
)
id = Column(Integer, primary_key=True, index=True)
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)
# Human-readable reference, unique per site (e.g. "ORD-0042")
public_ref = Column(String, unique=True, nullable=False)
order_type = Column(String, nullable=False) # "delivery" | "dine_in"
public_ref = Column(String, nullable=False)
# the customer's tracking page: random, unguessable (S.2; the ref alone was ambiguous across sites)
tracking_token = Column(String, nullable=True)
order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | reservation | preorder (S.6)
# Customer info
customer_name = Column(String, nullable=False)
customer_phone = Column(String, nullable=True)
customer_address = Column(Text, nullable=True) # required for delivery
customer_notes = Column(Text, nullable=True)
table_label = Column(String, nullable=True) # the QR menu's table (S.7: from the table's QR token)
table_id = Column(Integer, nullable=True) # the site's table id, from a valid QR token (S.7)
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)
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)
# Order content — JSON array of ordered items
items_json = Column(Text, nullable=False)
@@ -30,6 +43,8 @@ class OnlineOrder(Base):
# Status lifecycle:
# pending_acceptance → accepted | rejected
# 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)
rejection_reason = Column(String, nullable=True)
+7
View File
@@ -41,3 +41,10 @@ class Site(Base):
# What the site reported it can run (heartbeat `module_catalog`, D-20): drives the editor.
module_catalog = Column(JSON, nullable=True)
module_catalog_at = Column(DateTime(timezone=True), nullable=True)
@property
def apps_url(self) -> str | None:
"""Where customers open this cloud's apps (PUBLIC_APPS_URL; phase 3S): the sysadmin's
menu and ordering links are built from it. Not stored per site."""
from config import settings
return settings.PUBLIC_APPS_URL.rstrip("/") or None
+1
View File
@@ -40,4 +40,5 @@ def heartbeat(
waiter_domain=site.waiter_domain,
site_numeric_id=site.id,
license_token=issue_license_token(site, now),
apps_url=settings.PUBLIC_APPS_URL.rstrip("/") or None,
)
+27 -5
View File
@@ -30,8 +30,9 @@ def _require_site(
# ── Public ────────────────────────────────────────────────────────────────────
@router.get("/{site_slug}")
def get_menu(site_slug: str, db: Session = Depends(get_db)):
"""Return the latest menu snapshot for a site. Used by the public menu SPA."""
def get_menu(site_slug: str, t: str | None = None, db: Session = Depends(get_db)):
"""Return the latest menu snapshot for a site. Used by the public menu SPA. `t`: a table's
QR token (S.7) → `table` {id, label}, or `table_invalid` when it isn't one of the venue's."""
site = db.query(Site).filter(Site.site_id == site_slug).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
@@ -42,7 +43,19 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)):
import json
data = json.loads(snapshot.snapshot_json)
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
from services import qr
data["table_ordering"] = qr.ordering_on(data, site) # S.7: ordering at the table (with a table's QR)
if t is not None:
table = qr.table_for(data, t)
data["table"] = table
data["table_invalid"] = table is None
data.pop("qr", None) # the tables' token hashes stay on the cloud
data["restaurant"] = {
"name": site.menu_display_name,
"tagline": {"en": site.menu_tagline_en, "gr": site.menu_tagline_gr},
@@ -71,12 +84,21 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)):
@router.post("/sync", response_model=MenuSyncResponse)
def sync_menu(body: MenuSyncRequest, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
"""Upsert the menu snapshot for this site. Called by local_backend on each sync."""
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == body.site_id).first()
"""Upsert the menu snapshot for this site. Called by local_backend on each sync. Only the
authenticated site's own (before S.2 the body's site_id was trusted: one site could
overwrite another's menu)."""
if body.site_id != site.id:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's menu")
import json
try:
json.loads(body.snapshot_json)
except ValueError:
raise HTTPException(status_code=422, detail="snapshot_json is not JSON")
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
if snapshot:
snapshot.snapshot_json = body.snapshot_json
else:
snapshot = MenuSnapshot(site_id=body.site_id, snapshot_json=body.snapshot_json)
snapshot = MenuSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
db.add(snapshot)
db.commit()
return MenuSyncResponse(ok=True)
+152 -15
View File
@@ -1,15 +1,30 @@
import json
from fastapi import APIRouter, Depends, HTTPException, Header, status
import secrets
from datetime import date, timezone
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from database import get_db
from models.site import Site
from models.online_order import OnlineOrder
from models.menu_snapshot import MenuSnapshot
from schemas.online_order import (
OnlineOrderCreate, OnlineOrderCreated, OrderStatusOut,
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest,
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest,
)
from services.checkout import CheckoutError, check_sent, price_cart
from services import ordering, qr, 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()
@@ -23,6 +38,15 @@ _TRANSITIONS: dict[str, set[str]] = {
"ready": {"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(
@@ -38,12 +62,89 @@ def _require_site(
# ── Public endpoints ──────────────────────────────────────────────────────────
@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)):
"""Customer submits an order from the public menu SPA."""
def _site_and_menu(db, site_slug):
site = db.query(Site).filter(Site.site_id == site_slug).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
snap = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
if snap is None:
raise HTTPException(status_code=409, detail={"code": "order.no_menu", "params": {}})
return site, json.loads(snap.snapshot_json)
def _priced(menu, order_type, items, area_id=None, postcode=None):
try:
return price_cart(menu, order_type, items, area_id=area_id, postcode=postcode)
except CheckoutError as e:
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.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")
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, 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]
reservation = body.order_type in ordering.RES_TYPES # S.6: a table, maybe with food
table = None
if body.order_type == "dine_in": # S.7: only from a table's QR code
if not qr.ordering_on(menu, site):
raise HTTPException(status_code=409, detail={"code": "order.service_unavailable", "params": {"service": "dine_in"}})
table = qr.table_for(menu, body.table_token)
if table is None:
raise HTTPException(status_code=403, detail={"code": "order.table_invalid", "params": {}})
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)
else:
problem = None
if problem:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
if (reservation or body.order_type in ("takeaway", "delivery")) and not (body.customer_phone or "").strip():
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
if priced is not None:
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()):
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone", "customer_address"]}})
# Atomically increment counter and generate public_ref
site.order_counter = (site.order_counter or 0) + 1
@@ -57,24 +158,57 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(
customer_phone=body.customer_phone,
customer_address=body.customer_address,
customer_notes=body.customer_notes,
items_json=json.dumps([item.model_dump() for item in body.items]),
subtotal=body.subtotal,
delivery_fee=body.delivery_fee,
total=body.total,
table_label=table["label"] if table else None,
table_id=table["id"] if table else None,
delivery_area=priced.area_name if priced else None,
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)
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None),
party_size=body.party_size if reservation else None,
sales_point=priced.sales_point if priced else None,
items_json=json.dumps([line.out() for line in priced.lines] if priced else []),
subtotal=priced.subtotal if priced else 0.0,
delivery_fee=priced.delivery_fee if priced else 0.0,
total=priced.total if priced else 0.0,
status="pending_acceptance",
)
order.tracking_token = secrets.token_urlsafe(12)
db.add(order)
db.commit()
db.refresh(order)
return OnlineOrderCreated(order_id=order.id, public_ref=order.public_ref, status=order.status)
return OnlineOrderCreated(order_id=order.id, public_ref=order.public_ref, status=order.status,
tracking_token=order.tracking_token, total=order.total)
@router.get("/track/{token}", response_model=OrderStatusOut)
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")
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,
party_size=order.party_size,
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)
def get_order_status(public_ref: str, db: Session = Depends(get_db)):
"""Customer polls this to track their order."""
order = db.query(OnlineOrder).filter(OnlineOrder.public_ref == public_ref).first()
if not order:
"""Old tracking by the public ref (menu-app links before S.2): only while the ref is unique
across sites; otherwise 404 (the new link is /track/{token})."""
orders = db.query(OnlineOrder).filter(OnlineOrder.public_ref == public_ref).limit(2).all()
if len(orders) != 1:
raise HTTPException(status_code=404, detail="Order not found")
order = orders[0]
return OrderStatusOut(
public_ref=order.public_ref,
status=order.status,
@@ -86,7 +220,10 @@ def get_order_status(public_ref: str, db: Session = Depends(get_db)):
@router.get("/pending/{site_id}", response_model=list[PendingOrderOut])
def get_pending_orders(site_id: int, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
"""Return all orders not yet synced to the local backend."""
"""Return all orders not yet synced to the local backend. Only the authenticated site's own
(before S.2 any site with a valid key could read another site's by its number)."""
if site_id != site.id:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's orders")
orders = (
db.query(OnlineOrder)
.filter(OnlineOrder.site_id == site_id, OnlineOrder.synced_to_local == 0)
@@ -128,7 +265,7 @@ def update_order_status(
if not order:
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:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+4 -2
View File
@@ -91,11 +91,13 @@ def push_stats_snapshot(
if not site or not _pwd.verify(x_site_key, site.secret_key_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid site credentials")
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == body.site_id).first()
if body.site_id != site.id: # S.2: only its own (the body's site_id was trusted before)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's stats")
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == site.id).first()
if snap:
snap.snapshot_json = body.snapshot_json
else:
snap = StatsSnapshot(site_id=body.site_id, snapshot_json=body.snapshot_json)
snap = StatsSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
db.add(snap)
db.commit()
+64 -13
View File
@@ -1,39 +1,79 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
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):
"""What the customer wants. Prices come from the venue's menu (services/checkout.py);
name and unit_price, if sent, are only compared (phase 3S, S.2)."""
product_id: int
name: str
quantity: int
unit_price: float
options: list = []
name: Optional[str] = None
unit_price: Optional[float] = None
options: list = [] # quick option ids (or {id})
class QuoteRequest(BaseModel):
order_type: str # dine_in | takeaway | delivery | preorder
items: list[OrderItemIn] = Field(max_length=100)
area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20)
class OnlineOrderCreate(BaseModel):
order_type: str # "delivery" | "dine_in"
customer_name: str
customer_phone: Optional[str] = None
customer_address: Optional[str] = None
customer_notes: Optional[str] = None
items: list[OrderItemIn]
subtotal: float
delivery_fee: float = 0.0
total: float
order_type: str # dine_in | takeaway | delivery | reservation | preorder
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_address: Optional[str] = Field(default=None, max_length=500)
customer_notes: Optional[str] = Field(default=None, max_length=1000)
customer_table: Optional[str] = Field(default=None, max_length=40) # ignored since S.7 (the token says)
table_token: Optional[str] = Field(default=None, max_length=100) # the table's QR token (S.7)
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(default_factory=list, max_length=100)
# what the customer was shown: compared, never stored as sent
subtotal: Optional[float] = None
delivery_fee: Optional[float] = None
total: Optional[float] = None
class OnlineOrderCreated(BaseModel):
order_id: int
public_ref: str
status: str
tracking_token: Optional[str] = None # the tracking page: GET /api/orders/track/{token} (S.2)
total: Optional[float] = None
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
party_size: Optional[int] = None # reservations (S.6)
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):
@@ -44,6 +84,13 @@ class PendingOrderOut(BaseModel):
customer_phone: Optional[str] = None
customer_address: Optional[str] = None
customer_notes: Optional[str] = None
table_label: Optional[str] = None # the QR menu's table (S.2)
table_id: Optional[int] = None # the site's table, from a valid QR token (S.7)
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)
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)
items_json: str
subtotal: float
delivery_fee: float
@@ -53,6 +100,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
+2
View File
@@ -56,6 +56,7 @@ class SiteOut(BaseModel):
menu_blurb_gr: str | None
menu_hours: str | None
menu_header_image_url: str | None
apps_url: str | None = None # PUBLIC_APPS_URL: the customer apps' address (phase 3S)
model_config = {"from_attributes": True}
@@ -83,3 +84,4 @@ class HeartbeatResponse(BaseModel):
latest_version: str | None = None
waiter_domain: str | None = None
site_numeric_id: int # cloud DB pk — needed by the Connect workers
apps_url: str | None = None # the customer apps' public address (S.7; table QR codes)
+194
View File
@@ -0,0 +1,194 @@
"""The cloud prices online orders itself (plan phase 3S, step S.2).
The customer's browser sends what it wants (product ids, quantities, chosen quick options);
the price of everything comes from the venue's menu snapshot (pushed by the site), for the
order's sales point. A total the browser sends is only compared: a difference means the
customer saw old prices (or edited them) and the order is refused with the current ones.
price_cart(snapshot, order_type, items) -> Priced
CheckoutError(status, code, **params) the router turns it into {"detail": {code, params}}
Snapshot product (site services/cloud_sync._push_menu_snapshot):
{id, name, digital_name, base_price, digital_price, digital_discount, digital_available,
sold_at: [sales point], prices: {sales point: price}, quick_options: [{id, name, price}]}
Snapshots from before S.2 have no `prices` / `sold_at`: every customer-app sales point, at
digital_price (or base_price) less digital_discount %.
The fee (S.3): the snapshot's `fees` {areas, rules} through services/fees.py (the same file
as the site's) at the venue's time (`timezone`). A delivery outside the venue's areas ->
order.area_not_served; below a minimum -> order.minimum_not_met {minimum, subtotal}.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from services import fees as fee_engine
# the cloud order's type → the site's sales point (core/sales_points.py)
POINT_FOR_TYPE = {
"dine_in": "qr_table",
"takeaway": "online_takeaway",
"delivery": "online_delivery",
"preorder": "online_preorder",
}
DIGITAL = tuple(POINT_FOR_TYPE.values())
MAX_QTY = 99
MAX_LINES = 100
EPS = 0.005
class CheckoutError(Exception):
def __init__(self, status: int, code: str, **params):
super().__init__(code)
self.status, self.code, self.params = status, code, params
def detail(self) -> dict:
return {"code": self.code, "params": self.params}
@dataclass
class Line:
product_id: int
name: str
quantity: int
unit_price: float
options: list = field(default_factory=list) # [{id, name, price}]
def out(self) -> dict:
return {"product_id": self.product_id, "name": self.name, "quantity": self.quantity,
"unit_price": self.unit_price, "options": self.options}
@dataclass
class Priced:
sales_point: str
lines: list
subtotal: float
delivery_fee: float
total: float
area_id: int | None = None
area_name: str | None = None
fee_rules: list = field(default_factory=list) # names of the rules that applied
def out(self) -> dict:
return {"sales_point": self.sales_point, "lines": [x.out() for x in self.lines],
"subtotal": self.subtotal, "delivery_fee": self.delivery_fee, "total": self.total,
"area_id": self.area_id, "area_name": self.area_name, "fee_rules": self.fee_rules}
def venue_clock(snapshot: dict, now: datetime | None = None) -> tuple[int, str]:
"""(weekday Mon=0, "HH:MM") at the venue, from the snapshot's time zone."""
try:
tz = ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
except Exception:
tz = ZoneInfo("Europe/Athens")
local = (now or datetime.now(timezone.utc)).astimezone(tz)
return local.weekday(), local.strftime("%H:%M")
def delivery_areas(snapshot: dict) -> list:
"""The active areas a customer picks from: [{id, name}] (no postcodes, no rules)."""
return [{"id": a.get("id"), "name": a.get("name")} for a in (snapshot.get("fees") or {}).get("areas") or []
if a.get("is_active", True)]
def products_of(snapshot: dict) -> dict[int, dict]:
out: dict[int, dict] = {}
for cat in snapshot.get("categories", []):
for p in cat.get("products", []):
if isinstance(p.get("id"), int):
out.setdefault(p["id"], p) # a product listed in several categories: once
return out
def price_at(product: dict, point: str) -> float | None:
"""The product's price at a sales point; None = not sold there."""
sold = product.get("sold_at")
if sold is not None and point not in sold:
return None
prices = product.get("prices")
if prices is not None:
value = prices.get(point)
return None if value is None else round(float(value), 2)
base = product.get("digital_price")
if base is None:
base = product.get("base_price") or 0.0
pct = product.get("digital_discount") or 0.0
return round(float(base) * (1 - float(pct) / 100.0), 2)
def _display_name(product: dict) -> str:
name = product.get("digital_name") or product.get("name") or f"#{product.get('id')}"
return name if isinstance(name, str) else str(name)
def _option_ids(raw) -> list:
out = []
for o in raw or []:
oid = o.get("id") if isinstance(o, dict) else o
if not isinstance(oid, int) or isinstance(oid, bool):
raise CheckoutError(422, "order.option_unavailable", option_id=oid)
out.append(oid)
return out
def price_cart(snapshot: dict, order_type: str, items: list[dict], area_id=None, postcode=None,
now: datetime | None = None) -> Priced:
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]; the
customer's area (picked, or by postcode) for the fee."""
point = POINT_FOR_TYPE.get(order_type)
if point is None:
raise CheckoutError(422, "order.type_invalid", order_type=order_type)
if not items:
raise CheckoutError(422, "order.empty")
if len(items) > MAX_LINES:
raise CheckoutError(422, "order.too_many_lines", max=MAX_LINES)
products = products_of(snapshot)
lines = []
for it in items:
pid, qty = it.get("product_id"), it.get("quantity")
if isinstance(qty, bool) or not isinstance(qty, int) or not 1 <= qty <= MAX_QTY:
raise CheckoutError(422, "order.quantity_invalid", product_id=pid, max=MAX_QTY)
product = products.get(pid) if isinstance(pid, int) else None
unit = price_at(product, point) if product is not None else None
if product is None or unit is None or product.get("digital_available") is False:
raise CheckoutError(409, "order.item_unavailable", product_id=pid,
name=_display_name(product) if product else None)
quick = {q.get("id"): q for q in product.get("quick_options") or [] if isinstance(q, dict)}
options = []
for oid in _option_ids(it.get("options")):
q = quick.get(oid)
if q is None:
raise CheckoutError(409, "order.option_unavailable", product_id=pid, option_id=oid)
options.append({"id": oid, "name": q.get("name"), "price": round(float(q.get("price") or 0.0), 2)})
unit = round(unit + sum(o["price"] for o in options), 2)
lines.append(Line(product_id=pid, name=_display_name(product), quantity=qty, unit_price=unit, options=options))
subtotal = round(sum(x.unit_price * x.quantity for x in lines), 2)
rules = snapshot.get("fees") or {}
weekday, hhmm = venue_clock(snapshot, now)
result = fee_engine.compute(rules.get("rules") or [], rules.get("areas") or [], sales_point=point,
subtotal=subtotal, items=sum(x.quantity for x in lines),
area_id=area_id, postcode=postcode, weekday=weekday, hhmm=hhmm)
if result["refused"] == "area_not_served":
raise CheckoutError(409, "order.area_not_served", postcode=postcode, area_id=area_id)
if result["refused"] == "minimum_not_met":
raise CheckoutError(409, "order.minimum_not_met", minimum=result["minimum"], subtotal=subtotal)
fee = result["fee"]
area = next((a for a in rules.get("areas") or [] if a.get("id") == result["area_id"]), None)
return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2),
area_id=result["area_id"], area_name=area.get("name") if area else None,
fee_rules=[a["name"] for a in result["applied"] if a["action"] != "minimum"])
def check_sent(priced: Priced, items: list[dict], total: float | None) -> None:
"""What the browser showed must be what we charge: each line's unit price (if sent) and
the total (if sent). Otherwise order.price_changed with the current prices."""
changed = total is not None and abs(float(total) - priced.total) > EPS
for sent, line in zip(items, priced.lines):
up = sent.get("unit_price")
if up is not None and abs(float(up) - line.unit_price) > EPS:
changed = True
if changed:
raise CheckoutError(409, "order.price_changed", **priced.out())
+128
View File
@@ -0,0 +1,128 @@
"""Delivery fees and minimum orders (plan phase 3S, step S.3).
ONE engine, two copies: client-services/local_backend/services/fees.py (the manager's "test
an order", the site's check of pulled orders) and cloud-service/cloud_backend/services/fees.py
(checkout). The files are identical and both repos run the same cases
(tests/fixtures/fee_cases.json); a site test fails if the copies differ. Pure Python: plain
dicts in, a dict out, no database, no clock (the caller gives the venue's weekday and time).
compute(rules, areas, *, sales_point, subtotal, items, area_id=None, postcode=None,
weekday=None, hhmm=None) -> {"fee", "refused", "minimum", "area_id", "applied"}
Areas: {id, name, postcodes: [str], is_active}. The customer's area is the one picked (by id)
or the one whose postcodes contain theirs (spaces ignored). When the venue has active areas,
a delivery to none of them is refused ("area_not_served"); with no areas, anywhere is fine.
Rules: {id, name, is_active, sort_order, sales_points: [..], area_ids: [..], subtotal_min,
subtotal_max, items_min, items_max, days: [0-6], time_from, time_to, action, value, stop}.
Inactive rules are skipped; the rest are looked at in (sort_order, id) order. A rule applies
when every condition it sets holds (empty lists / nulls = any):
sales point in sales_points · area in area_ids · subtotal_min <= subtotal < subtotal_max ·
items_min <= items <= items_max · weekday in days · time_from <= time < time_to (crosses
midnight when time_from > time_to)
What an applying rule does to the fee (which starts at 0):
set fee = value add fee += value
percent fee += subtotal × value / 100
free fee = 0 minimum refuse the order when subtotal < value
`stop`: once this rule applies, no later rule is looked at (first match wins). The fee is
never negative and is rounded to cents.
"""
from __future__ import annotations
EPS = 0.0005
ACTIONS = ("set", "add", "percent", "free", "minimum")
def _norm_postcode(value) -> str:
return "".join(str(value or "").split()).upper()
def resolve_area(areas: list, area_id=None, postcode=None):
"""The customer's active area: by id, else by postcode; None when neither matches."""
active = [a for a in areas or [] if a.get("is_active", True)]
if area_id is not None:
for a in active:
if a.get("id") == area_id:
return a
code = _norm_postcode(postcode)
if code:
for a in active:
if code in {_norm_postcode(p) for p in a.get("postcodes") or []}:
return a
return None
def _minutes(hhmm):
try:
h, m = str(hhmm).split(":")
h, m = int(h), int(m)
except (ValueError, TypeError):
return None
return h * 60 + m if 0 <= h <= 23 and 0 <= m <= 59 else None
def _in_time(rule, hhmm) -> bool:
start, end = _minutes(rule.get("time_from")), _minutes(rule.get("time_to"))
if start is None and end is None:
return True
now = _minutes(hhmm)
if now is None:
return False
start = 0 if start is None else start
end = 24 * 60 if end is None else end
return start <= now < end if start <= end else (now >= start or now < end)
def applies(rule, *, sales_point, subtotal, items, area, weekday, hhmm) -> bool:
if rule.get("sales_points") and sales_point not in rule["sales_points"]:
return False
if rule.get("area_ids") and (area is None or area.get("id") not in rule["area_ids"]):
return False
if rule.get("subtotal_min") is not None and subtotal + EPS < rule["subtotal_min"]:
return False
if rule.get("subtotal_max") is not None and subtotal + EPS >= rule["subtotal_max"]:
return False
if rule.get("items_min") is not None and items < rule["items_min"]:
return False
if rule.get("items_max") is not None and items > rule["items_max"]:
return False
if rule.get("days") and weekday not in rule["days"]:
return False
return _in_time(rule, hhmm)
def compute(rules, areas, *, sales_point, subtotal, items, area_id=None, postcode=None,
weekday=None, hhmm=None) -> dict:
area = resolve_area(areas, area_id, postcode)
result = {"fee": 0.0, "refused": None, "minimum": None, "area_id": area.get("id") if area else None, "applied": []}
if sales_point == "online_delivery" and area is None and any(a.get("is_active", True) for a in areas or []):
result["refused"] = "area_not_served"
return result
fee = 0.0
ordered = sorted((r for r in rules or [] if r.get("is_active", True) and r.get("action") in ACTIONS),
key=lambda r: (r.get("sort_order") or 0, r.get("id") or 0))
for rule in ordered:
if not applies(rule, sales_point=sales_point, subtotal=subtotal, items=items, area=area,
weekday=weekday, hhmm=hhmm):
continue
action, value = rule["action"], float(rule.get("value") or 0.0)
if action == "minimum":
if subtotal + EPS < value:
result.update(refused="minimum_not_met", minimum=round(value, 2), fee=round(max(fee, 0.0), 2))
result["applied"].append({"rule_id": rule.get("id"), "name": rule.get("name"), "action": action,
"value": value, "fee": round(max(fee, 0.0), 2)})
return result
elif action == "set":
fee = value
elif action == "add":
fee += value
elif action == "percent":
fee += subtotal * value / 100.0
elif action == "free":
fee = 0.0
result["applied"].append({"rule_id": rule.get("id"), "name": rule.get("name"), "action": action,
"value": value, "fee": round(max(fee, 0.0), 2)})
if rule.get("stop"):
break
result["fee"] = round(max(fee, 0.0), 2)
return result
+185
View File
@@ -0,0 +1,185 @@
"""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)],
"reservations": res_summary(snapshot, now)} # S.6
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", {}
# ── 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", {}
+35
View File
@@ -0,0 +1,35 @@
"""The QR menu at the table (plan phase 3S, step S.7).
Each table's QR code carries a random token the venue's server made for that table
(client-services services/table_qr.py). The menu snapshot brings, under `qr`:
{ordering: bool, tables: [{id, label, token_hash}]} token_hash = sha256(token) hex
so the cloud never holds the tokens themselves, and a token is checked by its hash. A new
QR code for a table (the venue "rotates" it) makes the old one useless at the next menu push.
Ordering at the table needs the venue's `ordering`, the site's menu_mode "order" (sysadmin)
and a valid token; otherwise the QR menu is read-only. The public menu never shows `qr`.
"""
from __future__ import annotations
import hashlib
import hmac
def token_hash(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def table_for(snapshot: dict, token: str | None) -> dict | None:
"""{id, label} of the table this token belongs to, or None."""
if not token or not isinstance(token, str) or len(token) > 100:
return None
wanted = token_hash(token)
for t in (snapshot.get("qr") or {}).get("tables") or []:
if isinstance(t, dict) and hmac.compare_digest(str(t.get("token_hash") or ""), wanted):
return {"id": t.get("id"), "label": t.get("label")}
return None
def ordering_on(snapshot: dict, site) -> bool:
return site.menu_mode == "order" and bool((snapshot.get("qr") or {}).get("ordering"))
+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
+108
View File
@@ -0,0 +1,108 @@
{
"_about": "Delivery fee cases (plan phase 3S, S.3). The SAME file in client-services/local_backend/tests/fixtures and cloud-service/cloud_backend/tests/fixtures; both repos run every case through their copy of services/fees.py.",
"areas": [
{"id": 1, "name": "Village centre", "postcodes": ["241 00"], "is_active": true},
{"id": 2, "name": "Kalamata", "postcodes": ["24100", "24131"], "is_active": true},
{"id": 3, "name": "Old area", "postcodes": ["99999"], "is_active": false}
],
"cases": [
{"name": "no rules: free",
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "fixed fee",
"rules": [{"id": 1, "name": "Delivery", "sales_points": ["online_delivery"], "action": "set", "value": 2.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 1},
"expect": {"fee": 2.5, "refused": null, "area_id": 1}},
{"name": "fixed fee does not touch takeaway",
"rules": [{"id": 1, "name": "Delivery", "sales_points": ["online_delivery"], "action": "set", "value": 2.5}],
"ctx": {"sales_point": "online_takeaway", "subtotal": 12, "items": 2},
"expect": {"fee": 0.0, "refused": null, "area_id": null}},
{"name": "by area: the far area costs more (area by postcode, spaces ignored)",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5},
{"id": 2, "name": "Kalamata", "area_ids": [2], "action": "set", "value": 3.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "postcode": "241 31"},
"expect": {"fee": 3.5, "refused": null, "area_id": 2}},
{"name": "by area: the near area keeps the base",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5},
{"id": 2, "name": "Kalamata", "area_ids": [2], "action": "set", "value": 3.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "area_id": 1},
"expect": {"fee": 1.5, "refused": null, "area_id": 1}},
{"name": "area not served (unknown postcode)",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "postcode": "11111"},
"expect": {"fee": 0.0, "refused": "area_not_served", "area_id": null}},
{"name": "an inactive area is not served",
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "area_id": 3},
"expect": {"fee": 0.0, "refused": "area_not_served", "area_id": null}},
{"name": "free above 25 (first match wins)",
"rules": [{"id": 1, "name": "Free over 25", "subtotal_min": 25, "action": "free", "stop": true, "sort_order": 0},
{"id": 2, "name": "Base", "action": "set", "value": 2.0, "sort_order": 1}],
"ctx": {"sales_point": "online_delivery", "subtotal": 30, "items": 4, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "free above 25: below it pays",
"rules": [{"id": 1, "name": "Free over 25", "subtotal_min": 25, "action": "free", "stop": true, "sort_order": 0},
{"id": 2, "name": "Base", "action": "set", "value": 2.0, "sort_order": 1}],
"ctx": {"sales_point": "online_delivery", "subtotal": 24.99, "items": 4, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "lower above 15 (subtotal range)",
"rules": [{"id": 1, "name": "Under 15", "subtotal_max": 15, "action": "set", "value": 3.0},
{"id": 2, "name": "15 and up", "subtotal_min": 15, "action": "set", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 15, "items": 2, "area_id": 1},
"expect": {"fee": 1.0, "refused": null, "area_id": 1}},
{"name": "item-count tier: a big order adds 1",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Big order", "items_min": 10, "action": "add", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 40, "items": 12, "area_id": 1},
"expect": {"fee": 3.0, "refused": null, "area_id": 1}},
{"name": "item-count tier: a small order pays the base only",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Big order", "items_min": 10, "action": "add", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 40, "items": 9, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "percent of the products",
"rules": [{"id": 1, "name": "5 %", "action": "percent", "value": 5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 33, "items": 3, "area_id": 1},
"expect": {"fee": 1.65, "refused": null, "area_id": 1}},
{"name": "minimum order refused",
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 10},
{"id": 2, "name": "Base", "action": "set", "value": 2.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 8.5, "items": 1, "area_id": 1},
"expect": {"fee": 0.0, "refused": "minimum_not_met", "minimum": 10.0, "area_id": 1}},
{"name": "minimum met: the fee rules go on",
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 10},
{"id": 2, "name": "Base", "action": "set", "value": 2.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 10, "items": 1, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "a higher minimum for the far area",
"rules": [{"id": 1, "name": "Far minimum", "area_ids": [2], "action": "minimum", "value": 15},
{"id": 2, "name": "Minimum", "action": "minimum", "value": 10}],
"ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 2},
"expect": {"fee": 0.0, "refused": "minimum_not_met", "minimum": 15.0, "area_id": 2}},
{"name": "stacking: base + late-night surcharge",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 4, "hhmm": "23:30"},
"expect": {"fee": 2.5, "refused": null, "area_id": 1}},
{"name": "time window crossing midnight, after midnight",
"rules": [{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 5, "hhmm": "01:15"},
"expect": {"fee": 0.5, "refused": null, "area_id": 1}},
{"name": "time window, outside",
"rules": [{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 5, "hhmm": "12:00"},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "weekend only",
"rules": [{"id": 1, "name": "Weekend", "days": [5, 6], "action": "set", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 2, "hhmm": "12:00"},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "an inactive rule is skipped; the fee is never negative",
"rules": [{"id": 1, "name": "Off", "is_active": false, "action": "set", "value": 9},
{"id": 2, "name": "Discount", "action": "add", "value": -2}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "a takeaway packaging fee (areas only matter for delivery)",
"rules": [{"id": 1, "name": "Packaging", "sales_points": ["online_takeaway"], "action": "set", "value": 0.3}],
"ctx": {"sales_point": "online_takeaway", "subtotal": 9, "items": 3, "postcode": "nowhere"},
"expect": {"fee": 0.3, "refused": null, "area_id": null}}
]
}
+142
View File
@@ -0,0 +1,142 @@
"""The cloud prices online orders itself; sites only touch their own data (plan phase 3S, S.2).
Done when: a tampered price or total is refused, a correct order is stored with the cloud's
prices, and one site can't read or overwrite another's data."""
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):
return {"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]}
def _menu(client, site, numeric):
"""A snapshot as the site pushes it after S.2: prices per sales point, where it's sold."""
snap = {"categories": [{"id": 1, "name": "All", "products": [
{"id": COLA, "name": "Cola 1.5L", "base_price": 3.5, "digital_price": 3.0, "digital_available": True,
"sold_at": ["qr_table", "online_takeaway", "online_delivery"],
"prices": {"qr_table": 3.0, "online_takeaway": 2.5, "online_delivery": 2.8},
"quick_options": [{"id": 7, "name": "Ice", "price": 0.2}]},
{"id": PIE, "name": "Pie", "base_price": 5.0, "digital_price": 5.0, "digital_available": True,
"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
def _venue(client, admin_h):
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
_menu(client, site, numeric)
return site, numeric
def _order(client, site, order_type="takeaway", **extra):
body = {"order_type": order_type, "customer_name": "Maria", "customer_phone": "6900000000",
"items": [{"product_id": COLA, "quantity": 2}], **extra}
return client.post(f"/api/orders/{site['site_id']}", json=body)
def _code(r):
return r.json()["detail"]["code"]
def test_the_cloud_prices_by_sales_point(client, admin_h):
site, _ = _venue(client, admin_h)
q = lambda t, items: client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": t, "items": items}) # noqa: E731
take = q("takeaway", [{"product_id": COLA, "quantity": 2, "options": [7]}]).json()
assert (take["sales_point"], take["lines"][0]["unit_price"], take["total"]) == ("online_takeaway", 2.7, 5.4)
assert q("dine_in", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 3.0
assert q("delivery", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 2.8
assert _code(q("takeaway", [{"product_id": PIE, "quantity": 1}])) == "order.item_unavailable" # QR menu only
assert _code(q("delivery", [{"product_id": SOUP, "quantity": 1}])) == "order.item_unavailable" # out of stock now
assert _code(q("takeaway", [{"product_id": 999, "quantity": 1}])) == "order.item_unavailable"
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 0}])) == "order.quantity_invalid"
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 1, "options": [8]}])) == "order.option_unavailable"
assert _code(q("teleport", [{"product_id": COLA, "quantity": 1}])) == "order.type_invalid"
assert _code(q("takeaway", [])) == "order.empty"
def test_a_tampered_order_is_refused_and_a_correct_one_stored_at_the_clouds_prices(client, admin_h):
"""The done-when, first part."""
site, numeric = _venue(client, admin_h)
r = _order(client, site, items=[{"product_id": COLA, "quantity": 2, "unit_price": 0.01}], subtotal=0.02, total=0.02)
assert r.status_code == 409 and _code(r) == "order.price_changed"
assert r.json()["detail"]["params"]["total"] == 5.0 # the current prices come back
assert _code(_order(client, site, total=1.0)) == "order.price_changed"
ok = _order(client, site, total=5.0, delivery_fee=-3, customer_table=" ")
assert ok.status_code == 201, ok.text
pending = client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()
stored = next(o for o in pending if o["public_ref"] == ok.json()["public_ref"])
assert (stored["subtotal"], stored["delivery_fee"], stored["total"], stored["sales_point"]) == (5.0, 0.0, 5.0, "online_takeaway")
assert json.loads(stored["items_json"]) == [{"product_id": COLA, "name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}]
# no total sent at all: priced by the cloud anyway (the old menu app's fields are optional)
assert _order(client, site).status_code == 201
def test_delivery_details(client, admin_h):
site, numeric = _venue(client, admin_h) # table orders: tests/test_qr.py (S.7)
assert _code(_order(client, site, "delivery")) == "order.details_missing"
assert _order(client, site, "delivery", customer_address="Main square 3").status_code == 201
def test_a_site_only_touches_its_own_data(client, admin_h):
"""The done-when, second part: a site's key can't read or overwrite another site's data."""
a, a_num = _venue(client, admin_h)
b, b_num = _venue(client, admin_h)
assert _order(client, a).status_code == 201
assert client.get(f"/api/orders/pending/{a_num}", headers=_h(b)).status_code == 403
assert client.post("/api/menu/sync", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
assert client.post("/api/remote/snapshot", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
# a's menu is intact
assert _order(client, a, total=5.0).status_code == 201
assert client.post("/api/menu/sync", headers=_h(a), json={"site_id": a_num, "snapshot_json": "not json"}).status_code == 422
def test_a_snapshot_from_before_s2_still_prices(client, admin_h):
"""A site that hasn't updated yet pushes digital_price / digital_discount only."""
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
old = {"categories": [{"id": 1, "name": "All", "products": [
{"id": COLA, "name": "Cola", "base_price": 4.0, "digital_price": None, "digital_discount": 25, "digital_available": True,
"quick_options": []}]}]}
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(old)})
r = client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "dine_in", "items": [{"product_id": COLA, "quantity": 1}]})
assert r.json()["total"] == 3.0
def test_order_numbers_per_site_and_tracking_by_token(client, admin_h):
"""Two venues both have an ORD-0001 (the second used to fail); the customer tracks their
order by its random token, and the bare number no longer identifies it."""
a, _ = _venue(client, admin_h)
b, _ = _venue(client, admin_h)
ra, rb = _order(client, a).json(), _order(client, b).json()
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']}")
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
def test_the_public_menu_carries_each_products_allergens(client, admin_h):
"""Plan step 6.3 (contract C-2): the site sends `allergens` {key: contains | may_contain} per
product; the public menu passes them to the QR menu and the order app as they are."""
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
snap = {"categories": [{"id": 1, "name": "All", "products": [
{"id": PIE, "name": "Pie", "base_price": 5.0, "digital_price": 5.0, "digital_available": True,
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": [],
"allergens": {"gluten": "contains", "sesame": "may_contain"}}]}], "ordering": ORDERING, "timezone": "Europe/Athens"}
assert client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)}).status_code == 200
menu = client.get(f"/api/menu/{site['site_id']}").json()
assert menu["categories"][0]["products"][0]["allergens"] == {"gluten": "contains", "sesame": "may_contain"}
+86
View File
@@ -0,0 +1,86 @@
"""Delivery fees at checkout (plan phase 3S, step S.3).
The engine (services/fees.py) is the site's file; both repos run the same cases
(tests/fixtures/fee_cases.json, identical in both; the site's tests check the copies match).
Done when (cloud half): the cloud charges the venue's fee and refuses an order below the minimum."""
import json
from datetime import datetime, timezone
from pathlib import Path
import pytest
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"))
@pytest.mark.parametrize("case", CASES["cases"], ids=[c["name"] for c in CASES["cases"]])
def test_shared_fee_cases(case):
from services.fees import compute
got = compute(case["rules"], CASES["areas"], **case["ctx"])
for key, value in case["expect"].items():
assert got[key] == value, (key, got)
FEES = {"areas": [{"id": 1, "name": "Centre", "postcodes": ["24100"], "is_active": True},
{"id": 2, "name": "Far", "postcodes": ["24131"], "is_active": True}],
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 5, "sales_points": ["online_delivery"]},
{"id": 2, "name": "Base", "action": "set", "value": 2, "sales_points": ["online_delivery"]},
{"id": 3, "name": "Far", "area_ids": [2], "action": "add", "value": 1.5, "sales_points": ["online_delivery"]}]}
def _venue_with_fees(client, admin_h):
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
_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, "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
def _quote(client, site, **body):
return client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "delivery", **body})
def test_the_cloud_charges_the_venues_fee(client, admin_h):
site, numeric = _venue_with_fees(client, admin_h)
q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], area_id=1).json() # 2 × 2.8 delivery price
assert (q["subtotal"], q["delivery_fee"], q["total"], q["area_name"], q["fee_rules"]) == (5.6, 2.0, 7.6, "Centre", ["Base"])
q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="241 31").json()
assert (q["delivery_fee"], q["area_name"]) == (3.5, "Far")
# the order: the fee is the cloud's, whatever the page sends; the area is stored
assert _code(_order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, delivery_fee=0, total=5.6)) == "order.price_changed"
ok = _order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, total=7.6)
assert ok.status_code == 201, ok.text
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == ok.json()["public_ref"])
assert (stored["delivery_fee"], stored["total"], stored["delivery_area"], stored["delivery_area_id"]) == (2.0, 7.6, "Centre", 1)
# takeaway: the delivery rules don't apply
assert client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "takeaway", "items": [{"product_id": COLA, "quantity": 1}]}).json()["delivery_fee"] == 0
def test_minimum_and_area_are_refused(client, admin_h):
site, _ = _venue_with_fees(client, admin_h)
r = _quote(client, site, items=[{"product_id": COLA, "quantity": 1}], area_id=1)
assert r.status_code == 409 and _code(r) == "order.minimum_not_met"
assert r.json()["detail"]["params"] == {"minimum": 5.0, "subtotal": 2.8}
assert _code(_order(client, site, "delivery", customer_address="x", area_id=1, items=[{"product_id": COLA, "quantity": 1}])) == "order.minimum_not_met"
assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="10431")) == "order.area_not_served"
assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}])) == "order.area_not_served"
def test_the_public_menu_lists_areas_but_not_the_rules(client, admin_h):
site, _ = _venue_with_fees(client, admin_h)
menu = client.get(f"/api/menu/{site['site_id']}").json()
assert menu["delivery_areas"] == [{"id": 1, "name": "Centre"}, {"id": 2, "name": "Far"}]
assert "fees" not in menu
def test_the_venue_clock():
from services.checkout import venue_clock
at = datetime(2026, 11, 15, 21, 30, tzinfo=timezone.utc) # Sunday 23:30 in Athens (UTC+2)
assert venue_clock({"timezone": "Europe/Athens"}, at) == (6, "23:30")
assert venue_clock({"timezone": "Nowhere/Bad"}, at) == (6, "23:30")
+1 -1
View File
@@ -40,7 +40,7 @@ def test_new_site_gets_default_preset_and_v2_token(client, admin_h):
site = _new_site(client, admin_h)
assert "ordering" in site["modules"]
hb = _heartbeat(client, site)
assert set(hb) == {"license_token", "latest_version", "waiter_domain", "site_numeric_id"}
assert set(hb) == {"license_token", "latest_version", "waiter_domain", "site_numeric_id", "apps_url"}
p = _decode(hb["license_token"])
assert p["v"] == 2 and p["site_id"] == site["site_id"] and p["modules"]["kds"] == {"limits": {"devices": None}}
assert {"active", "locked", "expires_at", "issued_at"} <= set(p)
+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
+70
View File
@@ -0,0 +1,70 @@
"""The QR menu at the table (plan phase 3S, step S.7): ordering only with a table's QR token
(checked by its hash from the snapshot), only when the venue allows it; the public menu says
which table the token is and never shows the hashes; a forged token is refused."""
import json
from services import qr
from test_checkout import ORDERING, PIE, _code, _h, _order, _venue
def _push_qr(client, site, numeric, ordering=True, tables=None):
menu = client.get(f"/api/menu/{site['site_id']}").json()
tables = tables if tables is not None else [{"id": 5, "label": "T5", "token_hash": qr.token_hash("tok-five")},
{"id": 6, "label": "Garden 6", "token_hash": qr.token_hash("tok-six")}]
snap = {"categories": menu["categories"], "ordering": ORDERING, "timezone": "Europe/Athens",
"qr": {"ordering": ordering, "tables": tables}}
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
def test_a_table_token_finds_its_table():
snap = {"qr": {"tables": [{"id": 5, "label": "T5", "token_hash": qr.token_hash("abc")}]}}
assert qr.table_for(snap, "abc") == {"id": 5, "label": "T5"}
assert qr.table_for(snap, "abd") is None
assert qr.table_for(snap, "") is None and qr.table_for(snap, None) is None
assert qr.table_for({}, "abc") is None
def test_ordering_at_the_table_needs_a_real_table_token(client, admin_h):
site, numeric = _venue(client, admin_h)
_push_qr(client, site, numeric)
menu = client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-five"}).json()
assert menu["table_ordering"] is True and menu["table"] == {"id": 5, "label": "T5"} and menu["table_invalid"] is False
assert "qr" not in menu # the hashes stay on the cloud
forged = client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-seven"}).json()
assert forged["table"] is None and forged["table_invalid"] is True
assert "table" not in client.get(f"/api/menu/{site['site_id']}").json()
r = _order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 2}])
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 (stored["table_id"], stored["table_label"], stored["sales_point"], stored["total"]) == (5, "T5", "qr_table", 10.0)
# a forged token, none, or a table name typed in by hand: refused
assert _code(_order(client, site, "dine_in", table_token="tok-seven", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
assert _code(_order(client, site, "dine_in", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
r = _order(client, site, "dine_in", customer_table="5", items=[{"product_id": PIE, "quantity": 1}])
assert r.status_code == 403 and _code(r) == "order.table_invalid"
# a new QR code for table 5: the old one stops working at the next push
_push_qr(client, site, numeric, tables=[{"id": 5, "label": "T5", "token_hash": qr.token_hash("tok-five-new")}])
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
assert _order(client, site, "dine_in", table_token="tok-five-new", items=[{"product_id": PIE, "quantity": 1}]).status_code == 201
def test_read_only_menus_take_no_table_orders(client, admin_h):
site, numeric = _venue(client, admin_h)
_push_qr(client, site, numeric, ordering=False)
assert client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-five"}).json()["table_ordering"] is False
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.service_unavailable"
# the venue allows it, but the sysadmin set the site's menu to view only
_push_qr(client, site, numeric, ordering=True)
r = client.put(f"/api/sites/{site['site_id']}", headers=admin_h, json={"menu_mode": "view_only"})
assert r.status_code == 200, r.text
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.service_unavailable"
def test_the_sysadmin_gets_the_apps_address(client, admin_h, monkeypatch):
from config import settings
site, _ = _venue(client, admin_h)
monkeypatch.setattr(settings, "PUBLIC_APPS_URL", "https://menu.example.com/")
got = client.get(f"/api/sites/{site['site_id']}", headers=admin_h).json()
assert got["apps_url"] == "https://menu.example.com"
+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"
+30
View File
@@ -89,3 +89,33 @@ def test_nothing_calls_create_all():
if not p.relative_to(root).as_posix().startswith(("tests/", "migrations/"))
and re.search(r"\.create_all\(", p.read_text(encoding="utf-8", errors="ignore"))]
assert bad == []
def test_0003_keeps_orders_gives_tokens_and_refs_per_site(tmp_path):
"""Existing online orders survive the table rebuild, get a tracking token, and two sites
may now both have ORD-0001 (plan phase 3S, S.2)."""
from schema import alembic_config
from alembic import command
import sqlalchemy as sa
eng = create_engine(f"sqlite:///{(tmp_path / 'c.db').as_posix()}")
with eng.begin() as conn:
command.upgrade(alembic_config(conn), "0002_v2_licensing")
for sid in (1, 2):
conn.execute(text("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, "
"license_expires_at, created_at, order_counter, menu_mode) "
"values (:i, :s, 'S', 'O', 'o@x', 'x', 1, '2027-01-01', '2026-01-01', 1, 'order')"), {"i": sid, "s": f"site-{sid}"})
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (1, 'ORD-0001', 'dine_in', 'A', '[]', 1, 0, 1, 'delivered', 1)"))
upgrade_to_head(eng)
with eng.begin() as conn:
row = conn.execute(text("select public_ref, tracking_token from online_orders")).one()
assert row[0] == "ORD-0001" and row[1]
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'B', '[]', 1, 0, 1, 'delivered', 0)"))
with pytest.raises(sa.exc.IntegrityError):
with conn.begin_nested():
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'C', '[]', 1, 0, 1, 'delivered', 0)"))
idx = {i["name"] for i in sa.inspect(conn).get_indexes("online_orders")}
eng.dispose()
assert {"ix_online_orders_site_id", "ix_online_orders_status"} <= idx
+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
+2 -1
View File
@@ -2,7 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#1f3a34" />
<title>Menu</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-33
View File
@@ -12,7 +12,6 @@
"lucide-react": "^1.14.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hot-toast": "^2.4.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
@@ -1579,12 +1578,6 @@
"node": ">=4"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -1930,15 +1923,6 @@
"node": ">=10.13.0"
}
},
"node_modules/goober": {
"version": "2.1.19",
"resolved": "https://registry.npmjs.org/goober/-/goober-2.1.19.tgz",
"integrity": "sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg==",
"license": "MIT",
"peerDependencies": {
"csstype": "^3.0.10"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -2554,23 +2538,6 @@
"react": "^18.3.1"
}
},
"node_modules/react-hot-toast": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz",
"integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==",
"license": "MIT",
"dependencies": {
"csstype": "^3.1.3",
"goober": "^2.1.16"
},
"engines": {
"node": ">=10"
},
"peerDependencies": {
"react": ">=16",
"react-dom": ">=16"
}
},
"node_modules/react-refresh": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
+2 -2
View File
@@ -6,14 +6,14 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
"preview": "vite preview",
"test": "node --test \"tests/*.test.mjs\""
},
"dependencies": {
"axios": "^1.7.9",
"lucide-react": "^1.14.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hot-toast": "^2.4.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
-13
View File
@@ -1,13 +0,0 @@
import { Routes, Route, Navigate } from 'react-router-dom'
import MenuPage from './pages/MenuPage'
import OrderConfirm from './pages/OrderConfirm'
export default function App() {
return (
<Routes>
<Route path="/:siteSlug" element={<MenuPage />} />
<Route path="/:siteSlug/confirm/:ref" element={<OrderConfirm />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
)
}
+15 -14
View File
@@ -1,20 +1,21 @@
// The cloud's public endpoints for the QR menu (cloud_backend/routers/menu.py, orders.py).
import axios from 'axios'
export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || ''
const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 })
const api = axios.create({ baseURL: CLOUD_URL })
export async function fetchMenu(siteSlug) {
const { data } = await api.get(`/api/menu/${siteSlug}`)
return data
/** The menu; with a table's QR token (phase 3S, S.7) also which table it is (`table`, or
* `table_invalid`) and whether ordering at the table is on (`table_ordering`). */
export const fetchMenu = async (site, tableToken) =>
(await api.get(`/api/menu/${encodeURIComponent(site)}`, { params: tableToken ? { t: tableToken } : {} })).data
export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data
/** The tracking link carries the order's random token (S.2); older links carry the public ref. */
export async function track(ref) {
try {
return (await api.get(`/api/orders/track/${encodeURIComponent(ref)}`)).data
} catch (err) {
if (err?.response?.status !== 404 || !/^ORD-\d+$/.test(ref)) throw err
return (await api.get(`/api/orders/status/${encodeURIComponent(ref)}`)).data
}
export async function submitOrder(siteSlug, body) {
const { data } = await api.post(`/api/orders/${siteSlug}`, body)
return data // { order_id, public_ref, status }
}
export async function fetchOrderStatus(publicRef) {
const { data } = await api.get(`/api/orders/status/${publicRef}`)
return data // { public_ref, status, rejection_reason }
}
export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`)
@@ -1,209 +0,0 @@
import {
Leaf, Sprout, Wheat, Flame, Star, ChefHat,
Minus, Plus,
} from 'lucide-react'
// ── Money helpers ────────────────────────────────────────────────────────────
export function eur(n) {
return '€' + Number(n).toFixed(2)
}
export function discountedPrice(product) {
const base = product.digital_price ?? product.base_price ?? product.price ?? 0
const pct = product.digital_discount ?? product.discountPct ?? 0
if (!pct) return base
return Math.round(base * (1 - pct / 100) * 100) / 100
}
export function basePrice(product) {
return product.digital_price ?? product.base_price ?? product.price ?? 0
}
export function hasDiscount(product) {
const pct = product.digital_discount ?? product.discountPct ?? 0
return pct > 0
}
export function discountPct(product) {
return product.digital_discount ?? product.discountPct ?? 0
}
// ── Placeholder gradient art ─────────────────────────────────────────────────
export function DishArt({ product, category, size = 'card' }) {
const hue = category?.hue ?? 40
const GlyphIcon = category?.GlyphIcon ?? null
const id = product?.id ?? 'x'
let seed = 0
for (let i = 0; i < id.length; i++) seed += id.charCodeAt(i)
const lift = (seed % 5) - 2
const c1 = `hsl(${hue} 34% ${90 + lift}%)`
const c2 = `hsl(${hue} 30% ${80 + lift}%)`
const glyphColor = `hsl(${hue} 32% 42%)`
const firstName = product?.digital_name || product?.name || '?'
const letter = typeof firstName === 'object' ? (firstName.en?.[0] ?? '?') : (firstName[0] ?? '?')
const sizeClass =
size === 'hero'
? 'self-stretch min-h-[100px] w-[100px]'
: size === 'sm'
? 'h-16 w-16'
: 'h-[92px] w-[92px]'
const iconClass = size === 'sm' ? 'h-7 w-7' : 'h-9 w-9'
return (
<div
className={`relative flex ${sizeClass} shrink-0 items-center justify-center overflow-hidden rounded-[13px]`}
style={{ background: `linear-gradient(135deg, ${c1}, ${c2})` }}
>
<span
className="absolute -right-2 -top-3 font-display text-[56px] leading-none opacity-[0.14] select-none"
style={{ color: glyphColor }}
>
{letter}
</span>
{GlyphIcon && (
<GlyphIcon
className={iconClass}
style={{ color: glyphColor, opacity: 0.62 }}
strokeWidth={1.4}
/>
)}
</div>
)
}
// ── Badge (Popular / Chef's pick) ────────────────────────────────────────────
export function Badge({ kind, t }) {
if (kind === 'popular') {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-[#f4ecd8] px-2 py-[3px] text-[10px] font-semibold uppercase tracking-[0.08em] text-[#a9842f] ring-1 ring-inset ring-[#e4d4a8]">
<Flame className="h-3 w-3" strokeWidth={2.2} />
{t?.popular ?? 'Popular'}
</span>
)
}
if (kind === 'chefs') {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-[#2d3b2d] px-2 py-[3px] text-[10px] font-semibold uppercase tracking-[0.08em] text-[#f0e9d6]">
<ChefHat className="h-3 w-3" strokeWidth={2} />
{t?.chefs ?? "Chef's pick"}
</span>
)
}
return null
}
// ── Dietary chips (with text labels) ────────────────────────────────────────
const DIET_STYLE = {
vegan: { Icon: Leaf, fg: '#3f7d4e', bg: '#e7f1e7', ring: '#c9e2cb' },
vegetarian: { Icon: Sprout, fg: '#5d7a37', bg: '#eef2e0', ring: '#d8e2bd' },
'gluten-free': { Icon: Wheat, fg: '#a9842f', bg: '#f5edd8', ring: '#e6d6a6' },
spicy: { Icon: Flame, fg: '#c2602f', bg: '#f7e6dc', ring: '#eccab3' },
}
export function DietChip({ tag, t }) {
const s = DIET_STYLE[tag]
if (!s) return null
const { Icon } = s
const label = t?.dietary?.[tag] ?? tag
return (
<span
className="inline-flex items-center gap-1 rounded-full px-[7px] py-[2px] text-[10px] font-medium ring-1 ring-inset"
style={{ color: s.fg, background: s.bg, borderColor: s.ring }}
>
<Icon className="h-[11px] w-[11px]" strokeWidth={2} />
{label}
</span>
)
}
// ── Compact tag icon badges (card title row) ─────────────────────────────────
const TAG_BADGE = {
vegan: { Icon: Leaf, fg: '#3f7d4e', bg: '#e7f1e7', ring: '#bcdcc0' },
vegetarian: { Icon: Sprout, fg: '#5d7a37', bg: '#eef2e0', ring: '#cfe0b0' },
'gluten-free': { Icon: Wheat, fg: '#9a7726', bg: '#f6edd6', ring: '#e6d49e' },
spicy: { Icon: Flame, fg: '#c2602f', bg: '#f8e6da', ring: '#eec4ac' },
}
const PRIORITY_BADGE = {
popular: { Icon: Star, fg: '#a9842f', bg: '#f6edd6', ring: '#e6d49e' },
chefs: { Icon: ChefHat, fg: '#f0e9d6', bg: '#2d3b2d', ring: '#2d3b2d' },
}
export function TagIcons({ product }) {
const items = []
const badge = product.badge ?? product.digital_badge
if (badge && PRIORITY_BADGE[badge]) items.push(PRIORITY_BADGE[badge])
const tags = product.tags ?? product.digital_tags ?? []
tags.forEach(tag => { if (TAG_BADGE[tag]) items.push(TAG_BADGE[tag]) })
const shown = items.slice(0, 3)
if (!shown.length) return null
return (
<div className="flex shrink-0 items-center gap-1 pt-[3px]">
{shown.map((s, i) => {
const { Icon } = s
return (
<span
key={i}
className="flex h-[19px] w-[19px] items-center justify-center rounded-full ring-1 ring-inset"
style={{ color: s.fg, background: s.bg, borderColor: s.ring }}
>
<Icon className="h-[11px] w-[11px]" strokeWidth={2.2} />
</span>
)
})}
</div>
)
}
// ── Price display ─────────────────────────────────────────────────────────────
export function Price({ product, large }) {
const base = basePrice(product)
const now = discountedPrice(product)
const discounted = hasDiscount(product)
return (
<div className="flex items-baseline gap-1.5">
{discounted && (
<span className="font-display text-[13px] text-[#b3aa97] line-through">{eur(base)}</span>
)}
<span
className={`font-display ${large ? 'text-[18px]' : 'text-[16px]'} font-semibold ${discounted ? 'text-[#c2602f]' : 'text-[#2d3b2d]'}`}
>
{eur(now)}
</span>
</div>
)
}
// ── Discount flag ─────────────────────────────────────────────────────────────
export function DiscountFlag({ product, t }) {
const pct = discountPct(product)
if (!pct) return null
return (
<span className="inline-flex items-center rounded-md bg-[#c2602f] px-1.5 py-[2px] font-sans text-[10px] font-bold tracking-[0.05em] text-white">
−{pct}% {t?.off ?? 'OFF'}
</span>
)
}
// ── Quantity stepper ─────────────────────────────────────────────────────────
export function Stepper({ qty, onInc, onDec }) {
return (
<div className="flex items-center gap-3 rounded-full bg-[#f3efe5] p-1 ring-1 ring-inset ring-[#e8e1d1]">
<button
onClick={onDec}
className="flex h-7 w-7 items-center justify-center rounded-full bg-white text-[#2d3b2d] shadow-sm ring-1 ring-[#e8e1d1] transition active:scale-90"
>
<Minus className="h-3.5 w-3.5" strokeWidth={2.5} />
</button>
<span className="min-w-[16px] text-center font-display text-[16px] font-semibold tabular-nums text-[#2d3b2d]">
{qty}
</span>
<button
onClick={onInc}
className="flex h-7 w-7 items-center justify-center rounded-full bg-[#2d3b2d] text-white shadow-sm transition active:scale-90"
>
<Plus className="h-3.5 w-3.5" strokeWidth={2.5} />
</button>
</div>
)
}
+97
View File
@@ -0,0 +1,97 @@
// The QR menu's texts (en, el; plan step 6.5, same shape as the order app's). The guest's choice
// is remembered on this device; the first visit follows the browser's language.
import { createContext, useContext } from 'react'
const STORE = 'xenia-menu-lang'
const OLD_STORE = 'ot_lang' // the menu app before 6.5 kept 'en' / 'gr' here
export const TEXTS = {
en: {
menu: 'Menu', loading: 'Loading the menu…', notFound: 'This menu was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.',
retry: 'Try again', language: 'Language', categories: 'Categories', search: 'Search the menu…', searchOpen: 'Search', close: 'Close',
noResults: 'No dishes found', noResultsBody: 'Try a different word.',
add: 'Add', soldOut: 'Sold out', more: 'More', less: 'Less',
allergens: 'Allergens', contains: 'Contains', mayContain: 'May contain', noAllergens: 'No allergens declared. Ask the staff if you have an allergy.',
allergenNote: 'Ask the staff if you have an allergy.',
atTable: 'Table {{table}}: order from your phone', tableInvalid: 'This QR code is no longer valid. Please ask the staff.',
orderingOff: 'Ordering from the table is not available right now. Please ask the staff.',
viewOrder: 'Your order', items_one: '{{count}} item', items_other: '{{count}} items',
yourOrder: 'Your order', empty: 'Your order is empty.', emptyBody: 'Add a few dishes to get started.', total: 'Total', continue: 'Continue', back: 'Back',
table: 'Table', checkout: 'Send to the kitchen', name: 'Your name (optional)', namePlaceholder: 'e.g. Alex', summary: 'Your order',
placeOrder: 'Place order · {{total}}', sending: 'Sending…', payNote: 'You pay at the table.',
refused: {
changed: 'Something on the menu changed since you opened it. Please reload the page and check your order.',
rate: 'Too many attempts. Please wait a few minutes.', failed: 'The order could not be sent. Please try again.',
},
track: {
pending_acceptance: 'Sending your order to the kitchen…', accepted: 'Your order is in the kitchen', rejected: 'Order not taken',
acceptedBody: 'Thank you! Your waiter will bring it to your table. Enjoy your meal.',
rejectedBody: 'We\'re sorry we couldn\'t take your order this time. Please speak to the staff.',
waiting: 'This page updates by itself. Keep it open.', reason: 'Reason: {{reason}}', failed: 'Could not load the order\'s status.', back: 'Back to the menu',
},
allergen: {
gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk',
nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs',
},
},
el: {
menu: 'Μενού', loading: 'Φόρτωση μενού…', notFound: 'Το μενού δεν βρέθηκε.', loadFailed: 'Το μενού δεν φορτώθηκε. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά.',
retry: 'Δοκιμάστε ξανά', language: 'Γλώσσα', categories: 'Κατηγορίες', search: 'Αναζήτηση στο μενού…', searchOpen: 'Αναζήτηση', close: 'Κλείσιμο',
noResults: 'Δεν βρέθηκαν πιάτα', noResultsBody: 'Δοκιμάστε άλλη λέξη.',
add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', more: 'Περισσότερο', less: 'Λιγότερο',
allergens: 'Αλλεργιογόνα', contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει', noAllergens: 'Δεν έχουν δηλωθεί αλλεργιογόνα. Ρωτήστε το προσωπικό αν έχετε αλλεργία.',
allergenNote: 'Ρωτήστε το προσωπικό αν έχετε αλλεργία.',
atTable: 'Τραπέζι {{table}}: παραγγείλτε από το κινητό σας', tableInvalid: 'Αυτό το QR δεν ισχύει πλέον. Ρωτήστε το προσωπικό.',
orderingOff: 'Η παραγγελία από το τραπέζι δεν είναι διαθέσιμη τώρα. Ρωτήστε το προσωπικό.',
viewOrder: 'Η παραγγελία σας', items_one: '{{count}} πιάτο', items_other: '{{count}} πιάτα',
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', emptyBody: 'Προσθέστε μερικά πιάτα για να ξεκινήσετε.', total: 'Σύνολο', continue: 'Συνέχεια', back: 'Πίσω',
table: 'Τραπέζι', checkout: 'Αποστολή στην κουζίνα', name: 'Το όνομά σας (προαιρετικά)', namePlaceholder: 'π.χ. Αλέξης', summary: 'Η παραγγελία σας',
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', payNote: 'Πληρώνετε στο τραπέζι.',
refused: {
changed: 'Κάτι άλλαξε στο μενού από τότε που το ανοίξατε. Ανανεώστε τη σελίδα και ελέγξτε την παραγγελία σας.',
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', failed: 'Η παραγγελία δεν στάλθηκε. Δοκιμάστε ξανά.',
},
track: {
pending_acceptance: 'Η παραγγελία σας στέλνεται στην κουζίνα…', accepted: 'Η παραγγελία σας είναι στην κουζίνα', rejected: 'Η παραγγελία δεν έγινε δεκτή',
acceptedBody: 'Ευχαριστούμε! Ο σερβιτόρος θα τη φέρει στο τραπέζι σας. Καλή όρεξη.',
rejectedBody: 'Λυπούμαστε, δεν μπορέσαμε να δεχτούμε την παραγγελία. Μιλήστε με το προσωπικό.',
waiting: 'Η σελίδα ενημερώνεται μόνη της. Κρατήστε την ανοιχτή.', reason: 'Λόγος: {{reason}}', failed: 'Δεν φορτώθηκε η κατάσταση της παραγγελίας.', back: 'Πίσω στο μενού',
},
allergen: {
gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα',
nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια',
},
},
}
export function initialLang() {
try {
const saved = localStorage.getItem(STORE)
if (saved && TEXTS[saved]) return saved
const old = localStorage.getItem(OLD_STORE)
if (old) return old === 'gr' ? 'el' : 'en'
} catch { /* private mode */ }
return (navigator.language || 'en').toLowerCase().startsWith('el') ? 'el' : 'en'
}
export function saveLang(lang) {
try { localStorage.setItem(STORE, lang) } catch { /* private mode */ }
}
/** t('a.b', {x}) with {{x}} and _one/_other plurals by `count`. */
export function translate(lang, key, params = {}) {
const dict = TEXTS[lang] ?? TEXTS.en
const find = k => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), dict)
let s = params.count != null ? find(`${key}_${params.count === 1 ? 'one' : 'other'}`) : undefined
if (s === undefined) s = find(key)
if (typeof s !== 'string') return key
return s.replace(/\{\{(\w+)\}\}/g, (_, k) => (params[k] ?? ''))
}
export const LangContext = createContext({ lang: 'en', setLang: () => {} })
export function useT() {
const { lang, setLang } = useContext(LangContext)
const money = n => new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-IE', { style: 'currency', currency: 'EUR' }).format(n ?? 0)
return { lang, setLang, t: (key, params) => translate(lang, key, params), money }
}
+28 -11
View File
@@ -2,17 +2,34 @@
@tailwind components;
@tailwind utilities;
* { box-sizing: border-box; }
body {
margin: 0;
font-family: 'Hanken Grotesk', system-ui, sans-serif;
background: radial-gradient(ellipse at top, #f3eedf 0%, #ece4d2 50%, #e6ddc8 100%);
min-height: 100dvh;
/* The app's tokens (RGB triples, used through tailwind.config.js). Light only for now. */
:root {
--o-canvas: 246 244 239;
--o-surface: 255 255 255;
--o-surface-2: 239 236 228;
--o-line: 226 221 209;
--o-ink: 28 36 33;
--o-ink-2: 88 96 92;
--o-ink-3: 140 145 140;
--o-accent: 31 58 52;
--o-accent-fg: 247 244 236;
--o-accent-soft: 222 234 228;
--o-accent-ink: 24 66 56;
--o-success: 48 120 78;
--o-success-soft: 225 242 231;
--o-success-ink: 30 92 56;
--o-warning-soft: 252 240 214;
--o-warning-ink: 124 82 10;
--o-danger-soft: 251 228 222;
--o-danger-ink: 160 50 30;
--o-shadow: 28 36 33;
color-scheme: light;
}
@layer utilities {
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
.font-display { font-family: 'Bricolage Grotesque', serif; }
html, body { background: rgb(var(--o-canvas)); color: rgb(var(--o-ink)); }
body { font-family: theme('fontFamily.sans'); -webkit-font-smoothing: antialiased; }
button { -webkit-tap-highlight-color: transparent; }
:focus-visible { outline: 3px solid rgb(var(--o-accent) / 0.45); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
+107
View File
@@ -0,0 +1,107 @@
// The QR menu's logic (plan step 6.5). Pure: unit-tested in Node (tests/logic.test.mjs).
//
// The venue's menu comes from GET /api/menu/{site}: categories with products, each with the
// prices per sales point (this app sells at `qr_table`), its texts per language (`names`,
// `descriptions`, 6.4) and allergens (6.3). The cloud prices the order itself; the numbers here
// are what the guest sees before sending.
export const QR_POINT = 'qr_table'
export const LANGS = ['el', 'en']
/** The 14 EU allergens, in the order the venue's apps list them (the site's core/allergens.py). */
export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs']
const round2 = n => Math.round(n * 100) / 100
/** A product's allergens to show: what it contains, then what it may contain (traces). */
export function allergenList(map) {
const m = map && typeof map === 'object' && !Array.isArray(map) ? map : {}
const list = Array.isArray(map) ? map.filter(k => ALLERGENS.includes(k)).map(key => ({ key, level: 'contains' })) : []
for (const level of ['contains', 'may_contain']) for (const key of ALLERGENS) if (m[key] === level) list.push({ key, level })
return list
}
/** A text in the guest's language: `texts` {el, en} from the venue (already falling back), else the base. */
const pick = (texts, lang, base) => (texts && texts[lang]) || base || ''
/**
* The menu as this app shows it: the categories with the products sold on the QR menu, each
* product's text in `lang`, its price, availability and allergens. A product listed in several
* categories shows in each (`repeat` marks the later ones, so search shows it once).
*/
export function menuFor(data, lang) {
const seen = new Set()
return (data?.categories ?? []).map(c => ({
id: String(c.id),
name: pick(c.names, lang, c.name),
products: (c.products ?? [])
.filter(p => !p.sold_at || p.sold_at.includes(QR_POINT))
.map(p => ({
id: String(p.id),
name: pick(p.names, lang, p.digital_name || p.name),
names: p.names ?? null,
baseName: p.digital_name || p.name || '',
description: pick(p.descriptions, lang, p.digital_description || p.description || ''),
price: p.prices ? (p.prices[QR_POINT] ?? 0) : (p.digital_price ?? p.base_price ?? 0),
available: p.digital_available !== false,
image: p.digital_image_url || p.image_url || null,
tags: p.tags ?? [],
allergens: allergenList(p.allergens),
repeat: seen.has(String(p.id)) || !seen.add(String(p.id)),
})),
})).filter(c => c.products.length > 0)
}
/** Lowercase, no accents: "Σουβλάκι" and "σουβλακι" match. */
export function fold(text) {
return String(text ?? '').normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim()
}
/** What a search finds, once each: by its name in either language (or as typed) or description. */
export function search(categories, query) {
const q = fold(query)
if (!q) return []
return categories.flatMap(c => c.products.filter(p => !p.repeat))
.filter(p => [p.name, p.baseName, ...Object.values(p.names ?? {}), p.description].some(s => fold(s).includes(q)))
}
/** The cart is {productId: quantity}. */
export function setQty(cart, id, qty) {
const next = { ...cart }
if (qty <= 0) delete next[id]
else next[id] = Math.min(99, qty)
return next
}
/** The cart's lines priced from the menu; products no longer on it (or sold out) are left out. */
export function cartLines(cart, categories) {
const byId = new Map(categories.flatMap(c => c.products).map(p => [p.id, p]))
return Object.entries(cart ?? {}).flatMap(([id, qty]) => {
const p = byId.get(id)
if (!p || !p.available || qty <= 0) return []
return [{ product: p, qty, total: round2(p.price * qty) }]
})
}
export const cartTotal = lines => round2(lines.reduce((s, l) => s + l.total, 0))
export const cartCount = lines => lines.reduce((s, l) => s + l.qty, 0)
/** The order as the cloud takes it: at the table its QR code names (the cloud checks the token). */
export function orderBody(lines, { tableToken, name, tableLabel, tableWord }) {
return {
order_type: 'dine_in',
table_token: tableToken,
customer_name: (name ?? '').trim() || `${tableWord} ${tableLabel ?? ''}`.trim(),
items: lines.map(l => ({ product_id: Number(l.product.id), quantity: l.qty, unit_price: l.product.price })),
total: cartTotal(lines),
}
}
/** The text key for a refused order (the cloud's error code). */
export function refusalKey(code) {
if (['order.price_changed', 'order.item_unavailable', 'order.option_unavailable'].includes(code)) return 'refused.changed'
if (code === 'order.table_invalid') return 'tableInvalid'
if (code === 'order.service_unavailable') return 'orderingOff'
if (code === 'rate.limited') return 'refused.rate'
return 'refused.failed'
}
+22 -10
View File
@@ -1,15 +1,27 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { Toaster } from 'react-hot-toast'
import App from './App'
// The QR menu (plan step 6.5): read the venue's menu, or order at a table with its QR code.
import { StrictMode, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
import './index.css'
import { initialLang, LangContext, saveLang } from './i18n'
import ConfirmPage from './pages/ConfirmPage'
import MenuPage from './pages/MenuPage'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
function App() {
const [lang, setLangState] = useState(initialLang)
const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l }
document.documentElement.lang = lang
return (
<LangContext.Provider value={{ lang, setLang }}>
<BrowserRouter basename="/menu">
<App />
<Toaster position="top-center" />
<Routes>
<Route path="/:site" element={<MenuPage />} />
<Route path="/:site/confirm/:ref" element={<ConfirmPage />} />
<Route path="*" element={<p className="p-6 text-ink-2">Xenia</p>} />
</Routes>
</BrowserRouter>
</React.StrictMode>
</LangContext.Provider>
)
}
createRoot(document.getElementById('root')).render(<StrictMode><App /></StrictMode>)
@@ -0,0 +1,55 @@
// After a table order (plan step 6.5): sending → in the kitchen, or not taken (with the
// venue's reason). Polls every 10 s until it's settled.
import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { Check, Clock, X } from 'lucide-react'
import { track } from '../api'
import { useT } from '../i18n'
const SETTLED = new Set(['accepted', 'rejected', 'delivered', 'preparing', 'ready'])
const POLL_MS = 10_000
export default function ConfirmPage() {
const { site, ref } = useParams()
const { t } = useT()
const [order, setOrder] = useState(null)
const [failed, setFailed] = useState(false)
useEffect(() => {
let timer
let stop = false
const poll = async () => {
try {
const data = await track(ref)
if (stop) return
setOrder(data)
if (!SETTLED.has(data.status)) timer = setTimeout(poll, POLL_MS)
} catch { if (!stop) setFailed(true) }
}
poll()
return () => { stop = true; clearTimeout(timer) }
}, [ref])
const status = order?.status
const state = status === 'rejected' ? 'rejected' : SETTLED.has(status) ? 'accepted' : 'pending_acceptance'
const Icon = { pending_acceptance: Clock, accepted: Check, rejected: X }[state]
const tone = { pending_acceptance: 'bg-warning-soft text-warning-ink', accepted: 'bg-success-soft text-success-ink', rejected: 'bg-danger-soft text-danger-ink' }[state]
return (
<div className="mx-auto max-w-lg min-h-dvh bg-canvas flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
<div className={`w-20 h-20 rounded-full flex items-center justify-center ${tone}`}><Icon size={38} strokeWidth={2.2} aria-hidden="true" /></div>
{order?.public_ref && <p className="text-xs font-semibold uppercase tracking-[0.2em] text-ink-3">{order.public_ref}</p>}
<h1 data-testid="confirm-status" data-status={status ?? ''} className="font-display text-2xl font-semibold text-ink leading-tight">
{failed ? t('track.failed') : t(`track.${state}`)}
</h1>
{order?.rejection_reason && <p className="text-ink-2">{t('track.reason', { reason: order.rejection_reason })}</p>}
{state === 'accepted' && <p className="max-w-xs text-ink-2">{t('track.acceptedBody')}</p>}
{state === 'rejected' && <p className="max-w-xs text-ink-2">{t('track.rejectedBody')}</p>}
{state === 'pending_acceptance' && !failed && (<>
<p className="text-sm text-ink-3">{t('track.waiting')}</p>
<div className="w-5 h-5 rounded-full border-2 border-accent border-t-transparent animate-spin" role="status" aria-label={t('track.waiting')} />
</>)}
<Link to={`/${site}`} className="mt-4 px-5 h-11 rounded-full bg-surface border border-line text-ink font-semibold flex items-center">{t('track.back')}</Link>
</div>
)
}
File diff suppressed because it is too large Load Diff
@@ -1,115 +0,0 @@
import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Check, Clock, X, ChefHat, Truck, Package, Leaf } from 'lucide-react'
import { fetchOrderStatus } from '../api'
const STATUS_CONFIG = {
pending_acceptance: { label: 'Waiting for confirmation', Icon: Clock, color: '#c9a24b', bg: '#f6edd6' },
accepted: { label: 'Order accepted!', Icon: Check, color: '#3f7d4e', bg: '#e7f1e7' },
rejected: { label: 'Order declined', Icon: X, color: '#c2602f', bg: '#f7e6dc' },
preparing: { label: 'Being prepared', Icon: ChefHat, color: '#2d3b2d', bg: '#e7ede7' },
ready: { label: 'Ready for pickup!', Icon: Package, color: '#3f7d4e', bg: '#e7f1e7' },
out_for_delivery: { label: 'Out for delivery', Icon: Truck, color: '#2d3b2d', bg: '#e7ede7' },
delivered: { label: 'Delivered!', Icon: Check, color: '#3f7d4e', bg: '#e7f1e7' },
}
const TERMINAL = new Set(['rejected', 'delivered'])
const POLL_MS = 10_000
export default function OrderConfirm() {
const { ref } = useParams()
const [orderStatus, setOrderStatus] = useState(null)
const [rejectionReason, setRejectionReason] = useState(null)
const [error, setError] = useState(false)
useEffect(() => {
let timer
async function poll() {
try {
const data = await fetchOrderStatus(ref)
setOrderStatus(data.status)
setRejectionReason(data.rejection_reason)
if (!TERMINAL.has(data.status)) {
timer = setTimeout(poll, POLL_MS)
}
} catch {
setError(true)
}
}
poll()
return () => clearTimeout(timer)
}, [ref])
const cfg = STATUS_CONFIG[orderStatus] ?? STATUS_CONFIG.pending_acceptance
const { label, Icon, color, bg } = cfg
return (
<div className="relative mx-auto min-h-dvh max-w-[480px] bg-[#faf7f0] shadow-[0_0_60px_-20px_rgba(45,42,31,0.3)] flex flex-col items-center justify-center px-6 py-12">
{/* Ornament top */}
<div className="mb-8 flex w-32 items-center gap-2">
<span className="h-px flex-1 bg-gradient-to-r from-transparent to-[#d8cfb6]" />
<Leaf className="h-3.5 w-3.5 text-[#c9a24b]" strokeWidth={1.6} />
<span className="h-px flex-1 bg-gradient-to-l from-transparent to-[#d8cfb6]" />
</div>
{/* Status icon */}
<div
className="flex h-20 w-20 items-center justify-center rounded-full"
style={{ background: bg }}
>
<Icon size={38} style={{ color }} strokeWidth={2.2} />
</div>
{/* Ref number */}
<p className="mt-5 font-sans text-[11px] font-semibold uppercase tracking-[0.22em] text-[#b3aa90]">
{ref}
</p>
{/* Status label */}
<h1 className="mt-2 font-display text-[28px] font-semibold leading-tight text-center text-[#2d3b2d]">
{error ? 'Could not load status' : label}
</h1>
{/* Rejection reason */}
{rejectionReason && (
<p className="mt-2 text-[14px] text-center text-[#7d7660]">
Reason: {rejectionReason}
</p>
)}
{/* Subtext */}
{orderStatus === 'delivered' && (
<p className="mt-3 max-w-[280px] text-center text-[14px] leading-relaxed text-[#7d7660]">
Thank you for your order! Enjoy your meal.
</p>
)}
{orderStatus === 'rejected' && (
<p className="mt-3 max-w-[280px] text-center text-[14px] leading-relaxed text-[#7d7660]">
We're sorry we couldn't take your order this time. Please try again or speak to staff.
</p>
)}
{!TERMINAL.has(orderStatus) && !error && (
<p className="mt-3 text-[13px] text-[#9a917a]">
We'll update this page automatically. Keep it open.
</p>
)}
{/* Spinner */}
{!TERMINAL.has(orderStatus) && !error && (
<div className="mt-6 flex justify-center">
<div className="h-5 w-5 rounded-full border-2 border-[#2d3b2d] border-t-transparent animate-spin" />
</div>
)}
{/* Ornament bottom */}
<div className="mt-10 flex w-32 items-center gap-2">
<span className="h-px flex-1 bg-gradient-to-r from-transparent to-[#d8cfb6]" />
<Leaf className="h-3 w-3 text-[#c9a24b]" strokeWidth={1.6} />
<span className="h-px flex-1 bg-gradient-to-l from-transparent to-[#d8cfb6]" />
</div>
</div>
)
}
+16 -38
View File
@@ -1,51 +1,29 @@
// The QR menu (plan step 6.5) on the customer apps' look: the same tokens as the order app.
/** @type {import('tailwindcss').Config} */
// Colours are tokens (CSS variables in src/index.css), never literals in components: one
// place to restyle the app, the same token names as the venue apps' @xenia/ui.
const c = name => `rgb(var(--o-${name}) / <alpha-value>)`
export default {
content: ['./index.html', './src/**/*.{js,jsx}'],
theme: {
extend: {
fontFamily: {
display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'],
sans: ['Hanken Grotesk', 'Noto Sans', 'system-ui', 'sans-serif'],
display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'],
},
colors: {
brand: {
dark: '#2d3b2d',
hover: '#26331f',
},
cream: '#faf7f0',
card: '#fcfbf7',
gold: '#c9a24b',
terracotta: '#c2602f',
sage: '#9caf88',
success: '#3f7d4e',
},
borderRadius: {
card: '20px',
section: '22px',
sheet: '24px',
},
boxShadow: {
card: '0 5px 16px -10px rgba(45,42,31,0.45)',
'card-hover': '0 10px 24px -12px rgba(45,42,31,0.5)',
cart: '0 12px 28px -8px rgba(45,59,45,0.55)',
},
keyframes: {
fade: { from: { opacity: 0 }, to: { opacity: 1 } },
slideup: {
from: { transform: 'translateY(100%)' },
to: { transform: 'translateY(0)' },
},
pop: {
'0%': { transform: 'scale(1)' },
'50%': { transform: 'scale(1.06)' },
'100%': { transform: 'scale(1)' },
},
},
animation: {
fade: 'fade 0.2s ease',
slideup: 'slideup 0.28s cubic-bezier(0.22,1,0.36,1)',
pop: 'pop 0.32s ease',
canvas: c('canvas'),
surface: { DEFAULT: c('surface'), 2: c('surface-2') },
line: c('line'),
ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') },
accent: { DEFAULT: c('accent'), fg: c('accent-fg'), soft: c('accent-soft'), ink: c('accent-ink') },
success: { DEFAULT: c('success'), soft: c('success-soft'), ink: c('success-ink') },
warning: { soft: c('warning-soft'), ink: c('warning-ink') },
danger: { soft: c('danger-soft'), ink: c('danger-ink') },
},
borderRadius: { card: '18px', control: '12px' },
boxShadow: { card: '0 6px 18px -12px rgb(var(--o-shadow) / 0.45)', bar: '0 12px 28px -10px rgb(var(--o-shadow) / 0.6)' },
},
},
plugins: [],
@@ -0,0 +1,61 @@
// The QR menu's logic (plan step 6.5).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { allergenList, cartCount, cartLines, cartTotal, fold, menuFor, orderBody, refusalKey, search, setQty } from '../src/logic.js'
const data = { categories: [
{ id: 1, name: 'Ψητά', names: { el: 'Ψητά', en: 'Grill' }, products: [
{ id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, descriptions: { el: 'Με πίτα', en: 'With pitta' },
prices: { qr_table: 3.5, online_delivery: 4 }, sold_at: ['qr_table', 'online_delivery'], allergens: { gluten: 'contains', sesame: 'may_contain' } },
{ id: 6, name: 'Μπριζόλα', prices: { qr_table: 12 }, sold_at: ['qr_table'], digital_available: false },
{ id: 7, name: 'Delivery only', prices: { online_delivery: 9 }, sold_at: ['online_delivery'] },
] },
{ id: 2, name: 'Ορεκτικά', products: [{ id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, prices: { qr_table: 3.5 }, sold_at: ['qr_table'] }] },
{ id: 3, name: 'Empty', products: [{ id: 7, name: 'x', prices: {}, sold_at: ['online_takeaway'] }] },
] }
test('the menu in the guest\'s language, the QR menu\'s prices, only what it sells', () => {
const en = menuFor(data, 'en')
assert.deepEqual(en.map(c => c.name), ['Grill', 'Ορεκτικά']) // a category without a translation: as typed
const souv = en[0].products[0]
assert.equal(souv.name, 'Pork skewer')
assert.equal(souv.description, 'With pitta')
assert.equal(souv.price, 3.5)
assert.equal(en[0].products.length, 2) // the delivery-only dish isn't here
assert.equal(en[0].products[1].available, false)
assert.equal(en[1].products[0].repeat, true) // listed twice: search shows it once
assert.equal(menuFor(data, 'el')[0].products[0].name, 'Σουβλάκι')
})
test('allergens: contains first, then may contain; older array data still read', () => {
assert.deepEqual(allergenList({ sesame: 'may_contain', milk: 'contains', pollen: 'contains' }), [{ key: 'milk', level: 'contains' }, { key: 'sesame', level: 'may_contain' }])
assert.deepEqual(allergenList(['gluten', 'dairy']), [{ key: 'gluten', level: 'contains' }])
assert.deepEqual(allergenList(null), [])
})
test('search: either language, no accents, each dish once', () => {
const en = menuFor(data, 'en')
assert.deepEqual(search(en, 'σουβλακι').map(p => p.id), ['5'])
assert.deepEqual(search(en, 'pork').map(p => p.id), ['5'])
assert.deepEqual(search(en, 'pitta').map(p => p.id), ['5'])
assert.deepEqual(search(en, ''), [])
assert.equal(fold('Σουβλάκι'), 'σουβλακι')
})
test('the cart, its total and the order the cloud takes', () => {
const en = menuFor(data, 'en')
let cart = setQty({}, '5', 2)
cart = setQty(cart, '6', 1) // sold out: left out
cart = setQty(cart, '99', 1) // not on the menu any more
const lines = cartLines(cart, en)
assert.deepEqual(lines.map(l => [l.product.id, l.qty, l.total]), [['5', 2, 7]])
assert.equal(cartTotal(lines), 7)
assert.equal(cartCount(lines), 2)
assert.deepEqual(setQty({ 5: 1 }, '5', 0), {})
assert.deepEqual(orderBody(lines, { tableToken: 'tok', name: ' ', tableLabel: '5', tableWord: 'Table' }), {
order_type: 'dine_in', table_token: 'tok', customer_name: 'Table 5', items: [{ product_id: 5, quantity: 2, unit_price: 3.5 }], total: 7,
})
assert.equal(refusalKey('order.price_changed'), 'refused.changed')
assert.equal(refusalKey('order.table_invalid'), 'tableInvalid')
assert.equal(refusalKey('nope'), 'refused.failed')
})
+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: {} } }
+15
View File
@@ -0,0 +1,15 @@
// 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}`)
/** 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
+146
View File
@@ -0,0 +1,146 @@
// 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: {
service: 'How', bookTable: 'Book a table',
book: {
party: 'People', day: 'Day', time: 'Time', none: 'No tables can be booked online right now.', noTimes: 'No free times this day. Try another day.',
food: 'Order food for when you arrive', foodHint: 'Pick dishes now: the kitchen prepares them for your arrival. You pay at the venue.',
continue: 'Continue', title: 'Book a table', tableFor_one: 'Table for {{count}}', tableFor_other: 'Table for {{count}}',
send: 'Request booking', note: 'The venue confirms your booking. You pay at the venue.', foodReady: 'Ready for when you arrive.',
},
takeaway: 'Takeaway', delivery: 'Delivery', open: 'Open now', closed: 'Closed now',
closedBody: 'You can still order for a later time.', noOrdering: 'Online ordering is not available right now.',
loading: 'Loading the menu…', notFound: 'This venue was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.',
contains: 'Contains', mayContain: 'May contain',
allergen: {
gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk',
nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs',
},
retry: 'Try again', add: 'Add', soldOut: 'Sold out', options: 'Extras', addToOrder: 'Add to order', cancel: 'Cancel',
viewOrder: 'View order', items_one: '{{count}} item', items_other: '{{count}} items',
yourOrder: 'Your order', empty: 'Your order is empty.', products: 'Products', fee: 'Delivery fee', total: 'Total',
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: {
party: 'Pick how many people.',
name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.',
area: 'Pick your area.', postcode: 'Enter your postcode.', when: 'Pick a time.',
},
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.',
party_invalid: 'We take online bookings for up to {{max}} people. Call us for larger groups.',
rate: 'Too many attempts. Please wait a few minutes.', no_menu: 'The menu is not available right now.', failed: 'Something went wrong. Please try again.',
},
track: {
booking: {
title: 'Booking {{ref}}', placed: 'Thank you! We got your booking request.',
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', delivered: 'Welcome, you\'re here',
rejected: 'The venue could not take this booking', cancelled: 'Cancelled by the venue',
},
title: 'Order {{ref}}', placed: 'Thank you! We got your order.', for: 'For {{when}}', asap: 'As soon as possible',
keep: 'Keep this page open, or save its address, to follow your order.',
status: {
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: {
service: 'Τρόπος', bookTable: 'Κράτηση τραπεζιού',
book: {
party: 'Άτομα', day: 'Ημέρα', time: 'Ώρα', none: 'Δεν γίνονται online κρατήσεις αυτή τη στιγμή.', noTimes: 'Δεν υπάρχουν ελεύθερες ώρες αυτή τη μέρα. Δοκιμάστε άλλη.',
food: 'Παραγγείλετε φαγητό για την άφιξή σας', foodHint: 'Διαλέξτε πιάτα τώρα: η κουζίνα τα ετοιμάζει για την ώρα που έρχεστε. Πληρώνετε στο κατάστημα.',
continue: 'Συνέχεια', title: 'Κράτηση τραπεζιού', tableFor_one: 'Τραπέζι για {{count}}', tableFor_other: 'Τραπέζι για {{count}}',
send: 'Αίτημα κράτησης', note: 'Το κατάστημα επιβεβαιώνει την κράτηση. Πληρώνετε στο κατάστημα.', foodReady: 'Έτοιμα για την άφιξή σας.',
},
takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα',
closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.',
loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.',
contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει',
allergen: {
gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα',
nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια',
},
retry: 'Δοκιμάστε ξανά', add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', options: 'Έξτρα', addToOrder: 'Στην παραγγελία', cancel: 'Ακύρωση',
viewOrder: 'Η παραγγελία', items_one: '{{count}} τεμάχιο', items_other: '{{count}} τεμάχια',
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', products: 'Προϊόντα', fee: 'Χρέωση διανομής', total: 'Σύνολο',
pricing: 'Υπολογισμός τιμής…', details: 'Τα στοιχεία σας', name: 'Όνομα', phone: 'Τηλέφωνο',
address: 'Οδός και αριθμός', area: 'Περιοχή', areaPick: 'Επιλέξτε περιοχή', byPostcode: 'Ή γράψτε τον Τ.Κ.',
byArea: 'Επιλογή από τη λίστα', postcode: 'Τ.Κ.', notes: 'Σημειώσεις για το κατάστημα (προαιρετικά)',
when: 'Πότε', asap: 'Το συντομότερο', pickTime: 'Επιλέξτε ώρα', today: 'Σήμερα', tomorrow: 'Αύριο',
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
problem: {
party: 'Επιλέξτε πόσα άτομα.',
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: 'Συμπληρώστε τα στοιχεία σας.',
party_invalid: 'Online κρατήσεις έως {{max}} άτομα. Για μεγαλύτερες παρέες τηλεφωνήστε μας.',
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.',
},
track: {
booking: {
title: 'Κράτηση {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε το αίτημα κράτησης.',
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', delivered: 'Καλώς ήρθατε',
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την κράτηση', cancelled: 'Ακυρώθηκε από το κατάστημα',
},
title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο',
keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.',
status: {
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; }
}
+187
View File
@@ -0,0 +1,187 @@
// 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']
// '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
/** 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
/** The 14 EU allergens (plan step 6.3), in the venue's order. */
export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs']
/** A product's allergens by level: {contains: [keys], may_contain: [keys]}. */
export function allergensOf(p) {
const m = p?.allergens && typeof p.allergens === 'object' && !Array.isArray(p.allergens) ? p.allergens : {}
return { contains: ALLERGENS.filter(k => m[k] === 'contains'), may_contain: ALLERGENS.filter(k => m[k] === 'may_contain') }
}
/**
* The menu in the guest's language (plan step 6.4): the venue sends each product's, quick option's
* and category's `names` (and `descriptions`) per menu language, already falling back to the text
* as typed; menus from older sites have none and stay as they are.
*/
export function localizeMenu(categories, lang) {
const pick = (texts, base) => (texts && texts[lang]) || base
return (categories ?? []).map(c => ({
...c,
name: pick(c.names, c.name),
products: (c.products ?? []).map(p => (p.names ? {
...p,
name: pick(p.names, p.digital_name || p.name),
digital_name: null,
digital_description: pick(p.descriptions, p.digital_description || '') || null,
quick_options: (p.quick_options ?? []).map(o => ({ ...o, name: pick(o.names, o.name) })),
} : p)),
}))
}
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
}
/** What a table booking still needs (S.6): field keys (empty = can send). */
export function bookingProblems(form, booking, partyMax = 99) {
const out = []
if (!form.name.trim()) out.push('name')
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
if (!(booking.party >= 1 && booking.party <= partyMax)) out.push('party')
if (!booking.when) out.push('when')
return out
}
/** The booking request (POST /api/orders/{site}): a table only, or with food (a preorder). */
export function bookingBody(form, booking, lines, quote) {
const food = lines.length > 0
return {
order_type: food ? 'preorder' : 'reservation',
customer_name: form.name.trim(),
customer_phone: form.phone.trim(),
customer_notes: form.notes.trim() || null,
party_size: booking.party,
requested_for: booking.when,
items: food ? itemsBody(lines) : [],
total: food ? (quote?.total ?? undefined) : undefined,
}
}
/** The tracking page's steps for an order type, and how far it got. */
export function trackSteps(orderType, status) {
if (BOOKING_TYPES.includes(orderType)) {
const steps = ['pending_acceptance', 'accepted', 'delivered']
const over = ['rejected', 'cancelled'].includes(status)
return { steps, at: over ? -1 : steps.indexOf(status), done: status === 'delivered' || over }
}
const steps = orderType === 'delivery'
? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered']
: ['pending_acceptance', 'accepted', 'preparing', 'ready', 'delivered']
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,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>
)
}
@@ -0,0 +1,235 @@
// 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.
// S.6: service 'book' = a table booking (`booking` {party, when}), with food ordered ahead
// when there are lines (priced as a pre-order); no address, no time picker here.
import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowLeft, Minus, Plus } from 'lucide-react'
import { fetchSlots, placeOrder, quote } from '../api'
import { useT } from '../i18n'
import { bookingBody, bookingProblems, 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, booking, menu, lines, setCart, onBack, onPlaced }) {
const { t, money, lang } = useT()
const book = service === 'book'
const quoteType = book ? 'preorder' : service
const areas = menu.delivery_areas ?? []
const [form, setForm] = useState(() => ({
name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(),
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 (!book && form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0])
}, [slots, form.when, book])
// the cloud prices the order whenever what affects the price changes
const quoteKey = JSON.stringify([itemsBody(lines).map(i => [i.product_id, i.quantity, i.options]), service,
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: quoteType, items: body.items, area_id: body.area_id, postcode: body.postcode })
if (mine === seq.current) setPriced({ quote: q, problem: null, pending: false })
} catch (err) {
if (mine === seq.current) setPriced({ quote: null, problem: refusal(err), pending: false })
}
}, 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 = book
? bookingProblems(form, booking, menu.ordering?.reservations?.party_max)
: checkoutProblems(form, service, { areas, asap: !!slots.asap, slots: slots.slots ?? [] })
const q = priced.quote
const canSend = book && !lines.length ? !sending : (q && !priced.pending && !priced.problem && !sending)
const tz = menu.ordering?.timezone || 'Europe/Athens'
const bookedFor = book && booking.when
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: tz }).format(new Date(booking.when))
: null
const submit = async () => {
setTried(true)
setSendProblem(null)
if (problems.length || !canSend) return
setSending(true)
try {
const body = book ? bookingBody(form, booking, lines, q) : orderBody(form, service, lines, q)
const result = await placeOrder(site, body)
try { localStorage.setItem(FORM_KEY, JSON.stringify({ name: form.name, phone: form.phone, address: form.address, postcode: form.postcode })) } catch { /* private mode */ }
onPlaced(result)
} 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">{book ? t('book.title') : `${t('yourOrder')} · ${t(service)}`}</h1>
</header>
{book && (
<section className="mx-4 mt-4 p-4 rounded-card bg-accent-soft text-accent-ink grid gap-0.5" data-testid="booking-summary">
<p className="font-semibold">{t('book.tableFor', { count: booking.party })}</p>
<p>{bookedFor}</p>
</section>
)}
<section className="p-4 grid gap-2" aria-label={t('yourOrder')}>
{lines.length === 0 && !book && <p className="text-ink-2">{t('empty')}</p>}
{lines.map(l => {
const cloudLine = q?.lines?.find(x => x.product_id === l.productId && JSON.stringify((x.options ?? []).map(o => o.id).sort()) === JSON.stringify(l.options))
return (
<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>
{!book && <Field label={t('when')} error={fieldErr('when')}>
<select className={input} value={form.when} onChange={e => set('when', e.target.value)} data-testid="f-when">
{slots.asap && <option value="asap">{t('asap')}</option>}
{!slots.asap && <option value="asap" disabled>{t('pickTime')}</option>}
{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>
{(!book || lines.length > 0) && <section className="m-4 p-4 rounded-card bg-surface border border-line grid gap-1.5" aria-live="polite" data-testid="totals"
data-total={q?.total ?? ''} data-fee={q?.delivery_fee ?? ''}>
{priced.pending && <p className="text-sm text-ink-2">{t('pricing')}</p>}
{priced.problem && <p className="text-sm font-medium text-danger-ink" role="alert" data-testid="quote-problem" data-code={priced.problem[0]}>{refusedText(t, money, priced.problem)}</p>}
{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 || (!book && !lines.length)} data-testid="place-order"
className={`h-14 rounded-full font-semibold ${canSend ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-3'}`}>
{sending ? t('sending') : book ? t('book.send') : t('placeOrder', { total: q ? money(q.total) : '…' })}
</button>
<p className="text-sm text-ink-2 text-center">{book ? t('book.note') : 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,266 @@
// 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.
// S.6: "Book a table" (when the venue takes bookings): party, day, time, and maybe food ordered
// ahead at the pre-order prices; the details and the request on the next screen.
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Bike, CalendarDays, Clock, Minus, Plus, ShoppingBag, Store, X } from 'lucide-react'
import { fetchMenu, imageUrl } from '../api'
import { useT } from '../i18n'
import { addToCart, allergensOf, cartCount, cartLines, localizeMenu, menuFor, productName, productText, SERVICES } from '../logic'
import BookingPicker from './BookingPicker'
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 [booking, setBooking] = useState({ party: 2, day: null, when: null, food: false })
const load = useCallback(async () => {
setError(null)
try {
const data = await fetchMenu(site)
setMenu(data)
setService(s => s ?? data.ordering?.services?.[0] ?? (data.ordering?.reservations?.enabled ? 'book' : 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 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(localizeMenu(menu.categories, lang), priceService) : []), [menu, priceService, lang])
const products = useMemo(() => sections.flatMap(c => c.products), [sections])
const lines = useMemo(() => (priceService ? cartLines(cart, products, priceService) : []), [cart, products, priceService])
const count = cartCount(lines)
const subtotal = lines.reduce((s, l) => s + l.total, 0)
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 res = ordering.reservations ?? { enabled: false, days: [] }
const offered = [...SERVICES.filter(s => ordering.services.includes(s)), ...(res.enabled ? ['book'] : [])]
const ICON = { delivery: Bike, takeaway: Store, book: CalendarDays }
const name = menu.restaurant?.name || site
const add = (product, options = []) => setCart(c => addToCart(c, product, options))
if (checkout && service) {
return (
<Shell>
<Checkout site={site} service={book ? 'book' : service} booking={book ? booking : null} menu={menu} lines={lines} setCart={setCart}
onBack={() => setCheckout(false)}
onPlaced={(result) => {
// cleared here too: the page unmounts before its storage effect would run
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>
{offered.length === 0 ? (
<p className="p-3 rounded-control bg-warning-soft text-warning-ink text-sm" data-testid="no-ordering">{t('noOrdering')}</p>
) : (
<>
<div className={`grid gap-2 ${offered.length === 3 ? 'grid-cols-3' : offered.length === 2 ? 'grid-cols-2' : 'grid-cols-1'}`} role="radiogroup" aria-label={t('service')}>
{offered.map(s => {
const Icon = ICON[s]
return (
<button key={s} type="button" role="radio" aria-checked={service === s} onClick={() => setService(s)} data-testid={`service-${s}`}
className={`h-12 rounded-control flex items-center justify-center gap-2 font-semibold transition-colors
${offered.length === 3 ? 'gap-1.5 px-1.5 text-sm leading-tight' : ''}
${service === s ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
<Icon size={18} aria-hidden="true" />{t(s === 'book' ? 'bookTable' : s)}
</button>
)
})}
</div>
{book ? (
<BookingPicker site={site} res={res} timeZone={ordering.timezone || 'Europe/Athens'} booking={booking} setBooking={setBooking} />
) : (
<p className={`text-sm flex items-center gap-1.5 ${ordering.open_now ? 'text-success-ink' : 'text-warning-ink'}`} data-testid="open-state">
<Clock size={15} aria-hidden="true" />
{ordering.open_now ? t('open') : `${t('closed')} · ${t('closedBody')}`}
</p>
)}
</>
)}
</header>
{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>
{book && booking.when && (
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<button type="button" onClick={() => setCheckout(true)} data-testid="book-continue"
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
<CalendarDays size={20} aria-hidden="true" />
<span className="flex-1 text-left">{t('book.continue')}{count > 0 ? ` · ${t('items', { count })}` : ''}</span>
{count > 0 && <span>{money(subtotal)}</span>}
</button>
</div>
)}
{!book && count > 0 && service && (
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<button type="button" onClick={() => setCheckout(true)} data-testid="view-order"
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
<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>}
<AllergenLine product={product} />
<div className="flex items-center justify-between gap-2 mt-1">
<span className="font-semibold text-ink" data-testid="price">{money(product.price)}</span>
{!product.available ? (
<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>
)
}
/** What a dish contains and may contain (plan steps 6.3, 6.5). */
function AllergenLine({ product }) {
const { t } = useT()
const a = allergensOf(product)
if (!a.contains.length && !a.may_contain.length) return null
return (
<p className="text-xs" data-testid="allergens">
{a.contains.length > 0 && <span className="text-warning-ink">{t('contains')}: {a.contains.map(k => t(`allergen.${k}`)).join(', ')}</span>}
{a.contains.length > 0 && a.may_contain.length > 0 && ' · '}
{a.may_contain.length > 0 && <span className="text-ink-3">{t('mayContain')}: {a.may_contain.map(k => t(`allergen.${k}`)).join(', ')}</span>}
</p>
)
}
function ExtrasSheet({ product, onClose, onAdd }) {
const { t, money } = useT()
const [chosen, setChosen] = useState([])
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,107 @@
// 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 { BOOKING_TYPES, 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' || order.status === 'cancelled'
const booked = BOOKING_TYPES.includes(order.order_type) // a table booking (S.6)
const when = order.requested_for
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', booked
? { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit', hour12: false }
: { weekday: 'long', hour: '2-digit', minute: '2-digit' }).format(new Date(order.requested_for))
: null
const st = s => t(booked ? `track.booking.${s}` : `track.status.${s}`)
return (
<Page>
<div className="p-4 grid gap-4" data-testid="track" data-status={order.status}>
{placed && <p className="p-3 rounded-control bg-success-soft text-success-ink font-medium">{t(booked ? 'track.booking.placed' : 'track.placed')}</p>}
<header className="grid gap-1">
<h1 className="font-display text-2xl font-semibold" data-testid="track-ref">{t(booked ? 'track.booking.title' : 'track.title', { ref: order.public_ref })}</h1>
<p className="text-ink-2">
{booked ? `${t('book.tableFor', { count: order.party_size ?? 1 })} · ${when}`
: `${t(order.order_type === 'delivery' ? 'delivery' : 'takeaway')} · ${order.requested_for ? t('track.for', { when }) : t('track.asap')}`}
</p>
</header>
{rejected ? (
<div className="p-4 rounded-card bg-danger-soft text-danger-ink grid gap-1" role="status">
<p className="font-semibold flex items-center gap-2"><X size={18} aria-hidden="true" />{booked ? st(order.status) : t('track.rejected')}</p>
{order.rejection_reason && <p>{t('track.reason', { reason: order.rejection_reason })}</p>}
</div>
) : (
<ol className="grid gap-0" aria-label={st(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'}>{st(s)}</span>
</li>
)
})}
</ol>
)}
{(!booked || (order.lines ?? []).length > 0) && <section className="p-4 rounded-card bg-surface border border-line grid gap-1.5">
{(order.lines ?? []).map((l, i) => (
<div key={i} className="flex justify-between gap-3 text-ink-2">
<span>{l.quantity}× {l.name}{l.options?.length ? ` (${l.options.join(', ')})` : ''}</span>
<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>
{booked && <p className="text-sm text-ink-2">{t('book.foodReady')}</p>}
</section>}
{!trackSteps(order.order_type, order.status).done && <p className="text-sm text-ink-2">{t('track.keep')}</p>}
<Link to={`/${site}`} className="text-center text-accent-ink font-semibold">{t('track.newOrder')}</Link>
</div>
</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,103 @@
// The online ordering app's logic (plan phase 3S, step S.4).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
allergensOf, localizeMenu, productName,
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', {}])
})
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)
})
test('the menu in the guest’s language (6.4): names, descriptions, extras; old menus untouched', () => {
const cats = [{ id: 1, name: 'Ψητά', names: { el: 'Ψητά', en: 'Grill' }, products: [
{ id: 5, name: 'Σουβλάκι', digital_name: 'Σουβλάκι χοιρινό', names: { el: 'Σουβλάκι χοιρινό', en: 'Pork skewer' }, descriptions: { el: 'Με πίτα', en: 'With pitta' },
quick_options: [{ id: 9, name: 'Πίτα', names: { el: 'Πίτα', en: 'Pitta' } }] },
{ id: 6, name: 'Old', digital_name: 'Old one' }] }]
const en = localizeMenu(cats, 'en')
assert.equal(en[0].name, 'Grill')
assert.equal(productName(en[0].products[0]), 'Pork skewer')
assert.equal(en[0].products[0].digital_description, 'With pitta')
assert.equal(en[0].products[0].quick_options[0].name, 'Pitta')
assert.equal(productName(en[0].products[1]), 'Old one')
assert.equal(productName(localizeMenu(cats, 'el')[0].products[0]), 'Σουβλάκι χοιρινό')
})
test('a dish\'s allergens by level (6.3)', () => {
assert.deepEqual(allergensOf({ allergens: { sesame: 'may_contain', milk: 'contains', gluten: 'contains' } }), { contains: ['gluten', 'milk'], may_contain: ['sesame'] })
assert.deepEqual(allergensOf({ allergens: ['gluten'] }), { contains: [], may_contain: [] })
})
+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' },
})
+10 -3
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/` (the QR menu: read, or order at a table with its QR code), `order-app` at `/order/` (online ordering: takeaway, delivery, table bookings; phase 3S), `manager-app` at `/manage/`. Public address = `PUBLIC_APPS_URL` (cloud `.env`), sent to sites with the heartbeat | 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).
@@ -25,8 +25,8 @@ TLS and domains are handled in front of these ports on the VPS (`xenia-api.bonam
| `/api/auth` | `auth.py` | admin login | sysadmin panel |
| `/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/status; site headers for pending/synced/status | menu-app, local sites |
| `/api/menu` | `menu.py` | public GET (`?t=` a table's QR token → `table`; the snapshot's `fees` and `qr` never leave the cloud); site headers for sync | menu-app, order-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` (bookings: `res_*`, `/reservation-slots`), table codes `services/qr.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 |
@@ -56,6 +56,12 @@ If the cloud is down, restaurants must keep taking orders (global Rule 8). Don't
**CL-6. The license signing key is permanent.**
`LICENSE_SIGNING_KEY` (cloud `.env`) signs every site's license. Its public half is built into the site code. Never regenerate or lose it: a new key means every site needs a new image. Keep the backup at `%USERPROFILE%\.xenia\license_signing_key.txt` safe. Never add fields to the token payload that old sites would misread; bump `v` for incompatible changes.
**CL-9. Rate limits live in the process.** `services/ratelimit.py` counts per caller address in memory: right for the one uvicorn process the image runs. If the cloud ever runs several workers or replicas, move the counters to a shared store first, or each worker allows the full rate.
**CL-10. Table QR tokens are the site's secret.** The cloud only receives their sha256 (`qr.tables[].token_hash`) and compares in constant time (`services/qr.py`). Never store or log a token the cloud receives, and never return `qr` from a public endpoint.
**CL-8. The fee engine has two copies.** `cloud_backend/services/fees.py` is byte-identical to the site's `local_backend/services/fees.py` (the cloud charges what the manager's "test an order" shows). Change both, and `tests/fixtures/fee_cases.json` in both repos; the site's `tests/test_fees.py` compares them.
**CL-5. Frontend URLs are baked in at build time.**
`VITE_CLOUD_URL` is a build arg, so changing it means rebuilding the image, not restarting it.
@@ -72,6 +78,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/;
+9 -5
View File
@@ -466,9 +466,12 @@ export default function SiteDetailPage() {
{/* QR Codes */}
{(() => {
// the customer apps' address comes from the cloud (PUBLIC_APPS_URL, phase 3S); the
// tables' own QR codes (ordering at a table) are printed by the venue's manager
const slug = site.site_id
const menuUrl = `http://72.61.191.197:3100/menu/${slug}`
const orderUrl = `http://72.61.191.197:3100/menu/${slug}/order`
const base = site.apps_url || import.meta.env.VITE_CLOUD_URL || window.location.origin
const menuUrl = `${base}/menu/${slug}`
const orderUrl = `${base}/order/${slug}`
function handleDownload(canvasId, filename) {
const canvas = document.getElementById(canvasId)
@@ -482,11 +485,12 @@ export default function SiteDetailPage() {
return (
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 mt-4">
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">QR Codes</h2>
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">QR Codes</h2>
<p className="text-xs text-gray-500 mb-4">{site.apps_url ? '' : 'PUBLIC_APPS_URL is not set on the cloud: these links use the API address. '}Table codes (ordering at a table) are printed by the venue: manager → Table QR codes.</p>
<div className="flex flex-wrap gap-8">
{[
{ id: `qr-menu-${site.id}`, url: menuUrl, label: 'Menu QR Code', file: `menu-qr-${slug}.png` },
{ id: `qr-order-${site.id}`, url: orderUrl, label: 'Order QR Code', file: `order-qr-${slug}.png` },
{ id: `qr-menu-${site.id}`, url: menuUrl, label: 'QR menu (to read)', file: `menu-qr-${slug}.png` },
{ id: `qr-order-${site.id}`, url: orderUrl, label: 'Online ordering (takeaway, delivery, bookings)', file: `order-qr-${slug}.png` },
].map(({ id, url, label, file }) => (
<div key={id} className="flex flex-col items-center gap-3">
<p className="text-xs font-medium text-gray-400">{label}</p>