- staff: PUT /api/waiters/{id}/password (set, change, or take away; 6+ chars)
so the password sign-in mode works for everyone; PUT /{id}/pin with the PIN in
the body (was in the address: reset-pin?pin= removed); PINs 4-6 digits when
adding; a password can be given when adding; has_password on staff; editing
clears emptied fields and keeps usernames unique; delete only without history
(orders, items, shifts) and never yourself
- schedule: times checked (schedule.bad_time), one person's overlapping shifts
refused (schedule.overlap, past midnight understood), everyone active can be
scheduled (the kitchen too), changes need core.staff.manage
- manager: src/pages/staff (list with search and filters, person dialog with
photo, PIN / password dialog, zones) and src/pages/schedule (by person, by
hour with opening hours, shift dialog with clash check, view settings kept in
the browser); the never-used "automatic start/close" switches dropped; v1
StaffTab and SchedulePage removed; ApprovalsPage loads with useLiveQuery
- tests: test_staff_v2.py (done-when on a paired screen), staff.test.mjs, e2e
manager.mjs (add, password, sign-in on a paired till, a shift and a clash)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
230 lines
8.3 KiB
Python
230 lines
8.3 KiB
Python
from core.timeutil import to_venue, venue_day_window, venue_date
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from fastapi import APIRouter, Depends, status, Query
|
|
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
|
|
from database import get_db
|
|
from models.schedule import ScheduledShift
|
|
from models.shift import WaiterShift
|
|
from models.user import User
|
|
from schemas.schedule import ScheduledShiftCreate, ScheduledShiftUpdate, ScheduledShiftOut
|
|
from routers.deps import require_manager, require_staff_manager
|
|
from core.errors import XeniaError
|
|
import re
|
|
|
|
router = APIRouter()
|
|
_HHMM = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$")
|
|
|
|
|
|
def _time(value: str) -> str:
|
|
if not isinstance(value, str) or not _HHMM.match(value.strip()):
|
|
raise XeniaError("schedule.bad_time")
|
|
return value.strip()
|
|
|
|
|
|
def _minutes(t: str) -> int:
|
|
return int(t[:2]) * 60 + int(t[3:5])
|
|
|
|
|
|
def _overlaps(a_start: str, a_end: str, b_start: str, b_end: str) -> bool:
|
|
"""Same-day spans; an end at or before the start runs past midnight."""
|
|
a0, a1, b0, b1 = _minutes(a_start), _minutes(a_end), _minutes(b_start), _minutes(b_end)
|
|
a1 += 1440 if a1 <= a0 else 0
|
|
b1 += 1440 if b1 <= b0 else 0
|
|
return a0 < b1 and b0 < a1
|
|
|
|
|
|
def _check_overlap(db, user_id: int, day, start: str, end: str, skip_id: int | None = None) -> None:
|
|
"""One person can't have two shifts at the same time on one day (6.11)."""
|
|
q = db.query(ScheduledShift).filter(ScheduledShift.user_id == user_id, ScheduledShift.scheduled_date == day)
|
|
for other in q.all():
|
|
if other.id != skip_id and _overlaps(start, end, other.start_time, other.end_time):
|
|
u = other.user
|
|
raise XeniaError("schedule.overlap", name=(u.full_name or u.username) if u else f"#{user_id}",
|
|
start=other.start_time, end=other.end_time)
|
|
|
|
|
|
def _duration_hours(start: str, end: str) -> float:
|
|
"""Compute hours between two HH:MM strings. Handles overnight spans."""
|
|
sh, sm = int(start[:2]), int(start[3:5])
|
|
eh, em = int(end[:2]), int(end[3:5])
|
|
mins = (eh * 60 + em) - (sh * 60 + sm)
|
|
if mins <= 0:
|
|
mins += 24 * 60 # overnight
|
|
return round(mins / 60, 2)
|
|
|
|
|
|
def _enrich(s: ScheduledShift) -> dict:
|
|
u = s.user
|
|
user_name = (u.full_name or u.username) if u else f"#{s.user_id}"
|
|
hourly_rate = u.hourly_rate if u else None
|
|
dur = _duration_hours(s.start_time, s.end_time)
|
|
estimated_pay = round(dur * hourly_rate, 2) if hourly_rate else None
|
|
return {
|
|
"id": s.id,
|
|
"user_id": s.user_id,
|
|
"user_name": user_name,
|
|
"hourly_rate": hourly_rate,
|
|
"scheduled_date": s.scheduled_date,
|
|
"start_time": s.start_time,
|
|
"end_time": s.end_time,
|
|
"notes": s.notes,
|
|
"created_by_id": s.created_by_id,
|
|
"created_at": s.created_at,
|
|
"duration_hours": dur,
|
|
"estimated_pay": estimated_pay,
|
|
}
|
|
|
|
|
|
@router.get("/", response_model=List[ScheduledShiftOut])
|
|
def list_schedule(
|
|
from_date: Optional[date] = Query(default=None, alias="from"),
|
|
to_date: Optional[date] = Query(default=None, alias="to"),
|
|
user_id: Optional[int] = None,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(require_manager),
|
|
):
|
|
q = db.query(ScheduledShift)
|
|
if from_date:
|
|
q = q.filter(ScheduledShift.scheduled_date >= from_date)
|
|
if to_date:
|
|
q = q.filter(ScheduledShift.scheduled_date <= to_date)
|
|
if user_id:
|
|
q = q.filter(ScheduledShift.user_id == user_id)
|
|
shifts = q.order_by(ScheduledShift.scheduled_date, ScheduledShift.start_time).all()
|
|
return [_enrich(s) for s in shifts]
|
|
|
|
|
|
@router.post("/", response_model=ScheduledShiftOut, status_code=status.HTTP_201_CREATED)
|
|
def create_scheduled_shift(
|
|
body: ScheduledShiftCreate,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(require_staff_manager),
|
|
):
|
|
target = db.query(User).filter(User.id == body.user_id, User.is_active == True).first()
|
|
if not target:
|
|
raise XeniaError("staff.not_found")
|
|
start, end = _time(body.start_time), _time(body.end_time)
|
|
_check_overlap(db, body.user_id, body.scheduled_date, start, end)
|
|
s = ScheduledShift(
|
|
user_id=body.user_id,
|
|
scheduled_date=body.scheduled_date,
|
|
start_time=start,
|
|
end_time=end,
|
|
notes=body.notes,
|
|
created_by_id=user.id,
|
|
)
|
|
db.add(s)
|
|
db.commit()
|
|
db.refresh(s)
|
|
return _enrich(s)
|
|
|
|
|
|
@router.put("/{shift_id}", response_model=ScheduledShiftOut)
|
|
def update_scheduled_shift(
|
|
shift_id: int,
|
|
body: ScheduledShiftUpdate,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(require_staff_manager),
|
|
):
|
|
s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
|
|
if not s:
|
|
raise XeniaError("schedule.shift_not_found")
|
|
data = body.model_dump(exclude_none=True)
|
|
for k in ("start_time", "end_time"):
|
|
if k in data:
|
|
data[k] = _time(data[k])
|
|
_check_overlap(db, s.user_id, s.scheduled_date, data.get("start_time", s.start_time), data.get("end_time", s.end_time), skip_id=s.id)
|
|
if "notes" in body.model_fields_set and body.notes is not None:
|
|
data["notes"] = body.notes.strip() or None
|
|
for field, value in data.items():
|
|
setattr(s, field, value)
|
|
db.commit()
|
|
db.refresh(s)
|
|
return _enrich(s)
|
|
|
|
|
|
@router.delete("/{shift_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_scheduled_shift(
|
|
shift_id: int,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(require_staff_manager),
|
|
):
|
|
s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
|
|
if not s:
|
|
raise XeniaError("schedule.shift_not_found")
|
|
db.delete(s)
|
|
db.commit()
|
|
|
|
|
|
@router.get("/week")
|
|
def week_schedule(
|
|
week_start: Optional[date] = Query(default=None),
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(require_manager),
|
|
):
|
|
"""Current (or specified) week: scheduled shifts + actual WaiterShifts for comparison."""
|
|
if week_start is None:
|
|
today = venue_date()
|
|
week_start = today - timedelta(days=today.weekday()) # Monday
|
|
week_end = week_start + timedelta(days=6) # Sunday
|
|
|
|
scheduled = db.query(ScheduledShift).filter(
|
|
ScheduledShift.scheduled_date >= week_start,
|
|
ScheduledShift.scheduled_date <= week_end,
|
|
).order_by(ScheduledShift.scheduled_date, ScheduledShift.start_time).all()
|
|
|
|
# Actual shifts that started within the week
|
|
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,
|
|
).all()
|
|
|
|
# everyone who works here (6.11: the kitchen too, not only waiters); not support accounts
|
|
waiters = {u.id: u for u in db.query(User).filter(User.is_active == True, User.role != "superadmin").all()}
|
|
|
|
def _dt(dt):
|
|
if not dt:
|
|
return None
|
|
return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat()
|
|
|
|
# Build actual shifts lookup: (user_id, date_str) → list of actual shifts
|
|
actuals_map: dict = {}
|
|
for a in actuals:
|
|
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:
|
|
actuals_map[key] = []
|
|
actuals_map[key].append({
|
|
"id": a.id,
|
|
"started_at": _dt(a.started_at),
|
|
"ended_at": _dt(a.ended_at),
|
|
"is_active": a.ended_at is None,
|
|
})
|
|
|
|
# Estimate total weekly labor cost
|
|
total_estimated_pay = 0.0
|
|
scheduled_out = []
|
|
for s in scheduled:
|
|
enriched = _enrich(s)
|
|
key = (s.user_id, s.scheduled_date.isoformat())
|
|
enriched["actual_shifts"] = actuals_map.get(key, [])
|
|
scheduled_out.append(enriched)
|
|
if enriched["estimated_pay"]:
|
|
total_estimated_pay += enriched["estimated_pay"]
|
|
|
|
return {
|
|
"week_start": week_start.isoformat(),
|
|
"week_end": week_end.isoformat(),
|
|
"scheduled": scheduled_out,
|
|
"total_estimated_pay": round(total_estimated_pay, 2),
|
|
"waiters": [
|
|
{"id": u.id, "name": u.full_name or u.username, "nickname": u.nickname, "role": u.role, "hourly_rate": u.hourly_rate}
|
|
for u in sorted(waiters.values(), key=lambda x: x.full_name or x.username)
|
|
],
|
|
}
|