feat(cloud): the online ordering app (takeaway, delivery) with hours, time slots and rate limits (platform-v2 3S, S.4)

- connect_frontend/order-app at /order/{site}: menu per service at that service's prices,
  extras, basket (kept per tab), checkout priced by the cloud (fee, area by list or
  postcode, minimum), name/phone/address/notes (remembered), as soon as possible or a time
  slot, tracking page with steps, lines and totals; en/el; tokens in index.css. Logic in
  src/logic.js, unit-tested; built and served by the connect image (npm test in the build).
- services/ordering.py: the venue's services, hours (past midnight), preparation, slot grid,
  days ahead, ASAP; takeaway/delivery orders checked (order.service_unavailable,
  order.closed, order.time_invalid) and need a phone; GET /api/orders/{site}/slots; the
  public menu carries the ordering summary.
- services/ratelimit.py: per-caller limits on quote, order and track (429 rate.limited).
- online_orders.requested_for (0003, unreleased) stored as UTC; every datetime sent with its
  offset (the database keeps no zone: a 12:00 Athens slot came back as 12:00 unzoned).
- Tracking returns what was ordered, the totals, the type and the time.
- Tests: test_ordering.py (5), checkout/fees updated; order-app unit (4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 13:39:00 +02:00
co-authored by Claude Opus 5.5
parent 9e8ec4c4e6
commit b25bfcda3e
30 changed files with 4424 additions and 15 deletions
@@ -1,4 +1,4 @@
"""online orders: sales_point, table_label, delivery_area, tracking_token; public_ref unique per site (plan phase 3S, S.2/S.3)
"""online orders: sales_point, table_label, delivery_area, requested_for, tracking_token; public_ref unique per site (plan phase 3S, S.2/S.3)
- sales_point / table_label: the cloud prices orders per sales point; the QR menu's table
- public_ref ("ORD-0001") counts per site but was unique across all sites, so a second
@@ -60,6 +60,7 @@ def upgrade() -> None:
with op.batch_alter_table('online_orders', copy_from=_base(), recreate='always') as batch_op:
batch_op.add_column(sa.Column('table_label', sa.String(), nullable=True))
batch_op.add_column(sa.Column('delivery_area', sa.String(), nullable=True))
batch_op.add_column(sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True))
batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=True))
batch_op.add_column(sa.Column('tracking_token', sa.String(), nullable=True))
batch_op.create_unique_constraint('uq_online_orders_site_ref', ['site_id', 'public_ref'])
@@ -73,11 +74,13 @@ def upgrade() -> None:
def downgrade() -> None:
current = _base(sa.Column('table_label', sa.String(), nullable=True),
sa.Column('delivery_area', sa.String(), nullable=True),
sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True),
sa.Column('sales_point', sa.String(), nullable=True),
sa.Column('tracking_token', sa.String(), nullable=True))
with op.batch_alter_table('online_orders', copy_from=current, recreate='always') as batch_op:
batch_op.drop_column('tracking_token')
batch_op.drop_column('sales_point')
batch_op.drop_column('requested_for')
batch_op.drop_column('delivery_area')
batch_op.drop_column('table_label')
batch_op.create_unique_constraint('uq_online_orders_public_ref', ['public_ref'])
+1
View File
@@ -26,6 +26,7 @@ class OnlineOrder(Base):
customer_notes = Column(Text, nullable=True)
table_label = Column(String, nullable=True) # the QR menu's table, as the customer gave it
delivery_area = Column(String, nullable=True) # the delivery area's name (S.3)
requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
# Order content — JSON array of ordered items
+2
View File
@@ -45,6 +45,8 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)):
from services.checkout import delivery_areas
data["delivery_areas"] = delivery_areas(data) # S.3: what the customer picks from
data.pop("fees", None) # the rules and postcodes stay on the cloud
from services.ordering import summary
data["ordering"] = summary(data) # S.4: services, open now, slots
data["menu_mode"] = site.menu_mode
data["restaurant"] = {
"name": site.menu_display_name,
+46 -6
View File
@@ -1,6 +1,7 @@
import json
import secrets
from fastapi import APIRouter, Depends, HTTPException, Header, status
from datetime import timezone
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
@@ -13,6 +14,17 @@ from schemas.online_order import (
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest,
)
from services.checkout import CheckoutError, check_sent, price_cart
from services import ordering, ratelimit
# public endpoints, per caller address (CL-4)
QUOTE_LIMIT = (120, 60) # 120 quotes a minute
ORDER_LIMIT = (10, 600) # 10 orders in 10 minutes
TRACK_LIMIT = (240, 60)
def _limit(request, bucket, rule):
if not ratelimit.hit(bucket, ratelimit.client_ip(request), *rule):
raise HTTPException(status_code=429, detail={"code": "rate.limited", "params": {"seconds": rule[1]}})
from auth_utils import get_current_admin # manager JWT checked separately in manager_auth
router = APIRouter()
@@ -58,22 +70,37 @@ def _priced(menu, order_type, items, area_id=None, postcode=None):
raise HTTPException(status_code=e.status, detail=e.detail())
@router.get("/{site_slug}/slots")
def order_slots(site_slug: str, db: Session = Depends(get_db)):
"""When online orders can be placed (S.4): services, open now, ASAP offered, time slots."""
_site, menu = _site_and_menu(db, site_slug)
return ordering.summary(menu)
@router.post("/{site_slug}/quote")
def quote_order(site_slug: str, body: QuoteRequest, db: Session = Depends(get_db)):
def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Session = Depends(get_db)):
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
_limit(request, "quote", QUOTE_LIMIT)
_site, menu = _site_and_menu(db, site_slug)
return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode).out()
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(get_db)):
def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db: Session = Depends(get_db)):
"""Customer submits an order from a customer app. The cloud prices it from the venue's menu
for the order's sales point (services/checkout.py); a price or total the app sent that
differs → 409 order.price_changed with the current prices; nothing the browser says about
money is stored (phase 3S, S.2)."""
_limit(request, "order", ORDER_LIMIT)
site, menu = _site_and_menu(db, site_slug)
items = [i.model_dump() for i in body.items]
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode)
if body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
problem = ordering.check(menu, body.order_type, body.requested_for)
if problem:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
if not (body.customer_phone or "").strip():
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
try:
check_sent(priced, items, body.total)
except CheckoutError as e:
@@ -95,6 +122,9 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(
customer_notes=body.customer_notes,
table_label=(body.customer_table or "").strip() or None,
delivery_area=priced.area_name,
# stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it)
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
if body.order_type in ("takeaway", "delivery") and body.requested_for else None),
sales_point=priced.sales_point,
items_json=json.dumps([line.out() for line in priced.lines]),
subtotal=priced.subtotal,
@@ -111,12 +141,22 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(
@router.get("/track/{token}", response_model=OrderStatusOut)
def track_order(token: str, db: Session = Depends(get_db)):
"""The customer's tracking page (S.2): by the order's random token."""
def track_order(token: str, request: Request, db: Session = Depends(get_db)):
"""The customer's tracking page (S.2): by the order's random token. Since S.4 also what
was ordered and when it's wanted (the token is the customer's own secret)."""
_limit(request, "track", TRACK_LIMIT)
order = db.query(OnlineOrder).filter(OnlineOrder.tracking_token == token).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason)
try:
lines = json.loads(order.items_json or "[]")
except ValueError:
lines = []
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason,
order_type=order.order_type, requested_for=order.requested_for, created_at=order.created_at,
lines=[{"name": x.get("name"), "quantity": x.get("quantity"), "unit_price": x.get("unit_price"),
"options": [o.get("name") for o in x.get("options") or []]} for x in lines],
subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total)
@router.get("/status/{public_ref}", response_model=OrderStatusOut)
+28 -1
View File
@@ -1,7 +1,16 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from datetime import timezone
from pydantic import BaseModel, Field, field_serializer
def _utc(value):
"""The cloud's database keeps no time zone: a naive datetime is UTC. Sent with its offset."""
if value is None:
return None
return (value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value).isoformat()
class OrderItemIn(BaseModel):
@@ -30,6 +39,7 @@ class OnlineOrderCreate(BaseModel):
customer_table: Optional[str] = Field(default=None, max_length=40)
area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20)
requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible
items: list[OrderItemIn] = Field(max_length=100)
# what the customer was shown: compared, never stored as sent
subtotal: Optional[float] = None
@@ -49,6 +59,18 @@ class OrderStatusOut(BaseModel):
public_ref: str
status: str
rejection_reason: Optional[str] = None
# S.4: what the tracking page shows (all optional: older clients ignore them)
order_type: Optional[str] = None
requested_for: Optional[datetime] = None
created_at: Optional[datetime] = None
lines: Optional[list] = None
subtotal: Optional[float] = None
delivery_fee: Optional[float] = None
total: Optional[float] = None
@field_serializer('requested_for', 'created_at')
def _times(self, value):
return _utc(value)
class PendingOrderOut(BaseModel):
@@ -61,6 +83,7 @@ class PendingOrderOut(BaseModel):
customer_notes: Optional[str] = None
table_label: Optional[str] = None # the QR menu's table (S.2)
delivery_area: Optional[str] = None # the delivery area's name (S.3)
requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible
sales_point: Optional[str] = None # the site's sales point (S.2)
items_json: str
subtotal: float
@@ -71,6 +94,10 @@ class PendingOrderOut(BaseModel):
model_config = {"from_attributes": True}
@field_serializer('requested_for', 'created_at')
def _times(self, value):
return _utc(value)
class OrderSyncedRequest(BaseModel):
local_order_id: int
+111
View File
@@ -0,0 +1,111 @@
"""When online orders are taken (plan phase 3S, step S.4).
The venue's settings travel with the menu snapshot (`ordering`, site routers/fees.py
OrderingBody) and are enforced here at checkout:
{services: ["takeaway", "delivery"], hours: {"0".."6": [["HH:MM", "HH:MM"], ...]},
prep_minutes, slot_minutes, days_ahead, asap}
- a service not in `services` → order.service_unavailable
- hours: none at all = any time; otherwise a day without ranges is closed; a range whose end
is before its start runs past midnight into the next day
- "as soon as possible" (no requested time): only while open now, and only if `asap`
- a requested time: one of slots() — on the slot grid (every slot_minutes from local
midnight), at least prep_minutes from now, within today + days_ahead, while open
Times are the venue's local time (the snapshot's `timezone`).
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
DEFAULTS = {"services": [], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
MAX_SLOTS = 300
def config(snapshot: dict) -> dict:
cfg = {**DEFAULTS, **(snapshot.get("ordering") or {})}
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 15))
cfg["prep_minutes"] = max(0, int(cfg.get("prep_minutes") or 0))
cfg["days_ahead"] = max(0, min(7, int(cfg.get("days_ahead") or 0)))
return cfg
def venue_tz(snapshot: dict) -> ZoneInfo:
try:
return ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
except Exception:
return ZoneInfo("Europe/Athens")
def _mins(hhmm: str) -> int:
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def is_open(cfg: dict, local: datetime) -> bool:
hours = cfg.get("hours") or {}
if not hours:
return True
t = local.hour * 60 + local.minute
today, yesterday = str(local.weekday()), str((local.weekday() - 1) % 7)
for start, end in hours.get(today, []):
s, e = _mins(start), _mins(end)
if (s < e and s <= t < e) or (s > e and t >= s):
return True
for start, end in hours.get(yesterday, []):
s, e = _mins(start), _mins(end)
if s > e and t < e: # yesterday's range running past midnight
return True
return False
def _first_slot(cfg: dict, local_now: datetime) -> datetime:
earliest = local_now + timedelta(minutes=cfg["prep_minutes"])
step = cfg["slot_minutes"]
midnight = earliest.replace(hour=0, minute=0, second=0, microsecond=0)
mins = (earliest - midnight).total_seconds() / 60
n = int(-(-mins // step)) # round up to the grid
return midnight + timedelta(minutes=n * step)
def slots(snapshot: dict, now: datetime | None = None) -> list[datetime]:
"""The times a customer can pick (aware, venue local), in order."""
cfg, tz = config(snapshot), venue_tz(snapshot)
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
last_day = (local_now + timedelta(days=cfg["days_ahead"])).date()
out, t = [], _first_slot(cfg, local_now)
while t.date() <= last_day and len(out) < MAX_SLOTS:
if is_open(cfg, t):
out.append(t)
t = (t + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
return out
def summary(snapshot: dict, now: datetime | None = None) -> dict:
"""What the ordering app needs: services, open now, ASAP offered, the slots."""
cfg, tz = config(snapshot), venue_tz(snapshot)
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
open_now = is_open(cfg, local_now)
return {"services": cfg["services"], "open_now": open_now, "asap": bool(cfg["asap"]) and open_now,
"prep_minutes": cfg["prep_minutes"], "timezone": tz.key,
"slots": [t.isoformat() for t in slots(snapshot, now)]}
def check(snapshot: dict, service: str, requested_for: datetime | None, now: datetime | None = None):
"""None if the order may be placed for that time, else (code, params)."""
cfg = config(snapshot)
if service not in cfg["services"]:
return "order.service_unavailable", {"service": service}
tz = venue_tz(snapshot)
now = now or datetime.now(timezone.utc)
if requested_for is None:
if cfg["asap"] and is_open(cfg, now.astimezone(tz)):
return None
return "order.closed", {}
if requested_for.tzinfo is None:
return "order.time_invalid", {}
wanted = requested_for.astimezone(tz)
if any(abs((wanted - t).total_seconds()) < 1 for t in slots(snapshot, now)):
return None
return "order.time_invalid", {}
+44
View File
@@ -0,0 +1,44 @@
"""A small in-memory rate limit for the public endpoints (CL-4, plan phase 3S S.4).
hit(bucket, key, limit, per_seconds) -> bool True = allowed (and counted)
client_ip(request) the caller's address behind the proxy
Per process (the cloud runs one); a restart forgets. Enough to stop a script hammering the
order endpoint; not a defence against a distributed attack (that's the proxy's job).
"""
from __future__ import annotations
import threading
import time
from collections import deque
_lock = threading.Lock()
_hits: dict[tuple[str, str], deque] = {}
_MAX_KEYS = 50_000
def hit(bucket: str, key: str, limit: int, per_seconds: float, now: float | None = None) -> bool:
now = time.monotonic() if now is None else now
with _lock:
if len(_hits) > _MAX_KEYS: # never grow without bound
_hits.clear()
q = _hits.setdefault((bucket, key), deque())
while q and now - q[0] >= per_seconds:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
return True
def reset() -> None:
with _lock:
_hits.clear()
def client_ip(request) -> str:
"""The first X-Forwarded-For address (the VPS proxy sets it), else the socket's."""
fwd = request.headers.get("x-forwarded-for", "")
if fwd:
return fwd.split(",")[0].strip() or "?"
return getattr(request.client, "host", None) or "?"
+8
View File
@@ -41,3 +41,11 @@ def admin_h(client):
r = client.post("/api/auth/login", json={"username": "sysadmin", "password": "test-admin-pw"})
assert r.status_code == 200, r.text
return {"Authorization": f"Bearer {r.json()['access_token']}"}
@pytest.fixture(autouse=True)
def _fresh_rate_limits():
"""Every test starts with empty rate-limit counters (services/ratelimit.py, S.4)."""
from services import ratelimit
ratelimit.reset()
yield
+6 -2
View File
@@ -7,6 +7,8 @@ import json
from test_licensing_v2 import _heartbeat, _new_site
COLA, PIE, SOUP = 11, 12, 13
# online ordering on, any time (no hours), as soon as possible (S.4)
ORDERING = {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
def _h(site):
@@ -24,7 +26,7 @@ def _menu(client, site, numeric):
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": []},
{"id": SOUP, "name": "Soup", "base_price": 6.0, "digital_price": 6.0, "digital_available": False,
"sold_at": ["qr_table", "online_delivery"], "prices": {"qr_table": 6.0, "online_delivery": 6.0}, "quick_options": []},
]}]}
]}], "ordering": ORDERING, "timezone": "Europe/Athens"}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200, r.text
@@ -124,6 +126,8 @@ def test_order_numbers_per_site_and_tracking_by_token(client, admin_h):
assert ra["public_ref"] == rb["public_ref"] == "ORD-0001"
assert ra["tracking_token"] != rb["tracking_token"] and ra["total"] == 5.0
t = client.get(f"/api/orders/track/{ra['tracking_token']}")
assert t.status_code == 200 and t.json() == {"public_ref": "ORD-0001", "status": "pending_acceptance", "rejection_reason": None}
tj = t.json()
assert t.status_code == 200 and (tj["public_ref"], tj["status"], tj["rejection_reason"], tj["total"]) == ("ORD-0001", "pending_acceptance", None, 5.0)
assert tj["lines"] == [{"name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}] and tj["order_type"] == "takeaway"
assert client.get("/api/orders/status/ORD-0001").status_code == 404 # ambiguous now
assert client.get("/api/orders/track/nope").status_code == 404
+2 -2
View File
@@ -9,7 +9,7 @@ from pathlib import Path
import pytest
from test_checkout import COLA, _code, _h, _menu, _order
from test_checkout import COLA, ORDERING, _code, _h, _menu, _order
from test_licensing_v2 import _heartbeat, _new_site
CASES = json.loads((Path(__file__).resolve().parent / "fixtures" / "fee_cases.json").read_text(encoding="utf-8"))
@@ -36,7 +36,7 @@ def _venue_with_fees(client, admin_h):
_menu(client, site, numeric)
# the same menu plus the venue's fees, as the site pushes them since S.3
menu = client.get(f"/api/menu/{site['site_id']}").json()
snap = {"categories": menu["categories"], "fees": FEES, "timezone": "Europe/Athens"}
snap = {"categories": menu["categories"], "fees": FEES, "ordering": ORDERING, "timezone": "Europe/Athens"}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200
return site, numeric
+95
View File
@@ -0,0 +1,95 @@
"""When online orders are taken: services, hours, time slots, rate limits (plan phase 3S, S.4)."""
import json
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from services import ordering
from test_checkout import COLA, _code, _h, _menu, _order, _venue
ATH = ZoneInfo("Europe/Athens")
def snap(**cfg):
return {"timezone": "Europe/Athens", "ordering": {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20,
"slot_minutes": 15, "days_ahead": 0, "asap": True, **cfg}}
def at(y, mo, d, h, mi):
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
# Sunday 15 Nov 2026 is weekday 6; Monday 16 Nov is 0
EVENINGS = {"6": [["18:00", "23:00"]], "5": [["20:00", "02:00"]]}
def test_open_hours_including_past_midnight():
cfg = ordering.config(snap(hours=EVENINGS))
local = lambda *a: datetime(*a, tzinfo=ATH) # noqa: E731
assert ordering.is_open(cfg, local(2026, 11, 15, 18, 0))
assert not ordering.is_open(cfg, local(2026, 11, 15, 23, 0))
assert not ordering.is_open(cfg, local(2026, 11, 15, 12, 0))
assert ordering.is_open(cfg, local(2026, 11, 15, 1, 30)) # Saturday's 20:00–02:00, after midnight
assert not ordering.is_open(cfg, local(2026, 11, 16, 19, 0)) # Monday has no hours: closed
assert ordering.is_open(ordering.config(snap()), local(2026, 11, 16, 4, 0)) # no hours = any time
def test_slots_start_after_preparation_on_the_grid_and_stay_in_hours():
s = snap(hours=EVENINGS)
got = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 21, 7))]
assert got == ["21:30", "21:45", "22:00", "22:15", "22:30", "22:45"] # 21:07 + 20 → 21:27 → 21:30
assert ordering.slots(s, at(2026, 11, 15, 22, 50)) == [] # nothing left today
ahead = ordering.slots(snap(hours=EVENINGS, days_ahead=1, slot_minutes=30), at(2026, 11, 15, 22, 50))
assert ahead == [] # Monday closed
morning = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 10, 0))]
assert morning[0] == "18:00" and morning[-1] == "22:45"
def test_check_asap_and_requested_times():
s = snap(hours=EVENINGS)
evening, noon = at(2026, 11, 15, 21, 7), at(2026, 11, 15, 12, 0)
assert ordering.check(s, "delivery", None, evening) is None
assert ordering.check(s, "delivery", None, noon) == ("order.closed", {}) # closed now: no ASAP
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 30), noon) is None # but a later slot is fine
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 31), noon)[0] == "order.time_invalid" # off the grid
assert ordering.check(s, "takeaway", at(2026, 11, 15, 21, 15), evening)[0] == "order.time_invalid" # too soon
assert ordering.check(snap(asap=False), "delivery", None, evening) == ("order.closed", {})
assert ordering.check(snap(services=["takeaway"]), "delivery", None, evening) == ("order.service_unavailable", {"service": "delivery"})
assert ordering.check(s, "takeaway", datetime(2026, 11, 15, 18, 30), noon)[0] == "order.time_invalid" # no zone
def test_the_endpoints_enforce_it(client, admin_h):
site, numeric = _venue(client, admin_h)
# the venue turns delivery off and opens only on Mondays 12:00–13:00
menu = client.get(f"/api/menu/{site['site_id']}").json()
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
"ordering": {"services": ["takeaway"], "hours": {"0": [["12:00", "13:00"]]}, "prep_minutes": 0,
"slot_minutes": 15, "days_ahead": 7, "asap": True}}
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
s = client.get(f"/api/orders/{site['site_id']}/slots").json()
assert s["services"] == ["takeaway"] and len(s["slots"]) >= 4
first = datetime.fromisoformat(s["slots"][0])
assert first.astimezone(ATH).weekday() == 0 and first.astimezone(ATH).strftime("%H:%M") >= "12:00"
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["services"] == ["takeaway"]
assert _code(_order(client, site, "delivery", customer_address="x")) == "order.service_unavailable"
r = _order(client, site, "takeaway", requested_for=s["slots"][0])
assert r.status_code == 201, r.text
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == r.json()["public_ref"])
assert datetime.fromisoformat(stored["requested_for"].replace("Z", "+00:00")) == first
track = client.get(f"/api/orders/track/{r.json()['tracking_token']}").json()
assert track["requested_for"] and track["order_type"] == "takeaway"
# a takeaway or delivery order needs a phone number
assert _code(_order(client, site, "takeaway", customer_phone="", requested_for=s["slots"][0])) == "order.details_missing"
def test_rate_limits(client, admin_h):
from services import ratelimit
site, _ = _venue(client, admin_h)
statuses = [_order(client, site).status_code for _ in range(11)]
assert statuses[:10] == [201] * 10 and statuses[10] == 429
assert _code(_order(client, site)) == "rate.limited"
# another address is counted apart (behind the proxy)
ok = client.post(f"/api/orders/{site['site_id']}", headers={"X-Forwarded-For": "203.0.113.9"},
json={"order_type": "takeaway", "customer_name": "A", "customer_phone": "1", "items": [{"product_id": COLA, "quantity": 1}]})
assert ok.status_code == 201
assert ratelimit.hit("t", "k", 2, 60, now=0) and ratelimit.hit("t", "k", 2, 60, now=1) and not ratelimit.hit("t", "k", 2, 60, now=2)
assert ratelimit.hit("t", "k", 2, 60, now=61) # the window moves on