"""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", {}