feat(backend): UTC time model - venue zone, business date, aware-only datetimes
Platform v2 step 1.1 (APPS_PLATFORM D-11, §7, D-24). - core/timeutil.py: utcnow, venue_tz (venue.timezone, cached, invalidated on change - no restart), to_venue/venue_date/venue_strftime, parse_api_datetime (offset -> UTC; naive = venue-local; date = venue midnight), business_date_of /business_date_window (rollover hour, default 06:00), LocalClock + is_within, UTCDateTime column type (naive writes raise, reads are aware UTC), iso_z - every model column is UTCDateTime; Pydantic UTCDatetime emits "...Z" - business_days.business_date set at open; revision 0002 adds it (backfilled) and makes sync_events.created_at a UTCDateTime (AUTOINCREMENT restated) - tz.py deleted; system.timezone setting replaced by venue.timezone (validated) + business_day.rollover_hour; manager timezone picker writes venue.timezone - fixes: price-group schedules/time_range used the container's zone (happy hour bug); traffic report bucketed by UTC hour; reports' "date" meant the UTC calendar day, now the business date; reservations stored venue-local naive times (no-show check 2-3 h off) and listed by func.date; schedule week used UTC midnights; fiscal file names used container-local time - seed.py/demo_seed.py create store_manager with role permissions (regression from step 1.0: v1's startup ALTER list used to rename/grant role 'manager') - tzdata dependency; guard tests/guards/test_no_naive_time.py (AST scan); tests/test_timeutil.py covers the §7.3 DST cases and the API checks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import business_date_of, parse_api_datetime, utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -67,7 +68,9 @@ def open_business_day(
|
||||
},
|
||||
)
|
||||
|
||||
day = BusinessDay(opened_by_id=user.id, notes=body.notes)
|
||||
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)
|
||||
@@ -108,7 +111,7 @@ def close_business_day(
|
||||
},
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
|
||||
# Close all non-terminal orders for this business day (open, partially_paid, paid)
|
||||
all_unclosed = db.query(Order).filter(
|
||||
@@ -200,13 +203,11 @@ def patch_business_day(
|
||||
raise HTTPException(status_code=400, detail="Can only edit a closed business day")
|
||||
|
||||
try:
|
||||
new_closed = datetime.fromisoformat(body.closed_at.replace("Z", "+00:00"))
|
||||
if new_closed.tzinfo is None:
|
||||
new_closed = new_closed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
new_closed = parse_api_datetime(body.closed_at)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=422, detail="Invalid datetime format")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
if new_closed > now:
|
||||
raise HTTPException(status_code=400, detail="Close time cannot be in the future")
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Chat router — /api/chat
|
||||
"""
|
||||
from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
|
||||
@@ -28,8 +29,6 @@ router = APIRouter()
|
||||
# Internal helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _build_participant_out(p: ConversationParticipant) -> ParticipantOut:
|
||||
@@ -236,7 +235,7 @@ def create_conversation(
|
||||
db.add(conv)
|
||||
db.flush()
|
||||
|
||||
now = _utcnow()
|
||||
now = utcnow()
|
||||
for uid in participant_ids:
|
||||
db.add(ConversationParticipant(
|
||||
conversation_id=conv.id,
|
||||
@@ -302,7 +301,7 @@ def send_message(
|
||||
conversation_id=conv_id,
|
||||
sender_id=user.id,
|
||||
body=payload.body,
|
||||
sent_at=_utcnow(),
|
||||
sent_at=utcnow(),
|
||||
)
|
||||
db.add(msg)
|
||||
db.commit()
|
||||
@@ -344,7 +343,7 @@ def mark_read(
|
||||
)
|
||||
.first()
|
||||
)
|
||||
now = _utcnow()
|
||||
now = utcnow()
|
||||
participant.last_read_at = now
|
||||
db.commit()
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import venue_date, utcnow
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
@@ -87,10 +88,10 @@ def export_catalog(db: Session = Depends(get_db), user: User = Depends(require_m
|
||||
payload = {
|
||||
"xenia_export_version": EXPORT_VERSION,
|
||||
"bundle": "catalog",
|
||||
"exported_at": datetime.now(timezone.utc).isoformat(),
|
||||
"exported_at": utcnow().isoformat(),
|
||||
"data": data,
|
||||
}
|
||||
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
today = venue_date().isoformat()
|
||||
return JSONResponse(
|
||||
content=payload,
|
||||
headers={"Content-Disposition": f'attachment; filename="xenia-catalog-{today}.json"'},
|
||||
@@ -125,10 +126,10 @@ def export_tables(db: Session = Depends(get_db), user: User = Depends(require_ma
|
||||
payload = {
|
||||
"xenia_export_version": EXPORT_VERSION,
|
||||
"bundle": "tables",
|
||||
"exported_at": datetime.now(timezone.utc).isoformat(),
|
||||
"exported_at": utcnow().isoformat(),
|
||||
"data": {"table_groups": table_groups, "ungrouped_tables": ungrouped_tables},
|
||||
}
|
||||
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
today = venue_date().isoformat()
|
||||
return JSONResponse(
|
||||
content=payload,
|
||||
headers={"Content-Disposition": f'attachment; filename="xenia-tables-{today}.json"'},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
import jwt
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from fastapi import Depends, HTTPException, status
|
||||
@@ -61,7 +62,7 @@ def make_token(user: User) -> str:
|
||||
"sub": str(user.id),
|
||||
"username": user.username,
|
||||
"role": user.role,
|
||||
"exp": datetime.now(timezone.utc) + timedelta(hours=TOKEN_EXPIRY_HOURS),
|
||||
"exp": utcnow() + timedelta(hours=TOKEN_EXPIRY_HOURS),
|
||||
}
|
||||
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -17,8 +18,6 @@ contacts_router = APIRouter()
|
||||
expenses_router = APIRouter()
|
||||
|
||||
|
||||
def _utcnow():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _expense_status(total: float, paid: float) -> str:
|
||||
|
||||
@@ -20,6 +20,7 @@ PUT /api/kds/orders/{order_id}/order_type
|
||||
GET /api/kds/items (unchanged)
|
||||
PUT /api/kds/orders/{order_id}/items/{item_id}/status (unchanged)
|
||||
"""
|
||||
from core.timeutil import utcnow
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from datetime import datetime, timezone
|
||||
@@ -200,7 +201,7 @@ def _sync_order_kds_status(order: Order):
|
||||
new_status = "pending"
|
||||
if new_status != order.kds_status:
|
||||
order.kds_status = new_status
|
||||
order.kds_status_changed_at = datetime.now(timezone.utc)
|
||||
order.kds_status_changed_at = utcnow()
|
||||
|
||||
|
||||
# ─────────────────────────── endpoints ─────────────────────────────────────
|
||||
@@ -270,7 +271,7 @@ def update_order_kds_status(
|
||||
|
||||
if body.status != order.kds_status:
|
||||
order.kds_status = body.status
|
||||
order.kds_status_changed_at = datetime.now(timezone.utc)
|
||||
order.kds_status_changed_at = utcnow()
|
||||
|
||||
# Cascade order-level status to non-cancelled, non-served items only
|
||||
if body.status in ("pending", "preparing", "done"):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -12,8 +13,6 @@ from routers.deps import require_manager
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _utcnow():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _note_out(n: SiteNote) -> dict:
|
||||
@@ -80,7 +79,7 @@ def update_note(note_id: int, body: NoteUpdate, db: Session = Depends(get_db), u
|
||||
note.body = body.body
|
||||
if body.is_pinned is not None:
|
||||
note.is_pinned = body.is_pinned
|
||||
note.updated_at = _utcnow()
|
||||
note.updated_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(note)
|
||||
return _note_out(note)
|
||||
@@ -132,7 +131,7 @@ def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), u
|
||||
if body.is_done is not None:
|
||||
todo.is_done = body.is_done
|
||||
if body.is_done and not todo.done_at:
|
||||
todo.done_at = _utcnow()
|
||||
todo.done_at = utcnow()
|
||||
todo.done_by_id = user.id
|
||||
elif not body.is_done:
|
||||
todo.done_at = None
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from core.timeutil import parse_api_datetime, venue_strftime, utcnow
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
|
||||
from tz import local_strftime
|
||||
|
||||
|
||||
def _iso(dt) -> str | None:
|
||||
@@ -487,7 +487,7 @@ def add_items(
|
||||
pending_price_events = [] # (order_item_id, [PriceEvent]) — flushed after commit
|
||||
|
||||
# Build pricing context once for the whole batch
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
active_pg_ids = build_active_price_group_ids(db, now)
|
||||
# Determine order channel
|
||||
_channel_map = {"online": "online", "takeaway": "takeaway", "delivery": "takeaway"}
|
||||
@@ -760,7 +760,7 @@ def cancel_item(
|
||||
if item.status == "paid":
|
||||
raise HTTPException(status_code=400, detail="Το αντικείμενο έχει ήδη πληρωθεί")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
item.status = "cancelled"
|
||||
item.cancelled_by = user.id
|
||||
item.cancelled_at = now
|
||||
@@ -817,7 +817,7 @@ def pay_items(order_id: int, body: PayItemsRequest, db: Session = Depends(get_db
|
||||
detail=f"Fiscal printing is ON but the following products have no VAT group assigned: {names}"
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
active_shift = db.query(WaiterShift).filter(
|
||||
WaiterShift.waiter_id == user.id,
|
||||
WaiterShift.ended_at == None,
|
||||
@@ -940,7 +940,7 @@ def close_order(order_id: int, db: Session = Depends(get_db), user: User = Depen
|
||||
if order.status not in ("paid", "open", "partially_paid"):
|
||||
raise HTTPException(status_code=400, detail="Cannot close order in current status")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
|
||||
# Mark all still-active items as 'closed' — unpaid, closed by manager
|
||||
active_items = db.query(OrderItem).filter(
|
||||
@@ -1009,9 +1009,9 @@ def pay_items_offline(
|
||||
|
||||
# Use the client-recorded offline timestamp as paid_at so audit reflects real payment time
|
||||
try:
|
||||
paid_at = datetime.fromisoformat(body.offline_at.replace("Z", "+00:00")) if body.offline_at else datetime.now(timezone.utc)
|
||||
except (ValueError, AttributeError):
|
||||
paid_at = datetime.now(timezone.utc)
|
||||
paid_at = parse_api_datetime(body.offline_at) or utcnow()
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
paid_at = utcnow()
|
||||
|
||||
active_shift = db.query(WaiterShift).filter(
|
||||
WaiterShift.waiter_id == user.id,
|
||||
@@ -1085,7 +1085,7 @@ def cancel_order(
|
||||
if not is_manager and not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
|
||||
active_items = db.query(OrderItem).filter(
|
||||
OrderItem.order_id == order_id,
|
||||
@@ -1142,7 +1142,7 @@ def cancel_items_bulk(
|
||||
OrderItem.order_id == order_id,
|
||||
).all()
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
cancelled_ids = []
|
||||
skipped_paid = []
|
||||
for item in items:
|
||||
@@ -1273,8 +1273,8 @@ def print_order(
|
||||
"order_id": order.id,
|
||||
"table_name": table_name,
|
||||
"waiter_name": waiter_name,
|
||||
"opened_at": local_strftime(order.opened_at, "%d/%m/%Y %H:%M"),
|
||||
"closed_at": local_strftime(order.closed_at, "%d/%m/%Y %H:%M") if order.closed_at else None,
|
||||
"opened_at": venue_strftime(order.opened_at, "%d/%m/%Y %H:%M"),
|
||||
"closed_at": venue_strftime(order.closed_at, "%d/%m/%Y %H:%M") if order.closed_at else None,
|
||||
"status": order.status,
|
||||
"items": items_data,
|
||||
"total": grand_total,
|
||||
@@ -1385,7 +1385,7 @@ def merge_order(
|
||||
|
||||
# Cancel source order
|
||||
source.status = "cancelled"
|
||||
source.closed_at = datetime.now(timezone.utc)
|
||||
source.closed_at = utcnow()
|
||||
source.closed_by = user.id
|
||||
|
||||
_audit(db, source.id, "ORDER_CANCELLED", waiter_id=user.id,
|
||||
@@ -1676,7 +1676,7 @@ def cancel_print_job(
|
||||
|
||||
from datetime import datetime, timezone
|
||||
pj.status = "cancelled"
|
||||
pj.cancelled_at = datetime.now(timezone.utc)
|
||||
pj.cancelled_at = utcnow()
|
||||
pj.cancel_reason = "staff_cancelled"
|
||||
|
||||
# Mark affected items as printed so the UI warning goes away
|
||||
@@ -1834,7 +1834,7 @@ def print_synopsis(
|
||||
"order_id": order.id,
|
||||
"table_name": table_name,
|
||||
"waiter_name": waiter_name,
|
||||
"opened_at": local_strftime(order.opened_at, "%d/%m/%Y %H:%M"),
|
||||
"opened_at": venue_strftime(order.opened_at, "%d/%m/%Y %H:%M"),
|
||||
"items": items_data,
|
||||
"total": total,
|
||||
"paid_total": paid_total,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
@@ -25,8 +26,6 @@ from models.user import User
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _utcnow():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -198,7 +197,7 @@ def update_modifier(
|
||||
m.action_type = body.action_type
|
||||
m.action_value = body.action_value
|
||||
m.round_to = body.round_to
|
||||
m.updated_at = _utcnow()
|
||||
m.updated_at = utcnow()
|
||||
m.updated_by = user.id
|
||||
# Replace conditions and targets
|
||||
for c in list(m.conditions):
|
||||
@@ -223,7 +222,7 @@ def toggle_modifier(
|
||||
if not m:
|
||||
raise HTTPException(status_code=404, detail="Modifier not found")
|
||||
m.is_active = 0 if m.is_active else 1
|
||||
m.updated_at = _utcnow()
|
||||
m.updated_at = utcnow()
|
||||
m.updated_by = user.id
|
||||
db.commit()
|
||||
db.refresh(m)
|
||||
@@ -409,7 +408,7 @@ def set_global_discount_settings(
|
||||
"enabled", "max_total_value_workday",
|
||||
"max_total_value_shift", "max_items_per_shift",
|
||||
}
|
||||
now = _utcnow().isoformat()
|
||||
now = utcnow().isoformat()
|
||||
for k, v in body.items():
|
||||
if k not in allowed:
|
||||
continue
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
import secrets
|
||||
import bcrypt
|
||||
import logging
|
||||
@@ -42,7 +43,7 @@ def try_recovery_code(plain: str, user: "User", db: "Session") -> bool:
|
||||
matched = next((rc for rc in unused if _verify_code(plain, rc.code_hash)), None)
|
||||
if not matched:
|
||||
return False
|
||||
matched.used_at = datetime.now(timezone.utc)
|
||||
matched.used_at = utcnow()
|
||||
db.commit()
|
||||
_logger.warning("RECOVERY CODE USED for user_id=%d username=%s code_id=%d", user.id, user.username, matched.id)
|
||||
return True
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, HTTPException, BackgroundTasks
|
||||
from tz import local_strftime, to_local
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -53,12 +53,11 @@ def shift_summary(
|
||||
):
|
||||
"""Payments collected per waiter — based on paid_by on order items."""
|
||||
if from_dt and to_dt:
|
||||
start = datetime.fromisoformat(from_dt)
|
||||
end = datetime.fromisoformat(to_dt)
|
||||
start = parse_api_datetime(from_dt)
|
||||
end = parse_api_datetime(to_dt)
|
||||
else:
|
||||
target = report_date or date.today()
|
||||
start = datetime.combine(target, datetime.min.time())
|
||||
end = start + timedelta(days=1)
|
||||
# A date means a business date (D-11): its rollover-to-rollover window in UTC
|
||||
start, end = business_date_window(report_date or business_date_of())
|
||||
|
||||
q = db.query(OrderItem).filter(
|
||||
OrderItem.status == "paid",
|
||||
@@ -95,8 +94,8 @@ def shift_summary(
|
||||
order = db.query(Order).filter(Order.id == oid).first()
|
||||
summary[wid]["order_data"][oid] = {
|
||||
"id": oid,
|
||||
"time_open": local_strftime(order.opened_at, "%H:%M") if order else "",
|
||||
"time_close": local_strftime(order.closed_at, "%H:%M") if order and order.closed_at else "",
|
||||
"time_open": venue_strftime(order.opened_at, "%H:%M") if order else "",
|
||||
"time_close": venue_strftime(order.closed_at, "%H:%M") if order and order.closed_at else "",
|
||||
"table": tables_db.get(order.table_id, f"#{oid}") if order else f"#{oid}",
|
||||
"total": 0.0,
|
||||
"items": [],
|
||||
@@ -132,12 +131,10 @@ def shift_orders_summary(
|
||||
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
||||
else:
|
||||
if from_dt and to_dt:
|
||||
start = datetime.fromisoformat(from_dt)
|
||||
end = datetime.fromisoformat(to_dt)
|
||||
start = parse_api_datetime(from_dt)
|
||||
end = parse_api_datetime(to_dt)
|
||||
else:
|
||||
target = report_date or date.today()
|
||||
start = datetime.combine(target, datetime.min.time())
|
||||
end = start + timedelta(days=1)
|
||||
start, end = business_date_window(report_date or business_date_of())
|
||||
q = q.filter(OrderItem.added_at >= start, OrderItem.added_at < end)
|
||||
if waiter_id:
|
||||
q = q.filter(OrderItem.added_by == waiter_id)
|
||||
@@ -169,7 +166,7 @@ def shift_orders_summary(
|
||||
hours_by_waiter: dict[int, float] = {}
|
||||
for s in shifts_list:
|
||||
wid = s.waiter_id
|
||||
end_time = s.ended_at or datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
end_time = s.ended_at or utcnow()
|
||||
delta = (end_time - s.started_at).total_seconds() / 3600.0
|
||||
hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta
|
||||
|
||||
@@ -196,8 +193,8 @@ def shift_orders_summary(
|
||||
order = db.query(Order).filter(Order.id == oid).first()
|
||||
summary[wid]["order_data"][oid] = {
|
||||
"id": oid,
|
||||
"time_open": local_strftime(order.opened_at, "%H:%M") if order else "",
|
||||
"time_close": local_strftime(order.closed_at, "%H:%M") if order and order.closed_at else "",
|
||||
"time_open": venue_strftime(order.opened_at, "%H:%M") if order else "",
|
||||
"time_close": venue_strftime(order.closed_at, "%H:%M") if order and order.closed_at else "",
|
||||
"table": tables_db.get(order.table_id, f"#{oid}") if order else f"#{oid}",
|
||||
"total": 0.0,
|
||||
"items": [],
|
||||
@@ -258,9 +255,9 @@ def order_history(
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
elif from_date or to_date:
|
||||
if from_date:
|
||||
q = q.filter(Order.opened_at >= datetime.fromisoformat(from_date))
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_date))
|
||||
if to_date:
|
||||
q = q.filter(Order.opened_at <= datetime.fromisoformat(to_date))
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_date))
|
||||
if waiter_id:
|
||||
q = q.join(OrderWaiter).filter(OrderWaiter.waiter_id == waiter_id)
|
||||
if order_status:
|
||||
@@ -400,9 +397,9 @@ def printer_totals(
|
||||
"""Returns totals per printer based on print_log entries in the date range."""
|
||||
q = db.query(PrintLog).filter(PrintLog.success == True)
|
||||
if from_date:
|
||||
q = q.filter(PrintLog.printed_at >= datetime.fromisoformat(from_date))
|
||||
q = q.filter(PrintLog.printed_at >= parse_api_datetime(from_date))
|
||||
if to_date:
|
||||
q = q.filter(PrintLog.printed_at <= datetime.fromisoformat(to_date))
|
||||
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_date))
|
||||
logs = q.all()
|
||||
|
||||
printers_db = {p.id: p for p in db.query(Printer).all()}
|
||||
@@ -435,7 +432,7 @@ def printer_totals(
|
||||
order = db.query(Order).filter(Order.id == oid).first()
|
||||
order_map[pid][oid] = {
|
||||
"order_id": oid,
|
||||
"time": local_strftime(log.printed_at, "%H:%M"),
|
||||
"time": venue_strftime(log.printed_at, "%H:%M"),
|
||||
"table": tables_db.get(order.table_id, f"#{oid}") if order else f"#{oid}",
|
||||
"total": 0.0,
|
||||
"items": [],
|
||||
@@ -507,7 +504,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m
|
||||
if order:
|
||||
order_map[oid] = {
|
||||
"id": oid,
|
||||
"time": local_strftime(log.printed_at, "%H:%M"),
|
||||
"time": venue_strftime(log.printed_at, "%H:%M"),
|
||||
"table": tables.get(order.table_id, f"#{order.table_id}"),
|
||||
"total": 0.0,
|
||||
"items": [],
|
||||
@@ -567,8 +564,8 @@ def print_waiter(
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
|
||||
from_dt = datetime.fromisoformat(body.from_dt)
|
||||
to_dt = datetime.fromisoformat(body.to_dt)
|
||||
from_dt = parse_api_datetime(body.from_dt)
|
||||
to_dt = parse_api_datetime(body.to_dt)
|
||||
|
||||
# Gather orders for this waiter in time range
|
||||
waiter = db.query(User).filter(User.username == body.waiter_name).first()
|
||||
@@ -590,8 +587,8 @@ def print_waiter(
|
||||
total = sum(_item_val(i) for i in active_items)
|
||||
order_data.append({
|
||||
"id": o.id,
|
||||
"time_open": local_strftime(o.opened_at, "%H:%M"),
|
||||
"time_close": local_strftime(o.closed_at, "%H:%M") if o.closed_at else "",
|
||||
"time_open": venue_strftime(o.opened_at, "%H:%M"),
|
||||
"time_close": venue_strftime(o.closed_at, "%H:%M") if o.closed_at else "",
|
||||
"table": tables.get(o.table_id, f"#{o.table_id}"),
|
||||
"total": total,
|
||||
"items": [
|
||||
@@ -611,8 +608,8 @@ def print_waiter(
|
||||
"items": items_count,
|
||||
"total": grand_total,
|
||||
"order_data": order_data if body.mode == "extensive" else [],
|
||||
"from_dt": local_strftime(from_dt, "%d/%m/%Y %H:%M"),
|
||||
"to_dt": local_strftime(to_dt, "%d/%m/%Y %H:%M"),
|
||||
"from_dt": venue_strftime(from_dt, "%d/%m/%Y %H:%M"),
|
||||
"to_dt": venue_strftime(to_dt, "%d/%m/%Y %H:%M"),
|
||||
}
|
||||
|
||||
background_tasks.add_task(print_waiter_report, printer.ip_address, printer.port, report, body.mode, printer.codepage_n)
|
||||
@@ -639,21 +636,21 @@ def print_printer_totals(
|
||||
if body.business_day_id:
|
||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
from_dt = datetime.fromisoformat(body.from_dt)
|
||||
to_dt = datetime.fromisoformat(body.to_dt)
|
||||
from_dt = parse_api_datetime(body.from_dt)
|
||||
to_dt = parse_api_datetime(body.to_dt)
|
||||
q = q.filter(PrintLog.printed_at >= from_dt, PrintLog.printed_at <= to_dt)
|
||||
return q
|
||||
|
||||
# Determine period label for the receipt header
|
||||
if body.business_day_id:
|
||||
bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first()
|
||||
period_label = local_strftime(bd.opened_at, "%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
||||
period_label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
||||
period_is_workday = True
|
||||
else:
|
||||
from_dt = datetime.fromisoformat(body.from_dt) if body.from_dt else None
|
||||
to_dt = datetime.fromisoformat(body.to_dt) if body.to_dt else None
|
||||
from_dt = parse_api_datetime(body.from_dt) if body.from_dt else None
|
||||
to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None
|
||||
period_label = (
|
||||
f"{local_strftime(from_dt, '%d/%m/%Y')} - {local_strftime(to_dt, '%d/%m/%Y')}"
|
||||
f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}"
|
||||
if from_dt and to_dt else "—"
|
||||
)
|
||||
period_is_workday = False
|
||||
@@ -704,12 +701,12 @@ def _analytics_period(body: PrintAnalyticsBody, db) -> tuple[str, bool]:
|
||||
"""Return (period_label, period_is_workday)."""
|
||||
if body.business_day_id:
|
||||
bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first()
|
||||
label = local_strftime(bd.opened_at, "%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
||||
label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
||||
return label, True
|
||||
from_dt = datetime.fromisoformat(body.from_dt) if body.from_dt else None
|
||||
to_dt = datetime.fromisoformat(body.to_dt) if body.to_dt else None
|
||||
from_dt = parse_api_datetime(body.from_dt) if body.from_dt else None
|
||||
to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None
|
||||
label = (
|
||||
f"{local_strftime(from_dt, '%d/%m/%Y')} - {local_strftime(to_dt, '%d/%m/%Y')}"
|
||||
f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}"
|
||||
if from_dt and to_dt else "—"
|
||||
)
|
||||
return label, False
|
||||
@@ -736,8 +733,8 @@ def print_products(
|
||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
q = q.filter(
|
||||
OrderItem.added_at >= datetime.fromisoformat(body.from_dt),
|
||||
OrderItem.added_at <= datetime.fromisoformat(body.to_dt),
|
||||
OrderItem.added_at >= parse_api_datetime(body.from_dt),
|
||||
OrderItem.added_at <= parse_api_datetime(body.to_dt),
|
||||
)
|
||||
items = q.all()
|
||||
|
||||
@@ -796,8 +793,8 @@ def print_categories(
|
||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
q = q.filter(
|
||||
OrderItem.added_at >= datetime.fromisoformat(body.from_dt),
|
||||
OrderItem.added_at <= datetime.fromisoformat(body.to_dt),
|
||||
OrderItem.added_at >= parse_api_datetime(body.from_dt),
|
||||
OrderItem.added_at <= parse_api_datetime(body.to_dt),
|
||||
)
|
||||
items = q.all()
|
||||
|
||||
@@ -873,8 +870,8 @@ def print_tables(
|
||||
q = q.filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
q = q.filter(
|
||||
Order.opened_at >= datetime.fromisoformat(body.from_dt),
|
||||
Order.opened_at <= datetime.fromisoformat(body.to_dt),
|
||||
Order.opened_at >= parse_api_datetime(body.from_dt),
|
||||
Order.opened_at <= parse_api_datetime(body.to_dt),
|
||||
)
|
||||
orders = q.all()
|
||||
|
||||
@@ -935,9 +932,9 @@ def shifts_report(
|
||||
if business_day_id:
|
||||
q = q.filter(WaiterShift.business_day_id == business_day_id)
|
||||
if from_dt:
|
||||
q = q.filter(WaiterShift.started_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(WaiterShift.started_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(WaiterShift.started_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(WaiterShift.started_at <= parse_api_datetime(to_dt))
|
||||
if active_only:
|
||||
q = q.filter(WaiterShift.ended_at == None)
|
||||
|
||||
@@ -963,9 +960,9 @@ def product_performance(
|
||||
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(OrderItem.added_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(OrderItem.added_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(OrderItem.added_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
||||
|
||||
@@ -978,8 +975,8 @@ def product_performance(
|
||||
wq = wq.filter(WasteLog.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
wq = wq.filter(
|
||||
WasteLog.logged_at >= datetime.fromisoformat(from_dt),
|
||||
WasteLog.logged_at <= datetime.fromisoformat(to_dt),
|
||||
WasteLog.logged_at >= parse_api_datetime(from_dt),
|
||||
WasteLog.logged_at <= parse_api_datetime(to_dt),
|
||||
)
|
||||
waste_entries = wq.all()
|
||||
waste_by_product: dict = {}
|
||||
@@ -1068,9 +1065,9 @@ def table_performance(
|
||||
):
|
||||
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
orders = q.all()
|
||||
@@ -1113,6 +1110,30 @@ def table_performance(
|
||||
# Traffic analysis (hour-of-day / day-of-week)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def traffic_buckets(entries):
|
||||
"""(opened_at UTC, revenue) pairs -> hour-of-day and weekday buckets (D-11).
|
||||
|
||||
Hour = venue wall-clock hour (SQLite can't do zones, so this is done in Python).
|
||||
Weekday = weekday of the business date, so a 01:30 Saturday order counts on Friday.
|
||||
Both 03:xx hours of the autumn DST change land in bucket 3; nothing is dropped.
|
||||
"""
|
||||
by_hour = {h: {"hour": h, "orders": 0, "revenue": 0.0} for h in range(24)}
|
||||
day_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
||||
by_weekday = {d: {"day": d, "label": day_labels[d], "orders": 0, "revenue": 0.0} for d in range(7)}
|
||||
for opened_at, revenue in entries:
|
||||
h = to_venue(opened_at).hour
|
||||
d = business_date_of(opened_at).weekday()
|
||||
by_hour[h]["orders"] += 1
|
||||
by_hour[h]["revenue"] += revenue
|
||||
by_weekday[d]["orders"] += 1
|
||||
by_weekday[d]["revenue"] += revenue
|
||||
for h in by_hour:
|
||||
by_hour[h]["revenue"] = round(by_hour[h]["revenue"], 2)
|
||||
for d in by_weekday:
|
||||
by_weekday[d]["revenue"] = round(by_weekday[d]["revenue"], 2)
|
||||
return by_hour, by_weekday
|
||||
|
||||
|
||||
@router.get("/traffic")
|
||||
def traffic_analysis(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
@@ -1123,32 +1144,17 @@ def traffic_analysis(
|
||||
):
|
||||
q = db.query(Order)
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
orders = q.all()
|
||||
|
||||
by_hour = {h: {"hour": h, "orders": 0, "revenue": 0.0} for h in range(24)}
|
||||
day_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
||||
by_weekday = {d: {"day": d, "label": day_labels[d], "orders": 0, "revenue": 0.0} for d in range(7)}
|
||||
|
||||
for order in orders:
|
||||
revenue = sum(
|
||||
_item_val(i) for i in order.items if i.status in ("active", "paid")
|
||||
)
|
||||
h = order.opened_at.hour
|
||||
d = order.opened_at.weekday()
|
||||
by_hour[h]["orders"] += 1
|
||||
by_hour[h]["revenue"] += revenue
|
||||
by_weekday[d]["orders"] += 1
|
||||
by_weekday[d]["revenue"] += revenue
|
||||
|
||||
for h in by_hour:
|
||||
by_hour[h]["revenue"] = round(by_hour[h]["revenue"], 2)
|
||||
for d in by_weekday:
|
||||
by_weekday[d]["revenue"] = round(by_weekday[d]["revenue"], 2)
|
||||
by_hour, by_weekday = traffic_buckets(
|
||||
(order.opened_at, sum(_item_val(i) for i in order.items if i.status in ("active", "paid")))
|
||||
for order in orders
|
||||
)
|
||||
|
||||
return {
|
||||
"by_hour": list(by_hour.values()),
|
||||
@@ -1169,9 +1175,9 @@ def business_days_list(
|
||||
):
|
||||
q = db.query(BusinessDay)
|
||||
if from_dt:
|
||||
q = q.filter(BusinessDay.opened_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(BusinessDay.opened_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(BusinessDay.opened_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(BusinessDay.opened_at <= parse_api_datetime(to_dt))
|
||||
days = q.order_by(BusinessDay.opened_at.desc()).all()
|
||||
|
||||
waiters_db = {u.id: u for u in db.query(User).all()}
|
||||
@@ -1318,14 +1324,17 @@ def revenue_trends(
|
||||
):
|
||||
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
orders = q.all()
|
||||
|
||||
# Bucket by business date (D-11): the stored date of the order's business day,
|
||||
# or computed from opened_at for orders outside a business day.
|
||||
bd_dates = {bid: bdate for bid, bdate in db.query(BusinessDay.id, BusinessDay.business_date).all()}
|
||||
buckets: dict = {}
|
||||
for order in orders:
|
||||
dt = to_local(order.opened_at)
|
||||
dt = bd_dates.get(order.business_day_id) or business_date_of(order.opened_at)
|
||||
if granularity == "monthly":
|
||||
key = dt.strftime("%Y-%m")
|
||||
elif granularity == "weekly":
|
||||
@@ -1376,9 +1385,9 @@ def category_performance(
|
||||
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(OrderItem.added_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(OrderItem.added_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(OrderItem.added_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
||||
items = q.all()
|
||||
@@ -1454,14 +1463,14 @@ def cancellations_log(
|
||||
|
||||
# Date filter on cancelled_at if available, otherwise fall back to added_at
|
||||
if from_dt:
|
||||
dt_from = datetime.fromisoformat(from_dt)
|
||||
dt_from = parse_api_datetime(from_dt)
|
||||
from sqlalchemy import or_
|
||||
q = q.filter(or_(
|
||||
OrderItem.cancelled_at >= dt_from,
|
||||
(OrderItem.cancelled_at == None) & (OrderItem.added_at >= dt_from),
|
||||
))
|
||||
if to_dt:
|
||||
dt_to = datetime.fromisoformat(to_dt)
|
||||
dt_to = parse_api_datetime(to_dt)
|
||||
from sqlalchemy import or_
|
||||
q = q.filter(or_(
|
||||
OrderItem.cancelled_at <= dt_to,
|
||||
@@ -1530,9 +1539,9 @@ def printer_history(
|
||||
):
|
||||
q = db.query(PrintLog)
|
||||
if from_dt:
|
||||
q = q.filter(PrintLog.printed_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(PrintLog.printed_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(PrintLog.printed_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_dt))
|
||||
if printer_id:
|
||||
q = q.filter(PrintLog.printer_id == printer_id)
|
||||
if business_day_id:
|
||||
@@ -1828,9 +1837,9 @@ def prep_zones_report(
|
||||
# Query order items in the requested range
|
||||
q = db.query(OrderItem).join(Order)
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= datetime.fromisoformat(from_dt))
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= datetime.fromisoformat(to_dt))
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
q = q.filter(OrderItem.status.in_(["active", "paid"]))
|
||||
@@ -1940,10 +1949,10 @@ def print_prep_zone(
|
||||
if body.business_day_id:
|
||||
from models.business_day import BusinessDay
|
||||
bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first()
|
||||
period_label = bd.opened_at.strftime("%d/%m/%Y") if bd and bd.opened_at else f"#{body.business_day_id}"
|
||||
period_label = bd.business_date.strftime("%d/%m/%Y") if bd else f"#{body.business_day_id}"
|
||||
elif body.from_dt and body.to_dt:
|
||||
d1 = datetime.fromisoformat(body.from_dt).strftime("%d/%m/%Y")
|
||||
d2 = datetime.fromisoformat(body.to_dt).strftime("%d/%m/%Y")
|
||||
d1 = venue_strftime(parse_api_datetime(body.from_dt), "%d/%m/%Y")
|
||||
d2 = venue_strftime(parse_api_datetime(body.to_dt), "%d/%m/%Y")
|
||||
period_label = f"{d1} - {d2}"
|
||||
else:
|
||||
period_label = "Όλες"
|
||||
@@ -1953,9 +1962,9 @@ def print_prep_zone(
|
||||
|
||||
q = db.query(OrderItem).join(Order)
|
||||
if body.from_dt:
|
||||
q = q.filter(Order.opened_at >= datetime.fromisoformat(body.from_dt))
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(body.from_dt))
|
||||
if body.to_dt:
|
||||
q = q.filter(Order.opened_at <= datetime.fromisoformat(body.to_dt))
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
|
||||
if body.business_day_id:
|
||||
q = q.filter(Order.business_day_id == body.business_day_id)
|
||||
q = q.filter(OrderItem.status.in_(["active", "paid"]))
|
||||
@@ -2007,8 +2016,8 @@ def discounts_report(
|
||||
q = q.join(Order, Order.id == OrderDiscount.order_id).filter(Order.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
q = q.filter(
|
||||
OrderDiscount.applied_at >= datetime.fromisoformat(from_dt),
|
||||
OrderDiscount.applied_at <= datetime.fromisoformat(to_dt),
|
||||
OrderDiscount.applied_at >= parse_api_datetime(from_dt),
|
||||
OrderDiscount.applied_at <= parse_api_datetime(to_dt),
|
||||
)
|
||||
if applied_by:
|
||||
q = q.filter(OrderDiscount.applied_by == applied_by)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow, venue_day_window
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
@@ -71,8 +72,9 @@ def list_reservations(
|
||||
day = datetime.fromisoformat(date).date()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid date format")
|
||||
from sqlalchemy import func
|
||||
q = q.filter(func.date(Reservation.reserved_for) == day)
|
||||
# The venue's calendar day, as a UTC window (D-11; 23 h / 25 h on DST days)
|
||||
start, end = venue_day_window(day)
|
||||
q = q.filter(Reservation.reserved_for >= start, Reservation.reserved_for < end)
|
||||
|
||||
if tab == "upcoming":
|
||||
# pending + no_show (actionable), ordered soonest first
|
||||
@@ -80,7 +82,7 @@ def list_reservations(
|
||||
q = q.order_by(Reservation.reserved_for.asc())
|
||||
elif tab == "history":
|
||||
# arrived, cancelled, plus no_show/pending that are clearly in the past
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
q = q.filter(
|
||||
(Reservation.status.in_(["arrived", "cancelled"])) |
|
||||
(
|
||||
@@ -131,7 +133,7 @@ def update_reservation(
|
||||
for field, value in updates.items():
|
||||
setattr(r, field, value)
|
||||
|
||||
r.updated_at = datetime.now(timezone.utc)
|
||||
r.updated_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(r)
|
||||
return _enrich(r)
|
||||
@@ -152,7 +154,7 @@ def update_reservation_status(
|
||||
raise HTTPException(status_code=404, detail="Reservation not found")
|
||||
|
||||
r.status = body.status
|
||||
r.updated_at = datetime.now(timezone.utc)
|
||||
r.updated_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(r)
|
||||
return _enrich(r)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import to_venue, venue_day_window, venue_date
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -125,7 +126,7 @@ def week_schedule(
|
||||
):
|
||||
"""Current (or specified) week: scheduled shifts + actual WaiterShifts for comparison."""
|
||||
if week_start is None:
|
||||
today = date.today()
|
||||
today = venue_date()
|
||||
week_start = today - timedelta(days=today.weekday()) # Monday
|
||||
week_end = week_start + timedelta(days=6) # Sunday
|
||||
|
||||
@@ -135,11 +136,11 @@ def week_schedule(
|
||||
).order_by(ScheduledShift.scheduled_date, ScheduledShift.start_time).all()
|
||||
|
||||
# Actual shifts that started within the week
|
||||
week_start_dt = datetime.combine(week_start, datetime.min.time()).replace(tzinfo=timezone.utc)
|
||||
week_end_dt = datetime.combine(week_end, datetime.max.time()).replace(tzinfo=timezone.utc)
|
||||
week_start_dt = venue_day_window(week_start)[0] # venue days, as UTC (D-11)
|
||||
week_end_dt = venue_day_window(week_end)[1]
|
||||
actuals = db.query(WaiterShift).filter(
|
||||
WaiterShift.started_at >= week_start_dt,
|
||||
WaiterShift.started_at <= week_end_dt,
|
||||
WaiterShift.started_at < week_end_dt,
|
||||
).all()
|
||||
|
||||
waiters = {u.id: u for u in db.query(User).filter(User.perm_access_waiter_app == True, User.is_active == True).all()}
|
||||
@@ -152,7 +153,7 @@ def week_schedule(
|
||||
# Build actual shifts lookup: (user_id, date_str) → list of actual shifts
|
||||
actuals_map: dict = {}
|
||||
for a in actuals:
|
||||
d = a.started_at.date() if a.started_at else None
|
||||
d = to_venue(a.started_at).date() if a.started_at else None
|
||||
if d:
|
||||
key = (a.waiter_id, d.isoformat())
|
||||
if key not in actuals_map:
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from core import timeutil
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime, timezone
|
||||
@@ -22,7 +24,8 @@ VALID_SETTINGS = {
|
||||
"shifts.waiter_self_end": "Allow waiters to end their own shifts without manager action",
|
||||
"shifts.hide_revenue_from_waiters": "Hide ΕΙΣΠΡΑΞΗ and ΠΑΡΑΔ. ΠΟΣΟ stats from waiters in Shift Overview: 'true' | 'false'",
|
||||
"business_day.force_close_allowed": "Allow force-closing business day with open tables",
|
||||
"system.timezone": "IANA timezone name used by the backend container (e.g. Europe/Athens). Requires container restart to take effect.",
|
||||
"venue.timezone": "IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.",
|
||||
"business_day.rollover_hour": "Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.",
|
||||
"system.log_retention_days": "Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.",
|
||||
"ui.table_colours": "JSON blob of table card colour scheme (light + dark modes) for the Waiter PWA.",
|
||||
"dev.spoof_printing": "When enabled, all print jobs are silently dropped. Devices behave as if printing succeeded.",
|
||||
@@ -79,7 +82,8 @@ DEFAULTS = {
|
||||
"shifts.waiter_self_end": "true",
|
||||
"shifts.hide_revenue_from_waiters": "false",
|
||||
"business_day.force_close_allowed": "true",
|
||||
"system.timezone": "Europe/Athens",
|
||||
"venue.timezone": "Europe/Athens",
|
||||
"business_day.rollover_hour": "6",
|
||||
"system.log_retention_days": "30",
|
||||
"ui.table_colours": '{"light":{"free":{"cardBg":"#dde5ef","badgeBg":"rgba(255,255,255,0.92)","nameText":"#3d5270","badgeText":"#3d5270"},"mine":{"cardBg":"#e8610a","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#e8610a"},"open":{"cardBg":"#FF8F60","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#FF8F60"},"partially_paid":{"cardBg":"#FFDC67","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#d4a800"},"paid":{"cardBg":"#81D264","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#81D264"},"kds_ready":{"cardBg":"#22c55e","cardBg2":"#ffffff","badgeBg":"rgba(255,255,255,0.92)","badgeBg2":"rgba(255,255,255,0.92)","nameText":"#ffffff","nameText2":"#15803d","badgeText":"#15803d","badgeText2":"#22c55e","flash":true}},"dark":{"free":{"cardBg":"#243044","badgeBg":"rgba(255,255,255,0.92)","nameText":"#94b8d4","badgeText":"#94b8d4"},"mine":{"cardBg":"#e8610a","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#e8610a"},"open":{"cardBg":"#FF8F60","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#FF8F60"},"partially_paid":{"cardBg":"#FFDC67","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#d4a800"},"paid":{"cardBg":"#81D264","badgeBg":"rgba(255,255,255,0.92)","nameText":"#ffffff","badgeText":"#81D264"},"kds_ready":{"cardBg":"#16a34a","cardBg2":"#ffffff","badgeBg":"rgba(255,255,255,0.92)","badgeBg2":"rgba(255,255,255,0.92)","nameText":"#ffffff","nameText2":"#bbf7d0","badgeText":"#bbf7d0","badgeText2":"#16a34a","flash":true}}}',
|
||||
"dev.spoof_printing": "false",
|
||||
@@ -141,11 +145,19 @@ def update_setting(
|
||||
):
|
||||
if key not in VALID_SETTINGS:
|
||||
raise HTTPException(status_code=400, detail=f"Unknown setting key: {key}")
|
||||
if key == "venue.timezone":
|
||||
try:
|
||||
timeutil.validate_tz(body.value)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=422, detail=f"Unknown time zone: {body.value}")
|
||||
if key == "business_day.rollover_hour":
|
||||
if not (body.value.isdigit() and 0 <= int(body.value) <= 23):
|
||||
raise HTTPException(status_code=422, detail="rollover_hour must be 0-23")
|
||||
|
||||
setting = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if setting:
|
||||
setting.value = body.value
|
||||
setting.updated_at = datetime.now(timezone.utc)
|
||||
setting.updated_at = utcnow()
|
||||
setting.updated_by_id = user.id
|
||||
else:
|
||||
setting = PosSettings(key=key, value=body.value, updated_by_id=user.id)
|
||||
@@ -153,4 +165,6 @@ def update_setting(
|
||||
|
||||
db.commit()
|
||||
db.refresh(setting)
|
||||
if key in ("venue.timezone", "business_day.rollover_hour"):
|
||||
timeutil.invalidate() # live: next call re-reads the setting
|
||||
return {"key": setting.key, "value": setting.value}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel, EmailStr
|
||||
@@ -101,7 +102,7 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
||||
if body.venue_name or body.venue_type:
|
||||
from models.settings import PosSettings
|
||||
from datetime import datetime, timezone
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
if body.venue_name:
|
||||
setting = db.query(PosSettings).filter(PosSettings.key == "venue.name").first()
|
||||
if setting:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
@@ -55,7 +56,7 @@ def compute_shift_payment_split(shift_id: int, db: Session) -> dict:
|
||||
|
||||
def compute_shift_pay(shift: WaiterShift) -> dict:
|
||||
"""Return duration_hours and shift_pay. shift_pay is None if no rate snapshot."""
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
start = shift.started_at
|
||||
if start and start.tzinfo is None:
|
||||
start = start.replace(tzinfo=timezone.utc)
|
||||
@@ -206,7 +207,7 @@ def end_shift(
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="No active shift found")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
total = compute_shift_total(shift.id, db)
|
||||
shift.total_collected = total
|
||||
shift.ended_at = now
|
||||
@@ -277,7 +278,7 @@ def manager_end_shift(
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="Active shift not found")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
total = compute_shift_total(shift.id, db)
|
||||
shift.total_collected = total
|
||||
shift.ended_at = now
|
||||
@@ -343,7 +344,7 @@ def end_break(
|
||||
if not open_break:
|
||||
raise HTTPException(status_code=404, detail="No active break found")
|
||||
|
||||
open_break.ended_at = datetime.now(timezone.utc)
|
||||
open_break.ended_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(open_break)
|
||||
return {"id": open_break.id, "shift_id": open_break.shift_id, "started_at": _dt(open_break.started_at), "ended_at": _dt(open_break.ended_at)}
|
||||
@@ -448,7 +449,7 @@ def get_shift_summary(
|
||||
).all()
|
||||
|
||||
from datetime import timezone as tz
|
||||
upper_bound = shift.ended_at or datetime.now(tz.utc)
|
||||
upper_bound = shift.ended_at or utcnow()
|
||||
ordered_items = db.query(OrderItem).options(
|
||||
joinedload(OrderItem.product),
|
||||
joinedload(OrderItem.order),
|
||||
@@ -569,7 +570,7 @@ def get_shift_summary(
|
||||
duration_minutes = int((ended - started).total_seconds() / 60)
|
||||
elif started:
|
||||
from datetime import timezone as tz
|
||||
now = datetime.now(tz.utc)
|
||||
now = utcnow()
|
||||
s = started if started.tzinfo else started.replace(tzinfo=tz.utc)
|
||||
duration_minutes = int((now - s).total_seconds() / 60)
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Body
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
@@ -104,7 +105,7 @@ def list_tables(include_inactive: bool = False, db: Session = Depends(get_db), u
|
||||
}
|
||||
|
||||
# Fetch pending reservations due within the lookahead window for the RESERVED badge
|
||||
now = datetime.now(timezone.utc)
|
||||
now = utcnow()
|
||||
lookahead = now + timedelta(hours=RESERVATION_LOOKAHEAD_HOURS)
|
||||
upcoming_reservations = (
|
||||
db.query(Reservation)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -14,8 +15,6 @@ from routers.deps import require_manager
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _utcnow():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _tab_out(tab: Tab) -> dict:
|
||||
@@ -183,7 +182,7 @@ def close_tab(
|
||||
if balance > 0.005:
|
||||
raise HTTPException(status_code=400, detail=f"Tab still has a balance of €{balance:.2f} — pay it off first or use /forgive")
|
||||
tab.status = "closed"
|
||||
tab.closed_at = _utcnow()
|
||||
tab.closed_at = utcnow()
|
||||
tab.closed_by_id = user.id
|
||||
if body.notes:
|
||||
tab.notes = body.notes
|
||||
@@ -203,7 +202,7 @@ def forgive_tab(
|
||||
if not tab:
|
||||
raise HTTPException(status_code=404, detail="Open tab not found")
|
||||
tab.status = "forgiven"
|
||||
tab.closed_at = _utcnow()
|
||||
tab.closed_at = utcnow()
|
||||
tab.closed_by_id = user.id
|
||||
if body.reason:
|
||||
tab.notes = body.reason
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.timeutil import parse_api_datetime
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -65,8 +66,8 @@ def list_waste(
|
||||
q = q.filter(WasteLog.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
q = q.filter(
|
||||
WasteLog.logged_at >= datetime.fromisoformat(from_dt),
|
||||
WasteLog.logged_at <= datetime.fromisoformat(to_dt),
|
||||
WasteLog.logged_at >= parse_api_datetime(from_dt),
|
||||
WasteLog.logged_at <= parse_api_datetime(to_dt),
|
||||
)
|
||||
entries = q.all()
|
||||
return {"entries": [_waste_out(w) for w in entries]}
|
||||
@@ -143,8 +144,8 @@ def waste_summary(
|
||||
q = q.filter(WasteLog.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
q = q.filter(
|
||||
WasteLog.logged_at >= datetime.fromisoformat(from_dt),
|
||||
WasteLog.logged_at <= datetime.fromisoformat(to_dt),
|
||||
WasteLog.logged_at >= parse_api_datetime(from_dt),
|
||||
WasteLog.logged_at <= parse_api_datetime(to_dt),
|
||||
)
|
||||
entries = q.all()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user