From 2835b5dc68da0124890af750806ff7adf2e55ddc Mon Sep 17 00:00:00 2001 From: bonamin Date: Mon, 16 Nov 2026 01:26:33 +0200 Subject: [PATCH] feat(cloud): the QR menu at the table, ordering only with a table's QR code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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= → `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 --- cloud_backend/.env.example | 5 + cloud_backend/config.py | 4 + .../versions/0006_order_table_id.py | 24 +++++ cloud_backend/models/online_order.py | 3 +- cloud_backend/routers/heartbeat.py | 1 + cloud_backend/routers/menu.py | 12 ++- cloud_backend/routers/orders.py | 12 ++- cloud_backend/schemas/online_order.py | 4 +- cloud_backend/schemas/site.py | 1 + cloud_backend/services/qr.py | 35 +++++++ cloud_backend/tests/test_checkout.py | 9 +- cloud_backend/tests/test_licensing_v2.py | 2 +- cloud_backend/tests/test_qr.py | 62 ++++++++++++ connect_frontend/menu-app/src/api.js | 6 +- .../menu-app/src/components/primitives.jsx | 18 ++-- .../menu-app/src/pages/MenuPage.jsx | 97 ++++++++++++------- .../menu-app/src/pages/OrderConfirm.jsx | 24 +++-- 17 files changed, 245 insertions(+), 74 deletions(-) create mode 100644 cloud_backend/migrations/versions/0006_order_table_id.py create mode 100644 cloud_backend/services/qr.py create mode 100644 cloud_backend/tests/test_qr.py diff --git a/cloud_backend/.env.example b/cloud_backend/.env.example index 38c8d8f..a954870 100644 --- a/cloud_backend/.env.example +++ b/cloud_backend/.env.example @@ -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= diff --git a/cloud_backend/config.py b/cloud_backend/config.py index ae4a1a4..fa52f89 100644 --- a/cloud_backend/config.py +++ b/cloud_backend/config.py @@ -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")} diff --git a/cloud_backend/migrations/versions/0006_order_table_id.py b/cloud_backend/migrations/versions/0006_order_table_id.py new file mode 100644 index 0000000..55490c7 --- /dev/null +++ b/cloud_backend/migrations/versions/0006_order_table_id.py @@ -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') diff --git a/cloud_backend/models/online_order.py b/cloud_backend/models/online_order.py index 2b78807..0b660fc 100644 --- a/cloud_backend/models/online_order.py +++ b/cloud_backend/models/online_order.py @@ -24,7 +24,8 @@ class OnlineOrder(Base): 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, as the customer gave it + 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 diff --git a/cloud_backend/routers/heartbeat.py b/cloud_backend/routers/heartbeat.py index 1a2c58e..9dca8c1 100644 --- a/cloud_backend/routers/heartbeat.py +++ b/cloud_backend/routers/heartbeat.py @@ -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, ) diff --git a/cloud_backend/routers/menu.py b/cloud_backend/routers/menu.py index 390c9a6..d7acb7f 100644 --- a/cloud_backend/routers/menu.py +++ b/cloud_backend/routers/menu.py @@ -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") @@ -48,6 +49,13 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)): 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}, diff --git a/cloud_backend/routers/orders.py b/cloud_backend/routers/orders.py index 9d49e81..954a565 100644 --- a/cloud_backend/routers/orders.py +++ b/cloud_backend/routers/orders.py @@ -14,7 +14,7 @@ from schemas.online_order import ( PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest, ) from services.checkout import CheckoutError, check_sent, price_cart -from services import ordering, ratelimit +from services import ordering, qr, ratelimit # public endpoints, per caller address (CL-4) QUOTE_LIMIT = (120, 60) # 120 quotes a minute @@ -115,6 +115,13 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db: 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": {}}) @@ -151,7 +158,8 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db: customer_phone=body.customer_phone, customer_address=body.customer_address, customer_notes=body.customer_notes, - table_label=(body.customer_table or "").strip() or None, + 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) diff --git a/cloud_backend/schemas/online_order.py b/cloud_backend/schemas/online_order.py index 9f18188..4f33769 100644 --- a/cloud_backend/schemas/online_order.py +++ b/cloud_backend/schemas/online_order.py @@ -37,7 +37,8 @@ class OnlineOrderCreate(BaseModel): 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) + 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 @@ -84,6 +85,7 @@ class PendingOrderOut(BaseModel): 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 diff --git a/cloud_backend/schemas/site.py b/cloud_backend/schemas/site.py index 6139387..300686f 100644 --- a/cloud_backend/schemas/site.py +++ b/cloud_backend/schemas/site.py @@ -83,3 +83,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) diff --git a/cloud_backend/services/qr.py b/cloud_backend/services/qr.py new file mode 100644 index 0000000..36b5265 --- /dev/null +++ b/cloud_backend/services/qr.py @@ -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")) diff --git a/cloud_backend/tests/test_checkout.py b/cloud_backend/tests/test_checkout.py index 47f2461..b2e402c 100644 --- a/cloud_backend/tests/test_checkout.py +++ b/cloud_backend/tests/test_checkout.py @@ -81,13 +81,8 @@ def test_a_tampered_order_is_refused_and_a_correct_one_stored_at_the_clouds_pric assert _order(client, site).status_code == 201 -def test_the_qr_menus_table_and_delivery_details(client, admin_h): - site, numeric = _venue(client, admin_h) - r = _order(client, site, "dine_in", customer_table="5", items=[{"product_id": PIE, "quantity": 1}]) - assert r.status_code == 201 - 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_label"], stored["sales_point"]) == ("5", "qr_table") +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 diff --git a/cloud_backend/tests/test_licensing_v2.py b/cloud_backend/tests/test_licensing_v2.py index 95d3db3..12b2e67 100644 --- a/cloud_backend/tests/test_licensing_v2.py +++ b/cloud_backend/tests/test_licensing_v2.py @@ -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) diff --git a/cloud_backend/tests/test_qr.py b/cloud_backend/tests/test_qr.py new file mode 100644 index 0000000..0000070 --- /dev/null +++ b/cloud_backend/tests/test_qr.py @@ -0,0 +1,62 @@ +"""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" diff --git a/connect_frontend/menu-app/src/api.js b/connect_frontend/menu-app/src/api.js index 0ff9d6a..0a1280b 100644 --- a/connect_frontend/menu-app/src/api.js +++ b/connect_frontend/menu-app/src/api.js @@ -4,8 +4,10 @@ export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || '' const api = axios.create({ baseURL: CLOUD_URL }) -export async function fetchMenu(siteSlug) { - const { data } = await api.get(`/api/menu/${siteSlug}`) +/** The menu; with a table's QR token (phase 3S, S.7) it also says which table it is + * (`table`, or `table_invalid`) and whether ordering at the table is on (`table_ordering`). */ +export async function fetchMenu(siteSlug, tableToken) { + const { data } = await api.get(`/api/menu/${siteSlug}`, { params: tableToken ? { t: tableToken } : {} }) return data } diff --git a/connect_frontend/menu-app/src/components/primitives.jsx b/connect_frontend/menu-app/src/components/primitives.jsx index 550fbab..17dc6b2 100644 --- a/connect_frontend/menu-app/src/components/primitives.jsx +++ b/connect_frontend/menu-app/src/components/primitives.jsx @@ -8,24 +8,22 @@ export function eur(n) { return '€' + Number(n).toFixed(2) } +// The price is the QR menu's (sales point qr_table, set in normaliseProduct): since phase 3S +// discounts are price rules already in it, so there is no separate discount to show. 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 + return product.price ?? 0 } export function basePrice(product) { - return product.digital_price ?? product.base_price ?? product.price ?? 0 + return product.price ?? 0 } -export function hasDiscount(product) { - const pct = product.digital_discount ?? product.discountPct ?? 0 - return pct > 0 +export function hasDiscount() { + return false } -export function discountPct(product) { - return product.digital_discount ?? product.discountPct ?? 0 +export function discountPct() { + return 0 } // ── Placeholder gradient art ───────────────────────────────────────────────── diff --git a/connect_frontend/menu-app/src/pages/MenuPage.jsx b/connect_frontend/menu-app/src/pages/MenuPage.jsx index c25b8f9..ac27fa3 100644 --- a/connect_frontend/menu-app/src/pages/MenuPage.jsx +++ b/connect_frontend/menu-app/src/pages/MenuPage.jsx @@ -1,5 +1,5 @@ import { useState, useEffect, useRef, useMemo } from 'react' -import { useParams, useNavigate } from 'react-router-dom' +import { useParams, useNavigate, useSearchParams } from 'react-router-dom' import { Search, Leaf, X, Plus, ShoppingBag, ChevronLeft, ArrowRight, Send, Loader2, Info, @@ -33,8 +33,10 @@ const I18N = { orderChanged: 'Something on the menu changed since you opened it. Please reload the page and check your order.', orderFailed: 'The order could not be sent. Please try again.', orderPlaced: 'Order placed!', orderPlacedSub: 'Your order has been sent to the kitchen.', - newOrder: 'Back to menu', table: 'Table no.', name: 'Your name', - namePh: 'e.g. Alex', tablePh: 'e.g. 12', orderSummary: 'Order summary', + newOrder: 'Back to menu', table: 'Table', name: 'Your name (optional)', + namePh: 'e.g. Alex', orderSummary: 'Order summary', + 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.', contains: 'Contains', ingredients: 'Ingredients', noResults: 'No dishes found', noResultsSub: 'Try a different search.', popular: 'Popular', chefs: "Chef's pick", off: 'OFF', @@ -49,8 +51,10 @@ const I18N = { orderChanged: 'Κάτι άλλαξε στο μενού από τότε που το άνοιξες. Ανανέωσε τη σελίδα και έλεγξε την παραγγελία σου.', orderFailed: 'Η παραγγελία δεν στάλθηκε. Δοκίμασε ξανά.', orderPlaced: 'Η παραγγελία στάλθηκε!', orderPlacedSub: 'Η παραγγελία σου εστάλη στην κουζίνα.', - newOrder: 'Πίσω στο μενού', table: 'Τραπέζι', name: 'Το όνομά σου', - namePh: 'π.χ. Αλέξης', tablePh: 'π.χ. 12', orderSummary: 'Σύνοψη παραγγελίας', + newOrder: 'Πίσω στο μενού', table: 'Τραπέζι', name: 'Το όνομά σου (προαιρετικά)', + namePh: 'π.χ. Αλέξης', orderSummary: 'Σύνοψη παραγγελίας', + atTable: 'Τραπέζι {table}: παραγγείλτε από το κινητό σας', tableInvalid: 'Αυτό το QR δεν ισχύει πλέον. Ρωτήστε το προσωπικό.', + orderingOff: 'Η παραγγελία από το τραπέζι δεν είναι διαθέσιμη τώρα. Ρωτήστε το προσωπικό.', contains: 'Περιέχει', ingredients: 'Συστατικά', noResults: 'Δεν βρέθηκαν πιάτα', noResultsSub: 'Δοκίμασε διαφορετική αναζήτηση.', popular: 'Δημοφιλές', chefs: 'Επιλογή Σεφ', off: 'ΕΚΠΤΩΣΗ', @@ -66,19 +70,24 @@ function resolveImageUrl(url) { } // ── Normalise a backend product to the shape the UI expects ────────────────── +// The QR menu sells at the sales point qr_table (phase 3S): its price from `prices`; menus +// pushed before S.2 had digital_price. +const QR_POINT = 'qr_table' + function normaliseProduct(p, catId) { return { ...p, + digital_price: undefined, digital_discount: undefined, id: String(p.id), cat: catId, name: p.digital_name || p.name || '', desc: p.digital_description || p.description || '', - price: p.digital_price ?? p.base_price ?? 0, + price: p.prices ? (p.prices[QR_POINT] ?? 0) : (p.digital_price ?? p.base_price ?? 0), badge: p.digital_badge || p.badge || null, tags: p.digital_tags || p.tags || [], allergens: p.allergens || [], ingredients: p.ingredients || null, - discountPct: p.digital_discount || p.discountPct || 0, + discountPct: 0, image_url: resolveImageUrl(p.digital_image_url || p.image_url || null), digital_available: p.digital_available !== false, } @@ -92,9 +101,9 @@ function normaliseCategories(rawCats) { id, hue: cat.hue ?? CATEGORY_HUES[idx % CATEGORY_HUES.length], GlyphIcon: GLYPH_BY_ID[id] ?? GLYPH_FALLBACK[idx % GLYPH_FALLBACK.length], - products: (cat.products || []).map(p => normaliseProduct(p, id)), + products: (cat.products || []).filter(p => !p.sold_at || p.sold_at.includes(QR_POINT)).map(p => normaliseProduct(p, id)), } - }) + }).filter(c => c.products.length > 0) } // ── Bottom Sheet shell ──────────────────────────────────────────────────────── @@ -291,6 +300,7 @@ function ProductCard({ product, category, lang, t, onOpen, onAdd, qty, viewOnly return (
onOpen(product)} + data-testid="menu-product" data-product={product.id} className={`group overflow-hidden rounded-[20px] bg-[#fcfbf7] ring-1 ring-[#e7e1d1] shadow-card transition hover:shadow-card-hover active:scale-[0.992] ${unavailable ? 'opacity-50' : 'cursor-pointer'}`} >
@@ -327,6 +337,7 @@ function ProductCard({ product, category, lang, t, onOpen, onAdd, qty, viewOnly
-
+
+

{t.table} {table?.label}

-
{t.orderSummary}
@@ -754,6 +754,7 @@ function CartFlow({ stage, setStage, cart, setCart, categories, lang, t, onOpenP
diff --git a/connect_frontend/menu-app/src/pages/OrderConfirm.jsx b/connect_frontend/menu-app/src/pages/OrderConfirm.jsx index 6e3267d..a103b6c 100644 --- a/connect_frontend/menu-app/src/pages/OrderConfirm.jsx +++ b/connect_frontend/menu-app/src/pages/OrderConfirm.jsx @@ -1,19 +1,17 @@ import { useEffect, useState } from 'react' import { useParams } from 'react-router-dom' -import { Check, Clock, X, ChefHat, Truck, Package, Leaf } from 'lucide-react' +import { Check, Clock, X, Leaf } from 'lucide-react' import { fetchOrderStatus } from '../api' +// A table order from the QR menu (phase 3S, S.7): sent → in the kitchen (or not taken). +// Takeaway and delivery have their own app since S.4 (/order/), so their steps are gone here. 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' }, + pending_acceptance: { label: 'Sending your order to the kitchen…', Icon: Clock, color: '#c9a24b', bg: '#f6edd6' }, + accepted: { label: 'Your order is in the kitchen', Icon: Check, color: '#3f7d4e', bg: '#e7f1e7' }, + rejected: { label: 'Order not taken', Icon: X, color: '#c2602f', bg: '#f7e6dc' }, } -const TERMINAL = new Set(['rejected', 'delivered']) +const TERMINAL = new Set(['accepted', 'rejected', 'delivered', 'preparing', 'ready']) const POLL_MS = 10_000 export default function OrderConfirm() { @@ -44,7 +42,7 @@ export default function OrderConfirm() { return () => clearTimeout(timer) }, [ref]) - const cfg = STATUS_CONFIG[orderStatus] ?? STATUS_CONFIG.pending_acceptance + const cfg = STATUS_CONFIG[orderStatus] ?? (TERMINAL.has(orderStatus) ? STATUS_CONFIG.accepted : STATUS_CONFIG.pending_acceptance) const { label, Icon, color, bg } = cfg return ( @@ -71,7 +69,7 @@ export default function OrderConfirm() {

{/* Status label */} -

+

{error ? 'Could not load status' : label}

@@ -83,9 +81,9 @@ export default function OrderConfirm() { )} {/* Subtext */} - {orderStatus === 'delivered' && ( + {TERMINAL.has(orderStatus) && orderStatus !== 'rejected' && (

- Thank you for your order! Enjoy your meal. + Thank you! Your waiter will bring it to your table. Enjoy your meal.

)} {orderStatus === 'rejected' && (