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:
2026-11-19 08:05:01 +02:00
co-authored by Claude Opus 5.5
parent f31bdf42aa
commit 6643614ff6
27 changed files with 1554 additions and 1794 deletions
+7
View File
@@ -259,8 +259,15 @@ CODES: dict[str, tuple[int, str]] = {
"staff.role_invalid": (400, "There is no role {role}."),
"staff.avatar_type": (400, "The photo must be a picture file."),
"staff.assignment_exists": (400, "That assignment already exists."),
"staff.pin_invalid": (422, "A PIN is {min} to {max} digits."),
"staff.username_needed": (422, "Every person needs a username."),
"staff.password_own": (409, "Change your own password from your profile."),
"staff.delete_self": (409, "You can't delete yourself."),
"staff.has_history": (409, "{name} has orders or shifts on record, so they can't be deleted. Block them instead: they can't sign in, and the reports keep their name."),
"staff.assignment_not_found": (404, "Assignment not found."),
"schedule.shift_not_found": (404, "Scheduled shift not found."),
"schedule.bad_time": (422, "Times are written like 09:30."),
"schedule.overlap": (409, "{name} already has a shift from {start} to {end} that day."),
"setup.done": (409, "Setup is already done: a manager account exists."),
"shift.already_active": (400, "This person already has a shift going."),
"shift.start_needs_manager": (403, "Starting the shift needs a manager's approval."),
+49 -10
View File
@@ -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)
],
}
+70 -6
View File
@@ -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()
+3
View File
@@ -21,6 +21,7 @@ class UserBase(BaseModel):
class UserCreate(UserBase):
pin: str
password: Optional[str] = None # 6.11: for the password sign-in mode (6+ characters)
class UserUpdate(BaseModel):
@@ -51,6 +52,7 @@ class UserOut(UserBase):
zone_assignments: List[WaiterZoneOut] = []
waiter_settings: Optional[str] = None # JSON blob — per-waiter settings + favorites
permissions: List[str] = [] # permission keys (D-7); superadmin: [] = implicit all
has_password: bool = False # 6.11: can sign in by password (never the password itself)
model_config = {"from_attributes": True}
@@ -65,6 +67,7 @@ class UserOut(UserBase):
if name != "permissions"}
data["zone_assignments"] = list(getattr(obj, "zone_assignments", None) or [])
data["permissions"] = sorted(user_keys(obj))
data["has_password"] = bool(getattr(obj, "password_hash", None))
return {k: v for k, v in data.items() if v is not None or k in ("full_name",)}
+82
View File
@@ -0,0 +1,82 @@
"""Staff on v2 (plan step 6.11): passwords set by a manager (KI-014), PINs in the body and
checked, deleting only people without history, the schedule's times and overlaps."""
from datetime import date
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
def _new(client, h, **extra):
body = {"username": extra.pop("username", "eleni"), "role": "waiter", "pin": "4321", "full_name": "Eleni K", "nickname": "Eleni", **extra}
r = client.post("/api/waiters/", headers=h, json=body)
return r
def test_a_waiter_given_a_password_signs_in_with_it_on_a_paired_screen(client, owner_h, pair):
w = _new(client, owner_h).json()
assert w["has_password"] is False
token, r = pair("pos_counter", "Till", login_mode="password")
assert r.status_code == 201, r.text
dev = {"X-Xenia-Device": token}
login = lambda pw: client.post("/api/auth/login", headers=dev, json={"client": "terminal", "username": "eleni", "password": pw}) # noqa: E731
assert err(login("whatever1")) == "auth.invalid_credentials" # no password yet (KI-014)
assert err(client.put(f"/api/waiters/{w['id']}/password", headers=owner_h, json={"password": "short"})) == "auth.password_too_short"
r = client.put(f"/api/waiters/{w['id']}/password", headers=owner_h, json={"password": "kalimera6"})
assert r.json() == {"ok": True, "has_password": True}
assert next(s for s in client.get("/api/waiters/", headers=owner_h).json() if s["id"] == w["id"])["has_password"] is True
signed = login("kalimera6")
assert signed.status_code == 200, signed.text
assert signed.json()["user"]["username"] == "eleni"
# taken away: PIN only again
client.put(f"/api/waiters/{w['id']}/password", headers=owner_h, json={"password": None})
assert err(login("kalimera6")) == "auth.invalid_credentials"
def test_pins_are_digits_and_go_in_the_body(client, owner_h):
assert err(_new(client, owner_h, pin="12")) == "staff.pin_invalid"
assert err(_new(client, owner_h, pin="12ab")) == "staff.pin_invalid"
w = _new(client, owner_h, password="welcome1").json()
assert w["has_password"] is True
assert err(client.put(f"/api/waiters/{w['id']}/pin", headers=owner_h, json={"pin": "1234567"})) == "staff.pin_invalid"
assert client.put(f"/api/waiters/{w['id']}/pin", headers=owner_h, json={"pin": "2468"}).json() == {"ok": True}
r = client.post("/api/auth/login", json={"client": "waiter", "username": "eleni", "pin": "2468"})
assert r.status_code == 200, r.text
assert client.put(f"/api/waiters/{w['id']}/reset-pin?pin=1111", headers=owner_h).status_code in (404, 405) # the old route is gone
def test_delete_only_without_history_and_never_yourself(client, db, owner_h, make_user):
from core.timeutil import utcnow
from models.order import Order
fresh = _new(client, owner_h, username="fresh").json()
worked = _new(client, owner_h, username="worked").json()
db.add(Order(opened_by=worked["id"], opened_at=utcnow(), status="closed"))
db.commit()
assert err(client.delete(f"/api/waiters/{worked['id']}", headers=owner_h)) == "staff.has_history"
assert client.delete(f"/api/waiters/{fresh['id']}", headers=owner_h).status_code == 204
me = client.get("/api/auth/me", headers=owner_h).json()
assert err(client.delete(f"/api/waiters/{me['id']}", headers=owner_h)) == "staff.delete_self"
assert err(client.put(f"/api/waiters/{me['id']}/password", headers=owner_h, json={"password": None})) == "staff.password_own"
def test_the_schedule_checks_times_and_overlaps_and_lists_the_kitchen(client, owner_h):
cook = _new(client, owner_h, username="cook", role="chef").json()
day = date(2026, 11, 23).isoformat()
add = lambda s, e: client.post("/api/schedule/", headers=owner_h, json={"user_id": cook["id"], "scheduled_date": day, "start_time": s, "end_time": e}) # noqa: E731
assert err(add("9:00", "17:00")) == "schedule.bad_time"
first = add("18:00", "02:00") # past midnight
assert first.status_code == 201, first.text
assert first.json()["duration_hours"] == 8.0
assert err(add("23:00", "23:30")) == "schedule.overlap"
assert add("10:00", "14:00").status_code == 201
second = client.get("/api/schedule/week", headers=owner_h, params={"week_start": day}).json()
assert any(w["id"] == cook["id"] and w["role"] == "chef" for w in second["waiters"])
lunch = next(s for s in second["scheduled"] if s["start_time"] == "10:00")
assert err(client.put(f"/api/schedule/{lunch['id']}", headers=owner_h, json={"end_time": "19:00"})) == "schedule.overlap"
assert client.put(f"/api/schedule/{lunch['id']}", headers=owner_h, json={"end_time": "16:00", "notes": " "}).json()["notes"] is None
def test_editing_clears_what_is_emptied_and_keeps_usernames_unique(client, owner_h):
a = _new(client, owner_h, mobile_phone="6900000000").json()
_new(client, owner_h, username="other")
r = client.put(f"/api/waiters/{a['id']}", headers=owner_h, json={"mobile_phone": None, "full_name": "Eleni K.", "language": ""})
assert r.status_code == 200 and r.json().get("mobile_phone") is None and r.json()["full_name"] == "Eleni K."
assert err(client.put(f"/api/waiters/{a['id']}", headers=owner_h, json={"username": "other"})) == "staff.username_taken"