Files
xenia-pos-local/local_backend/routers/waiters.py
T
bonaminandClaude Opus 5.5 6643614ff6 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>
2026-11-19 08:05:01 +02:00

389 lines
17 KiB
Python

import os
import uuid
import bcrypt
from core.i18n import normalize_language
from fastapi import APIRouter, Depends, status, UploadFile, File
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel
from database import get_db
from models.user import User, AssistantAssignment, WaiterZone
from models.shift import WaiterShift
from schemas.user import UserCreate, UserUpdate, UserOut, AssistantAssignmentOut, SetZonesRequest
from routers.deps import require_staff_manager, get_current_user
from services.chat_service import add_user_to_system_group
from roles import ALL_ROLES, VALID_ROLES
from core.access.check import holds, user_keys
from core.access.queries import holders_filter
from core.access.templates import apply_role_template, manifest_template, role_template, set_role_keys, set_user_keys
from core.errors import XeniaError
from core.modules.registry import registry
router = APIRouter()
AVATAR_DIR = "/app/data/avatars"
# ── Helpers ───────────────────────────────────────────────────────────────────
def _user_or_404(user_id: int, db: Session) -> User:
u = db.query(User).filter(User.id == user_id).first()
if not u:
raise XeniaError("staff.not_found")
return u
def _guard_superadmin_target(target: User, acting_user: User):
"""Prevent any modification of a superadmin by a non-superadmin."""
if target.role == "superadmin" and acting_user.role != "superadmin":
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":
return
for k in sorted(keys):
if not holds(acting_user, k):
raise XeniaError("access.cannot_grant", key=k)
# ── Metadata ──────────────────────────────────────────────────────────────────
@router.get("/roles")
def list_roles(user: User = Depends(get_current_user)):
"""Return the full ordered list of available roles."""
return ALL_ROLES
# ── Permission keys (D-7) ─────────────────────────────────────────────────────
class PermissionKeys(BaseModel):
keys: List[str]
@router.get("/permission-catalog")
def permission_catalog(db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
"""Every permission key, grouped by module, with each role's template."""
from roles import ALL_ROLES as _roles
return {
"modules": [{"key": m.key, "name": m.name, "kind": m.kind,
"permissions": [{"key": p.key, "description": p.description, "roles": list(p.roles), "overridable": p.overridable}
for p in m.permissions]}
for m in registry().values() if m.permissions],
"role_templates": {r["value"]: sorted(role_template(r["value"], db)) for r in _roles},
}
@router.get("/{waiter_id}/permissions")
def get_permissions(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
target = _user_or_404(waiter_id, db)
return {"user_id": target.id, "role": target.role, "superadmin": target.role == "superadmin",
"keys": sorted(user_keys(target)), "role_template": sorted(role_template(target.role, db))}
@router.put("/{waiter_id}/permissions")
def set_permissions(waiter_id: int, body: PermissionKeys, db: Session = Depends(get_db),
user: User = Depends(require_staff_manager)):
"""Replace a user's keys. You can only add keys you hold yourself (superadmin: any)."""
target = _user_or_404(waiter_id, db)
_guard_superadmin_target(target, user)
from core.modules.registry import all_permissions
unknown = sorted(set(body.keys) - set(all_permissions()))
if unknown:
raise XeniaError("access.unknown_key", key=unknown[0])
_guard_grant(user, set(body.keys) - set(user_keys(target)))
set_user_keys(target, body.keys)
db.commit()
return {"user_id": target.id, "keys": sorted(user_keys(target))}
# ── What each role may do (plan step 4.3) ─────────────────────────────────────
# The venue's own role defaults: Settings → Operation → "What each role may do". A change
# applies to everyone with the role and to staff added later (core/access/templates.py).
def _role_or_404(role: str) -> str:
if role not in VALID_ROLES or role in ("superadmin", "custom"):
raise XeniaError("validation.invalid", field="role")
return role
@router.get("/roles/{role}/permissions")
def get_role_permissions(role: str, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
"""{role, keys (the venue's), default_keys (the manifests'), people (how many have it)}."""
_role_or_404(role)
return {"role": role, "keys": sorted(role_template(role, db)), "default_keys": sorted(manifest_template(role)),
"people": db.query(User).filter(User.role == role).count()}
@router.put("/roles/{role}/permissions")
def set_role_permissions(role: str, body: PermissionKeys, db: Session = Depends(get_db),
user: User = Depends(require_staff_manager)):
"""Replace the role's keys; the difference is applied to everyone with the role. You can
only add keys you hold yourself (superadmin: any)."""
_role_or_404(role)
_guard_grant(user, set(body.keys) - role_template(role, db))
added, removed = set_role_keys(db, role, body.keys)
db.commit()
return {"role": role, "keys": sorted(role_template(role, db)), "added": added, "removed": removed}
# ── CRUD ──────────────────────────────────────────────────────────────────────
@router.get("/on-shift", response_model=List[UserOut])
def list_waiters_on_shift(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Staff with an active (not-ended) shift. Accessible to all staff."""
waiter_ids = db.query(WaiterShift.waiter_id).filter(WaiterShift.ended_at == None).subquery()
return db.query(User).filter(User.id.in_(waiter_ids), holders_filter("waiter_app.access"), User.is_active == True).all()
@router.get("/", response_model=List[UserOut])
def list_staff(db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
"""List all staff members regardless of role."""
return db.query(User).order_by(User.created_at).all()
@router.post("/", response_model=UserOut, status_code=status.HTTP_201_CREATED)
def create_staff(body: UserCreate, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
if body.role not in VALID_ROLES:
raise XeniaError("staff.role_invalid", role=body.role)
if body.role == "superadmin" and user.role != "superadmin":
raise XeniaError("staff.superadmin_only")
if db.query(User).filter(User.username == body.username).first():
raise XeniaError("staff.username_taken", status=400)
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,
nickname=body.nickname,
mobile_phone=body.mobile_phone,
email=body.email,
note=body.note,
hourly_rate=body.hourly_rate,
)
apply_role_template(new_user, db) # the role's keys (manifests + the venue's changes); edit them with PUT /{id}/permissions
db.add(new_user)
db.commit()
db.refresh(new_user)
# Give waiter-app users access to all zones by default
if holds(new_user, "waiter_app.access"):
db.add(WaiterZone(waiter_id=new_user.id, group_id=None))
db.commit()
add_user_to_system_group(db, new_user.id)
return new_user
@router.put("/{waiter_id}", response_model=UserOut)
def update_staff(waiter_id: int, body: UserUpdate, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
target = _user_or_404(waiter_id, db)
_guard_superadmin_target(target, user)
if body.role is not None and body.role not in VALID_ROLES:
raise XeniaError("staff.role_invalid", role=body.role)
if body.role == "superadmin" and user.role != "superadmin":
raise XeniaError("staff.superadmin_only")
if body.language is not None:
body.language = normalize_language(body.language) or ""
# 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
db.commit()
db.refresh(target)
return target
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 = _hash(_check_pin(body.pin))
db.commit()
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")
def toggle_block(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
target = _user_or_404(waiter_id, db)
_guard_superadmin_target(target, user)
target.is_active = not target.is_active
db.commit()
if not target.is_active: # a blocked user is logged out everywhere at once (D-9)
from core import sessions
sessions.end_for_user(db, target.id, "user_blocked")
return {"is_active": target.is_active}
@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()
# ── Avatar upload / delete ───────────────────────────────────────────────────
@router.post("/{waiter_id}/avatar", response_model=UserOut)
async def upload_avatar(waiter_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
target = _user_or_404(waiter_id, db)
if not file.content_type.startswith("image/"):
raise XeniaError("staff.avatar_type")
if target.avatar_url:
old_path = os.path.join(AVATAR_DIR, os.path.basename(target.avatar_url))
if os.path.exists(old_path):
os.remove(old_path)
ext = os.path.splitext(file.filename or "")[1] or ".jpg"
filename = f"staff_{waiter_id}_{uuid.uuid4().hex[:8]}{ext}"
dest = os.path.join(AVATAR_DIR, filename)
os.makedirs(AVATAR_DIR, exist_ok=True)
content = await file.read()
with open(dest, "wb") as f:
f.write(content)
target.avatar_url = f"/static/avatars/{filename}"
db.commit()
db.refresh(target)
return target
@router.delete("/{waiter_id}/avatar", response_model=UserOut)
def delete_avatar(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
target = _user_or_404(waiter_id, db)
if target.avatar_url:
old_path = os.path.join(AVATAR_DIR, os.path.basename(target.avatar_url))
if os.path.exists(old_path):
os.remove(old_path)
target.avatar_url = None
db.commit()
db.refresh(target)
return target
# ── Zone assignments ──────────────────────────────────────────────────────────
@router.put("/{waiter_id}/zones")
def set_zones(waiter_id: int, body: SetZonesRequest, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
"""Replace all zone assignments for a staff member atomically.
- all_zones=True → single NULL group_id row (sees everything)
- group_ids=[1,2] → rows for groups 1 and 2 only
- group_ids=[] → no rows at all (sees nothing)
"""
_user_or_404(waiter_id, db)
db.query(WaiterZone).filter(WaiterZone.waiter_id == waiter_id).delete()
if body.all_zones:
db.add(WaiterZone(waiter_id=waiter_id, group_id=None))
elif body.group_ids:
for gid in body.group_ids:
db.add(WaiterZone(waiter_id=waiter_id, group_id=gid))
db.commit()
zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == waiter_id).all()
return {"waiter_id": waiter_id, "zones": [{"id": z.id, "group_id": z.group_id} for z in zones]}
# ── Assistant assignments (kept for backwards compat) ─────────────────────────
@router.post("/{waiter_id}/assign-assistant", response_model=AssistantAssignmentOut)
def assign_assistant(waiter_id: int, assistant_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
existing = db.query(AssistantAssignment).filter(
AssistantAssignment.primary_waiter_id == waiter_id,
AssistantAssignment.assistant_waiter_id == assistant_id,
).first()
if existing:
raise XeniaError("staff.assignment_exists")
assignment = AssistantAssignment(primary_waiter_id=waiter_id, assistant_waiter_id=assistant_id)
db.add(assignment)
db.commit()
db.refresh(assignment)
return assignment
@router.delete("/{waiter_id}/assistant", status_code=status.HTTP_204_NO_CONTENT)
def remove_assistant(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
assignment = db.query(AssistantAssignment).filter(
AssistantAssignment.primary_waiter_id == waiter_id
).first()
if not assignment:
raise XeniaError("staff.assignment_not_found")
db.delete(assignment)
db.commit()