Files
xenia-pos-cloud/cloud_backend/services/ordering.py
T
bonaminandClaude Opus 5.5 3459c80611 feat(cloud): table bookings online, with food ordered ahead
Plan phase 3S, step S.6.
- New order types "reservation" (a table only, no items) and "preorder" (a table with food,
  priced at the online_preorder sales point); online_orders.party_size (migration 0005).
- services/ordering.py: the venue's booking settings (ordering.reservations in the snapshot):
  hours (none = any time), time grid, notice, days ahead (≤ 90), party size; res_slots per
  venue day, res_days, res_check (order.service_unavailable, order.party_invalid,
  order.time_invalid). The public menu's ordering summary gains `reservations`
  {enabled, with_food, party_max, days}; GET /api/orders/{site}/reservation-slots?day=.
- Bookings need a phone; a plain booking refuses items (order.items_not_allowed).
- Status steps for bookings: pending_acceptance → accepted | rejected; accepted → delivered
  (arrived) | cancelled (by the venue); ordinary orders unchanged.
- Order app: "Book a table" (people, day, time, optional food at the pre-order prices),
  booking summary at checkout, a booking tracking page (waiting, confirmed, welcome;
  declined / cancelled with the reason). en/el.
- Tests: tests/test_reservations.py (3), order-app logic test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:31:21 +02:00

186 lines
8.3 KiB
Python

"""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)],
"reservations": res_summary(snapshot, now)} # S.6
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", {}
# ── Reservations online (plan phase 3S, step S.6) ─────────────────────────────
# The snapshot's `ordering.reservations` (site routers/fees.py ReservationsBody):
# {enabled, with_food, hours: {"0".."6": [[from, to], ...]}, slot_minutes, days_ahead,
# notice_minutes, party_max, fire_minutes}
# "reservation" = a table only; "preorder" = a table with food ready on arrival (with_food).
# Times: on the slot grid of the venue's day, at least notice_minutes from now, within today +
# days_ahead, inside the hours (none = any time). fire_minutes is the site's (the kitchen).
RES_DEFAULTS = {"enabled": False, "with_food": False, "hours": {}, "slot_minutes": 30, "days_ahead": 30,
"notice_minutes": 60, "party_max": 10}
RES_TYPES = ("reservation", "preorder")
def res_config(snapshot: dict) -> dict:
cfg = {**RES_DEFAULTS, **((snapshot.get("ordering") or {}).get("reservations") or {})}
cfg["enabled"] = bool(cfg.get("enabled"))
cfg["with_food"] = cfg["enabled"] and bool(cfg.get("with_food"))
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 30))
cfg["days_ahead"] = max(0, min(90, int(cfg.get("days_ahead") or 0)))
cfg["notice_minutes"] = max(0, int(cfg.get("notice_minutes") or 0))
cfg["party_max"] = max(1, min(100, int(cfg.get("party_max") or 1)))
return cfg
def res_slots(snapshot: dict, day, now: datetime | None = None) -> list[datetime]:
"""The reservation times on one venue day (a date), aware venue local, in order."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
if day < local_now.date() or day > (local_now + timedelta(days=cfg["days_ahead"])).date():
return []
earliest = local_now + timedelta(minutes=cfg["notice_minutes"])
t = datetime(day.year, day.month, day.day, tzinfo=tz)
out = []
while t.date() == day:
if t >= earliest and is_open(cfg, t):
out.append(t)
t = (t.astimezone(timezone.utc) + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
return out
def res_days(snapshot: dict, now: datetime | None = None) -> list[str]:
"""The venue days (ISO dates) with at least one reservation time."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
today = (now or datetime.now(timezone.utc)).astimezone(tz).date()
days = (today + timedelta(days=n) for n in range(cfg["days_ahead"] + 1))
return [d.isoformat() for d in days if res_slots(snapshot, d, now)]
def res_summary(snapshot: dict, now: datetime | None = None) -> dict:
cfg = res_config(snapshot)
return {"enabled": cfg["enabled"], "with_food": cfg["with_food"], "party_max": cfg["party_max"],
"days": res_days(snapshot, now)}
def res_check(snapshot: dict, order_type: str, requested_for: datetime | None, party_size, now: datetime | None = None):
"""None if the reservation may be requested, else (code, params)."""
cfg = res_config(snapshot)
if not cfg["enabled"] or (order_type == "preorder" and not cfg["with_food"]):
return "order.service_unavailable", {"service": order_type}
if isinstance(party_size, bool) or not isinstance(party_size, int) or not 1 <= party_size <= cfg["party_max"]:
return "order.party_invalid", {"max": cfg["party_max"]}
if requested_for is None or requested_for.tzinfo is None:
return "order.time_invalid", {}
wanted = requested_for.astimezone(venue_tz(snapshot))
if any(abs((wanted - t).total_seconds()) < 1 for t in res_slots(snapshot, wanted.date(), now)):
return None
return "order.time_invalid", {}