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:
@@ -90,6 +90,12 @@
|
|||||||
"print": {
|
"print": {
|
||||||
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
|
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
|
||||||
"failing": "Ένα δελτίο της παραγγελίας #{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": {
|
"system_product": {
|
||||||
|
|||||||
@@ -90,6 +90,12 @@
|
|||||||
"print": {
|
"print": {
|
||||||
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).",
|
"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."
|
"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": {
|
"system_product": {
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
|
|||||||
row = db.query(Notification).filter(
|
row = db.query(Notification).filter(
|
||||||
Notification.dedupe_key == dedupe_key,
|
Notification.dedupe_key == dedupe_key,
|
||||||
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
|
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
|
||||||
|
Notification.resolved_at.is_(None),
|
||||||
).order_by(Notification.id.desc()).first()
|
).order_by(Notification.id.desc()).first()
|
||||||
if row is not None:
|
if row is not None:
|
||||||
if not fold:
|
if not fold:
|
||||||
@@ -119,6 +120,27 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
|
|||||||
db.close()
|
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 ───────────────────────────────────────
|
# ── producers that need a little logic ───────────────────────────────────────
|
||||||
|
|
||||||
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
|
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
|
||||||
|
|||||||
@@ -79,7 +79,10 @@ async def lifespan(app: FastAPI):
|
|||||||
from core.modules import supervisor
|
from core.modules import supervisor
|
||||||
supervisor.start(loop)
|
supervisor.start(loop)
|
||||||
reservation_task = await start_reservation_tasks()
|
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
|
yield
|
||||||
|
day_task.cancel()
|
||||||
supervisor.stop_all()
|
supervisor.stop_all()
|
||||||
sync_task.cancel()
|
sync_task.cancel()
|
||||||
reservation_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')
|
||||||
@@ -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 core.timeutil import UTCDateTime, utcnow
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from database import Base
|
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
|
# 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.
|
# core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it.
|
||||||
business_date = Column(Date, nullable=False, index=True)
|
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_at = Column(UTCDateTime, nullable=True)
|
||||||
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
notes = Column(Text, nullable=True)
|
notes = Column(Text, nullable=True)
|
||||||
|
|||||||
@@ -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
|
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
|
||||||
in the reader's language when listed.
|
in the reader's language when listed.
|
||||||
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
|
- 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),
|
- dedupe_key: while a row with the same key is still live (expires_at NULL or future, not
|
||||||
notify() bumps its `count` / `last_at` instead of adding a row.
|
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.
|
Written through core/notifications.py only.
|
||||||
"""
|
"""
|
||||||
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
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)
|
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
|
||||||
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
|
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):
|
class NotificationRead(Base):
|
||||||
|
|||||||
@@ -22,6 +22,13 @@ MODULE = Module(
|
|||||||
),
|
),
|
||||||
settings=(
|
settings=(
|
||||||
SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'),
|
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('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.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'),
|
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'),
|
||||||
|
|||||||
@@ -44,25 +44,8 @@ def open_business_day(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require_manager),
|
||||||
):
|
):
|
||||||
existing = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
from services.business_days import open_day
|
||||||
if existing:
|
return open_day(db, user_id=user.id, notes=body.notes)
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/close", response_model=BusinessDayOut)
|
@router.post("/close", response_model=BusinessDayOut)
|
||||||
@@ -71,90 +54,9 @@ def close_business_day(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require_manager),
|
||||||
):
|
):
|
||||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
from services.business_days import close_day
|
||||||
if not day:
|
return close_day(db, user_id=user.id, force=body.force, notes=body.notes,
|
||||||
raise XeniaError("business_day.none_open")
|
store_closing_cash=body.store_closing_cash)
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
class PatchBusinessDayRequest(BaseModel):
|
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,
|
"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_id": day.closed_by_id,
|
||||||
"closed_by_name": (w_closer.full_name or w_closer.username) if w_closer else None,
|
"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,
|
"notes": day.notes,
|
||||||
"order_count": order_count,
|
"order_count": order_count,
|
||||||
"revenue": round(revenue, 2),
|
"revenue": round(revenue, 2),
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ router = APIRouter()
|
|||||||
|
|
||||||
def _live(user):
|
def _live(user):
|
||||||
now = utcnow()
|
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:
|
def _text(n, lang) -> str:
|
||||||
|
|||||||
@@ -1187,6 +1187,7 @@ def business_days_list(
|
|||||||
"closed_at": _dt(d.closed_at),
|
"closed_at": _dt(d.closed_at),
|
||||||
"opened_by": (opener.full_name or opener.username) if opener else None,
|
"opened_by": (opener.full_name or opener.username) if opener else None,
|
||||||
"closed_by": (closer.full_name or closer.username) if closer 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,
|
"notes": d.notes,
|
||||||
"order_count": len(orders),
|
"order_count": len(orders),
|
||||||
"closed_order_count": len(closed_orders),
|
"closed_order_count": len(closed_orders),
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ class BusinessDayOut(BaseModel):
|
|||||||
status: str
|
status: str
|
||||||
opened_at: UTCDatetime
|
opened_at: UTCDatetime
|
||||||
business_date: date
|
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_at: Optional[UTCDatetime] = None
|
||||||
closed_by_id: Optional[int] = None
|
closed_by_id: Optional[int] = None
|
||||||
notes: Optional[str] = None
|
notes: Optional[str] = None
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -5,10 +5,15 @@
|
|||||||
// `platform_notification` {id} and after every reconnect ('ready').
|
// `platform_notification` {id} and after every reconnect ('ready').
|
||||||
// - A NEW warning/critical one also pops up as a toast.
|
// - A NEW warning/critical one also pops up as a toast.
|
||||||
// - Opening an item marks it read; "Mark all as read" does the rest.
|
// - Opening an item marks it read; "Mark all as read" does the rest.
|
||||||
|
// - 6F.8: an item whose params carry an `action` gets a button: 'open_day' opens the business
|
||||||
|
// day here (POST /api/business-day/open), 'overview' goes to the overview. Those alerts stay
|
||||||
|
// until their cause is gone (the backend resolves them; a live event refreshes the list).
|
||||||
// Not staff chat (/api/notifications, the chat module), which stays separate.
|
// Not staff chat (/api/notifications, the chat module), which stays separate.
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import toast from 'react-hot-toast'
|
import toast from 'react-hot-toast'
|
||||||
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { Bell, CheckCheck } from 'lucide-react'
|
import { Bell, CheckCheck } from 'lucide-react'
|
||||||
|
import { errorMessage } from '@xenia/api'
|
||||||
import { useTranslation, useFormat } from '@xenia/i18n'
|
import { useTranslation, useFormat } from '@xenia/i18n'
|
||||||
import client from '../api/client'
|
import client from '../api/client'
|
||||||
import { useLiveEvent } from '../live/useLiveEvent'
|
import { useLiveEvent } from '../live/useLiveEvent'
|
||||||
@@ -22,6 +27,7 @@ export default function NotificationBell() {
|
|||||||
const [data, setData] = useState({ items: [], unread: 0 })
|
const [data, setData] = useState({ items: [], unread: 0 })
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const ref = useRef(null)
|
const ref = useRef(null)
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const asked = useRef(0)
|
const asked = useRef(0)
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
@@ -74,6 +80,20 @@ export default function NotificationBell() {
|
|||||||
load()
|
load()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function act(n) {
|
||||||
|
await markRead(n)
|
||||||
|
if (n.params?.action === 'overview') { setOpen(false); navigate('/'); return }
|
||||||
|
if (n.params?.action === 'open_day') {
|
||||||
|
try {
|
||||||
|
await client.post('/api/business-day/open', {})
|
||||||
|
toast.success(t('notifications.dayOpened'))
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(errorMessage(err, t))
|
||||||
|
}
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const badge = data.unread > 9 ? '9+' : String(data.unread)
|
const badge = data.unread > 9 ? '9+' : String(data.unread)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -109,11 +129,17 @@ export default function NotificationBell() {
|
|||||||
: (
|
: (
|
||||||
<ul className="max-h-[60vh] overflow-y-auto divide-y divide-line">
|
<ul className="max-h-[60vh] overflow-y-auto divide-y divide-line">
|
||||||
{data.items.map(n => (
|
{data.items.map(n => (
|
||||||
<li key={n.id}>
|
<li key={n.id} className="relative">
|
||||||
|
{n.params?.action && (
|
||||||
|
<button onClick={() => act(n)} data-testid={`notif-action-${n.id}`}
|
||||||
|
className="absolute right-3 top-3 z-10 rounded-control border border-line bg-surface px-2.5 py-1 text-caption font-medium text-accent-ink hover:bg-surface-2">
|
||||||
|
{t(`notifications.actions.${n.params.action}`, { defaultValue: n.params.action })}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button onClick={() => markRead(n)} className={`w-full text-left flex gap-3 px-4 py-3 hover:bg-surface-2 ${n.read ? '' : 'bg-accent-soft/40'}`}
|
<button onClick={() => markRead(n)} className={`w-full text-left flex gap-3 px-4 py-3 hover:bg-surface-2 ${n.read ? '' : 'bg-accent-soft/40'}`}
|
||||||
data-testid={`notif-${n.id}`} data-read={n.read ? 'true' : 'false'}>
|
data-testid={`notif-${n.id}`} data-read={n.read ? 'true' : 'false'}>
|
||||||
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT[n.severity] || DOT.info}`} />
|
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT[n.severity] || DOT.info}`} />
|
||||||
<span className="flex-1 min-w-0">
|
<span className={`flex-1 min-w-0 ${n.params?.action ? 'pr-28' : ''}`}>
|
||||||
<span className={`block text-label ${n.read ? 'text-ink-2' : 'text-ink font-medium'}`}>{n.message}</span>
|
<span className={`block text-label ${n.read ? 'text-ink-2' : 'text-ink font-medium'}`}>{n.message}</span>
|
||||||
<span className="block text-caption text-ink-3 mt-0.5">
|
<span className="block text-caption text-ink-3 mt-0.5">
|
||||||
{f.formatRelative(n.last_at)}
|
{f.formatRelative(n.last_at)}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
// Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches
|
// Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches
|
||||||
// were kept in the browser only and nothing ever read them).
|
// were kept in the browser only and nothing ever read them).
|
||||||
import { useId, useState } from 'react'
|
import { useId, useState } from 'react'
|
||||||
import { useMutation } from '@tanstack/react-query'
|
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||||
import toast from 'react-hot-toast'
|
import toast from 'react-hot-toast'
|
||||||
import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react'
|
import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react'
|
||||||
import { useModule } from '@xenia/access'
|
import { useModule } from '@xenia/access'
|
||||||
@@ -70,9 +70,66 @@ function OrderingSettings() {
|
|||||||
<PriceChangeSettings s={s} />
|
<PriceChangeSettings s={s} />
|
||||||
<QuantitySettings s={s} />
|
<QuantitySettings s={s} />
|
||||||
<SplitSettings s={s} />
|
<SplitSettings s={s} />
|
||||||
|
<AutoDaySettings s={s} />
|
||||||
</>)
|
</>)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DAY_MODES = ['off', 'schedule', 'time', 'alert']
|
||||||
|
const OFFSETS = ['0', '15', '30', '45', '60', '90', '120']
|
||||||
|
|
||||||
|
/** The day opens and closes by itself (6F.8, services/day_auto.py): at the opening hours (the
|
||||||
|
* Schedule page), at a time of its own, or only an alert. Closing waits for every table (Q-10). */
|
||||||
|
function AutoDaySettings({ s }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const a = (k, o) => t(`settings.autoDay.${k}`, o)
|
||||||
|
const ids = { open: useId(), close: useId(), openTime: useId(), closeTime: useId(), openOff: useId(), closeOff: useId() }
|
||||||
|
const { data: hours } = useQuery({ queryKey: ['opening-hours'], queryFn: () => client.get('/api/identity/hours').then(r => r.data) })
|
||||||
|
const mode = which => s.get(`business_day.auto_${which}`, 'off')
|
||||||
|
const usesHours = ['open', 'close'].some(w => ['schedule', 'alert'].includes(mode(w)))
|
||||||
|
const noHours = usesHours && hours && !hours.set
|
||||||
|
const side = which => {
|
||||||
|
const m = mode(which)
|
||||||
|
const key = `business_day.auto_${which}`
|
||||||
|
return (<>
|
||||||
|
<SettingRow label={a(which)} hint={which === 'close' ? a('closeHint') : a('openHint')} tip={a(`${which}Tip`)} htmlFor={ids[which]}
|
||||||
|
warning={m !== 'off' && m !== 'time' && noHours ? a('noHours') : undefined}>
|
||||||
|
<Select id={ids[which]} value={m} disabled={s.saving} data-testid={`setting-${key}`}
|
||||||
|
onChange={e => s.save(key, e.target.value)}
|
||||||
|
options={DAY_MODES.map(v => ({ value: v, label: a(`modes.${which}.${v}`) }))} />
|
||||||
|
</SettingRow>
|
||||||
|
{m === 'time' && (
|
||||||
|
<SettingRow label={a(`${which}Time`)} htmlFor={ids[`${which}Time`]}>
|
||||||
|
<TimeField id={ids[`${which}Time`]} value={s.get(`${key}_time`, which === 'open' ? '09:00' : '23:30')} disabled={s.saving}
|
||||||
|
testId={`setting-${key}_time`} onSave={v => s.save(`${key}_time`, v)} />
|
||||||
|
</SettingRow>
|
||||||
|
)}
|
||||||
|
{m === 'schedule' && (
|
||||||
|
<SettingRow label={a(`${which}Offset`)} htmlFor={ids[`${which}Off`]}>
|
||||||
|
<Select id={ids[`${which}Off`]} value={String(s.get(`${key}_offset_min`, '0'))} disabled={s.saving} data-testid={`setting-${key}_offset_min`}
|
||||||
|
onChange={e => s.save(`${key}_offset_min`, e.target.value)}
|
||||||
|
options={OFFSETS.map(n => ({ value: n, label: n === '0' ? a('offsetNone') : a(which === 'open' ? 'before' : 'after', { count: Number(n) }) }))} />
|
||||||
|
</SettingRow>
|
||||||
|
)}
|
||||||
|
</>)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<SettingsCard title={a('title')} description={a('intro')} testId="settings-auto-day">
|
||||||
|
{side('open')}
|
||||||
|
{side('close')}
|
||||||
|
{usesHours && <Toggle s={s} k="business_day.auto_ignore_break" fallback="true" label={a('ignoreBreak')} hint={a('ignoreBreakHint')} tip={a('ignoreBreakTip')} />}
|
||||||
|
</SettingsCard>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** HH:MM, saved when a whole time is typed. */
|
||||||
|
function TimeField({ id, value, disabled, testId, onSave }) {
|
||||||
|
const [v, setV] = useState(value)
|
||||||
|
return (
|
||||||
|
<Input id={id} type="time" value={v} disabled={disabled} data-testid={testId} className="w-32"
|
||||||
|
onChange={e => { setV(e.target.value); if (/^\d\d:\d\d$/.test(e.target.value) && e.target.value !== value) onSave(e.target.value) }} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/** Splitting a bill by amount (6F.6), each level with the ones before. Who may:
|
/** Splitting a bill by amount (6F.6), each level with the ones before. Who may:
|
||||||
* ordering.payments.split_amount ("What each role may do", a person's permissions). */
|
* ordering.payments.split_amount ("What each role may do", a person's permissions). */
|
||||||
function SplitSettings({ s }) {
|
function SplitSettings({ s }) {
|
||||||
|
|||||||
@@ -48,7 +48,14 @@ export default function DaysTab() {
|
|||||||
const columns = [
|
const columns = [
|
||||||
{ key: 'opened_at', label: t('reports.store.day'), render: d => <span className="font-semibold text-ink capitalize">{dateOf(d)}</span> },
|
{ key: 'opened_at', label: t('reports.store.day'), render: d => <span className="font-semibold text-ink capitalize">{dateOf(d)}</span> },
|
||||||
{ key: 'times', label: t('reports.store.hours'), sort: false,
|
{ key: 'times', label: t('reports.store.hours'), sort: false,
|
||||||
render: d => `${fmt.formatTime(d.opened_at)} – ${d.closed_at ? fmt.formatTime(d.closed_at) : '…'} (${since(d.opened_at, d.closed_at ? Date.parse(d.closed_at) : undefined)})` },
|
render: d => (<>
|
||||||
|
{`${fmt.formatTime(d.opened_at)} – ${d.closed_at ? fmt.formatTime(d.closed_at) : '…'} (${since(d.opened_at, d.closed_at ? Date.parse(d.closed_at) : undefined)})`}
|
||||||
|
{(d.opened_auto || d.closed_auto) && (
|
||||||
|
<span className="block text-caption text-ink-3" data-testid="day-auto">
|
||||||
|
{t(d.opened_auto && d.closed_auto ? 'reports.store.autoBoth' : d.opened_auto ? 'reports.store.autoOpened' : 'reports.store.autoClosed')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>) },
|
||||||
{ key: 'order_count', label: t('reports.orders'), align: 'right' },
|
{ key: 'order_count', label: t('reports.orders'), align: 'right' },
|
||||||
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: d => <span className="font-semibold">{fmt.formatMoney(d.revenue)}</span> },
|
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: d => <span className="font-semibold">{fmt.formatMoney(d.revenue)}</span> },
|
||||||
{ key: 'fees', label: t('reports.fees'), align: 'right', render: d => (d.fees ? fmt.formatMoney(d.fees) : '') },
|
{ key: 'fees', label: t('reports.fees'), align: 'right', render: d => (d.fees ? fmt.formatMoney(d.fees) : '') },
|
||||||
|
|||||||
@@ -368,7 +368,12 @@
|
|||||||
"empty": "Τίποτα καινούργιο. Εδώ εμφανίζονται ειδοποιήσεις για την άδεια, την εκτύπωση και την υποστήριξη.",
|
"empty": "Τίποτα καινούργιο. Εδώ εμφανίζονται ειδοποιήσεις για την άδεια, την εκτύπωση και την υποστήριξη.",
|
||||||
"markAll": "Όλες διαβασμένες",
|
"markAll": "Όλες διαβασμένες",
|
||||||
"times_one": "{{count}} φορά",
|
"times_one": "{{count}} φορά",
|
||||||
"times_other": "{{count}} φορές"
|
"times_other": "{{count}} φορές",
|
||||||
|
"dayOpened": "Η ημέρα άνοιξε",
|
||||||
|
"actions": {
|
||||||
|
"open_day": "Άνοιγμα τώρα",
|
||||||
|
"overview": "Στην επισκόπηση"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"saved": "Αποθηκεύτηκε",
|
"saved": "Αποθηκεύτηκε",
|
||||||
@@ -797,6 +802,43 @@
|
|||||||
},
|
},
|
||||||
"max": "Μέγιστα ίσα μέρη",
|
"max": "Μέγιστα ίσα μέρη",
|
||||||
"maxHint": "Τα μέρη ξεκινούν από τους πελάτες του τραπεζιού, όταν υπάρχουν."
|
"maxHint": "Τα μέρη ξεκινούν από τους πελάτες του τραπεζιού, όταν υπάρχουν."
|
||||||
|
},
|
||||||
|
"autoDay": {
|
||||||
|
"title": "Άνοιγμα και κλείσιμο της ημέρας",
|
||||||
|
"intro": "Η εργάσιμη ημέρα μπορεί να ανοίγει και να κλείνει μόνη της, στο ωράριο (σελίδα Πρόγραμμα) ή σε δική της ώρα. Δουλεύει και χωρίς ίντερνετ.",
|
||||||
|
"open": "Η ημέρα ανοίγει",
|
||||||
|
"openHint": "Μια ημέρα που έκλεισε υπεύθυνος με το χέρι δεν ξανανοίγει πριν το επόμενο άνοιγμα.",
|
||||||
|
"openTip": "Στο ωράριο: η ημέρα ανοίγει όταν αρχίζει το ωράριο. Σε ώρα: κάθε μέρα εκείνη την ώρα, όποιο κι αν είναι το ωράριο. Μόνο ειδοποίηση: οι υπεύθυνοι παίρνουν μήνυμα που μένει μέχρι να ανοίξει η ημέρα, με κουμπί «Άνοιγμα τώρα».",
|
||||||
|
"close": "Η ημέρα κλείνει",
|
||||||
|
"closeHint": "Κλείνει μόνο όταν έχουν κλείσει όλα τα τραπέζια· αλλιώς ειδοποιείστε και ξαναδοκιμάζει κάθε 15 λεπτά.",
|
||||||
|
"closeTip": "Οι ανοιχτές βάρδιες τελειώνουν όπως σε χειροκίνητο κλείσιμο. Αν ο server ήταν κλειστός την ώρα του κλεισίματος, η ημέρα δεν κλείνει αργότερα μόνη της: ειδοποιείστε.",
|
||||||
|
"modes": {
|
||||||
|
"open": {
|
||||||
|
"off": "Με το χέρι",
|
||||||
|
"schedule": "Μόνη της στο ωράριο",
|
||||||
|
"time": "Μόνη της σε ώρα",
|
||||||
|
"alert": "Μόνο ειδοποίηση στο ωράριο"
|
||||||
|
},
|
||||||
|
"close": {
|
||||||
|
"off": "Με το χέρι",
|
||||||
|
"schedule": "Μόνη της στο τέλος του ωραρίου",
|
||||||
|
"time": "Μόνη της σε ώρα",
|
||||||
|
"alert": "Μόνο ειδοποίηση στο τέλος του ωραρίου"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"openTime": "Ανοίγει στις",
|
||||||
|
"closeTime": "Κλείνει στις",
|
||||||
|
"openOffset": "Άνοιγμα νωρίτερα",
|
||||||
|
"closeOffset": "Κλείσιμο αργότερα",
|
||||||
|
"offsetNone": "Ακριβώς στο ωράριο",
|
||||||
|
"before_one": "{{count}} λεπτό πριν",
|
||||||
|
"before_other": "{{count}} λεπτά πριν",
|
||||||
|
"after_one": "{{count}} λεπτό μετά",
|
||||||
|
"after_other": "{{count}} λεπτά μετά",
|
||||||
|
"ignoreBreak": "Μία ημέρα και με διάλειμμα",
|
||||||
|
"ignoreBreakHint": "Κλειστό: το διάλειμμα ανάμεσα σε δύο διαστήματα κλείνει την ημέρα και το επόμενο ανοίγει νέα.",
|
||||||
|
"ignoreBreakTip": "Με ωράριο 12:00–16:00 και 19:00–23:00: ανοιχτό = μία ημέρα 12:00–23:00· κλειστό = δύο ημέρες.",
|
||||||
|
"noHours": "Δεν υπάρχει ακόμα ωράριο: ορίστε το στη σελίδα Πρόγραμμα, αλλιώς δεν γίνεται τίποτα."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"logs": {
|
"logs": {
|
||||||
@@ -4082,7 +4124,10 @@
|
|||||||
"anyTable": "Κάθε τραπέζι",
|
"anyTable": "Κάθε τραπέζι",
|
||||||
"cancelledLines": "Ακυρωμένες γραμμές",
|
"cancelledLines": "Ακυρωμένες γραμμές",
|
||||||
"ordersCount_one": "{{count}} παραγγελία · {{total}}",
|
"ordersCount_one": "{{count}} παραγγελία · {{total}}",
|
||||||
"ordersCount_other": "{{count}} παραγγελίες · {{total}}"
|
"ordersCount_other": "{{count}} παραγγελίες · {{total}}",
|
||||||
|
"autoBoth": "Άνοιξε και έκλεισε μόνη της",
|
||||||
|
"autoOpened": "Άνοιξε μόνη της",
|
||||||
|
"autoClosed": "Έκλεισε μόνη της"
|
||||||
},
|
},
|
||||||
"traffic": {
|
"traffic": {
|
||||||
"orders": "Παραγγελίες",
|
"orders": "Παραγγελίες",
|
||||||
|
|||||||
@@ -368,7 +368,12 @@
|
|||||||
"empty": "Nothing new. Licence, printing and support alerts show up here.",
|
"empty": "Nothing new. Licence, printing and support alerts show up here.",
|
||||||
"markAll": "Mark all as read",
|
"markAll": "Mark all as read",
|
||||||
"times_one": "{{count}} time",
|
"times_one": "{{count}} time",
|
||||||
"times_other": "{{count}} times"
|
"times_other": "{{count}} times",
|
||||||
|
"dayOpened": "The day is open",
|
||||||
|
"actions": {
|
||||||
|
"open_day": "Open now",
|
||||||
|
"overview": "Go to the overview"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"saved": "Saved",
|
"saved": "Saved",
|
||||||
@@ -797,6 +802,43 @@
|
|||||||
},
|
},
|
||||||
"max": "The most equal parts",
|
"max": "The most equal parts",
|
||||||
"maxHint": "The parts start at the table's customers when it has some."
|
"maxHint": "The parts start at the table's customers when it has some."
|
||||||
|
},
|
||||||
|
"autoDay": {
|
||||||
|
"title": "Opening and closing the day",
|
||||||
|
"intro": "The business day can open and close by itself, at the opening hours (Schedule page) or at a time of its own. It works without the internet.",
|
||||||
|
"open": "The day opens",
|
||||||
|
"openHint": "A day a manager closed by hand isn't reopened before the next opening.",
|
||||||
|
"openTip": "At the opening hours: the day opens when the hours start. At a time: every day at that time, whatever the hours. Only alert: managers get a message that stays until the day is opened, with an \"Open now\" button.",
|
||||||
|
"close": "The day closes",
|
||||||
|
"closeHint": "Closes only when every table is closed; otherwise you're alerted and it tries again every 15 minutes.",
|
||||||
|
"closeTip": "Open shifts end as with a manual close. If the server was off at closing time, the day isn't closed later by itself: you're alerted instead.",
|
||||||
|
"modes": {
|
||||||
|
"open": {
|
||||||
|
"off": "By hand",
|
||||||
|
"schedule": "By itself at the opening hours",
|
||||||
|
"time": "By itself at a time",
|
||||||
|
"alert": "Only alert at the opening hours"
|
||||||
|
},
|
||||||
|
"close": {
|
||||||
|
"off": "By hand",
|
||||||
|
"schedule": "By itself at the end of the opening hours",
|
||||||
|
"time": "By itself at a time",
|
||||||
|
"alert": "Only alert at the end of the opening hours"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"openTime": "Opens at",
|
||||||
|
"closeTime": "Closes at",
|
||||||
|
"openOffset": "Open earlier",
|
||||||
|
"closeOffset": "Close later",
|
||||||
|
"offsetNone": "Exactly at the hours",
|
||||||
|
"before_one": "{{count}} minute before",
|
||||||
|
"before_other": "{{count}} minutes before",
|
||||||
|
"after_one": "{{count}} minute after",
|
||||||
|
"after_other": "{{count}} minutes after",
|
||||||
|
"ignoreBreak": "One day across the break",
|
||||||
|
"ignoreBreakHint": "Off: the break between two opening spans closes the day and the next span opens a new one.",
|
||||||
|
"ignoreBreakTip": "With hours 12:00–16:00 and 19:00–23:00: on = one day from 12:00 to 23:00; off = two days.",
|
||||||
|
"noHours": "No opening hours yet: set them on the Schedule page, or nothing happens."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"logs": {
|
"logs": {
|
||||||
@@ -4082,7 +4124,10 @@
|
|||||||
"anyTable": "Any table",
|
"anyTable": "Any table",
|
||||||
"cancelledLines": "Cancelled lines",
|
"cancelledLines": "Cancelled lines",
|
||||||
"ordersCount_one": "{{count}} order · {{total}}",
|
"ordersCount_one": "{{count}} order · {{total}}",
|
||||||
"ordersCount_other": "{{count}} orders · {{total}}"
|
"ordersCount_other": "{{count}} orders · {{total}}",
|
||||||
|
"autoBoth": "Opened and closed by itself",
|
||||||
|
"autoOpened": "Opened by itself",
|
||||||
|
"autoClosed": "Closed by itself"
|
||||||
},
|
},
|
||||||
"traffic": {
|
"traffic": {
|
||||||
"orders": "Orders",
|
"orders": "Orders",
|
||||||
|
|||||||
@@ -777,6 +777,22 @@ try {
|
|||||||
r.check(`${st6} Operation: splitting by amount into up to 6 equal parts`, await settingValue2('payments.split_amount') === 'multiple_equal' && sMax === '6')
|
r.check(`${st6} Operation: splitting by amount into up to 6 equal parts`, await settingValue2('payments.split_amount') === 'multiple_equal' && sMax === '6')
|
||||||
await page.getByTestId('setting-payments.split_amount').selectOption('off')
|
await page.getByTestId('setting-payments.split_amount').selectOption('off')
|
||||||
r.check(`${st6} …"the most parts" hides when equal parts are off`, await page.getByTestId('setting-payments.split_max_parts').waitFor({ state: 'detached', timeout: 5000 }).then(() => true).catch(() => false))
|
r.check(`${st6} …"the most parts" hides when equal parts are off`, await page.getByTestId('setting-payments.split_max_parts').waitFor({ state: 'detached', timeout: 5000 }).then(() => true).catch(() => false))
|
||||||
|
// 6F.8: the day opens / closes by itself; the close says it waits for every table (Q-10)
|
||||||
|
await page.getByTestId('setting-business_day.auto_open').selectOption('schedule')
|
||||||
|
await page.getByTestId('setting-business_day.auto_open_offset_min').selectOption('30', { timeout: 5000 }).catch(() => {})
|
||||||
|
await page.getByTestId('setting-business_day.auto_close').selectOption('time')
|
||||||
|
const closeAt = page.getByTestId('setting-business_day.auto_close_time')
|
||||||
|
await closeAt.fill('23:45', { timeout: 5000 }).catch(() => {})
|
||||||
|
let dayOff = ''
|
||||||
|
for (let i = 0; i < 30 && dayOff !== '30'; i++) { await sleep(150); dayOff = await settingValue2('business_day.auto_open_offset_min') }
|
||||||
|
const autoCard = await page.getByTestId('settings-auto-day').innerText()
|
||||||
|
r.check(`${st6} 6F.8: the day opens at the hours (30 min before) and closes at 23:45, saved`, await settingValue2('business_day.auto_open') === 'schedule'
|
||||||
|
&& dayOff === '30' && await settingValue2('business_day.auto_close') === 'time' && await settingValue2('business_day.auto_close_time') === '23:45')
|
||||||
|
r.check(`${st6} 6F.8: beside the close: "only when every table is closed"`, autoCard.includes('Closes only when every table is closed'), autoCard.replace(/\s+/g, ' ').slice(0, 300))
|
||||||
|
await page.getByTestId('settings-auto-day').screenshot({ path: path.join(OUT, 'manager-settings-auto-day.png') })
|
||||||
|
await page.getByTestId('setting-business_day.auto_open').selectOption('off')
|
||||||
|
await page.getByTestId('setting-business_day.auto_close').selectOption('off')
|
||||||
|
await sleep(500)
|
||||||
await page.getByTestId('flag-new').click()
|
await page.getByTestId('flag-new').click()
|
||||||
await page.getByTestId('flag-save').click()
|
await page.getByTestId('flag-save').click()
|
||||||
r.check(`${st6} a table flag needs a name`, (await page.getByTestId('flag-dialog').textContent()).includes('Enter a name'))
|
r.check(`${st6} a table flag needs a name`, (await page.getByTestId('flag-dialog').textContent()).includes('Enter a name'))
|
||||||
|
|||||||
Reference in New Issue
Block a user