feat(backend,manager): the business day opens and closes by itself (opening hours, a time, or only an alert)

- services/day_auto.py: a minute loop (venue time, offline) opens the day when the opening
  hours start (or at business_day.auto_open_time) and closes it when they end (or at
  auto_close_time); 'alert' only tells the managers. Offsets before / after, one day across
  the break or one per span, spans past midnight belong to the day they start, a day closed
  by hand isn't reopened in the same span, a restart catches up the open (until the business
  date changes for 'time') and alerts a missed close instead of doing it late.
- The close runs only when no order of the day is unclosed (Q-10): otherwise a sticky alert
  and a new try every 15 minutes. A locked / expired license turns the open into an alert.
- Sticky notifications: notifications.resolved_at + core.notifications.resolve(); the
  alerts resolve when the day opens / closes (by hand or by itself).
- services/business_days.py: the one open / close path (the routes and the loop); days opened
  or closed by the system have no opener / closer and opened_auto / closed_auto (Alembic 0052).
- Manager: Settings -> Operation "Opening and closing the day"; the bell's action buttons
  ("Open now", "Go to the overview"); Reports -> Days marks days opened / closed by itself.

Plan platform-v2 6F.8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 13:17:15 +02:00
co-authored by Claude Opus 5.5
parent 7706bf2470
commit 096bd53dbd
21 changed files with 856 additions and 117 deletions
+132
View File
@@ -0,0 +1,132 @@
"""Opening and closing the business day: the one way, used by the manager's buttons
(routers/business_day.py) and by the automatic open / close (services/day_auto.py, plan 6F.8).
- open_day(db, user_id=None, auto=True): a day opened by the system has no opener
(opened_by_id NULL) and opened_auto set. The license gates apply to both.
- close_day(db, user_id=None, auto=True): the same close as a manager's: unclosed orders are
closed (the automatic close only runs when there are none, Q-10), open shifts end with
their totals, flags and staff messages are cleared, a lock the cloud asked for while the
day was open takes effect, the license is re-evaluated.
- unclosed_orders(db, day): what "a table is still open" means for the automatic close: every
order of the day that isn't closed or cancelled (paid but not closed counts too).
"""
from __future__ import annotations
from core.errors import XeniaError
from core.timeutil import business_date_of, utcnow
def current(db):
from models.business_day import BusinessDay
return db.query(BusinessDay).filter(BusinessDay.status == "open").first()
def license_blocked() -> str | None:
"""The error code that stops a day from opening now, or None."""
from services.license_state import license_state
if license_state.get("locked") or license_state.get("lock_pending"):
return "license.locked"
if not license_state.get("licensed", True):
return "license.expired"
return None
def open_day(db, *, user_id: int | None = None, notes: str | None = None, auto: bool = False, at=None):
from models.business_day import BusinessDay
if current(db) is not None:
raise XeniaError("business_day.already_open")
blocked = license_blocked()
if blocked:
raise XeniaError(blocked)
opened_at = at or utcnow() # `at`: the automatic open's clock (tests drive it)
day = BusinessDay(opened_by_id=user_id, notes=notes, opened_at=opened_at,
business_date=business_date_of(opened_at), opened_auto=auto)
db.add(day)
db.commit()
db.refresh(day)
from services import day_auto
day_auto.resolve_alerts(db)
return day
def unclosed_orders(db, day):
from models.order import Order
return db.query(Order).filter(Order.business_day_id == day.id,
Order.status.in_(["open", "partially_paid", "paid"])).all()
def close_day(db, *, user_id: int | None = None, force: bool = False, notes: str | None = None,
store_closing_cash: float | None = None, auto: bool = False, at=None):
from models.business_day import BusinessDay # noqa: F401
from models.flag import TableFlagAssignment
from models.message import StaffMessage, StaffMessageAck
from models.order import Order, OrderAuditLog, OrderItem
from models.shift import WaiterShift
from services.license_state import license_state
day = current(db)
if not day:
raise XeniaError("business_day.none_open")
open_orders = db.query(Order).filter(
Order.business_day_id == day.id,
Order.status.in_(["open", "partially_paid"]),
).all()
if open_orders and not force:
# Count orders that have at least one active (unpaid) item — covers both
# "open" (fully unpaid) and "partially_paid" (partially unpaid) orders.
with_pending = sum(
1 for o in open_orders
if db.query(OrderItem).filter(OrderItem.order_id == o.id, OrderItem.status == "active").first() is not None
)
raise XeniaError("business_day.orders_open", open_orders=len(open_orders), partially_paid=with_pending)
now = at or utcnow()
# Close all non-terminal orders for this business day (open, partially_paid, paid)
for order in unclosed_orders(db, day):
was_unpaid = order.status in ("open", "partially_paid")
order.status = "closed"
order.closed_at = now
order.closed_by = user_id
if was_unpaid:
db.add(OrderAuditLog(order_id=order.id, event_type="ORDER_CLOSED", waiter_id=user_id,
note="Force-closed at end of business day"))
from routers.shifts import compute_shift_total
for shift in db.query(WaiterShift).filter(WaiterShift.business_day_id == day.id, WaiterShift.ended_at == None).all(): # noqa: E711
shift.total_collected = compute_shift_total(shift.id, db)
shift.ended_at = now
# Clear all table flags and staff messages — fresh slate for the next day
db.query(TableFlagAssignment).delete(synchronize_session=False)
db.query(StaffMessageAck).delete(synchronize_session=False)
db.query(StaffMessage).delete(synchronize_session=False)
day.status = "closed"
day.closed_at = now
day.closed_by_id = user_id
day.closed_auto = auto
if notes:
day.notes = notes
# Phase 2E: store-level cash reconciliation
if store_closing_cash is not None:
day.store_closing_cash = store_closing_cash
all_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == day.id).all()
expected_closing = (day.store_opening_cash or 0.0) + sum(s.total_collected or 0.0 for s in all_shifts)
day.store_cash_discrepancy = round(store_closing_cash - expected_closing, 2)
db.commit()
db.refresh(day)
# Deferred lock: if cloud requested a lock while the workday was open, enforce it now.
if license_state.get("lock_pending"):
license_state["lock_pending"] = False
license_state["locked"] = True
# Re-evaluate the license now that no workday is open (an expiry whose grace
# ended mid-service takes effect here) — also persists the state
from services.cloud_sync import apply_license
apply_license()
from services import day_auto
day_auto.resolve_alerts(db)
return day
+253
View File
@@ -0,0 +1,253 @@
"""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:<key>', '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)