"""The business day opens and closes by itself (owner 2026-11-23, plan 6F.8). Settings (modules/ordering/manifest.py, Settings → Operation → "Opening and closing the day"): - business_day.auto_open / auto_close: 'off' | 'schedule' (the venue's opening hours, venue.opening_hours) | 'time' (every day at business_day.auto_open_time / auto_close_time, whatever the hours) | 'alert' (at the opening hours' moment, only tell the managers). - business_day.auto_ignore_break: on = a day's spans count as one (first opening → last closing); off = the gap between spans closes the day and the next span opens a new one. - business_day.auto_open_offset_min / auto_close_offset_min (Q-11): open N minutes before the hours start, close N minutes after they end. Not used by 'time'. How it decides (tick(), every minute in the background, venue time, offline-safe): - Windows: each day's spans from the opening hours (a span whose `to` is before `from` ends the next day and belongs to the day it starts), with the offsets; yesterday, today and tomorrow are looked at. 'time' opens from its time until the next rollover hour (business_day. rollover_hour: a restart catches up only while it's still that business date) and closes at the last close time. - Open is due inside a window when no day is open and no day was opened or closed since the window began (a day a manager closed by hand isn't reopened inside the same span). On a restart this opens a day that is still due (catch-up). - Close is due when a day is open and was opened before the last closing moment. It runs only when no order of the day is still unclosed (Q-10); otherwise it alerts "tables still open" and tries again every 15 minutes. A close missed while the server was off isn't done later: the managers are alerted instead. - Alerts are sticky notifications for holders of ordering.business_day.manage (core notifications, dedupe below); they resolve when the day opens / closes (resolve_alerts, also called by services/business_days.py at once). A locked or expired license makes the open an alert too. - The day opened / closed by the system has no opener / closer and opened_auto / closed_auto. Agent notes: - tick(db, now=..., started_at=...) is pure apart from the DB and the in-memory retry time, so tests drive it with a fake clock (tests/test_day_auto.py). `now` is aware UTC, like utcnow(). - Only one process runs the loop (the backend's lifespan); the retry time lives in memory. """ from __future__ import annotations import asyncio import logging from datetime import date, datetime, time, timedelta from core.timeutil import utcnow logger = logging.getLogger("xenia.day_auto") MODES = ("off", "schedule", "time", "alert") CHECK_EVERY_S = 60 RETRY_CLOSE = timedelta(minutes=15) AUDIENCE = "perm:ordering.business_day.manage" # sticky alerts (dedupe keys) NOT_OPEN = "business_day.not_open" OPEN_BLOCKED = "business_day.open_blocked" TABLES_OPEN = "business_day.tables_open" NOT_CLOSED = "business_day.not_closed" _state = {"next_close_try": None, "started_at": None} # ── settings ───────────────────────────────────────────────────────────────── def _setting(db, key, default): from core.sessions import _setting as read return read(db, key, default) def _mode(db, which): v = _setting(db, f"business_day.auto_{which}", "off") return v if v in MODES else "off" def _minutes(db, key): try: return max(0, min(720, int(_setting(db, key, "0")))) except ValueError: return 0 def _clock(v): try: h, m = (int(x) for x in (v or "").split(":")) return time(h, m) except ValueError: return None # ── windows (venue time, naive) ────────────────────────────────────────────── def spans_of(hours_days, d: date, ignore_break: bool) -> list[tuple[datetime, datetime]]: """The opening spans of calendar day d (Monday-first hours), as naive venue datetimes.""" out = [] for s in (hours_days[d.weekday()] if hours_days and len(hours_days) == 7 else []): a, b = _clock(s.get("from")), _clock(s.get("to")) if a is None or b is None: continue start = datetime.combine(d, a) end = datetime.combine(d, b) if end <= start: end += timedelta(days=1) # past midnight: belongs to the day it starts out.append((start, end)) out.sort() if ignore_break and out: out = [(out[0][0], max(e for _, e in out))] return out def windows(db, which: str, now_local: datetime) -> list[tuple[datetime, datetime]]: """Open windows (start, end) around now for the open ('open') or close ('close') side.""" mode = _mode(db, which) if mode == "time": at = _clock(_setting(db, f"business_day.auto_{which}_time", "")) if at is None: return [] if which == "open": first = datetime.combine(now_local.date(), at) if first > now_local: first -= timedelta(days=1) # catch-up only until the business date changes (the rollover hour), not all night from core.timeutil import rollover_hour end = datetime.combine(first.date(), time(rollover_hour())) while end <= first: end += timedelta(days=1) return [(first, end)] last = datetime.combine(now_local.date(), at) if last > now_local: last -= timedelta(days=1) return [(last - timedelta(days=1), last)] # only its end (the close moment) is used from routers.identity import hours_out days = hours_out(db)["days"] ignore = _setting(db, "business_day.auto_ignore_break", "true") == "true" before = timedelta(minutes=_minutes(db, "business_day.auto_open_offset_min")) after = timedelta(minutes=_minutes(db, "business_day.auto_close_offset_min")) out = [] for k in (-1, 0, 1): for a, b in spans_of(days, now_local.date() + timedelta(days=k), ignore): out.append((a - before, b + after)) return sorted(out) # ── alerts ─────────────────────────────────────────────────────────────────── def _alert(db, dedupe, key, params, severity="warning"): from core.notifications import notify notify(key, severity, AUDIENCE, params, dedupe_key=dedupe, fold=False, db=db) def resolve_alerts(db) -> None: """Hide the alerts whose cause is gone: a day is open → the 'not open' ones; none open → the closing ones. Never raises.""" try: from core.notifications import resolve from services.business_days import current resolve(db, [NOT_OPEN, OPEN_BLOCKED] if current(db) is not None else [TABLES_OPEN, NOT_CLOSED]) except Exception: logger.exception("day_auto.resolve_failed") # ── the tick ───────────────────────────────────────────────────────────────── def tick(db, now: datetime | None = None, started_at: datetime | None = None) -> list[str]: """Do what is due now. Returns what happened (for logs and tests): 'opened', 'closed', 'alert:', 'waiting' (tables open, retry later).""" from core.timeutil import to_venue, venue_local_to_utc from models.business_day import BusinessDay from services import business_days as ops now = now or utcnow() started_at = started_at or _state["started_at"] or datetime.min.replace(tzinfo=now.tzinfo) open_mode, close_mode = _mode(db, "open"), _mode(db, "close") did: list[str] = [] if open_mode == "off" and close_mode == "off": return did now_local = to_venue(now).replace(tzinfo=None) utc = venue_local_to_utc # naive venue time → aware UTC hhmm = lambda local: local.strftime("%H:%M") # noqa: E731 day = ops.current(db) # ── close first (a break's end closes before the next span opens) ── if close_mode != "off" and day is not None: ends = [e for _, e in windows(db, "close", now_local) if e <= now_local] last = max(ends) if ends else None if last is not None and day.opened_at < utc(last): if close_mode == "alert" or started_at > utc(last): _alert(db, NOT_CLOSED, NOT_CLOSED, {"time": hhmm(last), "action": "overview"}) did.append(f"alert:{NOT_CLOSED}") else: retry = _state["next_close_try"] if retry is None or now >= retry: unclosed = ops.unclosed_orders(db, day) if unclosed: _state["next_close_try"] = now + RETRY_CLOSE _alert(db, TABLES_OPEN, TABLES_OPEN, {"time": hhmm(last), "count": len(unclosed), "action": "overview"}) did += [f"alert:{TABLES_OPEN}", "waiting"] else: ops.close_day(db, auto=True, at=now) _state["next_close_try"] = None logger.info("day_auto.closed day=%s moment=%s", day.id, last) did.append("closed") day = None else: did.append("waiting") # ── open ── if open_mode != "off" and day is None: inside = [(a, b) for a, b in windows(db, "open", now_local) if a <= now_local < b] if inside: start = max(a for a, _ in inside) since = utc(start) touched = db.query(BusinessDay).filter((BusinessDay.opened_at >= since) | (BusinessDay.closed_at >= since)).first() if touched is None: blocked = ops.license_blocked() if open_mode == "alert": _alert(db, NOT_OPEN, NOT_OPEN, {"time": hhmm(start), "action": "open_day"}) did.append(f"alert:{NOT_OPEN}") elif blocked: _alert(db, OPEN_BLOCKED, OPEN_BLOCKED, {"time": hhmm(start), "reason": blocked}, severity="critical") did.append(f"alert:{OPEN_BLOCKED}") else: ops.open_day(db, auto=True, at=now) logger.info("day_auto.opened moment=%s", start) did.append("opened") resolve_alerts(db) return did # ── the loop ───────────────────────────────────────────────────────────────── def _tick_once() -> None: from database import SessionLocal db = SessionLocal() try: did = tick(db) if did: logger.info("day_auto.tick %s", ",".join(did)) except Exception: logger.exception("day_auto.tick_failed") db.rollback() finally: db.close() async def _run() -> None: _state["started_at"] = utcnow() while True: await asyncio.to_thread(_tick_once) await asyncio.sleep(CHECK_EVERY_S) async def start() -> asyncio.Task: return asyncio.create_task(_run()) def reset_for_tests() -> None: _state.update(next_close_try=None, started_at=None)