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
+6
View File
@@ -90,6 +90,12 @@
"print": {
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
"failing": "Ένα δελτίο της παραγγελίας #{order_id} δεν έχει τυπωθεί ακόμα στον εκτυπωτή {printer} (αποτυχημένες προσπάθειες μέχρι τώρα: {attempts}· συνεχίζει να προσπαθεί). Ελέγξτε τον εκτυπωτή."
},
"business_day": {
"not_open": "Είναι {time} και η ημέρα δεν έχει ανοίξει.",
"open_blocked": "Η ημέρα δεν άνοιξε μόνη της στις {time}: η άδεια δεν το επιτρέπει ({reason}).",
"tables_open": "Είναι ώρα κλεισίματος ({time}) αλλά {count} παραγγελίες είναι ακόμα ανοιχτές. Η ημέρα κλείνει μόνη της μόλις κλείσουν.",
"not_closed": "Η ημέρα έπρεπε να κλείσει στις {time} και είναι ακόμα ανοιχτή."
}
},
"system_product": {
+6
View File
@@ -90,6 +90,12 @@
"print": {
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).",
"failing": "A ticket for order #{order_id} hasn't printed on {printer} yet (failed attempts so far: {attempts}; still retrying). Check the printer."
},
"business_day": {
"not_open": "It's {time} and the day isn't open.",
"open_blocked": "The day didn't open by itself at {time}: the license doesn't allow it ({reason}).",
"tables_open": "It's closing time ({time}) but {count} orders are still open. The day closes by itself once they are closed.",
"not_closed": "The day should have closed at {time} and is still open."
}
},
"system_product": {
+22
View File
@@ -85,6 +85,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
row = db.query(Notification).filter(
Notification.dedupe_key == dedupe_key,
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
Notification.resolved_at.is_(None),
).order_by(Notification.id.desc()).first()
if row is not None:
if not fold:
@@ -119,6 +120,27 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
db.close()
def resolve(db, dedupe_keys) -> int:
"""Sticky alerts whose cause is gone (6F.8): hide the live rows with these dedupe keys.
Sends `platform_notification` {id, resolved: true} so open bells refresh. Commits."""
from models.notification import Notification
rows = db.query(Notification).filter(Notification.dedupe_key.in_(list(dedupe_keys)),
Notification.resolved_at.is_(None)).all()
if not rows:
return 0
now = utcnow()
for r in rows:
r.resolved_at = now
db.commit()
try:
from services.ws_bus import broadcast_sync
for r in rows:
broadcast_sync(EVENT, {"id": r.id, "resolved": True}, user_ids=recipients(db, r.audience))
except Exception:
logger.exception("notification.resolve_event_failed")
return len(rows)
# ── producers that need a little logic ───────────────────────────────────────
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
+3
View File
@@ -79,7 +79,10 @@ async def lifespan(app: FastAPI):
from core.modules import supervisor
supervisor.start(loop)
reservation_task = await start_reservation_tasks()
from services import day_auto
day_task = await day_auto.start() # the day opens / closes by itself (6F.8)
yield
day_task.cancel()
supervisor.stop_all()
sync_task.cancel()
reservation_task.cancel()
@@ -0,0 +1,35 @@
"""The day opens and closes by itself (owner 2026-11-23, plan 6F.8, services/day_auto.py).
- business_days.opened_auto / closed_auto; opened_by_id may be NULL (opened by the system).
- notifications.resolved_at: sticky alerts that stay until their cause is gone.
Revision ID: 0052_day_auto
Revises: 0051_sign_in
Create Date: 2026-11-23 23:30:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0052_day_auto'
down_revision = '0051_sign_in'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('business_days') as b:
b.alter_column('opened_by_id', existing_type=sa.Integer(), nullable=True)
b.add_column(sa.Column('opened_auto', sa.Boolean(), nullable=False, server_default='0'))
b.add_column(sa.Column('closed_auto', sa.Boolean(), nullable=False, server_default='0'))
with op.batch_alter_table('notifications') as b:
b.add_column(sa.Column('resolved_at', UTCDateTime(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('notifications') as b:
b.drop_column('resolved_at')
with op.batch_alter_table('business_days') as b:
b.drop_column('closed_auto')
b.drop_column('opened_auto')
+4 -2
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Date, Integer, String, Float, ForeignKey, Text
from sqlalchemy import Boolean, Column, Date, Integer, String, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from database import Base
@@ -15,7 +15,9 @@ class BusinessDay(Base):
# The date this day counts as (D-11): set once when the day opens with
# core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it.
business_date = Column(Date, nullable=False, index=True)
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=True) # NULL = opened by the system (6F.8)
opened_auto = Column(Boolean, nullable=False, default=False) # 6F.8: opened / closed by
closed_auto = Column(Boolean, nullable=False, default=False) # services/day_auto.py
closed_at = Column(UTCDateTime, nullable=True)
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
notes = Column(Text, nullable=True)
+5 -2
View File
@@ -7,8 +7,10 @@ failures (later: Ergani, close-day reminders). NOT staff chat or manager message
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
in the reader's language when listed.
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
- dedupe_key: while a row with the same key is still live (expires_at NULL or future),
notify() bumps its `count` / `last_at` instead of adding a row.
- dedupe_key: while a row with the same key is still live (expires_at NULL or future, not
resolved), notify() bumps its `count` / `last_at` instead of adding a row.
- resolved_at (6F.8): a sticky alert ("the day isn't open") stays until its cause is gone;
core.notifications.resolve() then hides it.
Written through core/notifications.py only.
"""
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
@@ -31,6 +33,7 @@ class Notification(Base):
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
resolved_at = Column(UTCDateTime, nullable=True) # 6F.8: a sticky alert whose cause is gone (hidden, dedupe ends)
class NotificationRead(Base):
@@ -22,6 +22,13 @@ MODULE = Module(
),
settings=(
SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'),
SettingDef('business_day.auto_open', 'off', "The day opens by itself (6F.8): 'off' | 'schedule' (at the opening hours) | 'time' (every day at business_day.auto_open_time) | 'alert' (at the opening hours, only tell the managers)", type='enum', choices=('off', 'schedule', 'time', 'alert')),
SettingDef('business_day.auto_close', 'off', "The day closes by itself (6F.8): 'off' | 'schedule' | 'time' | 'alert'. Closes only when every order of the day is closed; otherwise the managers are alerted and it tries again every 15 minutes.", type='enum', choices=('off', 'schedule', 'time', 'alert')),
SettingDef('business_day.auto_open_time', '09:00', "HH:MM venue time, for business_day.auto_open = 'time' (6F.8).", type='str'),
SettingDef('business_day.auto_close_time', '23:30', "HH:MM venue time, for business_day.auto_close = 'time' (6F.8).", type='str'),
SettingDef('business_day.auto_ignore_break', 'true', "A day's opening spans count as one (first opening to last closing); 'false' = the break between spans closes the day and the next span opens a new one (6F.8).", type='bool'),
SettingDef('business_day.auto_open_offset_min', '0', 'Open this many minutes before the opening hours start (6F.8, 0-720).', type='int'),
SettingDef('business_day.auto_close_offset_min', '0', 'Close this many minutes after the opening hours end (6F.8, 0-720).', type='int'),
SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'),
SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'),
SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'),
+6 -103
View File
@@ -44,25 +44,8 @@ def open_business_day(
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
existing = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if existing:
raise XeniaError("business_day.already_open")
# Gate: admin lock (already enforced or pending)
if license_state.get("locked") or license_state.get("lock_pending"):
raise XeniaError("license.locked")
# Gate: license expired and expiry grace period also over
if not license_state.get("licensed", True):
raise XeniaError("license.expired")
opened_at = utcnow()
day = BusinessDay(opened_by_id=user.id, notes=body.notes,
opened_at=opened_at, business_date=business_date_of(opened_at))
db.add(day)
db.commit()
db.refresh(day)
return day
from services.business_days import open_day
return open_day(db, user_id=user.id, notes=body.notes)
@router.post("/close", response_model=BusinessDayOut)
@@ -71,90 +54,9 @@ def close_business_day(
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
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 body.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 = utcnow()
# Close all non-terminal orders for this business day (open, partially_paid, paid)
all_unclosed = db.query(Order).filter(
Order.business_day_id == day.id,
Order.status.in_(["open", "partially_paid", "paid"]),
).all()
for order in all_unclosed:
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",
))
active_shifts = db.query(WaiterShift).filter(
WaiterShift.business_day_id == day.id,
WaiterShift.ended_at == None,
).all()
for shift in active_shifts:
from routers.shifts import compute_shift_total
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
if body.notes:
day.notes = body.notes
# Phase 2E: store-level cash reconciliation
if body.store_closing_cash is not None:
day.store_closing_cash = body.store_closing_cash
# expected = store_opening_cash + sum of all waiter collected amounts this day
all_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == day.id).all()
total_collected = sum(s.total_collected or 0.0 for s in all_shifts)
expected_closing = (day.store_opening_cash or 0.0) + total_collected
day.store_cash_discrepancy = round(body.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 that the day has closed.
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()
return day
from services.business_days import close_day
return close_day(db, user_id=user.id, force=body.force, notes=body.notes,
store_closing_cash=body.store_closing_cash)
class PatchBusinessDayRequest(BaseModel):
@@ -596,6 +498,7 @@ def business_day_history(
"opened_by_name": (w_opener.full_name or w_opener.username) if w_opener else None,
"closed_by_id": day.closed_by_id,
"closed_by_name": (w_closer.full_name or w_closer.username) if w_closer else None,
"opened_auto": bool(day.opened_auto), "closed_auto": bool(day.closed_auto), # 6F.8
"notes": day.notes,
"order_count": order_count,
"revenue": round(revenue, 2),
+2 -1
View File
@@ -21,7 +21,8 @@ router = APIRouter()
def _live(user):
now = utcnow()
return (visible_filter(user), (Notification.expires_at.is_(None)) | (Notification.expires_at > now))
return (visible_filter(user), (Notification.expires_at.is_(None)) | (Notification.expires_at > now),
Notification.resolved_at.is_(None))
def _text(n, lang) -> str:
+1
View File
@@ -1187,6 +1187,7 @@ def business_days_list(
"closed_at": _dt(d.closed_at),
"opened_by": (opener.full_name or opener.username) if opener else None,
"closed_by": (closer.full_name or closer.username) if closer else None,
"opened_auto": bool(d.opened_auto), "closed_auto": bool(d.closed_auto), # 6F.8: by the system
"notes": d.notes,
"order_count": len(orders),
"closed_order_count": len(closed_orders),
+3 -1
View File
@@ -9,7 +9,9 @@ class BusinessDayOut(BaseModel):
status: str
opened_at: UTCDatetime
business_date: date
opened_by_id: int
opened_by_id: Optional[int] = None # None = opened by the system (6F.8)
opened_auto: bool = False
closed_auto: bool = False
closed_at: Optional[UTCDatetime] = None
closed_by_id: Optional[int] = None
notes: Optional[str] = None
+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)
+167
View File
@@ -0,0 +1,167 @@
"""The day opens and closes by itself (plan 6F.8): services/day_auto.tick with a fake clock.
Hours used: Monday 09:00-15:00 and 18:00-23:00; Tuesday 10:00-01:00 (past midnight).
2026-11-30 is a Monday; Athens is UTC+2 then."""
from datetime import datetime
import pytest
from services import day_auto
HOURS = {"days": [[{"from": "09:00", "to": "15:00"}, {"from": "18:00", "to": "23:00"}],
[{"from": "10:00", "to": "01:00"}], [], [], [], [], []], "note": None}
def at(local: str):
from core.timeutil import venue_local_to_utc
return venue_local_to_utc(datetime.fromisoformat(local))
@pytest.fixture
def boss(make_user, login):
return login(make_user(role="owner"))
@pytest.fixture
def venue(client, boss, monkeypatch):
import services.cloud_sync as cs
monkeypatch.setattr(cs, "apply_license", lambda *a, **k: None) # no cloud license here: keep it as it is
day_auto.reset_for_tests()
def set_(**values):
for k, v in values.items():
r = client.put(f"/api/settings/business_day.{k}", headers=boss, json={"value": v})
assert r.status_code == 200, r.text
assert client.put("/api/identity/hours", headers=boss, json=HOURS).status_code == 200
yield set_
day_auto.reset_for_tests()
def days(db):
from models.business_day import BusinessDay
db.expire_all()
return db.query(BusinessDay).order_by(BusinessDay.id).all()
def alerts(client, boss):
return [n["key"] for n in client.get("/api/platform/notifications", headers=boss).json()["items"]
if n["key"].startswith("business_day.")]
def test_off_by_default_does_nothing(db, venue):
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == []
assert days(db) == []
def test_schedule_one_day_over_the_break(db, venue):
venue(auto_open="schedule", auto_close="schedule")
assert day_auto.tick(db, now=at("2026-11-30T08:59")) == []
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == ["opened"]
d = days(db)[0]
assert d.status == "open" and d.opened_auto and d.opened_by_id is None
assert day_auto.tick(db, now=at("2026-11-30T16:00")) == [] # the break: one day
assert day_auto.tick(db, now=at("2026-11-30T23:00")) == ["closed"]
d = days(db)[0]
assert d.status == "closed" and d.closed_auto and d.closed_by_id is None
assert day_auto.tick(db, now=at("2026-11-30T23:05")) == [] # not reopened
assert len(days(db)) == 1
def test_break_closes_and_reopens_when_not_ignored(db, venue):
venue(auto_open="schedule", auto_close="schedule", auto_ignore_break="false")
day_auto.tick(db, now=at("2026-11-30T09:00"))
assert day_auto.tick(db, now=at("2026-11-30T15:00")) == ["closed"]
assert day_auto.tick(db, now=at("2026-11-30T17:59")) == []
assert day_auto.tick(db, now=at("2026-11-30T18:00")) == ["opened"]
assert [d.status for d in days(db)] == ["closed", "open"]
def test_a_day_closed_by_hand_is_not_reopened_in_the_same_span(db, venue, client, boss):
venue(auto_open="schedule")
day_auto.tick(db, now=at("2026-11-30T09:00"))
assert client.post("/api/business-day/close", headers=boss, json={}).status_code == 200
assert day_auto.tick(db, now=at("2026-11-30T12:00")) == []
assert day_auto.tick(db, now=at("2026-12-01T10:00")) == ["opened"] # the next day's span
def test_span_past_midnight_belongs_to_the_day_it_starts(db, venue):
venue(auto_open="schedule", auto_close="schedule")
assert day_auto.tick(db, now=at("2026-12-01T10:00")) == ["opened"] # Tuesday
assert day_auto.tick(db, now=at("2026-12-02T00:30")) == [] # still Tuesday's span
assert day_auto.tick(db, now=at("2026-12-02T01:00")) == ["closed"]
def test_offsets(db, venue):
venue(auto_open="schedule", auto_close="schedule", auto_open_offset_min="30", auto_close_offset_min="45")
assert day_auto.tick(db, now=at("2026-11-30T08:30")) == ["opened"]
assert day_auto.tick(db, now=at("2026-11-30T23:30")) == []
assert day_auto.tick(db, now=at("2026-11-30T23:45")) == ["closed"]
def test_time_overrides_the_hours(db, venue):
venue(auto_open="time", auto_open_time="07:00", auto_close="time", auto_close_time="22:00")
assert day_auto.tick(db, now=at("2026-12-03T06:59")) == [] # Thursday: no hours at all
assert day_auto.tick(db, now=at("2026-12-03T07:00")) == ["opened"]
assert day_auto.tick(db, now=at("2026-12-03T22:00")) == ["closed"]
assert day_auto.tick(db, now=at("2026-12-03T23:00")) == []
assert day_auto.tick(db, now=at("2026-12-04T06:30")) == [] # past the rollover: no catch-up
assert day_auto.tick(db, now=at("2026-12-04T07:00")) == ["opened"]
def test_alert_is_one_sticky_notification_that_resolves(db, venue, client, boss):
venue(auto_open="alert", auto_close="alert")
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == ["alert:business_day.not_open"]
day_auto.tick(db, now=at("2026-11-30T09:05"))
assert alerts(client, boss) == ["business_day.not_open"] # one, not two
n = client.get("/api/platform/notifications", headers=boss).json()["items"][0]
assert n["params"]["action"] == "open_day" and "09:00" in n["message"] and n["expires_at"] is None
assert days(db) == [] # alert only
assert client.post("/api/business-day/open", headers=boss, json={}).status_code == 201
assert alerts(client, boss) == [] # resolved at once
day_auto.tick(db, now=at("2026-11-30T23:00"))
assert alerts(client, boss) == ["business_day.not_closed"]
assert client.post("/api/business-day/close", headers=boss, json={}).status_code == 200
assert alerts(client, boss) == []
def test_open_tables_block_the_close_and_it_retries(db, venue, client, boss, make_user):
from models.order import Order
venue(auto_open="schedule", auto_close="schedule")
day_auto.tick(db, now=at("2026-11-30T09:00"))
d = days(db)[0]
o = Order(opened_by=make_user(role="waiter").id, business_day_id=d.id, status="paid")
db.add(o)
db.commit()
assert day_auto.tick(db, now=at("2026-11-30T23:00")) == ["alert:business_day.tables_open", "waiting"]
assert alerts(client, boss) == ["business_day.tables_open"]
o.status = "closed"
db.commit()
assert day_auto.tick(db, now=at("2026-11-30T23:10")) == ["waiting"] # every 15 minutes
assert days(db)[0].status == "open"
assert day_auto.tick(db, now=at("2026-11-30T23:15")) == ["closed"]
assert alerts(client, boss) == []
def test_restart_catches_up_the_open_and_alerts_a_missed_close(db, venue, client, boss):
venue(auto_open="schedule", auto_close="schedule")
assert day_auto.tick(db, now=at("2026-11-30T11:00"), started_at=at("2026-11-30T11:00")) == ["opened"]
out = day_auto.tick(db, now=at("2026-11-30T23:40"), started_at=at("2026-11-30T23:30"))
assert out == ["alert:business_day.not_closed"] and days(db)[0].status == "open"
assert alerts(client, boss) == ["business_day.not_closed"]
def test_locked_license_alerts_instead_of_opening(db, venue, client, boss, monkeypatch):
from services.license_state import license_state
venue(auto_open="schedule")
monkeypatch.setitem(license_state, "locked", True)
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == ["alert:business_day.open_blocked"]
assert days(db) == [] and alerts(client, boss) == ["business_day.open_blocked"]
def test_spans_of():
from datetime import date
mon = date(2026, 11, 30)
assert [(a.hour, b.hour) for a, b in day_auto.spans_of(HOURS["days"], mon, False)] == [(9, 15), (18, 23)]
assert [(a.hour, b.hour) for a, b in day_auto.spans_of(HOURS["days"], mon, True)] == [(9, 23)]
(a, b), = day_auto.spans_of(HOURS["days"], date(2026, 12, 1), True)
assert b.day == 2 and b.hour == 1