feat(connect): table bookings from the online ordering app; food fired to the kitchen before arrival

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 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 19:31:44 +02:00
co-authored by Claude Opus 5.5
parent 0ca700279a
commit 70c8f2bb57
33 changed files with 1402 additions and 105 deletions
+5 -3
View File
@@ -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():
+202
View File
@@ -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