feat: staff and the schedule on v2; managers give staff passwords (platform-v2 step 6.11, KI-014)
- 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>
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
from core.access.queries import holders_filter
|
||||
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
|
||||
@@ -10,10 +9,40 @@ 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
|
||||
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:
|
||||
@@ -71,16 +100,18 @@ def list_schedule(
|
||||
def create_scheduled_shift(
|
||||
body: ScheduledShiftCreate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_manager),
|
||||
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=body.start_time,
|
||||
end_time=body.end_time,
|
||||
start_time=start,
|
||||
end_time=end,
|
||||
notes=body.notes,
|
||||
created_by_id=user.id,
|
||||
)
|
||||
@@ -95,12 +126,19 @@ def update_scheduled_shift(
|
||||
shift_id: int,
|
||||
body: ScheduledShiftUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_manager),
|
||||
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")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
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)
|
||||
@@ -111,7 +149,7 @@ def update_scheduled_shift(
|
||||
def delete_scheduled_shift(
|
||||
shift_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_manager),
|
||||
user: User = Depends(require_staff_manager),
|
||||
):
|
||||
s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
|
||||
if not s:
|
||||
@@ -145,7 +183,8 @@ def week_schedule(
|
||||
WaiterShift.started_at < week_end_dt,
|
||||
).all()
|
||||
|
||||
waiters = {u.id: u for u in db.query(User).filter(holders_filter("waiter_app.access"), User.is_active == True).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:
|
||||
@@ -184,7 +223,7 @@ def week_schedule(
|
||||
"scheduled": scheduled_out,
|
||||
"total_estimated_pay": round(total_estimated_pay, 2),
|
||||
"waiters": [
|
||||
{"id": u.id, "name": u.full_name or u.username, "hourly_rate": u.hourly_rate}
|
||||
{"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)
|
||||
],
|
||||
}
|
||||
|
||||
@@ -39,6 +39,21 @@ def _guard_superadmin_target(target: User, acting_user: User):
|
||||
raise XeniaError("staff.superadmin_protected")
|
||||
|
||||
|
||||
PIN_LEN = (4, 6)
|
||||
PASSWORD_MIN = 6
|
||||
|
||||
|
||||
def _check_pin(pin: str) -> str:
|
||||
"""A PIN is 4 to 6 digits (the phones' and screens' PIN pad)."""
|
||||
if not isinstance(pin, str) or not pin.isdigit() or not PIN_LEN[0] <= len(pin) <= PIN_LEN[1]:
|
||||
raise XeniaError("staff.pin_invalid", min=PIN_LEN[0], max=PIN_LEN[1])
|
||||
return pin
|
||||
|
||||
|
||||
def _hash(secret: str) -> str:
|
||||
return bcrypt.hashpw(secret.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
|
||||
def _guard_grant(acting_user: User, keys) -> None:
|
||||
"""A non-superadmin may only give keys they hold themselves (no self-escalation via staff)."""
|
||||
if acting_user.role == "superadmin":
|
||||
@@ -152,10 +167,13 @@ def create_staff(body: UserCreate, db: Session = Depends(get_db), user: User = D
|
||||
if db.query(User).filter(User.username == body.username).first():
|
||||
raise XeniaError("staff.username_taken", status=400)
|
||||
|
||||
pin_hash = bcrypt.hashpw(body.pin.encode(), bcrypt.gensalt()).decode()
|
||||
pin_hash = _hash(_check_pin(body.pin))
|
||||
if body.password is not None and len(body.password) < PASSWORD_MIN:
|
||||
raise XeniaError("auth.password_too_short", min=PASSWORD_MIN)
|
||||
new_user = User(
|
||||
username=body.username,
|
||||
pin_hash=pin_hash,
|
||||
password_hash=_hash(body.password) if body.password else None, # 6.11: for the password sign-in mode
|
||||
role=body.role,
|
||||
is_active=body.is_active,
|
||||
full_name=body.full_name,
|
||||
@@ -192,8 +210,18 @@ def update_staff(waiter_id: int, body: UserUpdate, db: Session = Depends(get_db)
|
||||
|
||||
if body.language is not None:
|
||||
body.language = normalize_language(body.language) or ""
|
||||
data = body.model_dump(exclude_none=True)
|
||||
# 6.11: fields sent as null are cleared (phone, email, note, nickname, pay); the required
|
||||
# ones (username, role, active) are only changed when given
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
for field, value in data.items():
|
||||
if value is None and field in ("username", "role", "is_active", "language"):
|
||||
continue
|
||||
if field == "username":
|
||||
value = value.strip()
|
||||
if not value:
|
||||
raise XeniaError("staff.username_needed")
|
||||
if db.query(User).filter(User.username == value, User.id != target.id).first():
|
||||
raise XeniaError("staff.username_taken", status=409)
|
||||
setattr(target, field, value)
|
||||
if target.language == "":
|
||||
target.language = None # "" means inherit
|
||||
@@ -203,13 +231,40 @@ def update_staff(waiter_id: int, body: UserUpdate, db: Session = Depends(get_db)
|
||||
return target
|
||||
|
||||
|
||||
@router.put("/{waiter_id}/reset-pin")
|
||||
def reset_pin(waiter_id: int, pin: str, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
||||
class PinBody(BaseModel):
|
||||
pin: str
|
||||
|
||||
|
||||
class PasswordBody(BaseModel):
|
||||
password: str | None = None # None = take the password away (PIN sign-in only)
|
||||
|
||||
|
||||
@router.put("/{waiter_id}/pin")
|
||||
def set_pin(waiter_id: int, body: PinBody, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
||||
"""A new PIN for someone (6.11: in the body, never in the address; 4-6 digits)."""
|
||||
target = _user_or_404(waiter_id, db)
|
||||
_guard_superadmin_target(target, user)
|
||||
target.pin_hash = bcrypt.hashpw(pin.encode(), bcrypt.gensalt()).decode()
|
||||
target.pin_hash = _hash(_check_pin(body.pin))
|
||||
db.commit()
|
||||
return {"status": "pin reset"}
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.put("/{waiter_id}/password")
|
||||
def set_password(waiter_id: int, body: PasswordBody, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
||||
"""Give someone a password, change it, or take it away (6.11, KI-014): what the password
|
||||
sign-in mode (phones, paired screens, the manager) checks. Their open sessions stay."""
|
||||
target = _user_or_404(waiter_id, db)
|
||||
_guard_superadmin_target(target, user)
|
||||
if body.password is None:
|
||||
if target.id == user.id:
|
||||
raise XeniaError("staff.password_own") # your own: Profile → change password
|
||||
target.password_hash = None
|
||||
else:
|
||||
if len(body.password) < PASSWORD_MIN:
|
||||
raise XeniaError("auth.password_too_short", min=PASSWORD_MIN)
|
||||
target.password_hash = _hash(body.password)
|
||||
db.commit()
|
||||
return {"ok": True, "has_password": target.password_hash is not None}
|
||||
|
||||
|
||||
@router.put("/{waiter_id}/block")
|
||||
@@ -226,8 +281,17 @@ def toggle_block(waiter_id: int, db: Session = Depends(get_db), user: User = Dep
|
||||
|
||||
@router.delete("/{waiter_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_staff(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
||||
"""Only someone with no history (no orders, items or shifts): the reports keep who did
|
||||
what, so anyone else is blocked instead (6.11)."""
|
||||
from models.order import Order, OrderItem
|
||||
target = _user_or_404(waiter_id, db)
|
||||
_guard_superadmin_target(target, user)
|
||||
if target.id == user.id:
|
||||
raise XeniaError("staff.delete_self")
|
||||
if (db.query(Order.id).filter(Order.opened_by == target.id).first() or db.query(OrderItem.id).filter(OrderItem.added_by == target.id).first()
|
||||
or db.query(WaiterShift.id).filter(WaiterShift.waiter_id == target.id).first()):
|
||||
raise XeniaError("staff.has_history", name=target.full_name or target.username)
|
||||
db.query(WaiterZone).filter(WaiterZone.waiter_id == target.id).delete()
|
||||
db.delete(target)
|
||||
db.commit()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user