From 6643614ff6bda001bd7f5c448bd1faa908effae0 Mon Sep 17 00:00:00 2001 From: bonamin Date: Thu, 19 Nov 2026 08:05:01 +0200 Subject: [PATCH] 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 --- local_backend/core/errors.py | 7 + local_backend/routers/schedule.py | 59 +- local_backend/routers/waiters.py | 76 +- local_backend/schemas/user.py | 3 + local_backend/tests/test_staff_v2.py | 82 ++ manager_dashboard/src/App.jsx | 4 +- .../src/pages/Management/SchedulePage.jsx | 1 - .../src/pages/Management/StaffPage.jsx | 9 - manager_dashboard/src/pages/SchedulePage.jsx | 819 ---------------- manager_dashboard/src/pages/StaffTab.jsx | 925 ------------------ .../src/pages/schedule/SchedulePage.jsx | 196 ++++ .../src/pages/schedule/ShiftDialog.jsx | 58 ++ .../src/pages/schedule/ViewDialog.jsx | 33 + .../src/pages/schedule/scheduleLogic.js | 111 +++ .../src/pages/staff/ApprovalsPage.jsx | 21 +- .../src/pages/staff/SecretDialog.jsx | 58 ++ .../src/pages/staff/StaffDialog.jsx | 103 ++ .../src/pages/staff/StaffPage.jsx | 147 +++ .../src/pages/staff/ZonesDialog.jsx | 50 + .../src/pages/staff/staffLogic.js | 110 +++ manager_dashboard/tests/staff.test.mjs | 91 ++ manager_dashboard/v2.json | 4 +- packages/i18n/locales/el/errors.json | 11 +- packages/i18n/locales/el/manager.json | 149 +++ packages/i18n/locales/en/errors.json | 11 +- packages/i18n/locales/en/manager.json | 149 +++ tests/e2e/manager.mjs | 61 ++ 27 files changed, 1554 insertions(+), 1794 deletions(-) create mode 100644 local_backend/tests/test_staff_v2.py delete mode 100644 manager_dashboard/src/pages/Management/SchedulePage.jsx delete mode 100644 manager_dashboard/src/pages/Management/StaffPage.jsx delete mode 100644 manager_dashboard/src/pages/SchedulePage.jsx delete mode 100644 manager_dashboard/src/pages/StaffTab.jsx create mode 100644 manager_dashboard/src/pages/schedule/SchedulePage.jsx create mode 100644 manager_dashboard/src/pages/schedule/ShiftDialog.jsx create mode 100644 manager_dashboard/src/pages/schedule/ViewDialog.jsx create mode 100644 manager_dashboard/src/pages/schedule/scheduleLogic.js create mode 100644 manager_dashboard/src/pages/staff/SecretDialog.jsx create mode 100644 manager_dashboard/src/pages/staff/StaffDialog.jsx create mode 100644 manager_dashboard/src/pages/staff/StaffPage.jsx create mode 100644 manager_dashboard/src/pages/staff/ZonesDialog.jsx create mode 100644 manager_dashboard/src/pages/staff/staffLogic.js create mode 100644 manager_dashboard/tests/staff.test.mjs diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index c8557f6..5b5a1d0 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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."), diff --git a/local_backend/routers/schedule.py b/local_backend/routers/schedule.py index 0078bac..a70f5d5 100644 --- a/local_backend/routers/schedule.py +++ b/local_backend/routers/schedule.py @@ -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) ], } diff --git a/local_backend/routers/waiters.py b/local_backend/routers/waiters.py index 7fc56ac..1aea5fb 100644 --- a/local_backend/routers/waiters.py +++ b/local_backend/routers/waiters.py @@ -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() diff --git a/local_backend/schemas/user.py b/local_backend/schemas/user.py index 50f36b4..99747cd 100644 --- a/local_backend/schemas/user.py +++ b/local_backend/schemas/user.py @@ -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",)} diff --git a/local_backend/tests/test_staff_v2.py b/local_backend/tests/test_staff_v2.py new file mode 100644 index 0000000..dbb489a --- /dev/null +++ b/local_backend/tests/test_staff_v2.py @@ -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" diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 24a77df..68b157c 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -33,10 +33,10 @@ import ProductsPage from './pages/products/ProductsPage' import MediaPage from './pages/media/MediaPage' import SignagePage from './pages/signage/SignagePage' import TablesConfigPage from './pages/Management/TablesConfigPage' -import StaffPage from './pages/Management/StaffPage' +import StaffPage from './pages/staff/StaffPage' import SessionsPage from './pages/staff/SessionsPage' import ApprovalsPage from './pages/staff/ApprovalsPage' -import ManagementSchedulePage from './pages/Management/SchedulePage' +import ManagementSchedulePage from './pages/schedule/SchedulePage' import PrepZonesConfigPage from './pages/printing/PrepZonesPage' import PricingPage from './pages/pricing/PricingPage' diff --git a/manager_dashboard/src/pages/Management/SchedulePage.jsx b/manager_dashboard/src/pages/Management/SchedulePage.jsx deleted file mode 100644 index 3fbb1d4..0000000 --- a/manager_dashboard/src/pages/Management/SchedulePage.jsx +++ /dev/null @@ -1 +0,0 @@ -export { default } from '../SchedulePage' diff --git a/manager_dashboard/src/pages/Management/StaffPage.jsx b/manager_dashboard/src/pages/Management/StaffPage.jsx deleted file mode 100644 index 381d01c..0000000 --- a/manager_dashboard/src/pages/Management/StaffPage.jsx +++ /dev/null @@ -1,9 +0,0 @@ -import StaffTab from '../StaffTab' - -export default function StaffPage() { - return ( -
- -
- ) -} diff --git a/manager_dashboard/src/pages/SchedulePage.jsx b/manager_dashboard/src/pages/SchedulePage.jsx deleted file mode 100644 index 161f607..0000000 --- a/manager_dashboard/src/pages/SchedulePage.jsx +++ /dev/null @@ -1,819 +0,0 @@ -import { useState, useMemo } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import toast from 'react-hot-toast' -import client from '../api/client' - -// ── Constants ───────────────────────────────────────────────────────────────── - -const SCHED_STORAGE_KEY = 'xenia_schedule_settings_v1' -const SCHED_DEFAULTS = { - viewMode: 'bywaiter', - firstDayMonday: true, - firstHour: 6, - autoStartWorkday: false, - autoCloseWorkday: false, - autoCloseShiftsOnWorkday: false, - autoStartStaffShift: false, - autoCloseStaffShift: false, - workdayStart: '08:00', - workdayEnd: '23:00', -} - -function loadSchedSettings() { - try { return { ...SCHED_DEFAULTS, ...JSON.parse(localStorage.getItem(SCHED_STORAGE_KEY) || '{}') } } - catch { return { ...SCHED_DEFAULTS } } -} -function saveSchedSettings(s) { - localStorage.setItem(SCHED_STORAGE_KEY, JSON.stringify(s)) -} - -// ── Helpers ─────────────────────────────────────────────────────────────────── - -// Index 0=Sun, 1=Mon … 6=Sat (matches Date.getDay()) -const DAY_LABELS_BY_DOW = ['Κυρ', 'Δευ', 'Τρί', 'Τετ', 'Πέμ', 'Παρ', 'Σάβ'] - -function fmt(n) { - if (n == null) return '—' - return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €' -} - -function weekAnchorFor(d, firstDayMonday) { - const day = new Date(d) - const dow = day.getDay() // 0=Sun - if (firstDayMonday) { - const diff = dow === 0 ? -6 : 1 - dow - day.setDate(day.getDate() + diff) - } else { - day.setDate(day.getDate() - dow) - } - day.setHours(0, 0, 0, 0) - return day -} - -function addDays(d, n) { - const r = new Date(d) - r.setDate(r.getDate() + n) - return r -} - -function toLocalDateStr(d) { - const y = d.getFullYear() - const m = String(d.getMonth() + 1).padStart(2, '0') - const day = String(d.getDate()).padStart(2, '0') - return `${y}-${m}-${day}` -} - -function fmtShortDate(iso) { - if (!iso) return '' - const d = new Date(iso + 'T00:00:00') - return d.toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit' }) -} - -function fmtTime(t) { - if (!t) return '—' - return t.slice(0, 5) -} - -function timeToMinutes(t) { - if (!t) return 0 - const [h, m] = t.split(':').map(Number) - return h * 60 + m -} - -function getInitials(name) { - if (!name) return '?' - return name.split(' ').map(p => p[0]).join('').toUpperCase().slice(0, 2) -} - -function timesOverlap(s1, e1, s2, e2) { - const a = timeToMinutes(s1), b = timeToMinutes(e1) - const c = timeToMinutes(s2), d = timeToMinutes(e2) - const bAdj = b <= a ? b + 1440 : b - const dAdj = d <= c ? d + 1440 : d - return a < dAdj && c < bAdj -} - -// ── TripleSwitch ────────────────────────────────────────────────────────────── - -function TripleSwitch({ value, onChange, options }) { - return ( -
- {options.map(opt => ( - - ))} -
- ) -} - -// ── ShiftModal (add + edit) ─────────────────────────────────────────────────── - -function ShiftModal({ date, waiters, existingShifts, editShift, onClose, onSave, isPending }) { - const [userId, setUserId] = useState(editShift?.user_id ?? (waiters[0]?.id ?? '')) - const [start, setStart] = useState(editShift?.start_time ?? '09:00') - const [end, setEnd] = useState(editShift?.end_time ?? '17:00') - const [notes, setNotes] = useState(editShift?.notes ?? '') - - const isEdit = !!editShift - - const conflict = useMemo(() => { - if (!userId || !start || !end) return null - const uid = Number(userId) - const others = (existingShifts || []).filter(s => { - const ds = typeof s.scheduled_date === 'string' ? s.scheduled_date : toLocalDateStr(new Date(s.scheduled_date)) - return s.user_id === uid && ds === date && (!isEdit || s.id !== editShift.id) - }) - return others.find(s => timesOverlap(start, end, s.start_time, s.end_time)) || null - }, [userId, start, end, date, existingShifts, isEdit, editShift]) - - const canSave = userId && start && end && !conflict - - const inputStyle = { - width: '100%', padding: '7px 10px', border: '1px solid #e5e7eb', - borderRadius: 7, fontSize: 13, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box', - } - - return ( -
-
-
-
-
{isEdit ? 'Επεξεργασία Βάρδιας' : 'Νέα Βάρδια'}
-
{fmtShortDate(date)}
-
- -
-
-
- - -
-
-
- - setStart(e.target.value)} /> -
-
- - setEnd(e.target.value)} /> -
-
- {conflict && ( -
- Επικάλυψη με βάρδια {fmtTime(conflict.start_time)}–{fmtTime(conflict.end_time)} -
- )} -
- - setNotes(e.target.value)} placeholder="π.χ. Μόνο βράδυ" /> -
-
-
- - -
-
-
- ) -} - -// ── Schedule Settings Modal ─────────────────────────────────────────────────── - -function ToggleRow({ label, description, checked, onChange, indent }) { - return ( -
-
-
{label}
- {description &&
{description}
} -
- -
- ) -} - -function ScheduleSettingsModal({ settings, onChange, onClose }) { - const [s, setS] = useState({ ...settings }) - function set(key, val) { setS(prev => ({ ...prev, [key]: val })) } - - const inputStyle = { padding: '5px 10px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, fontFamily: 'inherit', outline: 'none' } - const sectionLabel = (t) => ( -
{t}
- ) - - return ( -
-
-
-
Ρυθμίσεις Προγράμματος
- -
-
- {sectionLabel('Εμφάνιση')} -
-
Πρώτη μέρα εβδομάδας
-
- {[{ v: true, l: 'Δευ' }, { v: false, l: 'Κυρ' }].map(opt => ( - - ))} -
-
-
-
-
Πρώτη ώρα ημέρας
-
Αρχή ωρολογιακής προβολής (Ωριαία / Εργάσιμη)
-
- -
-
-
-
Ώρες λειτουργίας
-
Για προβολή Εργάσιμης Ημέρας
-
-
- set('workdayStart', e.target.value)} style={{ ...inputStyle, width: 90 }} /> - – - set('workdayEnd', e.target.value)} style={{ ...inputStyle, width: 90 }} /> -
-
- - {sectionLabel('Αυτόματο Πρόγραμμα Καταστήματος')} - set('autoStartWorkday', v)} /> - set('autoCloseWorkday', v)} /> - {s.autoCloseWorkday && ( - set('autoCloseShiftsOnWorkday', v)} indent /> - )} - set('autoStartStaffShift', v)} /> - set('autoCloseStaffShift', v)} /> -
-
- - -
-
-
- ) -} - -// ── BY WAITER helpers ───────────────────────────────────────────────────────── - -function TimeBar({ shifts }) { - if (!shifts || shifts.length === 0) return null - const MINS = 24 * 60 - return ( -
- {shifts.map((s, i) => { - const sm = timeToMinutes(s.start_time) - const em = timeToMinutes(s.end_time) - const dur = em > sm ? em - sm : em + MINS - sm - const left = (sm / MINS) * 100 - const width = (dur / MINS) * 100 - const hasActual = s.actual_shifts?.length > 0 - return ( -
- ) - })} -
- ) -} - -function ShiftCard({ shift, actual, onEdit, onDelete }) { - const hasActual = actual && actual.length > 0 - const isActive = actual?.some(a => a.is_active) - return ( -
-
- - {fmtTime(shift.start_time)}–{fmtTime(shift.end_time)} - -
- {shift.estimated_pay != null && ( - {fmt(shift.estimated_pay)} - )} - -
-
- {shift.notes && ( -
- {shift.notes} -
- )} - {hasActual ? ( - actual.map(a => ( -
- ✓ {a.started_at ? new Date(a.started_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) : '—'} - {a.ended_at ? ` – ${new Date(a.ended_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}` : isActive ? ' (ενεργή)' : ''} -
- )) - ) : ( -
Δεν ξεκίνησε
- )} -
- ) -} - -// ── BY WAITER view ──────────────────────────────────────────────────────────── - -function ByWaiterView({ days, waiters, grid, scheduled, onAddShift, onEditShift, onDeleteShift }) { - return ( -
- - - - - {days.map(d => { - const isToday = toLocalDateStr(new Date()) === d.dateStr - return ( - - ) - })} - - - - {waiters.length === 0 && ( - - )} - {waiters.map((w, rowIdx) => { - const rowBg = rowIdx % 2 === 0 ? 'white' : '#fafafa' - return ( - - - {days.map(d => { - const cell = grid[w.id]?.[d.dateStr] - const cellShifts = cell?.scheduled || [] - const dayShiftsForWaiter = scheduled.filter(s => { - const ds = typeof s.scheduled_date === 'string' ? s.scheduled_date : toLocalDateStr(new Date(s.scheduled_date)) - return s.user_id === w.id && ds === d.dateStr - }) - - return ( - - ) - })} - - ) - })} - -
Σερβιτόρος -
{d.label}
-
{fmtShortDate(d.dateStr)}
-
Δεν υπάρχουν ενεργοί σερβιτόροι.
-
{w.name}
- {w.hourly_rate != null &&
{fmt(w.hourly_rate)}/ώρα
} -
-
- {cellShifts.map(s => ( - onEditShift(s, d.dateStr)} - onDelete={() => onDeleteShift(s.id)} - /> - ))} - - {cellShifts.length > 0 && } -
-
-
- ) -} - -// ── HOURLY / WORKDAY view ───────────────────────────────────────────────────── - -function HourlyView({ days, waiters, scheduled, firstHour, workdayBounds, onAddShift }) { - const [tooltip, setTooltip] = useState(null) - - const HOUR_HEIGHT = 54 - const TOTAL_HOURS = 24 - - const shiftsMap = useMemo(() => { - const m = {} - for (const s of scheduled) { - const ds = typeof s.scheduled_date === 'string' ? s.scheduled_date : toLocalDateStr(new Date(s.scheduled_date)) - if (!m[ds]) m[ds] = [] - m[ds].push(s) - } - return m - }, [scheduled]) - - const hours = useMemo(() => Array.from({ length: TOTAL_HOURS }, (_, i) => (firstHour + i) % 24), [firstHour]) - - function minuteToY(rawMinute) { - const adj = ((rawMinute - firstHour * 60) + 24 * 60) % (24 * 60) - return (adj / 60) * HOUR_HEIGHT - } - - const BAR_W = 28 - const BAR_GAP = 3 - - return ( -
-
- {/* Time axis */} -
- {hours.map((h, i) => ( -
- {String(h).padStart(2, '0')}:00 -
- ))} -
- - {/* Day columns */} -
- {days.map((d, di) => { - const isToday = toLocalDateStr(new Date()) === d.dateStr - const dayShifts = shiftsMap[d.dateStr] || [] - // Only waiters with shifts on this day - const activeWaiters = waiters.filter(w => dayShifts.some(s => s.user_id === w.id)) - const totalBarsW = activeWaiters.length * BAR_W + Math.max(0, activeWaiters.length - 1) * BAR_GAP - - return ( -
- {/* Day header */} -
-
{d.label}
-
{fmtShortDate(d.dateStr)}
-
- - {/* Timeline */} -
onAddShift(d.dateStr, null)} - > - {/* Hour grid lines */} - {hours.map((h, i) => { - const inWorkday = workdayBounds - ? (workdayBounds[0] <= workdayBounds[1] - ? h >= workdayBounds[0] && h < workdayBounds[1] - : h >= workdayBounds[0] || h < workdayBounds[1]) - : false - return ( -
- ) - })} - - {/* Midnight marker */} - {firstHour !== 0 && ( -
- 00:00 -
- )} - - {/* Waiter bars — only active waiters, centered */} - {activeWaiters.map((w, wi) => { - const wShifts = dayShifts.filter(s => s.user_id === w.id) - // Center the group of bars within the column - const offsetX = `calc(50% - ${totalBarsW / 2}px + ${wi * (BAR_W + BAR_GAP)}px)` - return wShifts.map(s => { - const sm = timeToMinutes(s.start_time) - const em = timeToMinutes(s.end_time) - const dur = em > sm ? em - sm : em + 1440 - sm - const top = minuteToY(sm) - const height = Math.max((dur / 60) * HOUR_HEIGHT, 10) - const hasActual = s.actual_shifts?.length > 0 - const initials = getInitials(w.name) - const fitsText = height > 20 - return ( -
{ - const rect = e.currentTarget.getBoundingClientRect() - setTooltip({ shift: s, waiter: w, x: rect.right + 8, y: rect.top }) - }} - onMouseLeave={() => setTooltip(null)} - onClick={e => e.stopPropagation()} - > - {fitsText ? initials : null} -
- ) - }) - })} -
-
- ) - })} -
-
- - {/* Tooltip */} - {tooltip && ( -
-
{tooltip.waiter?.name}
-
{fmtTime(tooltip.shift.start_time)} – {fmtTime(tooltip.shift.end_time)}
- {tooltip.shift.notes &&
{tooltip.shift.notes}
} -
- )} -
- ) -} - -// ── Main page ───────────────────────────────────────────────────────────────── - -export default function SchedulePage() { - const qc = useQueryClient() - const [schedSettings, setSchedSettings] = useState(loadSchedSettings) - const [weekAnchor, setWeekAnchor] = useState(() => weekAnchorFor(new Date(), loadSchedSettings().firstDayMonday)) - const [addModal, setAddModal] = useState(null) - const [editModal, setEditModal] = useState(null) - const [showSettings, setShowSettings] = useState(false) - - function updateSettings(s) { - setSchedSettings(s) - saveSchedSettings(s) - if (s.firstDayMonday !== schedSettings.firstDayMonday) { - setWeekAnchor(weekAnchorFor(weekAnchor, s.firstDayMonday)) - } - } - - const weekStartStr = toLocalDateStr(weekAnchor) - const weekEndStr = toLocalDateStr(addDays(weekAnchor, 6)) - - const { data, isLoading } = useQuery({ - queryKey: ['schedule-week', weekStartStr], - queryFn: () => client.get('/api/schedule/week', { params: { week_start: weekStartStr } }).then(r => r.data), - staleTime: 30_000, - }) - - const addShift = useMutation({ - mutationFn: (body) => client.post('/api/schedule/', body), - onSuccess: () => { qc.invalidateQueries({ queryKey: ['schedule-week'] }); setAddModal(null); toast.success('Βάρδια προστέθηκε') }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - - const updateShift = useMutation({ - mutationFn: ({ id, ...body }) => client.put(`/api/schedule/${id}`, body), - onSuccess: () => { qc.invalidateQueries({ queryKey: ['schedule-week'] }); setEditModal(null); toast.success('Βάρδια αποθηκεύτηκε') }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - - const deleteShift = useMutation({ - mutationFn: (id) => client.delete(`/api/schedule/${id}`), - onSuccess: () => { qc.invalidateQueries({ queryKey: ['schedule-week'] }); toast.success('Βάρδια διαγράφηκε') }, - onError: () => toast.error('Σφάλμα διαγραφής'), - }) - - const waiters = data?.waiters ?? [] - const scheduled = data?.scheduled ?? [] - const totalPay = data?.total_estimated_pay ?? 0 - - const days = useMemo(() => Array.from({ length: 7 }, (_, i) => { - const d = addDays(weekAnchor, i) - return { date: d, dateStr: toLocalDateStr(d), label: DAY_LABELS_BY_DOW[d.getDay()] } - }), [weekAnchor]) - - const grid = useMemo(() => { - const g = {} - for (const s of scheduled) { - if (!g[s.user_id]) g[s.user_id] = {} - const ds = typeof s.scheduled_date === 'string' ? s.scheduled_date : toLocalDateStr(new Date(s.scheduled_date)) - if (!g[s.user_id][ds]) g[s.user_id][ds] = { scheduled: [], actual: [] } - g[s.user_id][ds].scheduled.push(s) - g[s.user_id][ds].actual.push(...(s.actual_shifts || [])) - } - return g - }, [scheduled]) - - function handleSaveShift(body) { - const { _editId, ...rest } = body - if (_editId) { - updateShift.mutate({ id: _editId, ...rest }) - } else { - addShift.mutate(rest) - } - } - - function handleDeleteShift(id) { - if (window.confirm('Διαγραφή βάρδιας;')) deleteShift.mutate(id) - } - - const workdayBounds = useMemo(() => { - if (schedSettings.viewMode !== 'workday') return null - return [ - parseInt(schedSettings.workdayStart.split(':')[0], 10), - parseInt(schedSettings.workdayEnd.split(':')[0], 10), - ] - }, [schedSettings.viewMode, schedSettings.workdayStart, schedSettings.workdayEnd]) - - const btnStyle = { - padding: '6px 14px', border: '1px solid #e5e7eb', background: 'white', - borderRadius: 7, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit', - } - - return ( -
- {/* Header */} -
-
-
Πρόγραμμα Εβδομάδας
-
- {fmtShortDate(weekStartStr)} – {fmtShortDate(weekEndStr)} - {totalPay > 0 && Εκτ. κόστος: {fmt(totalPay)}} -
-
-
- {/* Settings + view switch group */} -
- - updateSettings({ ...schedSettings, viewMode: v })} - options={[ - { value: 'bywaiter', label: 'ΑΝΑ ΣΕΡΒΙΤΌΡΟ' }, - { value: 'hourly', label: 'ΩΡΙΑΙΑ' }, - { value: 'workday', label: 'ΕΡΓΆΣΙΜΗ' }, - ]} - /> -
- {/* Week navigation group */} -
- - - -
-
-
- - {isLoading && ( -
Φόρτωση…
- )} - - {!isLoading && schedSettings.viewMode === 'bywaiter' && ( - setAddModal({ date, userId })} - onEditShift={(shift, date) => setEditModal({ shift, date })} - onDeleteShift={handleDeleteShift} - /> - )} - - {!isLoading && (schedSettings.viewMode === 'hourly' || schedSettings.viewMode === 'workday') && ( - setAddModal({ date, userId })} - /> - )} - - {/* Legend */} - {!isLoading && schedSettings.viewMode === 'bywaiter' && ( -
- {[ - { color: '#bfdbfe', bg: '#eff6ff', label: 'Προγρ. (δεν ξεκίνησε)' }, - { color: '#86efac', bg: '#f0fdf4', label: 'Προγρ. + Πραγματική' }, - ].map(l => ( -
-
- {l.label} -
- ))} -
-
- Μπάρα 24ω (μπλε=σχεδ., πράσ.=πραγμ.) -
-
- )} - - {addModal && ( - w.id === addModal.userId).concat(waiters.filter(w => w.id !== addModal.userId)) - : waiters} - existingShifts={scheduled} - editShift={null} - onClose={() => setAddModal(null)} - isPending={addShift.isPending} - onSave={handleSaveShift} - /> - )} - - {editModal && ( - setEditModal(null)} - isPending={updateShift.isPending} - onSave={handleSaveShift} - /> - )} - - {showSettings && ( - setShowSettings(false)} - /> - )} -
- ) -} diff --git a/manager_dashboard/src/pages/StaffTab.jsx b/manager_dashboard/src/pages/StaffTab.jsx deleted file mode 100644 index 1fa45df..0000000 --- a/manager_dashboard/src/pages/StaffTab.jsx +++ /dev/null @@ -1,925 +0,0 @@ -import { useState, useRef, useEffect } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import toast from 'react-hot-toast' -import client from '../api/client' -import { ConfirmModal } from '../ui/Modal' -import Button from '../ui/Button' -import { useTranslation } from '@xenia/i18n' -import PermissionEditor from './staff/PermissionEditor' -import { differsFromRole } from './staff/permissionsLogic' - -// ── Role definitions (mirrors backend roles.py) ─────────────────────────────── -export const ALL_ROLES = [ - { value: 'superadmin', label: 'Superadmin', color: '#7c3aed' }, - { value: 'owner', label: 'Ιδιοκτήτης', color: '#0f172a' }, - { value: 'store_manager', label: 'Διαχ. Καταστήματος', color: '#0369a1' }, - { value: 'staff_manager', label: 'Διαχ. Προσωπικού', color: '#0891b2' }, - { value: 'chef', label: 'Σεφ', color: '#b45309' }, - { value: 'assistant_chef', label: 'Βοηθός Σεφ', color: '#d97706' }, - { value: 'barista', label: 'Barista', color: '#7c2d12' }, - { value: 'barman', label: 'Barman / Barwoman', color: '#92400e' }, - { value: 'waiter', label: 'Σερβιτόρος', color: '#166534' }, - { value: 'assistant_waiter', label: 'Βοηθός Σερβιτόρου', color: '#15803d' }, - { value: 'custom', label: 'Προσαρμοσμένος', color: '#6b7280' }, -] - -const ROLE_MAP = Object.fromEntries(ALL_ROLES.map(r => [r.value, r])) - -// ── Avatar helpers ───────────────────────────────────────────────────────────── -function avatarColor(name) { - const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775'] - let h = 0 - for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0 - return palette[h % palette.length] -} - -function WaiterAvatar({ waiter, size = 40 }) { - const displayName = waiter.full_name || waiter.nickname || waiter.username - if (waiter.avatar_url) { - return ( - {displayName} - ) - } - const parts = displayName.trim().split(' ') - const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase() - return ( -
{initials}
- ) -} - -// ── PIN input ────────────────────────────────────────────────────────────────── -const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫'] - -function PinInput({ value, onChange }) { - function press(d) { - if (d === '⌫') { onChange(value.slice(0, -1)); return } - if (d === '' || value.length >= 6) return - onChange(value + d) - } - return ( -
-
- {Array.from({ length: 4 }).map((_, i) => ( -
- ))} -
-
- {DIGITS.map((d, i) => ( - - ))} -
-
- ) -} - -// ── Actions dropdown ─────────────────────────────────────────────────────────── -function ActionsMenu({ member, onEdit, onZones, onResetPin, onBlock, onDelete, onPermissions, permissionsLabel, isSuperadmin }) { - const [open, setOpen] = useState(false) - const ref = useRef(null) - - useEffect(() => { - if (!open) return - function handler(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false) } - document.addEventListener('mousedown', handler) - return () => document.removeEventListener('mousedown', handler) - }, [open]) - - const items = [ - { label: 'Επεξεργασία', icon: editIcon, onClick: onEdit }, - { label: 'Πρόσβαση σε Ζώνες', icon: zonesIcon, onClick: onZones }, - { label: 'Επαναφορά PIN', icon: pinIcon, onClick: onResetPin }, - { label: permissionsLabel, icon: resetIcon, onClick: onPermissions }, - !isSuperadmin && { label: member.is_active ? 'Μπλοκάρισμα' : 'Ξεμπλοκάρισμα', icon: blockIcon, onClick: onBlock, color: member.is_active ? '#f97316' : '#22c55e' }, - !isSuperadmin && { label: 'Διαγραφή', icon: trashIcon, onClick: onDelete, color: '#ef4444' }, - ].filter(Boolean) - - return ( -
- - {open && ( -
- {items.map((item, i) => ( - - ))} -
- )} -
- ) -} - -// ── ZoneModal ────────────────────────────────────────────────────────────────── -function ZoneModal({ member, groups, onClose }) { - const qc = useQueryClient() - const hasAllZones = member.zone_assignments.some(z => z.group_id === null) - const assignedIds = new Set(member.zone_assignments.map(z => z.group_id).filter(id => id !== null)) - const [allZones, setAllZones] = useState(hasAllZones) - const [selected, setSelected] = useState(new Set(assignedIds)) - - const saveZones = useMutation({ - mutationFn: (body) => client.put(`/api/waiters/${member.id}/zones`, body), - onSuccess: () => { toast.success('Zones ενημερώθηκαν'); qc.invalidateQueries({ queryKey: ['staff'] }); onClose() }, - onError: () => toast.error('Σφάλμα'), - }) - - function toggleGroup(gid) { - setSelected(prev => { const next = new Set(prev); next.has(gid) ? next.delete(gid) : next.add(gid); return next }) - } - - return ( -
-
-

Ζώνες — {member.username}

- - {!allZones && ( -
- {groups.length === 0 &&

Δεν υπάρχουν ομάδες τραπεζιών.

} - {groups.map(g => ( - - ))} -
- )} - {!allZones && selected.size === 0 && ( -

Χωρίς επιλογή ο σερβιτόρος δεν βλέπει κανένα τραπέζι.

- )} -
- - -
-
-
- ) -} - -// ── Shared form primitives ───────────────────────────────────────────────────── -function FormField({ label, required, desc, children }) { - return ( -
- - {children} - {desc &&

{desc}

} -
- ) -} - -function SectionLabel({ children }) { - return ( -
- {children} -
- ) -} - -function InfoBlock({ label, value, valueColor }) { - return ( -
- {label} - {value || '—'} -
- ) -} - -const inputStyle = { - width: '100%', padding: '7px 10px', border: '1px solid #e5e7eb', borderRadius: 7, - fontSize: 13, outline: 'none', color: '#111827', background: '#fff', boxSizing: 'border-box', -} - -const EMPTY_FORM = { - username: '', full_name: '', nickname: '', mobile_phone: '', email: '', note: '', - role: 'waiter', pin: '', hourly_rate: '', -} - -// ── Main page ────────────────────────────────────────────────────────────────── -export default function StaffPage() { - const qc = useQueryClient() - const [addModal, setAddModal] = useState(false) - const [pinModal, setPinModal] = useState(null) - const [zoneModal, setZoneModal] = useState(null) - const [confirmDelete, setConfirmDelete] = useState(null) - const [newPin, setNewPin] = useState('') - const [newForm, setNewForm] = useState(EMPTY_FORM) - const [newAvatarFile, setNewAvatarFile] = useState(null) - const [newAvatarPreview, setNewAvatarPreview] = useState(null) - const [editModal, setEditModal] = useState(null) - const [editForm, setEditForm] = useState({ username: '', full_name: '', nickname: '', mobile_phone: '', email: '', note: '', role: 'waiter', hourly_rate: '' }) - const [filterRole, setFilterRole] = useState('all') - const [permEditor, setPermEditor] = useState(null) - const { t } = useTranslation('manager') - const avatarInputRef = useRef(null) - const newAvatarInputRef = useRef(null) - - const { data: staff = [], isLoading } = useQuery({ - queryKey: ['staff'], - queryFn: () => client.get('/api/waiters/').then(r => r.data), - }) - const { data: catalog } = useQuery({ - queryKey: ['permission-catalog'], - queryFn: () => client.get('/api/waiters/permission-catalog').then(r => r.data), - }) - const { data: groups = [] } = useQuery({ - queryKey: ['table-groups'], - queryFn: () => client.get('/api/tables/groups').then(r => r.data), - }) - - const invalidate = () => qc.invalidateQueries({ queryKey: ['staff'] }) - - const createStaff = useMutation({ - mutationFn: async (body) => { - const res = await client.post('/api/waiters/', body) - if (newAvatarFile) { - const fd = new FormData() - fd.append('file', newAvatarFile) - await client.post(`/api/waiters/${res.data.id}/avatar`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }) - } - return res - }, - onSuccess: () => { - toast.success('Εργαζόμενος δημιουργήθηκε') - setAddModal(false); setNewForm(EMPTY_FORM); setNewAvatarFile(null); setNewAvatarPreview(null) - invalidate() - }, - onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'), - }) - - const updateStaff = useMutation({ - mutationFn: ({ id, ...body }) => client.put(`/api/waiters/${id}`, body), - onSuccess: () => { toast.success('Στοιχεία ενημερώθηκαν'); setEditModal(null); invalidate() }, - onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'), - }) - - const uploadAvatar = useMutation({ - mutationFn: ({ id, file }) => { - const fd = new FormData(); fd.append('file', file) - return client.post(`/api/waiters/${id}/avatar`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }) - }, - onSuccess: (res) => { toast.success('Avatar ανέβηκε'); setEditModal(res.data); invalidate() }, - onError: () => toast.error('Σφάλμα μεταφόρτωσης'), - }) - - const deleteAvatar = useMutation({ - mutationFn: (id) => client.delete(`/api/waiters/${id}/avatar`), - onSuccess: (res) => { toast.success('Avatar αφαιρέθηκε'); setEditModal(res.data); invalidate() }, - onError: () => toast.error('Σφάλμα'), - }) - - const toggleBlock = useMutation({ - mutationFn: (id) => client.put(`/api/waiters/${id}/block`), - onSuccess: () => invalidate(), - onError: () => toast.error('Σφάλμα'), - }) - - const resetPin = useMutation({ - mutationFn: ({ id, pin }) => client.put(`/api/waiters/${id}/reset-pin?pin=${encodeURIComponent(pin)}`), - onSuccess: () => { toast.success('PIN ανανεώθηκε'); setPinModal(null); setNewPin('') }, - onError: () => toast.error('Σφάλμα'), - }) - - const deleteStaff = useMutation({ - mutationFn: (id) => client.delete(`/api/waiters/${id}`), - onSuccess: () => { toast.success('Διαγράφηκε'); setConfirmDelete(null); invalidate() }, - onError: () => toast.error('Σφάλμα'), - }) - - if (isLoading) return
Φόρτωση…
- - function openEdit(m) { - setEditModal(m) - setEditForm({ - username: m.username || '', full_name: m.full_name || '', - nickname: m.nickname || '', mobile_phone: m.mobile_phone || '', - email: m.email || '', note: m.note || '', - role: m.role || 'waiter', hourly_rate: m.hourly_rate ?? '', - }) - } - - // Group counts for header badges - const groupedCounts = staff.reduce((acc, m) => { - const g = m.role in { superadmin: 1, owner: 1, store_manager: 1, staff_manager: 1 } ? 'Διοίκηση' - : m.role in { chef: 1, assistant_chef: 1, barista: 1, barman: 1 } ? 'Κουζίνα / Bar' - : 'Σέρβις' - acc[g] = (acc[g] || 0) + 1 - return acc - }, {}) - - const filtered = filterRole === 'all' ? staff : staff.filter(m => m.role === filterRole) - - return ( -
- {/* ── Header bar ── */} -
-
- {Object.entries(groupedCounts).map(([group, count]) => ( - - {count} {group} - - ))} -
- - {/* Role filter */} - - - -
- - {/* ── Scrollable table area ── */} -
- {filtered.length === 0 ? ( -

- Δεν βρέθηκαν εργαζόμενοι. -

- ) : ( - - - - - - - - - {/* Column label row */} - - - - - - - - - {filtered.map((member, rowIdx) => { - const role = ROLE_MAP[member.role] - const isSuperadmin = member.role === 'superadmin' - const rowBg = rowIdx % 2 === 0 ? '#fff' : '#fafafa' - return ( - e.currentTarget.style.background = '#f0f9ff'} - onMouseLeave={e => e.currentTarget.style.background = rowBg} - > - {/* Identity cell */} - - - {/* Status cell */} - - - {/* Permissions (2.6e): count + "custom" when they differ from the role */} - - - {/* Actions cell */} - - - ) - })} - -
- Εργαζόμενος - Κατάσταση - {t('permissions.column')} - - Ενέργειες -
-
- -
-
- {member.full_name || member.username} -
-
- - {role?.label || member.role} - - {member.nickname && ( - - {member.nickname} - - )} -
-
-
-
- - {member.is_active ? 'Ενεργός' : 'Μπλοκαρ.'} - - - - - openEdit(member)} - onZones={() => setZoneModal(member)} - onResetPin={() => setPinModal(member.id)} - onBlock={() => toggleBlock.mutate(member.id)} - onDelete={() => setConfirmDelete(member.id)} - onPermissions={() => setPermEditor(member)} - permissionsLabel={t('permissions.open')} - /> -
- )} -
- - {/* ── Modals ── */} - {addModal && ( - { setAddModal(false); setNewForm(EMPTY_FORM); setNewAvatarFile(null); setNewAvatarPreview(null) }} - onSubmit={() => createStaff.mutate({ - username: newForm.username, full_name: newForm.full_name || null, - nickname: newForm.nickname || null, mobile_phone: newForm.mobile_phone || null, - email: newForm.email || null, note: newForm.note || null, - pin: newForm.pin, role: newForm.role, is_active: true, - hourly_rate: newForm.hourly_rate !== '' ? parseFloat(newForm.hourly_rate) : null, - })} - /> - )} - - {editModal && ( - setEditModal(null)} - onSubmit={() => updateStaff.mutate({ - id: editModal.id, - username: editForm.username.trim() || undefined, - full_name: editForm.full_name || null, nickname: editForm.nickname || null, - mobile_phone: editForm.mobile_phone || null, email: editForm.email || null, - note: editForm.note || null, role: editForm.role, - hourly_rate: editForm.hourly_rate !== '' ? parseFloat(editForm.hourly_rate) : null, - })} - onUploadAvatar={file => uploadAvatar.mutate({ id: editModal.id, file })} - onDeleteAvatar={() => deleteAvatar.mutate(editModal.id)} - /> - )} - - {pinModal !== null && ( -
-
-

Επαναφορά PIN — {staff.find(m => m.id === pinModal)?.username}

- -
- - -
-
-
- )} - - {confirmDelete !== null && ( - deleteStaff.mutate(confirmDelete)} - onCancel={() => setConfirmDelete(null)} - /> - )} - - {permEditor && setPermEditor(null)} />} - - {zoneModal && ( - setZoneModal(null)} /> - )} -
- ) -} - -const thBase = { - fontSize: 11, fontWeight: 600, color: '#6b7280', - padding: '6px 4px', background: '#f9fafb', - position: 'sticky', top: 0, zIndex: 1, -} - -// ── SVG icons ───────────────────────────────────────────────────────────────── -const editIcon = ( - - - -) -const zonesIcon = ( - - - -) -const pinIcon = ( - - - -) -const resetIcon = ( - - - -) -const blockIcon = ( - - - -) -const trashIcon = ( - - - -) - -// ── Add Staff Modal ──────────────────────────────────────────────────────────── -function AddStaffModal({ form, setForm, avatarFile, avatarPreview, setAvatarFile, setAvatarPreview, avatarInputRef, isPending, onClose, onSubmit }) { - const f = (field, val) => setForm(p => ({ ...p, [field]: val })) - const canSubmit = form.username.trim() && form.full_name.trim() && form.nickname.trim() && form.pin.length >= 4 - - return ( -
-
- {/* Header */} -
- {avatarPreview - ? preview - :
- 👤 -
- } -
-

Νέος εργαζόμενος

-

Συμπληρώστε τα στοιχεία του εργαζόμενου

-
-
- { - const file = e.target.files?.[0] - if (file) { setAvatarFile(file); setAvatarPreview(URL.createObjectURL(file)) } - e.target.value = '' - }} /> - - {avatarPreview && ( - - )} -
-
- - {/* Body — three columns */} -
- {/* Col 1: Identity + Account */} -
-
- Ταυτότητα -
- - f('full_name', e.target.value)} autoFocus /> - - - f('nickname', e.target.value)} /> - -
-
-
- Λογαριασμός -
- - f('username', e.target.value)} /> - - - - -
-
-
- - {/* Col 2: Contact */} -
-
- Επικοινωνία -
- - f('mobile_phone', e.target.value)} /> - - - f('email', e.target.value)} /> - - -