feat: online ordering settings (services, hours, preparation, slots) and the order app e2e (platform-v2 3S, S.4)

- connect_orders.ordering setting; GET/PUT /api/connect/fees/ordering (validated:
  services, hours per day incl. past midnight, preparation, slot minutes, days ahead,
  ASAP); pushed to the cloud with the menu (snapshot `ordering`).
- Manager: the Online ordering page gains "Services and hours" (OrderingSettings.jsx; logic
  in feesLogic.js, unit-tested); nav label "Online ordering".
- tests/e2e/order_app.mjs: a real cloud + the built order app in a phone-sized browser:
  takeaway and delivery placed, priced by the cloud (fee by area, minimum refused), the
  site moves the delivery to delivered and the page follows; a rejection with its reason;
  Greek. In run-all, with the order app's unit tests.
- Tests: backend +1 (406), manager unit +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 13:39:13 +02:00
co-authored by Claude Opus 5.5
parent df27133af9
commit 8ea44d71aa
12 changed files with 507 additions and 11 deletions
@@ -1,5 +1,5 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import Module, Mount, Perm
from core.modules.model import Module, Mount, Perm, SettingDef
MODULE = Module(
key='connect_orders',
@@ -11,6 +11,9 @@ MODULE = Module(
Perm('connect_orders.manage', 'Accept and manage online orders', roles=('owner', 'store_manager', 'staff_manager', 'barista', 'barman')),
Perm('connect_orders.fees', 'Set delivery areas and fees', roles=('owner', 'store_manager')),
),
settings=(
SettingDef('connect_orders.ordering', '{}', 'Online ordering (phase 3S): services offered, ordering hours, preparation and slot minutes, days ahead, as soon as possible. Edited on the Online ordering page.', type='json'),
),
routers=(
Mount('routers.fees', '/api/connect/fees'),
Mount('routers.connect_orders', '/api/connect'),
+77 -2
View File
@@ -1,6 +1,7 @@
"""Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees.
GET /api/connect/fees {areas, rules}
GET /api/connect/fees {areas, rules, ordering}
GET /api/connect/fees/ordering the online ordering settings PUT: save them
POST /api/connect/fees/areas add an area PUT/DELETE /areas/{id}
POST /api/connect/fees/rules add a rule PUT/DELETE /rules/{id}
PUT /api/connect/fees/rules/order [rule ids] in their new order
@@ -47,6 +48,24 @@ def rule_out(r) -> dict:
"time_from": r.time_from, "time_to": r.time_to, "action": r.action, "value": r.value, "stop": bool(r.stop)}
ORDERING_KEY = "connect_orders.ordering"
SERVICES = ("takeaway", "delivery")
def ordering_settings(db) -> dict:
"""Online ordering (S.4), with defaults: no services until the venue turns them on."""
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first()
try:
raw = json.loads(row.value) if row and row.value else {}
except ValueError:
raw = {}
try:
return OrderingBody(**{k: v for k, v in raw.items() if k in OrderingBody.model_fields}).model_dump()
except Exception:
return OrderingBody().model_dump()
def fees_payload(db) -> dict:
"""What the engine needs (and the cloud gets): active and inactive alike, in order."""
from models.fees import DeliveryArea, FeeRule
@@ -55,6 +74,42 @@ def fees_payload(db) -> dict:
return {"areas": [area_out(a) for a in areas], "rules": [rule_out(r) for r in rules]}
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 =
any time; once any day has hours, a day without them is closed. An end before its start
runs past midnight."""
services: List[Literal["takeaway", "delivery"]] = Field(default_factory=list)
hours: dict = Field(default_factory=dict)
prep_minutes: int = Field(default=20, ge=0, le=24 * 60) # earliest collection/delivery after ordering
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
@field_validator("services")
@classmethod
def _services(cls, v):
return [s for s in SERVICES if s in v]
@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
class AreaBody(BaseModel):
name: str = Field(min_length=1, max_length=80)
postcodes: List[str] = Field(default_factory=list, max_length=100)
@@ -164,7 +219,27 @@ def _changed():
@router.get("")
def list_fees(db: Session = Depends(get_db), user=Depends(require(KEY))):
return fees_payload(db)
return {**fees_payload(db), "ordering": ordering_settings(db)}
@router.get("/ordering")
def get_ordering(db: Session = Depends(get_db), user=Depends(require(KEY))):
return ordering_settings(db)
@router.put("/ordering")
def put_ordering(body: OrderingBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Save the online ordering settings (they reach the cloud with the menu, within seconds)."""
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first()
value = json.dumps(body.model_dump())
if row is None:
db.add(PosSettings(key=ORDERING_KEY, value=value))
else:
row.value = value
db.commit()
_changed()
return body.model_dump()
@router.post("/areas", status_code=201)
+3 -2
View File
@@ -295,8 +295,9 @@ def menu_snapshot(db) -> tuple[dict, list]:
# delivery areas and fee rules (S.3): the cloud applies them at checkout with the same
# engine (services/fees.py); the venue's time zone says what "22:00" and "Saturday" mean
from core.timeutil import venue_tz
from routers.fees import fees_payload
return {"categories": payload_categories, "fees": fees_payload(db), "timezone": venue_tz().key}, all_products
from routers.fees import fees_payload, ordering_settings
return {"categories": payload_categories, "fees": fees_payload(db), "ordering": ordering_settings(db),
"timezone": venue_tz().key}, all_products
async def _push_menu_snapshot():
+18
View File
@@ -133,3 +133,21 @@ def test_changes_push_the_menu_soon():
assert not menu_changed("GET", "/api/products/", 200)
assert not menu_changed("POST", "/api/pricing/modifiers", 422)
assert not menu_changed("POST", "/api/orders/1/items", 200)
def test_online_ordering_settings(client, db, owner_h):
"""S.4: the services, hours and timing the online ordering app follows (the cloud
enforces them); off until the venue turns a service on."""
from services.cloud_sync import menu_snapshot
assert client.get("/api/connect/fees/ordering", headers=owner_h).json()["services"] == []
body = {"services": ["delivery", "takeaway"], "hours": {"5": [["20:00", "02:00"]], "6": [["12:00", "16:00"], ["18:00", "23:00"]]},
"prep_minutes": 30, "slot_minutes": 15, "days_ahead": 1, "asap": False}
r = client.put("/api/connect/fees/ordering", headers=owner_h, json=body)
assert r.status_code == 200, r.text
assert r.json()["services"] == ["takeaway", "delivery"] # fixed order
assert client.get("/api/connect/fees", headers=owner_h).json()["ordering"]["days_ahead"] == 1
snap, _ = menu_snapshot(db)
assert snap["ordering"]["hours"]["6"] == [["12:00", "16:00"], ["18:00", "23:00"]] and snap["ordering"]["asap"] is False
for bad in ({"services": ["teleport"]}, {"hours": {"7": [["10:00", "11:00"]]}}, {"hours": {"1": [["10:00", "10:00"]]}},
{"hours": {"1": [["25:00", "11:00"]]}}, {"slot_minutes": 1}, {"days_ahead": 30}, {"prep_minutes": -5}):
assert client.put("/api/connect/fees/ordering", headers=owner_h, json=bad).status_code == 422, bad