From 70c8f2bb573f6d1f1fe2ae61277480c6d91ba381 Mon Sep 17 00:00:00 2001 From: bonamin Date: Sun, 15 Nov 2026 19:31:44 +0200 Subject: [PATCH] feat(connect): table bookings from the online ordering app; food fired to the kitchen before arrival MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plan phase 3S, step S.6. - Pull: "reservation" / "preorder" orders become Reservations waiting for an answer (status "requested"; services/online_reservations.py), with the food ordered ahead kept on the booking (items_json at the cloud's prices, the site's price check) — no order yet. Migration 0020 (reservations: online_order_cloud_id, online_ref, items_json, total, online_price_diff, fire_at, order_id, response_note). - Confirm → the food's fire time = booking time − fire minutes (setting); the fire worker (connect_orders, every 20 s) turns the food into an order at that time (needs an open business day; waits otherwise): kitchen tickets, KDS (reference and time). Early arrival fires at once. Seating moves the order to the table (refused if the table has an open order). Decline / cancel / no-show with a reason. Every step mirrored to the cloud. - Found: the KDS filter dropped every online order without an online status (SQL NULL in NOT(a AND b)) — made NULL-safe. - Counter: Online → Bookings (requests first, then upcoming), BookingPanel (confirm, decline with reasons, food and when it goes to the kitchen, seat at a free table, cancel, no-show); the Online badge and chime count booking requests. - Manager: Online ordering → Table bookings settings (on, food ahead, hours, slot, notice, days ahead, party size, fire minutes); the dashboard's reservations card confirms / declines online requests; the reservations router delegates online bookings' status steps. - Tests: tests/test_online_bookings.py (8), unit tests (terminal, manager), e2e: order app (book with food → the venue confirms), terminal (request → confirm → the two dishes reach the KDS at the fire time, not before → seated), manager (booking settings). Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + local_backend/core/errors.py | 4 + .../versions/0020_online_reservations.py | 38 +++ local_backend/models/reservation.py | 17 +- .../modules/connect_orders/manifest.py | 3 +- local_backend/routers/connect_orders.py | 128 +++++++++++ local_backend/routers/fees.py | 52 +++-- local_backend/routers/kds.py | 3 +- local_backend/routers/reservations.py | 25 +- local_backend/schemas/reservation.py | 6 + local_backend/services/cloud_sync.py | 76 ++++-- local_backend/services/online_reservations.py | 216 ++++++++++++++++++ local_backend/tests/test_modules.py | 8 +- local_backend/tests/test_online_bookings.py | 202 ++++++++++++++++ manager_dashboard/src/pages/DashboardPage.jsx | 31 ++- .../src/pages/online/OrderingSettings.jsx | 119 +++++++--- .../src/pages/online/feesLogic.js | 40 +++- manager_dashboard/tests/fees.test.mjs | 18 +- packages/i18n/locales/el/errors.json | 6 + packages/i18n/locales/el/manager.json | 17 ++ packages/i18n/locales/el/terminal.json | 39 +++- packages/i18n/locales/en/errors.json | 6 + packages/i18n/locales/en/manager.json | 17 ++ packages/i18n/locales/en/terminal.json | 39 +++- terminal/src/apps/pos/BookingPanel.jsx | 157 +++++++++++++ terminal/src/apps/pos/BookingsView.jsx | 48 ++++ terminal/src/apps/pos/PosScreen.jsx | 28 ++- terminal/src/apps/pos/logic/bookings.js | 37 +++ terminal/src/apps/pos/usePos.js | 16 ++ terminal/tests/pos.test.mjs | 18 ++ tests/e2e/manager.mjs | 13 ++ tests/e2e/order_app.mjs | 40 +++- tests/e2e/terminal.mjs | 39 +++- 33 files changed, 1402 insertions(+), 105 deletions(-) create mode 100644 local_backend/migrations/versions/0020_online_reservations.py create mode 100644 local_backend/services/online_reservations.py create mode 100644 local_backend/tests/test_online_bookings.py create mode 100644 terminal/src/apps/pos/BookingPanel.jsx create mode 100644 terminal/src/apps/pos/BookingsView.jsx create mode 100644 terminal/src/apps/pos/logic/bookings.js diff --git a/docs/README.md b/docs/README.md index 335c9d2..81df038 100644 --- a/docs/README.md +++ b/docs/README.md @@ -43,6 +43,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/services/fees.py` | Delivery fee engine (phase 3S). **Byte-identical copy in `cloud-service/cloud_backend/services/fees.py`**: change both, and `tests/fixtures/fee_cases.json` in both; `tests/test_fees.py` fails if they differ | | `local_backend/services/refunds.py` | Refunds: their own records (`models/refund.py`), never edits of the paid items; shift / day totals subtract them | | `local_backend/services/system_products.py`, `services/online_check.py` | Lines the system adds itself (phase 3S): the delivery fee is an order line whose product has `system_key` and `lifecycle_status = "system"` (never on a menu or in the catalogue, never added by hand, added printed + served so the kitchen never sees it; paid, counted, receipted and refunded like any line). The site's own price check of a pulled online order (`orders.online_price_diff`): shown, never applied — the customer pays the cloud's prices | +| `local_backend/services/online_reservations.py` | Table bookings from the online ordering app (phase 3S): stored as `Reservation` rows (`requested` → `pending` confirmed / `declined`; `arrived`, `cancelled`, `no_show`), food ordered ahead kept on the booking (`items_json`) and turned into an order **only at the fire time** (`fire_worker`, a connect_orders module worker; needs an open business day) or on early arrival. Every step mirrors the cloud status. The counter's Online → Bookings and `/api/connect/bookings/*` use it; the reservations router delegates online bookings to it | | `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | | `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below | diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 3b496b6..71157a5 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -85,6 +85,10 @@ CODES: dict[str, tuple[int, str]] = { "refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."), "online.not_found": (404, "Online order {order_id} not found."), "online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."), + "reservation.not_found": (404, "Booking {reservation_id} not found."), + "reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."), + "reservation.table_unknown": (404, "Table {table_id} not found."), + "reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."), "kds.item_not_found": (404, "Item {item_id} not found on this order."), "kds.item_claimed": (409, "{name} is already on this item."), "kds.claim_needs_staff": (403, "Only a staff member can claim an item."), diff --git a/local_backend/migrations/versions/0020_online_reservations.py b/local_backend/migrations/versions/0020_online_reservations.py new file mode 100644 index 0000000..e186289 --- /dev/null +++ b/local_backend/migrations/versions/0020_online_reservations.py @@ -0,0 +1,38 @@ +"""reservations: online bookings with food ordered ahead (plan phase 3S, S.6) + +Revision ID: 0020_online_reservations +Revises: 0019_online_order_site_side +Create Date: 2026-11-16 21:30:00 +""" +from alembic import op +import sqlalchemy as sa + +from core.timeutil import UTCDateTime + + +revision = '0020_online_reservations' +down_revision = '0019_online_order_site_side' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('reservations', schema=None) as batch_op: + batch_op.add_column(sa.Column('online_order_cloud_id', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('online_ref', sa.String(), nullable=True)) + batch_op.add_column(sa.Column('items_json', sa.Text(), nullable=True)) + batch_op.add_column(sa.Column('total', sa.Float(), nullable=True)) + batch_op.add_column(sa.Column('online_price_diff', sa.Text(), nullable=True)) + batch_op.add_column(sa.Column('fire_at', UTCDateTime(), nullable=True)) + batch_op.add_column(sa.Column('order_id', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('response_note', sa.Text(), nullable=True)) + batch_op.create_index(batch_op.f('ix_reservations_online_order_cloud_id'), ['online_order_cloud_id'], unique=False) + batch_op.create_foreign_key('fk_reservations_order_id_orders', 'orders', ['order_id'], ['id']) + + +def downgrade() -> None: + with op.batch_alter_table('reservations', schema=None) as batch_op: + batch_op.drop_constraint('fk_reservations_order_id_orders', type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_reservations_online_order_cloud_id')) + for c in ('response_note', 'order_id', 'fire_at', 'online_price_diff', 'total', 'items_json', 'online_ref', 'online_order_cloud_id'): + batch_op.drop_column(c) diff --git a/local_backend/models/reservation.py b/local_backend/models/reservation.py index 7d165cf..71a317a 100644 --- a/local_backend/models/reservation.py +++ b/local_backend/models/reservation.py @@ -1,4 +1,4 @@ -from sqlalchemy import Column, Integer, String, ForeignKey, Text +from sqlalchemy import Column, Float, Integer, String, ForeignKey, Text from core.timeutil import UTCDateTime, utcnow from sqlalchemy.orm import relationship from database import Base @@ -22,7 +22,8 @@ class Reservation(Base): # Optional table assignment (assignable/editable later) table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) - # Lifecycle: pending | arrived | cancelled | no_show + # Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show; + # online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined status = Column(String, nullable=False, default="pending") # Source: manager_app | waiter_app | online @@ -34,9 +35,21 @@ class Reservation(Base): # For future online reservations: cloud-side customer identifier online_customer_id = Column(String, nullable=True) + # Online bookings (phase 3S, S.6): the cloud's order (status mirrored to the customer's page) + online_order_cloud_id = Column(Integer, nullable=True, index=True) + online_ref = Column(String, nullable=True) # "ORD-0042" + # food ordered ahead: the cloud's lines (its prices) until the kitchen gets them, then the order + items_json = Column(Text, nullable=True) # JSON list as the cloud sent it; NULL = a table only + total = Column(Float, nullable=True) + online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched + fire_at = Column(UTCDateTime, nullable=True) # when the kitchen gets the food (set on confirming) + order_id = Column(Integer, ForeignKey("orders.id"), nullable=True) # created at fire time + response_note = Column(Text, nullable=True) # why it was declined / cancelled (the customer sees it) + created_at = Column(UTCDateTime, default=utcnow) updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow) table = relationship("Table", foreign_keys=[table_id]) + order = relationship("Order", foreign_keys=[order_id]) created_by = relationship("User", foreign_keys=[created_by_user_id]) diff --git a/local_backend/modules/connect_orders/manifest.py b/local_backend/modules/connect_orders/manifest.py index d3876a9..92aa4be 100644 --- a/local_backend/modules/connect_orders/manifest.py +++ b/local_backend/modules/connect_orders/manifest.py @@ -18,5 +18,6 @@ MODULE = Module( Mount('routers.fees', '/api/connect/fees'), Mount('routers.connect_orders', '/api/connect'), ), - workers=('services.cloud_sync:order_pull_worker',), + # S.6: bookings' food goes to the kitchen at its fire time + workers=('services.cloud_sync:order_pull_worker', 'services.online_reservations:fire_worker'), ) diff --git a/local_backend/routers/connect_orders.py b/local_backend/routers/connect_orders.py index 58b6aae..5e9ac6c 100644 --- a/local_backend/routers/connect_orders.py +++ b/local_backend/routers/connect_orders.py @@ -10,6 +10,8 @@ GET /api/connect/orders/incoming waiting for acceptance POST /api/connect/orders/{id}/accept → kitchen tickets and the KDS POST /api/connect/orders/{id}/reject POST /api/connect/orders/{id}/status preparing | ready | out_for_delivery | delivered +GET /api/connect/bookings table bookings: requested, upcoming (S.6) +POST /api/connect/bookings/{id}/confirm | decline | arrive | cancel The steps follow the cloud's (cloud_backend/routers/orders.py _TRANSITIONS), and every change is mirrored to the cloud in the background so the customer's tracking page follows; the site @@ -246,3 +248,129 @@ def update_order_status(order_id: int, body: StatusUpdateRequest, background: Ba if body.status == "delivered": broadcast_sync("kds_order_updated", {"order_id": order.id, "kds_status": order.kds_status}) return order + + +# ── Table bookings from the online ordering app (phase 3S, S.6) ─────────────── +# services/online_reservations.py has the rules; here the counter (and the manager) list them, +# confirm or decline, seat the guests (their food moves to the table) or cancel. + +class BookingAnswer(BaseModel): + reason: Optional[str] = Field(default=None, max_length=300) + + +class ArriveRequest(BaseModel): + table_id: Optional[int] = None + + +class CancelRequest(BaseModel): + status: Literal["cancelled", "no_show"] = "cancelled" + reason: Optional[str] = Field(default=None, max_length=300) + + +def _booking_lines(r) -> list: + import json + try: + lines = json.loads(r.items_json or "[]") + except ValueError: + lines = [] + return [{"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 [] if isinstance(o, dict)]} for x in lines] + + +def booking_out(r) -> dict: + return { + "id": r.id, "ref": r.online_ref, "status": r.status, "source": r.source, + "guest_name": r.guest_name, "party_size": r.party_size, "phone": r.phone, "note": r.note, + "reserved_for": _iso(r.reserved_for), + "table_id": r.table_id, "table_label": (r.table.label or f"T{r.table.number}") if r.table else None, + "lines": _booking_lines(r), "total": r.total, "price_diff": OrderOut._diff(r.online_price_diff), + "fire_at": _iso(r.fire_at), "order_id": r.order_id, "response_note": r.response_note, + } + + +def _booking(db, reservation_id: int): + from models.reservation import Reservation + r = db.get(Reservation, reservation_id) + if r is None: + raise XeniaError("reservation.not_found", reservation_id=reservation_id) + return r + + +def _booking_changed(background: BackgroundTasks, r) -> None: + from services.online_reservations import mirror_args + args = mirror_args(r) + if args: + background.add_task(_mirror_status_to_cloud, *args) + broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status}) + + +@router.get("/bookings") +def list_bookings(db: Session = Depends(get_db), user=Depends(require(MANAGE))): + """The counter's bookings: `requested` (online, waiting for an answer, soonest first) and + `upcoming` (confirmed, from 4 hours ago on, soonest first; any source).""" + from datetime import timedelta + from models.reservation import Reservation + q = db.query(Reservation) + requested = q.filter(Reservation.status == "requested").order_by(Reservation.reserved_for).all() + upcoming = (q.filter(Reservation.status == "pending", Reservation.reserved_for >= utcnow() - timedelta(hours=4)) + .order_by(Reservation.reserved_for).limit(100).all()) + return {"requested": [booking_out(r) for r in requested], "upcoming": [booking_out(r) for r in upcoming]} + + +@router.post("/bookings/{reservation_id}/confirm") +def confirm_booking(reservation_id: int, background: BackgroundTasks, db: Session = Depends(get_db), + user=Depends(require(MANAGE))): + """Confirm: the customer is told; food ordered ahead goes to the kitchen at its fire time + (at once if that time has passed and the day is open).""" + from routers import orders as orders_api + from services import online_reservations as svc + r = _booking(db, reservation_id) + svc.confirm(db, r) + db.commit() + svc.fire_due(db) + db.refresh(r) + if r.order_id: + orders_api._audit(db, r.order_id, "ONLINE_ACCEPTED", waiter_id=user.id, note=r.online_ref) + db.commit() + _booking_changed(background, r) + return booking_out(r) + + +@router.post("/bookings/{reservation_id}/decline") +def decline_booking(reservation_id: int, body: BookingAnswer, background: BackgroundTasks, + db: Session = Depends(get_db), user=Depends(require(MANAGE))): + from services import online_reservations as svc + r = _booking(db, reservation_id) + svc.decline(db, r, body.reason) + db.commit() + _booking_changed(background, r) + return booking_out(r) + + +@router.post("/bookings/{reservation_id}/arrive") +def arrive_booking(reservation_id: int, body: ArriveRequest, background: BackgroundTasks, + db: Session = Depends(get_db), user=Depends(require(MANAGE))): + """The guests are here: seat them (optional table); their food's order moves to the table + (and goes to the kitchen now if it hadn't yet).""" + from services import online_reservations as svc + r = _booking(db, reservation_id) + fired = svc.arrive(db, r, body.table_id) + db.commit() + if fired: + svc.send_to_kitchen(db, r.order_id, fired) + elif r.order_id: + broadcast_sync("order_updated", {"order_id": r.order_id, "table_id": r.table_id, "status": "open", "action": "moved"}) + db.refresh(r) + _booking_changed(background, r) + return booking_out(r) + + +@router.post("/bookings/{reservation_id}/cancel") +def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks, + db: Session = Depends(get_db), user=Depends(require(MANAGE))): + from services import online_reservations as svc + r = _booking(db, reservation_id) + svc.cancel(db, r, body.status, body.reason) + db.commit() + _booking_changed(background, r) + return booking_out(r) diff --git a/local_backend/routers/fees.py b/local_backend/routers/fees.py index 27ebfdd..fbc5f76 100644 --- a/local_backend/routers/fees.py +++ b/local_backend/routers/fees.py @@ -75,6 +75,42 @@ def fees_payload(db) -> dict: return {"areas": [area_out(a) for a in areas], "rules": [rule_out(r) for r in rules]} +def _clean_hours(v): + out = {} + for day, ranges in (v or {}).items(): + if str(day) not in {str(d) for d in range(7)}: + raise ValueError("hours are keyed 0 (Monday) to 6 (Sunday)") + if not isinstance(ranges, list) or len(ranges) > 4: + raise ValueError("at most 4 time ranges a day") + clean = [] + for r in ranges: + if not (isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, str) and HHMM.match(x) for x in r)) or r[0] == r[1]: + raise ValueError("a time range is [\"HH:MM\", \"HH:MM\"], start and end different") + clean.append([r[0], r[1]]) + if clean: + out[str(day)] = sorted(clean) + return out + + +class ReservationsBody(BaseModel): + """Table bookings online (plan phase 3S, S.6): a table only, or with food ordered ahead + (`with_food`). The cloud enforces hours, the time grid, notice, days ahead and party size; + `fire_minutes` is the site's: the kitchen gets pre-ordered food that long before arrival.""" + enabled: bool = False + with_food: bool = False + hours: dict = Field(default_factory=dict) # like OrderingBody.hours; none = any time + slot_minutes: int = Field(default=30, ge=5, le=120) + days_ahead: int = Field(default=30, ge=0, le=90) + notice_minutes: int = Field(default=60, ge=0, le=7 * 24 * 60) # the earliest booking from now + party_max: int = Field(default=10, ge=1, le=100) + fire_minutes: int = Field(default=20, ge=0, le=240) + + @field_validator("hours") + @classmethod + def _hours(cls, v): + return _clean_hours(v) + + class OrderingBody(BaseModel): """What the online ordering app offers and when (plan phase 3S, S.4). The cloud enforces it at checkout. hours: {"0".."6" (Mon..Sun): [["HH:MM", "HH:MM"], ...]}; no hours at all = @@ -86,6 +122,7 @@ class OrderingBody(BaseModel): slot_minutes: int = Field(default=15, ge=5, le=120) # the times offered, every N minutes days_ahead: int = Field(default=0, ge=0, le=7) # 0 = today only asap: bool = True # "as soon as possible" offered while open + reservations: ReservationsBody = Field(default_factory=ReservationsBody) # S.6 @field_validator("services") @classmethod @@ -95,20 +132,7 @@ class OrderingBody(BaseModel): @field_validator("hours") @classmethod def _hours(cls, v): - out = {} - for day, ranges in (v or {}).items(): - if str(day) not in {str(d) for d in range(7)}: - raise ValueError("hours are keyed 0 (Monday) to 6 (Sunday)") - if not isinstance(ranges, list) or len(ranges) > 4: - raise ValueError("at most 4 time ranges a day") - clean = [] - for r in ranges: - if not (isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, str) and HHMM.match(x) for x in r)) or r[0] == r[1]: - raise ValueError("a time range is [\"HH:MM\", \"HH:MM\"], start and end different") - clean.append([r[0], r[1]]) - if clean: - out[str(day)] = sorted(clean) - return out + return _clean_hours(v) class AreaBody(BaseModel): diff --git a/local_backend/routers/kds.py b/local_backend/routers/kds.py index 4ad2a17..ef52a01 100644 --- a/local_backend/routers/kds.py +++ b/local_backend/routers/kds.py @@ -314,7 +314,8 @@ def kds_orders( db.query(Order) .filter(Order.status.in_(["open", "partially_paid", "paid"])) # an online order waits for the counter to accept it (3.3d); before that it may still be rejected - .filter(~((Order.source == "online") & (Order.online_status == "pending_acceptance"))) + # (NULL-safe: a booking's food order has no online status, S.6) + .filter((Order.source != "online") | Order.online_status.is_(None) | (Order.online_status != "pending_acceptance")) .options( joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.ingredients), joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.options), diff --git a/local_backend/routers/reservations.py b/local_backend/routers/reservations.py index 0f72a81..0c5cee9 100644 --- a/local_backend/routers/reservations.py +++ b/local_backend/routers/reservations.py @@ -1,5 +1,5 @@ from core.timeutil import utcnow, venue_day_window -from fastapi import APIRouter, Depends, HTTPException, status, Query +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status, Query from sqlalchemy.orm import Session from typing import List, Optional from datetime import datetime, timezone @@ -77,14 +77,14 @@ def list_reservations( q = q.filter(Reservation.reserved_for >= start, Reservation.reserved_for < end) if tab == "upcoming": - # pending + no_show (actionable), ordered soonest first - q = q.filter(Reservation.status.in_(["pending", "no_show"])) + # requested (online, to confirm, S.6) + pending + no_show (actionable), soonest first + q = q.filter(Reservation.status.in_(["requested", "pending", "no_show"])) q = q.order_by(Reservation.reserved_for.asc()) elif tab == "history": # arrived, cancelled, plus no_show/pending that are clearly in the past now = utcnow() q = q.filter( - (Reservation.status.in_(["arrived", "cancelled"])) | + (Reservation.status.in_(["arrived", "cancelled", "declined"])) | ( Reservation.status.in_(["no_show", "pending"]) & (Reservation.reserved_for < now) @@ -143,6 +143,7 @@ def update_reservation( def update_reservation_status( reservation_id: int, body: ReservationStatusUpdate, + background: BackgroundTasks, db: Session = Depends(get_db), user: User = Depends(get_current_user), ): @@ -153,6 +154,22 @@ def update_reservation_status( if not r: raise HTTPException(status_code=404, detail="Reservation not found") + if r.online_order_cloud_id and r.status in ("requested", "pending") and body.status in ("arrived", "cancelled", "no_show"): + # an online booking (phase 3S, S.6): the same steps as the counter's, and the customer's page follows + from routers.connect_orders import _booking_changed + from services import online_reservations as svc + if body.status == "arrived": + fired = svc.arrive(db, r, r.table_id) + db.commit() + if fired: + svc.send_to_kitchen(db, r.order_id, fired) + else: + svc.cancel(db, r, body.status, None) + db.commit() + db.refresh(r) + _booking_changed(background, r) + return _enrich(r) + r.status = body.status r.updated_at = utcnow() db.commit() diff --git a/local_backend/schemas/reservation.py b/local_backend/schemas/reservation.py index a9c99f6..5a79d14 100644 --- a/local_backend/schemas/reservation.py +++ b/local_backend/schemas/reservation.py @@ -60,6 +60,12 @@ class ReservationOut(BaseModel): created_at: datetime updated_at: datetime + # online bookings (phase 3S, S.6) + online_ref: Optional[str] = None + total: Optional[float] = None + order_id: Optional[int] = None + fire_at: Optional[datetime] = None + # Denormalized for convenience table_label: Optional[str] = None created_by_name: Optional[str] = None diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 25f6fe7..318a7dd 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -347,7 +347,7 @@ def _with_table(cloud_order: dict): return f"Table {table}" + (f" · {notes}" if notes else "") -def store_online_orders(db, orders: list[dict]) -> dict: +def store_online_orders(db, orders: list[dict], booked: list | None = None) -> dict: """Store online orders as the cloud hands them over (GET /api/orders/pending/{site}): one local order each, waiting for acceptance (plan step 3.3d). An order already stored (an earlier pull whose "synced" mark didn't reach the cloud) isn't stored twice. @@ -356,11 +356,14 @@ def store_online_orders(db, orders: list[dict]) -> dict: Phase 3S, S.5: the order keeps the customer's time and delivery area; the cloud's prices are what the customer pays (items at the cloud's unit prices, the delivery fee as a system-product line, services/system_products.py), and the site's own engine checks them - (services/online_check.py: a difference is kept on the order and shown, never changed).""" + (services/online_check.py: a difference is kept on the order and shown, never changed). + + S.6: table bookings ("reservation", "preorder") become Reservations waiting to be confirmed + (services/online_reservations.py); their ids go into `booked` (new ones) and the map.""" from models.business_day import BusinessDay from models.order import Order, OrderItem from models.user import User - from services import online_check, system_products + from services import online_check, online_reservations, system_products # the opener is the first account with the manager dashboard (orders need one) system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first() @@ -368,6 +371,18 @@ def store_online_orders(db, orders: list[dict]) -> dict: day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() out = {} for cloud_order in orders: + if cloud_order.get("order_type") in ("reservation", "preorder"): + seen = online_reservations.known(db, cloud_order["id"]) + if seen is not None: + out[cloud_order["id"]] = -seen.id + continue + r = online_reservations.store(db, cloud_order, sales_points.ONLINE_PREORDER) + db.commit() + out[cloud_order["id"]] = r.id + if booked is not None: + booked.append(r.id) + logger.info("Online booking %s pulled as reservation %d", cloud_order["public_ref"], r.id) + continue known = db.query(Order).filter(Order.source == "online", Order.online_order_cloud_id == cloud_order["id"]).first() if known is not None: @@ -400,21 +415,7 @@ def store_online_orders(db, orders: list[dict]) -> dict: ) db.add(local_order) db.flush() - for item in json.loads(cloud_order.get("items_json") or "[]"): - db.add(OrderItem( - order_id=local_order.id, - product_id=item.get("product_id"), - added_by=opener_id, - quantity=item.get("quantity", 1), - unit_price=item.get("unit_price", 0.0), - unit_cost=_cost(db, item.get("product_id")), - # the site's entry shape (services/pos_cart.py: quick add-ons, prices included in unit_price) - selected_options=json.dumps([ - {"id": o.get("id"), "name": o.get("name"), "price_delta": o.get("price", 0.0), "type": "quick"} - if isinstance(o, dict) else o for o in item.get("options", [])]), - status="active", - printed=False, - )) + add_cloud_items(db, local_order.id, opener_id, json.loads(cloud_order.get("items_json") or "[]")) fee = round(float(cloud_order.get("delivery_fee") or 0.0), 2) if fee > 0: fee_product = system_products.get(db, system_products.DELIVERY_FEE) @@ -433,6 +434,37 @@ def store_online_orders(db, orders: list[dict]) -> dict: return out +def add_cloud_items(db, order_id: int, opener_id: int, items: list) -> list: + """The cloud's lines as order items, at the cloud's prices (what the customer pays).""" + from models.order import OrderItem + out = [] + for item in items: + row = OrderItem( + order_id=order_id, + product_id=item.get("product_id"), + added_by=opener_id, + quantity=item.get("quantity", 1), + unit_price=item.get("unit_price", 0.0), + unit_cost=_cost(db, item.get("product_id")), + # the site's entry shape (services/pos_cart.py: quick add-ons, prices included in unit_price) + selected_options=json.dumps([ + {"id": o.get("id"), "name": o.get("name"), "price_delta": o.get("price", 0.0), "type": "quick"} + if isinstance(o, dict) else o for o in item.get("options", [])]), + status="active", + printed=False, + ) + db.add(row) + out.append(row) + return out + + +def online_opener_id(db) -> int: + """Orders need an opener: the first account with the manager dashboard.""" + from models.user import User + system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first() + return system_user.id if system_user else 1 + + def _aware(raw): """An ISO time from the cloud → aware UTC (naive = UTC); None for none or garbage.""" if not raw: @@ -485,8 +517,9 @@ async def _pull_pending_orders(): from services.sse_bus import broadcast_sync db = SessionLocal() + booked = [] try: - stored = store_online_orders(db, orders) + stored = store_online_orders(db, orders, booked) except Exception as e: db.rollback() logger.error("Failed to process pulled orders: %s", e) @@ -494,7 +527,10 @@ async def _pull_pending_orders(): finally: db.close() - new_ids = [local_id for local_id in stored.values() if local_id > 0] + bookings = {o["id"] for o in orders if o.get("order_type") in ("reservation", "preorder")} + new_ids = [local_id for cloud_id, local_id in stored.items() if local_id > 0 and cloud_id not in bookings] + if booked: + broadcast_sync("reservation_requested", {"count": len(booked), "reservation_ids": booked}) if new_ids: # the counter POS and the manager light up (and ring) at once broadcast_sync("online_order_received", {"count": len(new_ids), "order_ids": new_ids}) diff --git a/local_backend/services/online_reservations.py b/local_backend/services/online_reservations.py new file mode 100644 index 0000000..d712d54 --- /dev/null +++ b/local_backend/services/online_reservations.py @@ -0,0 +1,216 @@ +"""Table bookings from the online ordering app (plan phase 3S, step S.6). + +A booking arrives with the online orders pull (services/cloud_sync.store_online_orders) as a +Reservation in status "requested": a table only (cloud type "reservation") or a table with food +ordered ahead ("preorder", its lines at the cloud's prices in `items_json`). The venue: + + confirm(db, r) requested → pending (confirmed); the food gets its fire time + decline(db, r, reason) requested → declined (the customer sees the reason) + arrive(db, r, table_id) pending → arrived; the food's order moves to the table + cancel(db, r, status, reason) pending → cancelled | no_show + +The food reaches the kitchen at `fire_at` = the booking time − the venue's fire minutes +(Online ordering → Reservations; connect_orders.ordering.reservations.fire_minutes), never at +once: fire_due() (the fire_worker, every FIRE_EVERY seconds, while connect_orders runs) turns +the lines into an order (an online order with no online status, so not on the counter's online +board; on the table once the guests arrive), prints its kitchen tickets and puts it on the KDS. +It needs an open business day; if none is open at fire time it waits for one. Guests who +arrive early get their food fired on arrival. + +Every step is mirrored to the cloud so the customer's page follows (cloud statuses: +accepted = confirmed, rejected = declined, delivered = arrived, cancelled). +""" +from __future__ import annotations + +import asyncio +import json +import logging +import os +from datetime import timedelta + +from core.errors import XeniaError +from core.timeutil import utcnow + +logger = logging.getLogger(__name__) +FIRE_EVERY = int(os.environ.get("XENIA_FIRE_CHECK_SECONDS", "20")) # tests run it faster +CLOUD_STATUS = {"pending": "accepted", "declined": "rejected", "arrived": "delivered", "cancelled": "cancelled", "no_show": "cancelled"} + + +def store(db, cloud_order: dict, point: str): + """A pulled booking → a Reservation waiting to be confirmed (flushed). Repeats return None.""" + from models.reservation import Reservation + from services import online_check + from services.cloud_sync import _aware + if db.query(Reservation).filter(Reservation.online_order_cloud_id == cloud_order["id"]).first() is not None: + return None + items = json.loads(cloud_order.get("items_json") or "[]") + food = cloud_order.get("order_type") == "preorder" and bool(items) + diff = online_check.diff(db, cloud_order, point) if food else None + r = Reservation( + guest_name=cloud_order.get("customer_name") or "?", + party_size=max(1, int(cloud_order.get("party_size") or 1)), + phone=cloud_order.get("customer_phone"), + note=cloud_order.get("customer_notes"), + reserved_for=_aware(cloud_order.get("requested_for")) or utcnow(), + status="requested", + source="online", + online_order_cloud_id=cloud_order["id"], + online_ref=cloud_order.get("public_ref"), + items_json=json.dumps(items) if food else None, + total=round(float(cloud_order.get("total") or 0.0), 2) if food else None, + online_price_diff=json.dumps(diff) if diff else None, + ) + db.add(r) + db.flush() + return r + + +def known(db, cloud_id: int): + from models.reservation import Reservation + return db.query(Reservation).filter(Reservation.online_order_cloud_id == cloud_id).first() + + +def fire_minutes(db) -> int: + from routers.fees import ordering_settings + return ordering_settings(db)["reservations"]["fire_minutes"] + + +def _need(r, *statuses): + if r.status not in statuses: + raise XeniaError("reservation.status_changed", current=r.status) + + +def confirm(db, r) -> None: + _need(r, "requested") + r.status = "pending" + if r.items_json: + r.fire_at = r.reserved_for - timedelta(minutes=fire_minutes(db)) + r.updated_at = utcnow() + + +def decline(db, r, reason: str | None) -> None: + _need(r, "requested") + r.status, r.response_note, r.updated_at = "declined", reason, utcnow() + + +def cancel(db, r, status: str, reason: str | None) -> None: + _need(r, "pending") + r.status, r.response_note, r.updated_at = status, reason, utcnow() + if r.order is not None: + # the food was already made: the order stays (the venue decides what to charge), the + # items not yet paid can be cancelled from the order as usual + logger.info("Reservation %s cancelled after its food was fired (order %s)", r.id, r.order_id) + + +def table_busy(db, table_id: int, order_id: int | None = None) -> bool: + from models.order import Order + q = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(("open", "partially_paid"))) + if order_id is not None: + q = q.filter(Order.id != order_id) + return q.first() is not None + + +def arrive(db, r, table_id: int | None) -> list: + """The guests are here: their table (optional), and their food (fired now if it wasn't). + Returns the item ids sent to the kitchen now.""" + from models.table import Table + _need(r, "pending") + if table_id is not None: + if db.query(Table).filter(Table.id == table_id, Table.is_active.is_(True)).first() is None: + raise XeniaError("reservation.table_unknown", table_id=table_id) + if table_busy(db, table_id, r.order_id): + raise XeniaError("reservation.table_busy", table_id=table_id) + r.table_id = table_id + r.status, r.updated_at = "arrived", utcnow() + fired = [] + if r.items_json and r.order_id is None: + fired = fire(db, r) or [] + if r.order is not None and r.table_id is not None: + r.order.table_id = r.table_id + return fired + + +def fire(db, r) -> list | None: + """The booking's food → an order for the kitchen (flushed; tickets printed by the caller). + None while no business day is open. Returns the new item ids.""" + from models.business_day import BusinessDay + from models.order import Order + from services.cloud_sync import add_cloud_items, online_opener_id + day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() + if day is None: + return None + opener = online_opener_id(db) + note = f"{r.guest_name} · {r.party_size}" + (f" · {r.note}" if r.note else "") + order = Order( + table_id=r.table_id if r.table_id and not table_busy(db, r.table_id) else None, + opened_by=opener, status="open", source="online", order_type="here", + sales_point="online_preorder", business_day_id=day.id, + online_order_ref=r.online_ref, online_order_type="preorder", online_status=None, + online_customer_name=r.guest_name, online_customer_phone=r.phone, online_customer_notes=note, + online_price_diff=r.online_price_diff, requested_for=r.reserved_for, customer_count=r.party_size, + ) + db.add(order) + db.flush() + items = add_cloud_items(db, order.id, opener, json.loads(r.items_json or "[]")) + db.flush() + r.order_id = order.id + logger.info("Reservation %s (%s): food fired as order %s", r.id, r.online_ref, order.id) + return [i.id for i in items] + + +def send_to_kitchen(db, order_id: int, item_ids: list) -> None: + """Kitchen tickets and the KDS for a fired booking's order (after commit).""" + from services.printer_service import route_and_print_sync + from services.sse_bus import broadcast_sync + if item_ids: + try: + route_and_print_sync(order_id, item_ids, db) + except Exception as e: # a printer problem never undoes the order + logger.error("Reservation food order %s: printing failed: %s", order_id, e) + broadcast_sync("order_updated", {"order_id": order_id, "table_id": None, "status": "open", "action": "items_added", "item_ids": item_ids}) + broadcast_sync("kds_order_updated", {"order_id": order_id, "kds_status": "pending"}) + + +def fire_due(db, now=None) -> list[int]: + """Fire every confirmed booking whose food is due (needs an open business day). Commits. + Returns the new order ids.""" + from models.reservation import Reservation + now = now or utcnow() + due = (db.query(Reservation) + .filter(Reservation.status.in_(("pending", "arrived")), Reservation.items_json.isnot(None), + Reservation.order_id.is_(None), Reservation.fire_at.isnot(None), Reservation.fire_at <= now) + .order_by(Reservation.fire_at).all()) + out = [] + for r in due: + ids = fire(db, r) + if ids is None: + break # no business day open: try again later + db.commit() + send_to_kitchen(db, r.order_id, ids) + out.append(r.order_id) + return out + + +async def fire_worker(): + """Module worker (connect_orders): fires bookings' food when it's due.""" + from database import SessionLocal + + def _run(): + db = SessionLocal() + try: + fire_due(db) + finally: + db.close() + while True: + try: + await asyncio.to_thread(_run) + except Exception as e: + logger.warning("Reservation fire check failed: %s", e) + await asyncio.sleep(FIRE_EVERY) + + +def mirror_args(r): + """(cloud id, cloud status, reason) for status mirroring, or None for a booking not from online.""" + if not r.online_order_cloud_id or r.status not in CLOUD_STATUS: + return None + return r.online_order_cloud_id, CLOUD_STATUS[r.status], r.response_note diff --git a/local_backend/tests/test_modules.py b/local_backend/tests/test_modules.py index 0c6caa7..c533881 100644 --- a/local_backend/tests/test_modules.py +++ b/local_backend/tests/test_modules.py @@ -190,9 +190,11 @@ def test_supervisor_starts_and_stops_workers(monkeypatch): started, after = asyncio.run(scenario()) assert started == ["connect_menu:services.cloud_sync:menu_push_worker", - "connect_orders:services.cloud_sync:order_pull_worker"] - assert after == ["connect_orders:services.cloud_sync:order_pull_worker"] - assert calls == ["run", "run"] + "connect_orders:services.cloud_sync:order_pull_worker", + "connect_orders:services.online_reservations:fire_worker"] # S.6 + assert after == ["connect_orders:services.cloud_sync:order_pull_worker", + "connect_orders:services.online_reservations:fire_worker"] + assert calls == ["run", "run", "run"] def test_worker_specs_resolve_to_coroutines(): diff --git a/local_backend/tests/test_online_bookings.py b/local_backend/tests/test_online_bookings.py new file mode 100644 index 0000000..dbf8a8f --- /dev/null +++ b/local_backend/tests/test_online_bookings.py @@ -0,0 +1,202 @@ +"""Table bookings from the online ordering app (plan phase 3S, step S.6): a booking arrives as a +reservation to confirm or decline; food ordered ahead reaches the kitchen at its fire time (the +booking time − the venue's fire minutes), not at once; the guests are seated and their food +moves to the table; every step is mirrored to the cloud.""" +import json +from datetime import timedelta + +import pytest + +from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures) +from tests.test_pos import drawer_printer, menu, till # noqa: F401 (fixtures) +from tests.test_pos_online import cloud, counter, kds_ids # noqa: F401 (fixtures) + + +def book(db, menu, cloud_id=701, *, minutes=120, food=True, party=4): + """A booking as the cloud hands it over.""" + from core.timeutil import utcnow + from services.cloud_sync import store_online_orders + booked = [] + lines = [{"product_id": menu["burger"].id, "name": "Burger", "quantity": 2, "unit_price": 10.0, "options": []}, + {"product_id": menu["coffee"].id, "name": "Freddo", "quantity": 1, "unit_price": 3.0, "options": []}] if food else [] + order = { + "id": cloud_id, "public_ref": f"ORD-{cloud_id:04d}", "order_type": "preorder" if food else "reservation", + "sales_point": "online_preorder" if food else None, "customer_name": "Eleni", "customer_phone": "6977777777", + "customer_notes": "By the window", "party_size": party, "status": "pending_acceptance", + "requested_for": (utcnow() + timedelta(minutes=minutes)).isoformat(), "created_at": utcnow().isoformat(), + "items_json": json.dumps(lines), "subtotal": 23.0 if food else 0.0, "delivery_fee": 0.0, "total": 23.0 if food else 0.0, + } + stored = store_online_orders(db, [order], booked) + return stored[cloud_id], booked + + +@pytest.fixture +def fire_in(db): + """The venue's fire minutes (Online ordering → Reservations).""" + from models.settings import PosSettings + + def _set(minutes): + value = json.dumps({"reservations": {"enabled": True, "with_food": True, "fire_minutes": minutes}}) + row = db.get(PosSettings, "connect_orders.ordering") + if row is None: + db.add(PosSettings(key="connect_orders.ordering", value=value)) + else: + row.value = value + db.commit() + return _set + + +def bookings(client, counter): + r = client.get("/api/connect/bookings", headers=counter["h"]) + assert r.status_code == 200, r.text + return r.json() + + +def test_a_booking_with_food_reaches_the_kitchen_at_its_fire_time(client, db, counter, menu, owner_h, cloud, fire_in): + from core.timeutil import utcnow + from models.order import Order + from models.reservation import Reservation + from services import online_reservations as svc + fire_in(30) + rid, booked = book(db, menu) + assert booked == [rid] + r = db.get(Reservation, rid) + assert (r.status, r.source, r.party_size, r.online_ref, r.total, r.order_id) == ("requested", "online", 4, "ORD-0701", 23.0, None) + assert book(db, menu)[0] == -rid # a repeated pull stores it once + b = bookings(client, counter) + assert [x["id"] for x in b["requested"]] == [rid] and b["upcoming"] == [] + x = b["requested"][0] + assert [(line["name"], line["quantity"]) for line in x["lines"]] == [("Burger", 2), ("Freddo", 1)] and x["price_diff"] is None + # confirmed two hours ahead: the kitchen doesn't get anything yet + c = client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"]) + assert c.status_code == 200, c.text + assert c.json()["status"] == "pending" and c.json()["order_id"] is None + db.refresh(r) + assert abs((r.fire_at - (r.reserved_for - timedelta(minutes=30))).total_seconds()) < 1 + assert cloud["mirror"] == [(701, "accepted", None)] and cloud["printed"] == [] + assert svc.fire_due(db) == [] + assert err(client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"])) == "reservation.status_changed" + # fire time: the order is made, printed, and on the KDS + fired = svc.fire_due(db, now=r.fire_at + timedelta(seconds=1)) + db.refresh(r) + assert fired == [r.order_id] + order = db.get(Order, r.order_id) + assert (order.source, order.online_status, order.online_order_ref, order.sales_point, order.customer_count) == \ + ("online", None, "ORD-0701", "online_preorder", 4) + assert [(i.product_name, i.quantity, i.unit_price) for i in order.items] == [("Burger", 2, 10.0), ("Freddo", 1, 3.0)] + assert cloud["printed"] == [(order.id, sorted(i.id for i in order.items))] + assert order.id in kds_ids(client, owner_h) + assert svc.fire_due(db, now=utcnow() + timedelta(days=1)) == [] # once + # not on the counter's online board (it's a booking's food, not an order to answer) + board = client.get("/api/connect/orders/board", headers=counter["h"]).json() + assert order.id not in [o["id"] for lst in board.values() for o in lst] + + +def test_seated_the_food_moves_to_the_table(client, db, counter, menu, cloud, fire_in, owner_h): + from models.order import Order + from models.reservation import Reservation + from models.table import Table + fire_in(15) + t5 = Table(number=5, label="T5", is_active=True) + t6 = Table(number=6, label="T6", is_active=True) + db.add_all([t5, t6]) + db.commit() + busy = Order(table_id=t6.id, opened_by=counter["user"].id, status="open", business_day_id=counter["day"].id) + db.add(busy) + db.commit() + rid, _ = book(db, menu, cloud_id=702) + h = counter["h"] + assert err(client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={})) == "reservation.status_changed" # not confirmed + client.post(f"/api/connect/bookings/{rid}/confirm", headers=h) + assert err(client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={"table_id": t6.id})) == "reservation.table_busy" + assert err(client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={"table_id": 9999})) == "reservation.table_unknown" + # early: the food goes to the kitchen now, on table 5 + a = client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={"table_id": t5.id}) + assert a.status_code == 200, a.text + assert a.json()["status"] == "arrived" and a.json()["table_label"] == "T5" and a.json()["order_id"] + order = db.get(Order, a.json()["order_id"]) + assert order.table_id == t5.id and len(cloud["printed"]) == 1 + assert [m[1] for m in cloud["mirror"]] == ["accepted", "delivered"] + assert db.get(Reservation, rid).status == "arrived" + + +def test_fired_before_arrival_then_seated(client, db, counter, menu, cloud, fire_in): + from models.order import Order + from models.table import Table + from services import online_reservations as svc + fire_in(60) + t7 = Table(number=7, label="T7", is_active=True) + db.add(t7) + db.commit() + rid, _ = book(db, menu, cloud_id=703, minutes=30) # due in 30 min, fire 60 before → at once + c = client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"]).json() + assert c["order_id"] and len(cloud["printed"]) == 1 # confirmed late: fired right away + order_id = c["order_id"] + assert db.get(Order, order_id).table_id is None + a = client.post(f"/api/connect/bookings/{rid}/arrive", headers=counter["h"], json={"table_id": t7.id}).json() + db.expire_all() + assert a["order_id"] == order_id and db.get(Order, order_id).table_id == t7.id and len(cloud["printed"]) == 1 + assert svc.fire_due(db) == [] + + +def test_no_business_day_the_food_waits(client, db, counter, menu, cloud, fire_in): + from models.business_day import BusinessDay + from models.reservation import Reservation + from services import online_reservations as svc + fire_in(0) + rid, _ = book(db, menu, cloud_id=704, minutes=1) + client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"]) + db.expire_all() + r = db.get(Reservation, rid) + counter["day"].status = "closed" + db.commit() + later = r.fire_at + timedelta(minutes=5) + assert svc.fire_due(db, now=later) == [] and db.get(Reservation, rid).order_id is None + db.add(BusinessDay(status="open", opened_at=later, business_date=counter["day"].business_date, opened_by_id=counter["user"].id)) + db.commit() + assert len(svc.fire_due(db, now=later)) == 1 + + +def test_a_table_only_decline_and_cancel(client, db, counter, menu, cloud): + from models.reservation import Reservation + rid, _ = book(db, menu, cloud_id=705, food=False, party=2) + r = db.get(Reservation, rid) + assert r.items_json is None and r.total is None + d = client.post(f"/api/connect/bookings/{rid}/decline", headers=counter["h"], json={"reason": "Fully booked"}) + assert d.json()["status"] == "declined" and d.json()["response_note"] == "Fully booked" + assert cloud["mirror"] == [(705, "rejected", "Fully booked")] + assert bookings(client, counter)["requested"] == [] + rid2, _ = book(db, menu, cloud_id=706, food=False) + client.post(f"/api/connect/bookings/{rid2}/confirm", headers=counter["h"]) + assert [x["id"] for x in bookings(client, counter)["upcoming"]] == [rid2] + x = client.post(f"/api/connect/bookings/{rid2}/cancel", headers=counter["h"], json={"status": "no_show"}).json() + assert x["status"] == "no_show" and cloud["mirror"][-1] == (706, "cancelled", None) + assert x["order_id"] is None + + +def test_the_manager_card_steps_are_mirrored(client, db, owner_h, menu, cloud, counter): + rid, _ = book(db, menu, cloud_id=707, food=False) + assert rid in [r["id"] for r in client.get("/api/reservations/?tab=upcoming", headers=owner_h).json()] + client.post(f"/api/connect/bookings/{rid}/confirm", headers=owner_h) + r = client.patch(f"/api/reservations/{rid}/status", headers=owner_h, json={"status": "arrived"}) + assert r.status_code == 200, r.text + assert r.json()["status"] == "arrived" and cloud["mirror"][-1] == (707, "delivered", None) + + +def test_bookings_need_the_key(client, pair, make_user): + token, _ = pair("pos_counter", "Other till") + jwt = terminal_login(client, token, make_user(role="waiter")) + h = {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"} + assert err(client.get("/api/connect/bookings", headers=h)) == "access.denied" + + +def test_reservation_settings(client, owner_h): + body = client.get("/api/connect/fees/ordering", headers=owner_h).json() + assert body["reservations"] == {"enabled": False, "with_food": False, "hours": {}, "slot_minutes": 30, "days_ahead": 30, + "notice_minutes": 60, "party_max": 10, "fire_minutes": 20} + body["reservations"].update(enabled=True, with_food=True, hours={"4": [["19:00", "23:30"]]}, party_max=8, fire_minutes=25) + r = client.put("/api/connect/fees/ordering", headers=owner_h, json=body) + assert r.status_code == 200, r.text + assert r.json()["reservations"]["hours"] == {"4": [["19:00", "23:30"]]} and r.json()["reservations"]["fire_minutes"] == 25 + body["reservations"]["party_max"] = 0 + assert client.put("/api/connect/fees/ordering", headers=owner_h, json=body).status_code == 422 diff --git a/manager_dashboard/src/pages/DashboardPage.jsx b/manager_dashboard/src/pages/DashboardPage.jsx index da40c17..8984b03 100644 --- a/manager_dashboard/src/pages/DashboardPage.jsx +++ b/manager_dashboard/src/pages/DashboardPage.jsx @@ -1396,13 +1396,14 @@ function RevenueChart({ orders }) { // ─── Reservations ───────────────────────────────────────────────────────────── const STATUS_META = { + requested: { label: 'Αίτημα online', bg: '#fff7ed', color: '#c2410c' }, // phase 3S, S.6: to confirm or decline pending: { label: 'Αναμονή', bg: '#f0f4ff', color: '#3758c9' }, arrived: { label: 'Έφτασε', bg: '#eef7f0', color: '#1f7042' }, cancelled: { label: 'Ακυρώθηκε', bg: '#fef2f2', color: '#dc2626' }, no_show: { label: 'Δεν ήρθε', bg: '#fff7ed', color: '#c2410c' }, } -function ReservationRow({ res, tables, onStatusChange, onEdit }) { +function ReservationRow({ res, tables, onStatusChange, onEdit, onAnswer }) { const meta = STATUS_META[res.status] || STATUS_META.pending const time = new Date(res.reserved_for).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) const dateStr = new Date(res.reserved_for).toLocaleDateString('el-GR', { day: 'numeric', month: 'short' }) @@ -1449,6 +1450,20 @@ function ReservationRow({ res, tables, onStatusChange, onEdit }) { background: 'white', cursor: 'pointer', fontSize: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', }}>✏️ + {res.status === 'requested' && ( + <> + + + + )} {res.status === 'pending' && ( - )} - - - ))} - - )} - + set('anyTime', v)} onDays={d => set('days', d)} testId="ordering-hours" />
@@ -92,7 +64,82 @@ export default function OrderingSettings({ ordering, onSaved }) {
set('asap', v)} label={t('ordering.asap')} description={t('ordering.asapHint')} /> + +
+
+

{t('booking.title')}

+

{t('booking.intro')}

+
+ setRes('enabled', v)} label={t('booking.enabled')} description={t('booking.enabledHint')} data-testid="booking-enabled" /> + {form.res.enabled && ( + <> + setRes('with_food', v)} label={t('booking.withFood')} description={t('booking.withFoodHint')} data-testid="booking-food" /> + setRes('anyTime', v)} onDays={d => setRes('days', d)} + anyLabel={t('booking.anyTime')} anyHint={t('booking.anyTimeHint')} testId="booking-hours" /> +
+ + + + + setRes('notice_minutes', e.target.value)} /> + + + setRes('days_ahead', e.target.value)} data-testid="booking-ahead" /> + + + setRes('party_max', e.target.value)} data-testid="booking-party" /> + + {form.res.with_food && ( + + setRes('fire_minutes', e.target.value)} data-testid="booking-fire" /> + + )} +
+ + )} +
) } + +/** Hours per day (several ranges, past midnight), or any time. */ +function Hours({ anyTime, days, onAnyTime, onDays, anyLabel, anyHint, testId }) { + const { t } = useTranslation('manager') + const setDay = (d, ranges) => onDays(days.map((r, i) => (i === d ? ranges : r))) + return ( +
+ + {!anyTime && ( +
    + {DAYS.map(d => ( +
  • + {t(`fees.dayLong.${d}`)} +
    + {days[d].length === 0 && {t('ordering.closedDay')}} + {days[d].map((r, i) => ( +
    + setDay(d, days[d].map((x, j) => (j === i ? { ...x, from: e.target.value } : x)))} /> + – + setDay(d, days[d].map((x, j) => (j === i ? { ...x, to: e.target.value } : x)))} /> + setDay(d, days[d].filter((_, j) => j !== i))}> +
    + ))} + {days[d].length < 4 && ( + + )} +
    +
  • + ))} +
+ )} +
+ ) +} diff --git a/manager_dashboard/src/pages/online/feesLogic.js b/manager_dashboard/src/pages/online/feesLogic.js index 0eadb64..d8787c6 100644 --- a/manager_dashboard/src/pages/online/feesLogic.js +++ b/manager_dashboard/src/pages/online/feesLogic.js @@ -104,28 +104,48 @@ export function previewBody(form) { } /** Online ordering settings (S.4) → the form: hours as editable rows per day. */ +const toDays = hours => DAYS.map(d => (hours?.[String(d)] ?? []).map(([from, to]) => ({ from, to }))) +function toHours(anyTime, days) { + const hours = {} + if (!anyTime) { + days.forEach((ranges, d) => { + const clean = ranges.filter(r => r.from && r.to && r.from !== r.to).map(r => [r.from, r.to]) + if (clean.length) hours[String(d)] = clean + }) + } + return hours +} +const int = (v, dflt) => (Number.isFinite(Number(v)) && String(v).trim() !== '' ? Math.round(Number(v)) : dflt) + +/** Table bookings online (S.6): the defaults the backend has. */ +export const RES_DEFAULTS = { enabled: false, with_food: false, hours: {}, slot_minutes: 30, days_ahead: 30, notice_minutes: 60, party_max: 10, fire_minutes: 20 } + export function orderingToForm(o) { const hours = o?.hours ?? {} + const r = { ...RES_DEFAULTS, ...(o?.reservations ?? {}) } return { services: o?.services ?? [], anyTime: Object.keys(hours).length === 0, - days: DAYS.map(d => (hours[String(d)] ?? []).map(([from, to]) => ({ from, to }))), + days: toDays(hours), prep_minutes: String(o?.prep_minutes ?? 20), slot_minutes: String(o?.slot_minutes ?? 15), days_ahead: String(o?.days_ahead ?? 0), asap: o?.asap ?? true, + res: { + enabled: !!r.enabled, with_food: !!r.with_food, anyTime: Object.keys(r.hours ?? {}).length === 0, days: toDays(r.hours), + slot_minutes: String(r.slot_minutes), days_ahead: String(r.days_ahead), notice_minutes: String(r.notice_minutes), + party_max: String(r.party_max), fire_minutes: String(r.fire_minutes), + }, } } /** The form → PUT /api/connect/fees/ordering. A day without ranges is closed (unless any time). */ export function orderingBody(form) { - const hours = {} - if (!form.anyTime) { - form.days.forEach((ranges, d) => { - const clean = ranges.filter(r => r.from && r.to && r.from !== r.to).map(r => [r.from, r.to]) - if (clean.length) hours[String(d)] = clean - }) - } - const int = (v, dflt) => (Number.isFinite(Number(v)) && String(v).trim() !== '' ? Math.round(Number(v)) : dflt) + const r = form.res ?? orderingToForm(null).res return { - services: form.services, hours, prep_minutes: int(form.prep_minutes, 20), slot_minutes: int(form.slot_minutes, 15), + services: form.services, hours: toHours(form.anyTime, form.days), prep_minutes: int(form.prep_minutes, 20), slot_minutes: int(form.slot_minutes, 15), days_ahead: int(form.days_ahead, 0), asap: !!form.asap, + reservations: { + enabled: !!r.enabled, with_food: !!r.enabled && !!r.with_food, hours: toHours(r.anyTime, r.days), + slot_minutes: int(r.slot_minutes, 30), days_ahead: int(r.days_ahead, 30), notice_minutes: int(r.notice_minutes, 60), + party_max: int(r.party_max, 10), fire_minutes: int(r.fire_minutes, 20), + }, } } diff --git a/manager_dashboard/tests/fees.test.mjs b/manager_dashboard/tests/fees.test.mjs index 5fa2b48..bbc283b 100644 --- a/manager_dashboard/tests/fees.test.mjs +++ b/manager_dashboard/tests/fees.test.mjs @@ -51,15 +51,27 @@ test('moving rules and the test form', () => { }) test('online ordering settings: hours per day, any time, numbers', async () => { - const { orderingBody, orderingToForm } = await import('../src/pages/online/feesLogic.js') - const saved = { services: ['delivery'], hours: { 5: [['20:00', '02:00']] }, prep_minutes: 30, slot_minutes: 15, days_ahead: 1, asap: false } + const { RES_DEFAULTS, orderingBody, orderingToForm } = await import('../src/pages/online/feesLogic.js') + const saved = { services: ['delivery'], hours: { 5: [['20:00', '02:00']] }, prep_minutes: 30, slot_minutes: 15, days_ahead: 1, asap: false, + reservations: RES_DEFAULTS } const form = orderingToForm(saved) assert.equal(form.anyTime, false) assert.deepEqual(form.days[5], [{ from: '20:00', to: '02:00' }]) assert.deepEqual(orderingBody(form), saved) assert.deepEqual(orderingBody({ ...form, anyTime: true }).hours, {}) const blank = orderingToForm(null) - assert.deepEqual(orderingBody({ ...blank, prep_minutes: '' }), { services: [], hours: {}, prep_minutes: 20, slot_minutes: 15, days_ahead: 0, asap: true }) + assert.deepEqual(orderingBody({ ...blank, prep_minutes: '' }), { services: [], hours: {}, prep_minutes: 20, slot_minutes: 15, days_ahead: 0, asap: true, reservations: RES_DEFAULTS }) form.days[0] = [{ from: '12:00', to: '12:00' }, { from: '', to: '15:00' }] assert.equal(orderingBody(form).hours['0'], undefined) }) + +test('table bookings online: settings round trip (S.6)', async () => { + const { orderingBody, orderingToForm } = await import('../src/pages/online/feesLogic.js') + const reservations = { enabled: true, with_food: true, hours: { 4: [['19:00', '23:30']] }, slot_minutes: 15, days_ahead: 14, notice_minutes: 90, party_max: 8, fire_minutes: 25 } + const form = orderingToForm({ services: [], hours: {}, reservations }) + assert.equal(form.res.anyTime, false) + assert.deepEqual(orderingBody(form).reservations, reservations) + assert.deepEqual(orderingBody({ ...form, res: { ...form.res, enabled: false } }).reservations.with_food, false) + assert.deepEqual(orderingBody({ ...form, res: { ...form.res, anyTime: true, party_max: '' } }).reservations, + { ...reservations, hours: {}, party_max: 10 }) +}) diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 6512674..522e38a 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -104,5 +104,11 @@ "area_in_use": "Αυτή η περιοχή χρησιμοποιείται από κανόνες χρέωσης: {{rules}}. Αλλάξτε πρώτα αυτούς τους κανόνες.", "order_invalid": "Η νέα σειρά πρέπει να περιέχει κάθε κανόνα μία φορά.", "vat_group_unknown": "Η ομάδα ΦΠΑ {{vat_group_id}} δεν είναι μία από τις ομάδες της φορολογικής μηχανής." + }, + "reservation": { + "not_found": "Η κράτηση {{reservation_id}} δεν βρέθηκε.", + "status_changed": "Η κράτηση άλλαξε από άλλη οθόνη στο μεταξύ (τώρα είναι {{current}}).", + "table_unknown": "Το τραπέζι {{table_id}} δεν βρέθηκε.", + "table_busy": "Αυτό το τραπέζι έχει ήδη ανοιχτή παραγγελία. Διαλέξτε άλλο τραπέζι ή κλείστε πρώτα εκείνη την παραγγελία." } } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 3932bf4..f04b11c 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -554,5 +554,22 @@ "vat": "Ομάδα ΦΠΑ", "vatNone": "Χωρίς ομάδα ΦΠΑ", "noGroups": "Ορίστε τις ομάδες ΦΠΑ της φορολογικής μηχανής στις Ρυθμίσεις → Φορολογικά για να διαλέξετε εδώ." + }, + "booking": { + "title": "Κρατήσεις τραπεζιών", + "intro": "Οι πελάτες κλείνουν τραπέζι από την εφαρμογή online παραγγελιών· εσείς επιβεβαιώνετε ή απορρίπτετε κάθε αίτημα στο ταμείο (Online → Κρατήσεις) ή στον πίνακα ελέγχου.", + "enabled": "Online κρατήσεις τραπεζιών", + "enabledHint": "Οι πελάτες επιλέγουν ημέρα, ώρα και άτομα.", + "withFood": "Παραγγελία φαγητού μαζί με την κράτηση", + "withFoodHint": "Τα πιάτα της κράτησης πηγαίνουν στην κουζίνα λίγο πριν φτάσουν οι πελάτες, με τις τιμές προπαραγγελίας (Σημεία πώλησης: Online προπαραγγελία).", + "anyTime": "Κρατήσεις οποιαδήποτε ώρα", + "anyTimeHint": "Ανενεργό: μόνο μέσα στις παρακάτω ώρες.", + "slotHint": "Οι ώρες που προσφέρονται.", + "notice": "Προειδοποίηση (λεπτά)", + "noticeHint": "Η νωρίτερη κράτηση από τώρα.", + "ahead": "Ημέρες μπροστά", + "party": "Μέγιστα άτομα ανά κράτηση", + "fire": "Η κουζίνα παίρνει το φαγητό (λεπτά πριν την άφιξη)", + "fireHint": "0 = την ώρα της κράτησης." } } diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index cc4003d..1c4907d 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -300,7 +300,8 @@ "lists": { "incoming": "Νέες", "in_progress": "Σε εξέλιξη", - "finished": "Ολοκληρωμένες" + "finished": "Ολοκληρωμένες", + "bookings": "Κρατήσεις" }, "empty": { "incoming": "Δεν υπάρχουν νέες online παραγγελίες", @@ -427,6 +428,42 @@ "card": "Η επιστροφή {{amount}} (κάρτα) καταγράφηκε. Το σύστημα δεν στέλνει ακόμη πιστωτικά σε αυτή τη φορολογική μηχανή: εκδώστε το στη μηχανή τώρα." }, "fiscalManualOk": "Έγινε" + }, + "bookings": { + "arrived_one": "Νέο αίτημα κράτησης", + "arrived_other": "{{count}} νέα αιτήματα κράτησης", + "empty": "Καμία κράτηση", + "emptyBody": "Οι κρατήσεις τραπεζιών από την εφαρμογή online παραγγελιών εμφανίζονται εδώ, με ήχο.", + "pick": "Επιλέξτε μια κράτηση", + "withFood": "Φαγητό με προπαραγγελία", + "people_one": "{{count}} άτομο", + "people_other": "{{count}} άτομα", + "today": "Σήμερα {{time}}", + "status": { + "requested": "Αναμένει απάντηση", + "pending": "Επιβεβαιωμένη", + "arrived": "Κάθισαν", + "declined": "Απορρίφθηκε", + "cancelled": "Ακυρώθηκε", + "no_show": "Δεν ήρθαν" + }, + "foodSent": "Το φαγητό στάλθηκε στην κουζίνα", + "foodAt": "Το φαγητό πηγαίνει στην κουζίνα: {{time}}", + "foodOnConfirm": "Το φαγητό πηγαίνει στην κουζίνα πριν έρθουν, μόλις επιβεβαιωθεί", + "confirm": "Επιβεβαίωση κράτησης", + "decline": "Απόρριψη", + "declineTitle": "Απόρριψη της κράτησης;", + "reasons": { + "full": "Είμαστε γεμάτοι εκείνη την ώρα", + "closed": "Είμαστε κλειστά τότε", + "party": "Δεν χωράει παρέα αυτού του μεγέθους", + "other": "Άλλος λόγος…" + }, + "table": "Τραπέζι", + "noTable": "Χωρίς τραπέζι ακόμα", + "arrive": "Ήρθαν: καθίστε τους", + "cancel": "Ακύρωση", + "noShow": "Δεν ήρθαν" } } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index b118cce..6ff11d9 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -104,5 +104,11 @@ "area_in_use": "This area is used by fee rules: {{rules}}. Change those rules first.", "order_invalid": "The new order must list every rule once.", "vat_group_unknown": "VAT group {{vat_group_id}} isn't one of the fiscal machine's groups." + }, + "reservation": { + "not_found": "Booking {{reservation_id}} not found.", + "status_changed": "This booking was changed on another screen in the meantime (it is now {{current}}).", + "table_unknown": "Table {{table_id}} not found.", + "table_busy": "That table already has an open order. Pick another table, or close that order first." } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index c2458b7..19836f9 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -554,5 +554,22 @@ "vat": "VAT group", "vatNone": "No VAT group", "noGroups": "Set up the fiscal machine's VAT groups in Settings → Fiscal to pick one here." + }, + "booking": { + "title": "Table bookings", + "intro": "Customers book a table in the online ordering app; you confirm or decline each request at the counter (Online → Bookings) or on the dashboard.", + "enabled": "Take table bookings online", + "enabledHint": "Customers pick the day, time and how many people.", + "withFood": "Let them order food ahead", + "withFoodHint": "Dishes picked with the booking go to the kitchen shortly before the guests arrive, at the pre-order prices (Sales points: Online pre-order).", + "anyTime": "Bookings any time", + "anyTimeHint": "Off: only inside the hours below.", + "slotHint": "The times offered.", + "notice": "Notice (minutes)", + "noticeHint": "The earliest booking from now.", + "ahead": "Days ahead", + "party": "Most people per booking", + "fire": "Kitchen gets the food (minutes before arrival)", + "fireHint": "0 = at the booking time." } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 1497152..8c48510 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -300,7 +300,8 @@ "lists": { "incoming": "New", "in_progress": "In progress", - "finished": "Finished" + "finished": "Finished", + "bookings": "Bookings" }, "empty": { "incoming": "No new online orders", @@ -427,6 +428,42 @@ "card": "The refund of {{amount}} (card) is recorded. The system can't send credit notes to this fiscal machine yet: issue it on the machine now." }, "fiscalManualOk": "Done" + }, + "bookings": { + "arrived_one": "New table booking request", + "arrived_other": "{{count}} new table booking requests", + "empty": "No bookings", + "emptyBody": "Table bookings from the online ordering app show here, with a sound.", + "pick": "Pick a booking to see it", + "withFood": "Food ordered ahead", + "people_one": "{{count}} person", + "people_other": "{{count}} people", + "today": "Today {{time}}", + "status": { + "requested": "Waiting for an answer", + "pending": "Confirmed", + "arrived": "Seated", + "declined": "Declined", + "cancelled": "Cancelled", + "no_show": "No-show" + }, + "foodSent": "The food has gone to the kitchen", + "foodAt": "The food goes to the kitchen: {{time}}", + "foodOnConfirm": "The food goes to the kitchen before they arrive, once confirmed", + "confirm": "Confirm booking", + "decline": "Decline", + "declineTitle": "Decline this booking?", + "reasons": { + "full": "We're fully booked then", + "closed": "We're closed then", + "party": "We can't seat a party this size", + "other": "Other reason…" + }, + "table": "Table", + "noTable": "No table yet", + "arrive": "They're here: seat them", + "cancel": "Cancel", + "noShow": "No-show" } } } diff --git a/terminal/src/apps/pos/BookingPanel.jsx b/terminal/src/apps/pos/BookingPanel.jsx new file mode 100644 index 0000000..4e4b99d --- /dev/null +++ b/terminal/src/apps/pos/BookingPanel.jsx @@ -0,0 +1,157 @@ +// One table booking at the counter (plan phase 3S, step S.6): who, how many, when, their note, +// and the food they ordered ahead (with a warning when the venue's prices differ). A request is +// confirmed or declined (the customer sees the answer and the reason); a confirmed booking says +// when its food goes to the kitchen, seats the guests at a free table (their food's order moves +// there, and is sent now if it hadn't been), or is cancelled / marked as a no-show. +import { useState } from 'react' +import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useFormat, useTranslation } from '@xenia/i18n' +import { Button, Dialog, EmptyState, Input, Select } from '@xenia/ui' +import client from '../../api/client' +import { bookingSteps, foodState, freeTables, whenLabel } from './logic/bookings' + +const REASONS = ['full', 'closed', 'party'] + +export default function BookingPanel({ booking, tables, onChanged }) { + const { t } = useTranslation('terminal') + const fmt = useFormat() + const [busy, setBusy] = useState(false) + const [error, setError] = useState('') + const [table, setTable] = useState('') + const [declining, setDeclining] = useState(false) + + if (!booking) { + return ( + + ) + } + + const steps = bookingSteps(booking) + const food = foodState(booking) + const free = freeTables(tables) + const run = async (path, body) => { + setBusy(true) + setError('') + try { + await client.post(`/api/connect/bookings/${booking.id}/${path}`, body ?? {}) + setDeclining(false) + onChanged() + } catch (err) { setError(errorMessage(err, t)); onChanged() } finally { setBusy(false) } + } + + return ( + + ) +} + +function Detail({ icon: Icon, children }) { + return
+} + +function DeclineDialog({ busy, error, onClose, onDecline }) { + const { t } = useTranslation('terminal') + const [choice, setChoice] = useState(null) + const [other, setOther] = useState('') + const reason = choice === 'other' ? other.trim() : choice ? t(`pos.bookings.reasons.${choice}`) : '' + return ( + + + + }> +
+

{t('pos.online.rejectBody')}

+
+ {[...REASONS, 'other'].map(r => ( + + ))} +
+ {choice === 'other' && setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} />} + {error &&

{error}

} +
+
+ ) +} diff --git a/terminal/src/apps/pos/BookingsView.jsx b/terminal/src/apps/pos/BookingsView.jsx new file mode 100644 index 0000000..5904ece --- /dev/null +++ b/terminal/src/apps/pos/BookingsView.jsx @@ -0,0 +1,48 @@ +// Table bookings at the counter (plan phase 3S, step S.6): Online → Bookings. Requests from the +// online ordering app waiting for an answer come first (they stand out), then the confirmed +// bookings from a few hours ago on, soonest first. A tap shows one on the right (BookingPanel). +import { CalendarClock, Users, UtensilsCrossed } from 'lucide-react' +import { useFormat, useTranslation } from '@xenia/i18n' +import { EmptyState, Spinner } from '@xenia/ui' +import { whenLabel } from './logic/bookings' + +export default function BookingsView({ data, picked, onPick }) { + const { t } = useTranslation('terminal') + if (!data) return
+ const all = [...data.requested, ...data.upcoming] + if (!all.length) { + return ( +
+ +
+ ) + } + return ( +
+ {all.map(b => onPick(b.id)} />)} +
+ ) +} + +function BookingCard({ booking, picked, onPick }) { + const { t } = useTranslation('terminal') + const fmt = useFormat() + const asking = booking.status === 'requested' + return ( + + ) +} diff --git a/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx index 7df359f..4b7d3bb 100644 --- a/terminal/src/apps/pos/PosScreen.jsx +++ b/terminal/src/apps/pos/PosScreen.jsx @@ -20,6 +20,9 @@ import { useLiveEvent } from '../../device/context' import { playChime } from './chime' import { addLine, categoriesWithProducts, forSalesPoint, salesPointFor, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart' import { findOnline, ONLINE_LISTS } from './logic/online' +import { BOOKING_LIST, findBooking } from './logic/bookings' +import BookingPanel from './BookingPanel' +import BookingsView from './BookingsView' import { zoneCounts } from './logic/tables' import OnlinePanel from './OnlinePanel' import OnlineView from './OnlineView' @@ -29,7 +32,7 @@ import ReceiptsView from './ReceiptsView' import SaleCart from './SaleCart' import TablePanel from './TablePanel' import TablesView from './TablesView' -import { useMenu, useOnline, useReceipts, useTables } from './usePos' +import { useBookings, useMenu, useOnline, useReceipts, useTables } from './usePos' const REMIND_MS = 30_000 @@ -61,9 +64,11 @@ function Counter({ menu, t }) { const online = useOnline(onlineOn) const [onlineList, setOnlineList] = useState('incoming') const [onlineId, setOnlineId] = useState(null) + const bookings = useBookings(onlineOn) // table bookings from the online app (S.6) + const [bookingId, setBookingId] = useState(null) const [now, setNow] = useState(() => Date.now()) const [chimes, setChimes] = useState(0) - const waiting = online.data?.incoming.length ?? 0 + const waiting = (online.data?.incoming.length ?? 0) + (bookings.data?.requested.length ?? 0) const [receiptScope, setReceiptScope] = useState('mine') const [receiptId, setReceiptId] = useState(null) const receipts = useReceipts(receiptScope, mode === 'receipts') @@ -74,6 +79,11 @@ function Counter({ menu, t }) { ring() if (mode !== 'online') toast.info(t('pos.online.arrived', { count: data?.count ?? 1 })) }) + useLiveEvent('reservation_requested', data => { + if (!onlineOn) return + ring() + if (mode !== 'online') toast.info(t('pos.bookings.arrived', { count: data?.count ?? 1 })) + }) // a reminder while an order waits for an answer; the waiting minutes move on too useEffect(() => { const id = setInterval(() => { @@ -88,6 +98,8 @@ function Counter({ menu, t }) { const atTable = mode === 'tables' && table != null const picking = mode === 'tables' && !atTable const onlineOrder = findOnline(online.data, onlineId) + const booking = findBooking(bookings.data, bookingId) + const onBookings = mode === 'online' && onlineList === BOOKING_LIST const setCart = atTable ? setTableCart : setSaleCart const leaveTable = () => { setTableId(null); setTableCart([]) } @@ -129,9 +141,9 @@ function Counter({ menu, t }) { )) ) : mode === 'online' ? ( - ONLINE_LISTS.map(list => ( + [...ONLINE_LISTS, BOOKING_LIST].map(list => ( setOnlineList(list)} testId={`online-list-${list}`} - tally={list === 'finished' ? null : online.data?.[list].length}> + tally={list === 'finished' ? null : list === BOOKING_LIST ? bookings.data?.requested.length : online.data?.[list].length}> {t(`pos.online.lists.${list}`)} )) @@ -162,6 +174,14 @@ function Counter({ menu, t }) { + ) : onBookings ? ( + <> +
+ +
+ { bookings.reload(); tables.reload() }} /> + ) : mode === 'online' ? ( <>
diff --git a/terminal/src/apps/pos/logic/bookings.js b/terminal/src/apps/pos/logic/bookings.js new file mode 100644 index 0000000..f5b337a --- /dev/null +++ b/terminal/src/apps/pos/logic/bookings.js @@ -0,0 +1,37 @@ +// Table bookings at the counter (plan phase 3S, step S.6). Pure: unit-tested in Node +// (tests/pos.test.mjs). The bookings come from GET /api/connect/bookings. + +export const BOOKING_LIST = 'bookings' + +/** The booking with this id in either list (null when gone). */ +export function findBooking(data, id) { + if (!data || id == null) return null + return data.requested.find(b => b.id === id) ?? data.upcoming.find(b => b.id === id) ?? null +} + +/** What the counter can do next with a booking. */ +export function bookingSteps(booking) { + if (!booking) return [] + if (booking.status === 'requested') return ['confirm', 'decline'] + if (booking.status === 'pending') return ['arrive', 'cancel', 'no_show'] + return [] +} + +/** Where the booking's food is: none | waiting (fire time ahead) | kitchen (its order exists). */ +export function foodState(booking) { + if (!booking?.lines?.length) return 'none' + return booking.order_id ? 'kitchen' : 'waiting' +} + +/** Free tables for seating: active, without an open order (from GET /api/pos/tables). */ +export function freeTables(tables) { + return (tables ?? []).filter(t => !t.order) +} + +/** "21:30" today, "Mon 16/11 21:30" another day (venue time, via the formatters). */ +export function whenLabel(iso, { formatDate, formatDateTime, formatTime }, t) { + if (!iso) return '' + return formatDate(iso) === formatDate(new Date()) + ? t('pos.bookings.today', { time: formatTime(iso) }) + : formatDateTime(iso, 'datetimeShort') +} diff --git a/terminal/src/apps/pos/usePos.js b/terminal/src/apps/pos/usePos.js index be9a5a8..b6f8303 100644 --- a/terminal/src/apps/pos/usePos.js +++ b/terminal/src/apps/pos/usePos.js @@ -130,6 +130,22 @@ export function useOnline(enabled) { return { data, reload: load } } +const BOOKING_EVENTS = ['reservation_requested', 'reservation_updated'] + +/** GET /api/connect/bookings: { requested, upcoming } (null while loading); live (S.6). */ +export function useBookings(enabled) { + const [data, setData] = useState(null) + const load = useCallback(async () => { + if (!enabled) { setData(null); return } + try { setData((await client.get('/api/connect/bookings', quiet)).data) } catch { /* the shell shows offline */ } + }, [enabled]) + const soon = useCoalesced(load) + useEffect(() => { load() }, [load]) + useLiveEvent('ready', load) + useLiveEvents(BOOKING_EVENTS, soon) + return { data, reload: load } +} + const RECEIPT_EVENTS = ['order_paid', 'order_refunded', 'order_closed'] /** GET /api/pos/receipts: today's paid orders ({ orders }, null while loading); live. */ diff --git a/terminal/tests/pos.test.mjs b/terminal/tests/pos.test.mjs index b982bb0..94a927d 100644 --- a/terminal/tests/pos.test.mjs +++ b/terminal/tests/pos.test.mjs @@ -203,3 +203,21 @@ test('sales points at the counter: what is sold and at which price (phase 3S)', assert.deepEqual(forSalesPoint([cola, soup, old], 'in_store_takeaway').map(p => [p.id, p.price]), [[1, 2.5], [3, 4]]) assert.deepEqual(forSalesPoint([cola, soup, old], 'in_store').map(p => [p.id, p.price]), [[1, 3.5], [2, 6], [3, 4]]) }) + +test('table bookings at the counter (S.6)', async () => { + const { bookingSteps, findBooking, foodState, freeTables, whenLabel } = await import('../src/apps/pos/logic/bookings.js') + const data = { requested: [{ id: 1, status: 'requested', lines: [] }], upcoming: [{ id: 2, status: 'pending', lines: [{}], order_id: null }] } + assert.equal(findBooking(data, 2).id, 2) + assert.equal(findBooking(data, 9), null) + assert.deepEqual(bookingSteps(data.requested[0]), ['confirm', 'decline']) + assert.deepEqual(bookingSteps(data.upcoming[0]), ['arrive', 'cancel', 'no_show']) + assert.deepEqual(bookingSteps({ status: 'arrived' }), []) + assert.equal(foodState(data.requested[0]), 'none') + assert.equal(foodState(data.upcoming[0]), 'waiting') + assert.equal(foodState({ lines: [{}], order_id: 5 }), 'kitchen') + assert.deepEqual(freeTables([{ id: 1, order: null }, { id: 2, order: { id: 9 } }]).map(t => t.id), [1]) + const fmt = { formatDate: d => new Date(d).toISOString().slice(0, 10), formatDateTime: () => 'other day', formatTime: () => '21:30' } + const t = (k, p) => `${k}:${p?.time ?? ''}` + assert.equal(whenLabel(new Date().toISOString(), fmt, t), 'pos.bookings.today:21:30') + assert.equal(whenLabel('2020-01-01T10:00:00Z', fmt, t), 'other day') +}) diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 84f47bd..c257838 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -572,6 +572,19 @@ try { if (feeProduct?.name !== 'Delivery') await sleep(100) } r.check('fees: the fee line\'s name and VAT group are saved', feeProduct?.name === 'Delivery' && feeProduct?.vat_group_id === 2, JSON.stringify(feeProduct)) + // S.6: table bookings online, with food ordered ahead + await page.getByTestId('booking-enabled').click() + await page.getByTestId('booking-food').click() + await page.getByTestId('booking-party').fill('8') + await page.getByTestId('booking-fire').fill('25') + await page.getByTestId('ordering-save').click() + let bookingCfg = null + for (let i = 0; i < 30 && !bookingCfg?.enabled; i++) { + bookingCfg = (await api('GET', '/api/connect/fees/ordering', { token: boss })).reservations + if (!bookingCfg?.enabled) await sleep(100) + } + r.check('ordering: table bookings on, with food, 8 people at most, the kitchen 25 min before', bookingCfg?.enabled && bookingCfg.with_food && bookingCfg.party_max === 8 + && bookingCfg.fire_minutes === 25, JSON.stringify(bookingCfg)) r.check('fees: …and it never shows in the products list', !(await api('GET', '/api/products/?all=true', { token: boss })).some(p => p.id === feeProduct?.id)) await page.screenshot({ path: path.join(OUT, 'manager-fees.png'), fullPage: true }) diff --git a/tests/e2e/order_app.mjs b/tests/e2e/order_app.mjs index 757f170..7ba32dd 100644 --- a/tests/e2e/order_app.mjs +++ b/tests/e2e/order_app.mjs @@ -20,7 +20,7 @@ const CLOUD_PORT = 8113 const APP_PORT = 5211 const CLOUD_URL = `http://127.0.0.1:${CLOUD_PORT}` const APP_DIR = path.join(REPO, 'cloud-service', 'connect_frontend', 'order-app') -const r = reporter('order app: takeaway + delivery, priced by the cloud, tracked') +const r = reporter('order app: takeaway + delivery + table booking, priced by the cloud, tracked') const procs = [] function start(cmd, args, opts, logName) { @@ -68,7 +68,7 @@ try { ] }, { id: 2, name: 'Food', products: [ { id: 12, name: 'Souvlaki', digital_description: 'Pork, pita, tzatziki', base_price: 4, digital_price: 4, digital_available: true, - sold_at: ['online_takeaway', 'online_delivery'], prices: { online_takeaway: 4, online_delivery: 4.2 }, quick_options: [] }, + sold_at: ['online_takeaway', 'online_delivery', 'online_preorder'], prices: { online_takeaway: 4, online_delivery: 4.2, online_preorder: 3.8 }, quick_options: [] }, { id: 13, name: 'Soup of the day', base_price: 6, digital_available: false, sold_at: ['online_delivery'], prices: { online_delivery: 6 }, quick_options: [] }, ] }, ], @@ -80,7 +80,9 @@ try { { id: 3, name: 'Hills', area_ids: [2], action: 'add', value: 1, sales_points: ['online_delivery'] }, ], }, - ordering: { services: ['takeaway', 'delivery'], hours: {}, prep_minutes: 20, slot_minutes: 15, days_ahead: 0, asap: true }, + ordering: { services: ['takeaway', 'delivery'], hours: {}, prep_minutes: 20, slot_minutes: 15, days_ahead: 0, asap: true, + // S.6: table bookings, with food ordered ahead + reservations: { enabled: true, with_food: true, hours: {}, slot_minutes: 30, days_ahead: 7, notice_minutes: 0, party_max: 6, fire_minutes: 20 } }, } await call('POST', '/api/menu/sync', { headers: siteH, body: { site_id: numeric, snapshot_json: JSON.stringify(snapshot) } }) @@ -171,6 +173,38 @@ try { r.check('a rejected order says so, with the reason', await page.waitForFunction(() => document.querySelector('[data-testid="track"]')?.dataset.status === 'rejected', null, { timeout: 15_000 }) .then(() => true).catch(() => false) && await page.getByText('Closing early').count() === 1) + // ── S.6: book a table, with food ready on arrival ──────────────────────── + await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`) + await page.getByTestId('service-book').click() + r.check('booking: the days the venue takes bookings (today + 7)', await page.getByTestId('booking').waitFor({ timeout: 5000 }).then(() => true).catch(() => false) + && await page.getByTestId('book-day').count() === 8) + await page.getByTestId('book-day').nth(1).click() // tomorrow + await page.getByTestId('book-time').filter({ hasText: '20:00' }).click({ timeout: 8000 }) + for (let i = 0; i < 2; i++) await page.getByTestId('booking').getByRole('button', { name: '+' }).click() + r.check('booking: 4 people, tomorrow 20:00 picked; no food yet = no menu', await page.getByTestId('party').textContent() === '4' && await product(12).count() === 0) + await page.getByTestId('book-food').check() + r.check('booking: with food → the menu at the pre-order prices (souvlaki €3.80; the cola is not pre-orderable)', + (await product(12).getByTestId('price').textContent()).includes('3.80') && await product(11).count() === 0) + await product(12).getByTestId('add').click() + await product(12).getByRole('button', { name: '+' }).click() + await page.screenshot({ path: path.join(OUT, 'order-app-booking.png'), fullPage: true }) + await page.getByTestId('book-continue').click() + await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '7.6', null, { timeout: 8000 }).catch(() => {}) + r.check('booking: the summary (table for 4, tomorrow) and the food priced by the cloud (€7.60)', + (await page.getByTestId('booking-summary').textContent()).includes('Table for 4') && await page.getByTestId('totals').getAttribute('data-total') === '7.6') + await page.getByTestId('place-order').click() + await page.getByTestId('track').waitFor({ timeout: 10_000 }).catch(() => {}) + r.check('booking: requested → its page (booking ORD-0003, table for 4, waiting for the venue)', + (await page.getByTestId('track-ref').textContent().catch(() => '')).includes('Booking ORD-0003') + && (await page.getByTestId('track').textContent()).includes('Table for 4') && await page.getByTestId('track').getAttribute('data-status') === 'pending_acceptance') + const booked = (await call('GET', `/api/orders/pending/${numeric}`, { headers: siteH })).find(o => o.public_ref === 'ORD-0003') + r.check('booking: the site receives a pre-order for 4 at the pre-order prices', booked?.order_type === 'preorder' && booked.party_size === 4 + && booked.total === 7.6 && booked.sales_point === 'online_preorder' && !!booked.requested_for, JSON.stringify(booked)) + await call('PATCH', `/api/orders/${booked.id}/status`, { headers: siteH, body: { status: 'accepted' } }) + r.check('booking: the venue confirms → the page says so', await page.waitForFunction(() => document.querySelector('[data-testid="track"]')?.dataset.status === 'accepted', null, { timeout: 15_000 }) + .then(() => true).catch(() => false) && (await page.getByTestId('track').textContent()).includes('Confirmed')) + await page.screenshot({ path: path.join(OUT, 'order-app-booking-track.png'), fullPage: true }) + // ── Greek ──────────────────────────────────────────────────────────────── await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`) await page.getByRole('button', { name: 'EL' }).click() diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index 314b2ac..f3e01a2 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -39,7 +39,7 @@ const cloudServer = http.createServer((req, res) => { }) await new Promise(res => cloudServer.listen(0, '127.0.0.1', res)) const backend = await startBackend({ port: 8059, siteId: 'test-site-1', cloudUrl: `http://127.0.0.1:${cloudServer.address().port}`, - env: { LICENSE_MODE: 'off', CONNECT_SYNC_INTERVAL_SECONDS: '1' } }) + env: { LICENSE_MODE: 'off', CONNECT_SYNC_INTERVAL_SECONDS: '1', XENIA_FIRE_CHECK_SECONDS: '2' } }) const term = await startTerminalVite({ port: 5187, backendUrl: backend.url }) const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) const r = reporter('terminal: pairing, sign-in, app states (paired screens)') @@ -607,6 +607,43 @@ try { r.check('3.3d: …and it leaves the New list', await page.waitForFunction(() => !document.querySelector('[data-testid="online-order"]'), null, { timeout: 5000 }) .then(() => true).catch(() => false)) + // ── S.6: a table booking with two dishes: confirmed, the dishes reach the KDS at the fire time ── + const ordering = await api('GET', '/api/connect/fees/ordering', { token: boss }) + await api('PUT', '/api/connect/fees/ordering', { token: boss, body: { ...ordering, + reservations: { ...ordering.reservations, enabled: true, with_food: true, fire_minutes: 1 } } }) + const arriving = new Date(Date.now() + 90_000) // the kitchen gets it a minute before: in ~30 s + cloud.queue.push(cloudOrder(43, 'preorder', 'Eleni Booking', 0, { party_size: 4, requested_for: arriving.toISOString(), sales_point: 'online_preorder', + customer_address: null })) + await page.getByTestId('online-list-bookings').click() + const bookingCard = page.locator('[data-testid="booking"][data-status="requested"]').first() + r.check('S.6: a booking request reaches the counter (Online → Bookings), waiting for an answer', + await bookingCard.waitFor({ timeout: 15_000 }).then(() => true).catch(() => false) && (await bookingCard.textContent()).includes('Eleni Booking')) + await bookingCard.click() + r.check('S.6: …it shows the party and the two dishes ordered ahead', await shown(page, 'booking-panel', 5000) + && (await page.getByTestId('booking-guest').textContent()).includes('4 people') && (await page.getByTestId('booking-food').textContent()).includes(`2× ${simple.name}`)) + await page.screenshot({ path: path.join(OUT, 'terminal-pos-booking.png') }) + await page.getByTestId('booking-confirm').click() + await page.waitForFunction(() => document.querySelector('[data-testid="booking-panel"]')?.dataset.status === 'pending', null, { timeout: 8000 }).catch(() => {}) + for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 43); i++) await sleep(100) + r.check('S.6: Confirm → confirmed, and the customer is told', await page.getByTestId('booking-panel').getAttribute('data-status') === 'pending' + && cloud.statuses.some(x => x.id === 43 && x.status === 'accepted'), JSON.stringify(cloud.statuses.filter(x => x.id === 43))) + const bookingOnKds = async () => (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.online_ref === 'ORD-0043') + r.check('S.6: …the kitchen does not get the dishes at once', !(await bookingOnKds()) + && (await page.getByTestId('booking-food').textContent()).includes('kitchen')) + let fired = null + for (let i = 0; i < 90 && !fired; i++) { fired = await bookingOnKds(); if (!fired) await sleep(1000) } + const firedAt = Date.now() + r.check('S.6: …at the fire time (a minute before arrival) the two dishes are on the KDS, with the time', + !!fired && fired.items.reduce((s, i) => s + i.quantity, 0) === 2 && !!fired.requested_for && firedAt < arriving.getTime() - 50_000, + JSON.stringify(fired?.items?.map(i => [i.product_name, i.quantity]))) + const freeTable = (await api('GET', '/api/pos/tables', { token: boss })).tables.find(x => !x.order) + await page.getByTestId('booking-table').selectOption(String(freeTable.id)) + await page.getByTestId('booking-arrive').click() + for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 43 && x.status === 'delivered'); i++) await sleep(100) + const seated = await api('GET', `/api/orders/${fired?.id}`, { token: boss }).catch(() => null) + r.check('S.6: the guests arrive and are seated → their order moves to the table; the customer\'s page says welcome', + seated?.table_id === freeTable.id && cloud.statuses.some(x => x.id === 43 && x.status === 'delivered')) + // ── 3.3e: refunds ─────────────────────────────────────────────────────── // fiscal receipts on, with today's text-file bridge: it can't take credit notes yet, so the // cashier is told to issue it on the machine (owner decision 2026-11-15)