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.role_invalid": (400, "There is no role {role}."),
"staff.avatar_type": (400, "The photo must be a picture file."), "staff.avatar_type": (400, "The photo must be a picture file."),
"staff.assignment_exists": (400, "That assignment already exists."), "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."), "staff.assignment_not_found": (404, "Assignment not found."),
"schedule.shift_not_found": (404, "Scheduled shift 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."), "setup.done": (409, "Setup is already done: a manager account exists."),
"shift.already_active": (400, "This person already has a shift going."), "shift.already_active": (400, "This person already has a shift going."),
"shift.start_needs_manager": (403, "Starting the shift needs a manager's approval."), "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 core.timeutil import to_venue, venue_day_window, venue_date
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
from fastapi import APIRouter, Depends, status, Query from fastapi import APIRouter, Depends, status, Query
@@ -10,10 +9,40 @@ from models.schedule import ScheduledShift
from models.shift import WaiterShift from models.shift import WaiterShift
from models.user import User from models.user import User
from schemas.schedule import ScheduledShiftCreate, ScheduledShiftUpdate, ScheduledShiftOut 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 from core.errors import XeniaError
import re
router = APIRouter() 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: def _duration_hours(start: str, end: str) -> float:
@@ -71,16 +100,18 @@ def list_schedule(
def create_scheduled_shift( def create_scheduled_shift(
body: ScheduledShiftCreate, body: ScheduledShiftCreate,
db: Session = Depends(get_db), 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() target = db.query(User).filter(User.id == body.user_id, User.is_active == True).first()
if not target: if not target:
raise XeniaError("staff.not_found") 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( s = ScheduledShift(
user_id=body.user_id, user_id=body.user_id,
scheduled_date=body.scheduled_date, scheduled_date=body.scheduled_date,
start_time=body.start_time, start_time=start,
end_time=body.end_time, end_time=end,
notes=body.notes, notes=body.notes,
created_by_id=user.id, created_by_id=user.id,
) )
@@ -95,12 +126,19 @@ def update_scheduled_shift(
shift_id: int, shift_id: int,
body: ScheduledShiftUpdate, body: ScheduledShiftUpdate,
db: Session = Depends(get_db), 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() s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
if not s: if not s:
raise XeniaError("schedule.shift_not_found") 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) setattr(s, field, value)
db.commit() db.commit()
db.refresh(s) db.refresh(s)
@@ -111,7 +149,7 @@ def update_scheduled_shift(
def delete_scheduled_shift( def delete_scheduled_shift(
shift_id: int, shift_id: int,
db: Session = Depends(get_db), 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() s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
if not s: if not s:
@@ -145,7 +183,8 @@ def week_schedule(
WaiterShift.started_at < week_end_dt, WaiterShift.started_at < week_end_dt,
).all() ).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): def _dt(dt):
if not dt: if not dt:
@@ -184,7 +223,7 @@ def week_schedule(
"scheduled": scheduled_out, "scheduled": scheduled_out,
"total_estimated_pay": round(total_estimated_pay, 2), "total_estimated_pay": round(total_estimated_pay, 2),
"waiters": [ "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) 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") 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: def _guard_grant(acting_user: User, keys) -> None:
"""A non-superadmin may only give keys they hold themselves (no self-escalation via staff).""" """A non-superadmin may only give keys they hold themselves (no self-escalation via staff)."""
if acting_user.role == "superadmin": 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(): if db.query(User).filter(User.username == body.username).first():
raise XeniaError("staff.username_taken", status=400) 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( new_user = User(
username=body.username, username=body.username,
pin_hash=pin_hash, 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, role=body.role,
is_active=body.is_active, is_active=body.is_active,
full_name=body.full_name, 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: if body.language is not None:
body.language = normalize_language(body.language) or "" 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(): 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) setattr(target, field, value)
if target.language == "": if target.language == "":
target.language = None # "" means inherit target.language = None # "" means inherit
@@ -203,13 +231,40 @@ def update_staff(waiter_id: int, body: UserUpdate, db: Session = Depends(get_db)
return target return target
@router.put("/{waiter_id}/reset-pin") class PinBody(BaseModel):
def reset_pin(waiter_id: int, pin: str, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)): 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) target = _user_or_404(waiter_id, db)
_guard_superadmin_target(target, user) _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() 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") @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) @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)): 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) target = _user_or_404(waiter_id, db)
_guard_superadmin_target(target, user) _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.delete(target)
db.commit() db.commit()
+3
View File
@@ -21,6 +21,7 @@ class UserBase(BaseModel):
class UserCreate(UserBase): class UserCreate(UserBase):
pin: str pin: str
password: Optional[str] = None # 6.11: for the password sign-in mode (6+ characters)
class UserUpdate(BaseModel): class UserUpdate(BaseModel):
@@ -51,6 +52,7 @@ class UserOut(UserBase):
zone_assignments: List[WaiterZoneOut] = [] zone_assignments: List[WaiterZoneOut] = []
waiter_settings: Optional[str] = None # JSON blob — per-waiter settings + favorites waiter_settings: Optional[str] = None # JSON blob — per-waiter settings + favorites
permissions: List[str] = [] # permission keys (D-7); superadmin: [] = implicit all 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} model_config = {"from_attributes": True}
@@ -65,6 +67,7 @@ class UserOut(UserBase):
if name != "permissions"} if name != "permissions"}
data["zone_assignments"] = list(getattr(obj, "zone_assignments", None) or []) data["zone_assignments"] = list(getattr(obj, "zone_assignments", None) or [])
data["permissions"] = sorted(user_keys(obj)) 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",)} 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"
+2 -2
View File
@@ -33,10 +33,10 @@ import ProductsPage from './pages/products/ProductsPage'
import MediaPage from './pages/media/MediaPage' import MediaPage from './pages/media/MediaPage'
import SignagePage from './pages/signage/SignagePage' import SignagePage from './pages/signage/SignagePage'
import TablesConfigPage from './pages/Management/TablesConfigPage' 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 SessionsPage from './pages/staff/SessionsPage'
import ApprovalsPage from './pages/staff/ApprovalsPage' 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 PrepZonesConfigPage from './pages/printing/PrepZonesPage'
import PricingPage from './pages/pricing/PricingPage' import PricingPage from './pages/pricing/PricingPage'
@@ -1 +0,0 @@
export { default } from '../SchedulePage'
@@ -1,9 +0,0 @@
import StaffTab from '../StaffTab'
export default function StaffPage() {
return (
<div className="flex flex-col h-full min-h-0">
<StaffTab />
</div>
)
}
@@ -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 (
<div style={{ display: 'flex', background: '#f3f4f6', borderRadius: 8, padding: 3, gap: 2, alignItems: 'stretch' }}>
{options.map(opt => (
<button
key={opt.value}
onClick={() => onChange(opt.value)}
style={{
padding: '6px 13px', borderRadius: 6, border: 'none', fontSize: 13, fontWeight: 600,
cursor: 'pointer', transition: 'all 0.15s', fontFamily: 'inherit',
background: value === opt.value ? 'white' : 'transparent',
color: value === opt.value ? '#111827' : '#6b7280',
boxShadow: value === opt.value ? '0 1px 3px rgba(0,0,0,0.12)' : 'none',
}}
>{opt.label}</button>
))}
</div>
)
}
// ── 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 (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 14, width: '100%', maxWidth: 420, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
<div style={{ padding: '16px 20px 12px', borderBottom: '1px solid #f0f0ef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{ fontSize: 15, fontWeight: 700 }}>{isEdit ? 'Επεξεργασία Βάρδιας' : 'Νέα Βάρδια'}</div>
<div style={{ fontSize: 12, color: '#6b7280', marginTop: 1 }}>{fmtShortDate(date)}</div>
</div>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
</div>
<div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Σερβιτόρος</label>
<select style={inputStyle} value={userId} onChange={e => setUserId(e.target.value)} disabled={isEdit}>
{waiters.map(w => <option key={w.id} value={w.id}>{w.name}</option>)}
</select>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Έναρξη</label>
<input type="time" style={inputStyle} value={start} onChange={e => setStart(e.target.value)} />
</div>
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Λήξη</label>
<input type="time" style={inputStyle} value={end} onChange={e => setEnd(e.target.value)} />
</div>
</div>
{conflict && (
<div style={{ background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 7, padding: '8px 12px', fontSize: 12, color: '#dc2626' }}>
Επικάλυψη με βάρδια {fmtTime(conflict.start_time)}–{fmtTime(conflict.end_time)}
</div>
)}
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Σημείωση <span style={{ fontWeight: 400, color: '#9ca3af' }}>(προαιρετική)</span></label>
<input style={inputStyle} value={notes} onChange={e => setNotes(e.target.value)} placeholder="π.χ. Μόνο βράδυ" />
</div>
</div>
<div style={{ padding: '12px 20px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
<button onClick={onClose} style={{ padding: '7px 16px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 7, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>Ακύρωση</button>
<button
onClick={() => onSave({ user_id: Number(userId), scheduled_date: date, start_time: start, end_time: end, notes: notes || null, _editId: editShift?.id })}
disabled={!canSave || isPending}
style={{ padding: '7px 18px', border: 'none', borderRadius: 7, fontSize: 13, fontWeight: 600, cursor: canSave ? 'pointer' : 'default', background: canSave ? '#111827' : '#e5e7eb', color: canSave ? 'white' : '#9ca3af', fontFamily: 'inherit' }}
>
{isPending ? 'Αποθήκευση…' : isEdit ? 'Αποθήκευση' : 'Προσθήκη'}
</button>
</div>
</div>
</div>
)
}
// ── Schedule Settings Modal ───────────────────────────────────────────────────
function ToggleRow({ label, description, checked, onChange, indent }) {
return (
<div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, padding: `10px ${indent ? 36 : 20}px 10px ${indent ? 36 : 20}px`, borderBottom: '1px solid #f4f4f2' }}>
<div>
<div style={{ fontSize: 13.5, fontWeight: 500, color: indent ? '#374151' : '#111827' }}>{label}</div>
{description && <div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 2 }}>{description}</div>}
</div>
<button
role="switch"
onClick={() => onChange(!checked)}
style={{
flexShrink: 0, width: 42, height: 23, borderRadius: 999, border: 'none', cursor: 'pointer',
background: checked ? '#3b82f6' : '#e5e7eb', position: 'relative', transition: 'background 0.15s',
}}
>
<span style={{
position: 'absolute', top: 3, width: 17, height: 17, borderRadius: '50%', background: 'white',
boxShadow: '0 1px 3px rgba(0,0,0,0.2)', transition: 'left 0.15s',
left: checked ? 22 : 3,
}} />
</button>
</div>
)
}
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) => (
<div style={{ padding: '12px 20px 4px', fontSize: 11, fontWeight: 700, color: '#9ca3af', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{t}</div>
)
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 14, width: '100%', maxWidth: 480, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}>
<div style={{ padding: '16px 20px 12px', borderBottom: '1px solid #f0f0ef', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
<div style={{ fontSize: 15, fontWeight: 700 }}>Ρυθμίσεις Προγράμματος</div>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
</div>
<div style={{ overflowY: 'auto', flex: 1 }}>
{sectionLabel('Εμφάνιση')}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, padding: '10px 20px', borderBottom: '1px solid #f4f4f2' }}>
<div style={{ fontSize: 13.5, fontWeight: 500, color: '#111827' }}>Πρώτη μέρα εβδομάδας</div>
<div style={{ display: 'flex', background: '#f3f4f6', borderRadius: 7, padding: 2, gap: 2 }}>
{[{ v: true, l: 'Δευ' }, { v: false, l: 'Κυρ' }].map(opt => (
<button key={opt.l} onClick={() => set('firstDayMonday', opt.v)} style={{
padding: '4px 12px', borderRadius: 5, border: 'none', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
background: s.firstDayMonday === opt.v ? 'white' : 'transparent',
color: s.firstDayMonday === opt.v ? '#111827' : '#6b7280',
boxShadow: s.firstDayMonday === opt.v ? '0 1px 2px rgba(0,0,0,0.1)' : 'none',
}}>{opt.l}</button>
))}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, padding: '10px 20px', borderBottom: '1px solid #f4f4f2' }}>
<div>
<div style={{ fontSize: 13.5, fontWeight: 500, color: '#111827' }}>Πρώτη ώρα ημέρας</div>
<div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 1 }}>Αρχή ωρολογιακής προβολής (Ωριαία / Εργάσιμη)</div>
</div>
<select value={s.firstHour} onChange={e => set('firstHour', Number(e.target.value))} style={inputStyle}>
{Array.from({ length: 24 }, (_, i) => (
<option key={i} value={i}>{String(i).padStart(2, '0')}:00</option>
))}
</select>
</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, padding: '10px 20px', borderBottom: '1px solid #f4f4f2' }}>
<div>
<div style={{ fontSize: 13.5, fontWeight: 500, color: '#111827' }}>Ώρες λειτουργίας</div>
<div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 1 }}>Για προβολή Εργάσιμης Ημέρας</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<input type="time" value={s.workdayStart} onChange={e => set('workdayStart', e.target.value)} style={{ ...inputStyle, width: 90 }} />
<span style={{ color: '#9ca3af', fontSize: 12 }}>–</span>
<input type="time" value={s.workdayEnd} onChange={e => set('workdayEnd', e.target.value)} style={{ ...inputStyle, width: 90 }} />
</div>
</div>
{sectionLabel('Αυτόματο Πρόγραμμα Καταστήματος')}
<ToggleRow label="Αυτόματη Έναρξη Εργάσιμης" description="Η εργάσιμη ξεκινά αυτόματα σύμφωνα με το πρόγραμμα" checked={s.autoStartWorkday} onChange={v => set('autoStartWorkday', v)} />
<ToggleRow label="Αυτόματο Κλείσιμο Εργάσιμης" description="Η εργάσιμη κλείνει αυτόματα σύμφωνα με το πρόγραμμα" checked={s.autoCloseWorkday} onChange={v => set('autoCloseWorkday', v)} />
{s.autoCloseWorkday && (
<ToggleRow label="Κλείσιμο βαρδιών προσωπικού" description="Κλείνουν αυτόματα αν δεν υπάρχουν ανοιχτές παραγγελίες" checked={s.autoCloseShiftsOnWorkday} onChange={v => set('autoCloseShiftsOnWorkday', v)} indent />
)}
<ToggleRow label="Αυτόματη Έναρξη Βάρδιας Προσωπικού" description="Οι βάρδιες ξεκινούν αυτόματα σύμφωνα με το πρόγραμμα" checked={s.autoStartStaffShift} onChange={v => set('autoStartStaffShift', v)} />
<ToggleRow label="Αυτόματο Κλείσιμο Βάρδιας Προσωπικού" description="Οι βάρδιες κλείνουν αυτόματα σύμφωνα με το πρόγραμμα" checked={s.autoCloseStaffShift} onChange={v => set('autoCloseStaffShift', v)} />
</div>
<div style={{ padding: '12px 20px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 8, flexShrink: 0 }}>
<button onClick={onClose} style={{ padding: '7px 16px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 7, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>Ακύρωση</button>
<button
onClick={() => { onChange(s); onClose() }}
style={{ padding: '7px 18px', border: 'none', borderRadius: 7, fontSize: 13, fontWeight: 600, cursor: 'pointer', background: '#111827', color: 'white', fontFamily: 'inherit' }}
>Αποθήκευση</button>
</div>
</div>
</div>
)
}
// ── BY WAITER helpers ─────────────────────────────────────────────────────────
function TimeBar({ shifts }) {
if (!shifts || shifts.length === 0) return null
const MINS = 24 * 60
return (
<div style={{ position: 'relative', width: '100%', height: 14, background: '#f3f4f6', borderRadius: 3, overflow: 'hidden', marginTop: 3 }}>
{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 (
<div key={s.id || i} style={{
position: 'absolute', top: 0, bottom: 0,
left: `${left}%`, width: `${Math.max(width, 0.5)}%`,
background: hasActual ? '#86efac' : '#93c5fd',
borderRadius: 2,
}} title={`${fmtTime(s.start_time)}–${fmtTime(s.end_time)}`} />
)
})}
</div>
)
}
function ShiftCard({ shift, actual, onEdit, onDelete }) {
const hasActual = actual && actual.length > 0
const isActive = actual?.some(a => a.is_active)
return (
<div
style={{
borderRadius: 7, overflow: 'hidden',
border: `1.5px solid ${hasActual ? '#86efac' : '#bfdbfe'}`,
background: hasActual ? '#f0fdf4' : '#eff6ff',
fontSize: 11.5, cursor: 'pointer',
}}
onClick={onEdit}
>
<div style={{ padding: '4px 7px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 3 }}>
<span style={{ fontWeight: 700, color: '#1d4ed8', whiteSpace: 'nowrap' }}>
{fmtTime(shift.start_time)}–{fmtTime(shift.end_time)}
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 3 }}>
{shift.estimated_pay != null && (
<span style={{ color: '#6b7280', fontSize: 10 }}>{fmt(shift.estimated_pay)}</span>
)}
<button
onClick={e => { e.stopPropagation(); onDelete() }}
style={{ fontSize: 10, color: '#9ca3af', background: 'none', border: 'none', cursor: 'pointer', padding: '0 2px', lineHeight: 1 }}
>✕</button>
</div>
</div>
{shift.notes && (
<div style={{ padding: '2px 7px 4px', fontSize: 10, color: '#6b7280', fontStyle: 'italic', borderTop: `1px solid ${hasActual ? '#bbf7d0' : '#bfdbfe'}` }}>
{shift.notes}
</div>
)}
{hasActual ? (
actual.map(a => (
<div key={a.id} style={{ padding: '2px 7px 3px', borderTop: `1px solid #bbf7d0`, fontSize: 10, color: '#15803d', fontWeight: 600 }}>
✓ {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 ? ' (ενεργή)' : ''}
</div>
))
) : (
<div style={{ padding: '2px 7px 3px', borderTop: '1px solid #bfdbfe', fontSize: 10, color: '#94a3b8' }}>Δεν ξεκίνησε</div>
)}
</div>
)
}
// ── BY WAITER view ────────────────────────────────────────────────────────────
function ByWaiterView({ days, waiters, grid, scheduled, onAddShift, onEditShift, onDeleteShift }) {
return (
<div style={{ overflowX: 'auto', overflowY: 'auto', flex: 1 }}>
<table style={{ borderCollapse: 'collapse', width: '100%', minWidth: 760 }}>
<thead>
<tr style={{ background: '#fafafa' }}>
<th style={{ padding: '9px 16px', textAlign: 'left', fontSize: 11.5, fontWeight: 700, color: '#9ca3af', width: 150, borderBottom: '2px solid #f0f0ef' }}>Σερβιτόρος</th>
{days.map(d => {
const isToday = toLocalDateStr(new Date()) === d.dateStr
return (
<th key={d.dateStr} style={{
padding: '9px 6px', textAlign: 'center', fontSize: 12,
fontWeight: isToday ? 800 : 600,
color: isToday ? '#3b82f6' : '#374151',
minWidth: 115, borderBottom: '2px solid #f0f0ef',
}}>
<div>{d.label}</div>
<div style={{ fontSize: 11, fontWeight: 500, color: isToday ? '#3b82f6' : '#9ca3af' }}>{fmtShortDate(d.dateStr)}</div>
</th>
)
})}
</tr>
</thead>
<tbody>
{waiters.length === 0 && (
<tr><td colSpan={8} style={{ textAlign: 'center', color: '#d1d5db', fontSize: 13, padding: '48px 0' }}>Δεν υπάρχουν ενεργοί σερβιτόροι.</td></tr>
)}
{waiters.map((w, rowIdx) => {
const rowBg = rowIdx % 2 === 0 ? 'white' : '#fafafa'
return (
<tr key={w.id} style={{ background: rowBg, borderTop: '1px solid #f0f0ef' }}>
<td style={{ padding: '8px 16px', verticalAlign: 'top', background: rowBg }}>
<div style={{ fontSize: 13, fontWeight: 700, color: '#111315' }}>{w.name}</div>
{w.hourly_rate != null && <div style={{ fontSize: 11, color: '#9ca3af' }}>{fmt(w.hourly_rate)}/ώρα</div>}
</td>
{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 (
<td key={d.dateStr} style={{ padding: '5px 4px', verticalAlign: 'top', background: rowBg }}>
<div style={{ minHeight: 52, display: 'flex', flexDirection: 'column', gap: 3 }}>
{cellShifts.map(s => (
<ShiftCard
key={s.id} shift={s}
actual={cell.actual}
onEdit={() => onEditShift(s, d.dateStr)}
onDelete={() => onDeleteShift(s.id)}
/>
))}
<button
onClick={() => onAddShift(d.dateStr, w.id)}
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center',
height: 24, borderRadius: 6, border: '1.5px dashed #d1d5db',
background: 'transparent', color: '#c0c4cc', fontSize: 14,
cursor: 'pointer', transition: 'all 0.12s', fontFamily: 'inherit',
}}
onMouseEnter={e => { e.currentTarget.style.borderColor = '#93c5fd'; e.currentTarget.style.color = '#3b82f6' }}
onMouseLeave={e => { e.currentTarget.style.borderColor = '#d1d5db'; e.currentTarget.style.color = '#c0c4cc' }}
>+</button>
{cellShifts.length > 0 && <TimeBar shifts={dayShiftsForWaiter} />}
</div>
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
</div>
)
}
// ── 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 (
<div style={{ overflowX: 'auto', overflowY: 'auto', flex: 1, paddingBottom: 16 }}>
<div style={{ display: 'flex', minWidth: 640 }}>
{/* Time axis */}
<div style={{ width: 46, flexShrink: 0, paddingTop: 42 }}>
{hours.map((h, i) => (
<div key={h} style={{ height: HOUR_HEIGHT, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end', paddingRight: 8 }}>
<span style={{ fontSize: 10, color: '#9ca3af', marginTop: -7, lineHeight: 1 }}>{String(h).padStart(2, '0')}:00</span>
</div>
))}
</div>
{/* Day columns */}
<div style={{ display: 'flex', flex: 1, gap: 6 }}>
{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 (
<div key={d.dateStr} style={{ flex: 1, minWidth: 80 }}>
{/* Day header */}
<div style={{
height: 42, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column',
borderBottom: '1px solid #e5e7eb',
background: isToday ? '#eff6ff' : di % 2 === 0 ? '#fafafa' : '#f5f5f5',
borderRadius: '6px 6px 0 0',
}}>
<div style={{ fontSize: 12, fontWeight: isToday ? 800 : 600, color: isToday ? '#3b82f6' : '#374151' }}>{d.label}</div>
<div style={{ fontSize: 10.5, color: isToday ? '#3b82f6' : '#9ca3af' }}>{fmtShortDate(d.dateStr)}</div>
</div>
{/* Timeline */}
<div
style={{
position: 'relative', height: TOTAL_HOURS * HOUR_HEIGHT, cursor: 'pointer',
background: isToday ? '#f8fbff' : di % 2 === 0 ? '#fafafa' : '#f5f5f5',
}}
onClick={() => 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 (
<div key={h} style={{
position: 'absolute', left: 0, right: 0, top: i * HOUR_HEIGHT, height: HOUR_HEIGHT,
borderTop: `1px solid ${h === 0 ? '#bfdbfe' : '#e9eaec'}`,
background: inWorkday ? 'rgba(219,234,254,0.35)' : 'transparent',
}} />
)
})}
{/* Midnight marker */}
{firstHour !== 0 && (
<div style={{ position: 'absolute', left: 0, right: 0, top: minuteToY(0), borderTop: '1.5px solid #93c5fd', zIndex: 3, pointerEvents: 'none' }}>
<span style={{ fontSize: 9, color: '#93c5fd', marginLeft: 2, lineHeight: 1 }}>00:00</span>
</div>
)}
{/* 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 (
<div
key={s.id}
style={{
position: 'absolute', top, left: offsetX, width: BAR_W, height,
borderRadius: 4, overflow: 'hidden', zIndex: 2,
background: hasActual ? '#86efac' : '#93c5fd',
border: `1px solid ${hasActual ? '#4ade80' : '#60a5fa'}`,
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 9, fontWeight: 700, color: hasActual ? '#166534' : '#1e40af',
cursor: 'default',
}}
onMouseEnter={e => {
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}
</div>
)
})
})}
</div>
</div>
)
})}
</div>
</div>
{/* Tooltip */}
{tooltip && (
<div style={{
position: 'fixed', left: tooltip.x, top: tooltip.y,
background: '#111827', color: 'white', borderRadius: 8,
padding: '8px 12px', fontSize: 12, zIndex: 100, pointerEvents: 'none',
boxShadow: '0 4px 12px rgba(0,0,0,0.3)', maxWidth: 220,
}}>
<div style={{ fontWeight: 700, marginBottom: 3 }}>{tooltip.waiter?.name}</div>
<div>{fmtTime(tooltip.shift.start_time)} – {fmtTime(tooltip.shift.end_time)}</div>
{tooltip.shift.notes && <div style={{ color: '#9ca3af', marginTop: 3, fontStyle: 'italic' }}>{tooltip.shift.notes}</div>}
</div>
)}
</div>
)
}
// ── 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 (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '11px 20px', borderBottom: '1px solid #f0f0ef', flexShrink: 0, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: '#111827' }}>Πρόγραμμα Εβδομάδας</div>
<div style={{ fontSize: 12, color: '#9ca3af' }}>
{fmtShortDate(weekStartStr)} – {fmtShortDate(weekEndStr)}
{totalPay > 0 && <span style={{ marginLeft: 10, color: '#6b7280' }}>Εκτ. κόστος: <strong style={{ color: '#111315' }}>{fmt(totalPay)}</strong></span>}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
{/* Settings + view switch group */}
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<button
onClick={() => setShowSettings(true)}
title="Ρυθμίσεις προγράμματος"
style={{ ...btnStyle, padding: '6px 10px', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15, color: '#6b7280' }}
>⚙</button>
<TripleSwitch
value={schedSettings.viewMode}
onChange={v => updateSettings({ ...schedSettings, viewMode: v })}
options={[
{ value: 'bywaiter', label: 'ΑΝΑ ΣΕΡΒΙΤΌΡΟ' },
{ value: 'hourly', label: 'ΩΡΙΑΙΑ' },
{ value: 'workday', label: 'ΕΡΓΆΣΙΜΗ' },
]}
/>
</div>
{/* Week navigation group */}
<div style={{ display: 'flex', alignItems: 'center', gap: 4, marginLeft: 8 }}>
<button onClick={() => setWeekAnchor(w => addDays(w, -7))} style={btnStyle}>← Προηγ.</button>
<button onClick={() => setWeekAnchor(weekAnchorFor(new Date(), schedSettings.firstDayMonday))} style={btnStyle}>Αυτή η εβδομάδα</button>
<button onClick={() => setWeekAnchor(w => addDays(w, 7))} style={btnStyle}>Επόμ. →</button>
</div>
</div>
</div>
{isLoading && (
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#9ca3af', fontSize: 13 }}>Φόρτωση…</div>
)}
{!isLoading && schedSettings.viewMode === 'bywaiter' && (
<ByWaiterView
days={days}
waiters={waiters}
grid={grid}
scheduled={scheduled}
onAddShift={(date, userId) => setAddModal({ date, userId })}
onEditShift={(shift, date) => setEditModal({ shift, date })}
onDeleteShift={handleDeleteShift}
/>
)}
{!isLoading && (schedSettings.viewMode === 'hourly' || schedSettings.viewMode === 'workday') && (
<HourlyView
days={days}
waiters={waiters}
scheduled={scheduled}
firstHour={schedSettings.firstHour}
workdayBounds={workdayBounds}
onAddShift={(date, userId) => setAddModal({ date, userId })}
/>
)}
{/* Legend */}
{!isLoading && schedSettings.viewMode === 'bywaiter' && (
<div style={{ padding: '7px 20px', borderTop: '1px solid #f0f0ef', background: '#fafafa', display: 'flex', gap: 16, flexWrap: 'wrap', flexShrink: 0 }}>
{[
{ color: '#bfdbfe', bg: '#eff6ff', label: 'Προγρ. (δεν ξεκίνησε)' },
{ color: '#86efac', bg: '#f0fdf4', label: 'Προγρ. + Πραγματική' },
].map(l => (
<div key={l.label} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: '#6b7280' }}>
<div style={{ width: 14, height: 10, borderRadius: 3, background: l.bg, border: `1.5px solid ${l.color}` }} />
{l.label}
</div>
))}
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: '#6b7280' }}>
<div style={{ width: 36, height: 8, borderRadius: 2, background: 'linear-gradient(to right, #93c5fd 50%, #86efac 50%)' }} />
Μπάρα 24ω (μπλε=σχεδ., πράσ.=πραγμ.)
</div>
</div>
)}
{addModal && (
<ShiftModal
date={addModal.date}
waiters={addModal.userId
? waiters.filter(w => 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 && (
<ShiftModal
date={editModal.date}
waiters={waiters}
existingShifts={scheduled}
editShift={editModal.shift}
onClose={() => setEditModal(null)}
isPending={updateShift.isPending}
onSave={handleSaveShift}
/>
)}
{showSettings && (
<ScheduleSettingsModal
settings={schedSettings}
onChange={updateSettings}
onClose={() => setShowSettings(false)}
/>
)}
</div>
)
}
-925
View File
@@ -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 (
<img src={waiter.avatar_url} alt={displayName}
style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} />
)
}
const parts = displayName.trim().split(' ')
const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
return (
<div style={{
width: size, height: size, borderRadius: '50%',
background: avatarColor(displayName), color: 'white',
fontSize: size * 0.38, fontWeight: 600,
display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
}}>{initials}</div>
)
}
// ── 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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'center' }}>
<div style={{ display: 'flex', gap: 10 }}>
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} style={{
width: 13, height: 13, borderRadius: '50%',
border: `2px solid ${i < value.length ? '#111827' : '#d1d5db'}`,
background: i < value.length ? '#111827' : 'transparent',
transition: 'all 150ms',
}} />
))}
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, width: '100%' }}>
{DIGITS.map((d, i) => (
<button key={i} type="button" onClick={() => press(d)} disabled={d === ''}
style={{
height: 46, borderRadius: 10, fontSize: 18, fontWeight: 600, border: 'none',
cursor: d === '' ? 'default' : 'pointer',
background: d === '' ? 'transparent' : d === '⌫' ? '#f3f4f6' : '#f8fafc',
color: d === '⌫' ? '#6b7280' : '#111827',
transition: 'background 100ms',
visibility: d === '' ? 'hidden' : 'visible',
}}>
{d}
</button>
))}
</div>
</div>
)
}
// ── 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 (
<div ref={ref} style={{ position: 'relative' }}>
<button onClick={() => setOpen(v => !v)} style={{
display: 'flex', alignItems: 'center', gap: 5,
fontSize: 12, padding: '0 10px', height: 30, borderRadius: 7,
border: '1px solid #e5e7eb', background: open ? '#f3f4f6' : '#fff',
color: '#374151', fontWeight: 500, cursor: 'pointer',
}}>
Ενέργειες
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M6 9l6 6 6-6" />
</svg>
</button>
{open && (
<div style={{
position: 'absolute', right: 0, top: 'calc(100% + 5px)', zIndex: 100,
background: '#fff', border: '1px solid #e5e7eb',
borderRadius: 12, boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
minWidth: 210, overflow: 'hidden', padding: '4px 0',
}}>
{items.map((item, i) => (
<button key={i}
onClick={() => { setOpen(false); item.onClick() }}
style={{
display: 'flex', alignItems: 'center', gap: 10,
width: '100%', padding: '9px 14px', border: 'none',
background: 'transparent', cursor: 'pointer', textAlign: 'left',
fontSize: 13.5, fontWeight: 500, color: item.color || '#111827',
}}
onMouseEnter={e => e.currentTarget.style.background = item.color ? `${item.color}10` : '#f9fafb'}
onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
>
<span style={{ color: item.color || '#6b7280', display: 'flex', flexShrink: 0 }}>{item.icon}</span>
{item.label}
</button>
))}
</div>
)}
</div>
)
}
// ── 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 (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-4">
<h2 className="font-bold text-gray-800">Ζώνες — {member.username}</h2>
<label className="flex items-center gap-3 cursor-pointer select-none">
<input type="checkbox" className="w-5 h-5 rounded accent-primary-700" checked={allZones}
onChange={e => { setAllZones(e.target.checked); if (e.target.checked) setSelected(new Set()) }} />
<span className="font-semibold text-gray-700">Όλες οι ζώνες</span>
</label>
{!allZones && (
<div className="space-y-2 max-h-60 overflow-y-auto">
{groups.length === 0 && <p className="text-sm text-gray-400">Δεν υπάρχουν ομάδες τραπεζιών.</p>}
{groups.map(g => (
<label key={g.id} className="flex items-center gap-3 cursor-pointer select-none px-1">
<input type="checkbox" className="w-5 h-5 rounded accent-primary-700" checked={selected.has(g.id)} onChange={() => toggleGroup(g.id)} />
<span className="text-gray-700">{g.name}</span>
{g.color && <span className="w-3 h-3 rounded-full inline-block ml-auto" style={{ background: g.color }} />}
</label>
))}
</div>
)}
{!allZones && selected.size === 0 && (
<p className="text-xs text-amber-600 bg-amber-50 rounded px-3 py-1.5">Χωρίς επιλογή ο σερβιτόρος δεν βλέπει κανένα τραπέζι.</p>
)}
<div className="flex gap-3 pt-2">
<button onClick={onClose} className="flex-1 btn btn-secondary">Ακύρωση</button>
<button
onClick={() => saveZones.mutate(allZones ? { all_zones: true, group_ids: [] } : { all_zones: false, group_ids: [...selected] })}
disabled={saveZones.isPending} className="flex-1 btn btn-primary">Αποθήκευση</button>
</div>
</div>
</div>
)
}
// ── Shared form primitives ─────────────────────────────────────────────────────
function FormField({ label, required, desc, children }) {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151' }}>
{label}{required && <span style={{ color: '#ef4444', marginLeft: 2 }}>*</span>}
</label>
{children}
{desc && <p style={{ margin: 0, fontSize: 11, color: '#9ca3af', lineHeight: 1.4 }}>{desc}</p>}
</div>
)
}
function SectionLabel({ children }) {
return (
<div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#9ca3af', marginBottom: 10 }}>
{children}
</div>
)
}
function InfoBlock({ label, value, valueColor }) {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
<span style={{ fontSize: 10.5, fontWeight: 600, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</span>
<span style={{ fontSize: 13.5, fontWeight: 500, color: valueColor || '#111827' }}>{value || '—'}</span>
</div>
)
}
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 <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
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 (
<div className="flex flex-col h-full min-h-0">
{/* ── Header bar ── */}
<div style={{
display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid #e5e7eb',
padding: '0 24px', height: 60, flexShrink: 0,
}}>
<div style={{ display: 'flex', gap: 14, flex: 1, flexWrap: 'wrap' }}>
{Object.entries(groupedCounts).map(([group, count]) => (
<span key={group} style={{ fontSize: 12, color: '#6b7280' }}>
<strong style={{ color: '#111827', fontWeight: 600 }}>{count}</strong> {group}
</span>
))}
</div>
{/* Role filter */}
<select
value={filterRole}
onChange={e => setFilterRole(e.target.value)}
style={{ ...inputStyle, width: 'auto', fontSize: 12, padding: '4px 8px', color: '#374151' }}
>
<option value="all">Όλοι οι ρόλοι</option>
{ALL_ROLES.map(r => (
<option key={r.value} value={r.value}>{r.label}</option>
))}
</select>
<Button variant="primary" size="sm" onClick={() => setAddModal(true)}>+ Νέος εργαζόμενος</Button>
</div>
{/* ── Scrollable table area ── */}
<div style={{ flex: 1, overflow: 'auto', padding: '0' }}>
{filtered.length === 0 ? (
<p style={{ textAlign: 'center', color: '#9ca3af', padding: '64px 0', fontSize: 14 }}>
Δεν βρέθηκαν εργαζόμενοι.
</p>
) : (
<table style={{
width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed',
fontSize: 12,
}}>
<colgroup>
<col style={{ width: 220, minWidth: 220 }} />
<col style={{ width: 90, minWidth: 90 }} />
<col style={{ width: 260, minWidth: 200 }} />
<col style={{ width: 120, minWidth: 110 }} />
</colgroup>
<thead>
{/* Column label row */}
<tr style={{ borderBottom: '2px solid #e5e7eb', background: '#f9fafb' }}>
<th style={{ ...thBase, textAlign: 'left', padding: '6px 16px', fontWeight: 600, color: '#374151' }}>
Εργαζόμενος
</th>
<th style={{ ...thBase, textAlign: 'center', color: '#6b7280', fontWeight: 500 }}>Κατάσταση</th>
<th style={{ ...thBase, textAlign: 'left', padding: '6px 12px', color: '#6b7280', fontWeight: 500 }}>
{t('permissions.column')}
</th>
<th style={{ ...thBase, textAlign: 'right', padding: '6px 12px', color: '#6b7280', fontWeight: 500 }}>
Ενέργειες
</th>
</tr>
</thead>
<tbody>
{filtered.map((member, rowIdx) => {
const role = ROLE_MAP[member.role]
const isSuperadmin = member.role === 'superadmin'
const rowBg = rowIdx % 2 === 0 ? '#fff' : '#fafafa'
return (
<tr key={member.id} style={{ background: rowBg, borderBottom: '1px solid #f3f4f6' }}
onMouseEnter={e => e.currentTarget.style.background = '#f0f9ff'}
onMouseLeave={e => e.currentTarget.style.background = rowBg}
>
{/* Identity cell */}
<td style={{ padding: '10px 16px', verticalAlign: 'middle' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<WaiterAvatar waiter={member} size={34} />
<div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 600, color: '#111827', fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{member.full_name || member.username}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
<span style={{
fontSize: 10, fontWeight: 600, padding: '1px 6px', borderRadius: 4,
background: `${role?.color || '#6b7280'}18`,
color: role?.color || '#6b7280',
whiteSpace: 'nowrap',
}}>
{role?.label || member.role}
</span>
{member.nickname && (
<span style={{ fontSize: 11, color: '#9ca3af', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{member.nickname}
</span>
)}
</div>
</div>
</div>
</td>
{/* Status cell */}
<td style={{ textAlign: 'center', verticalAlign: 'middle', padding: '0 4px' }}>
<span style={{
display: 'inline-block', fontSize: 10.5, fontWeight: 600,
padding: '2px 8px', borderRadius: 999,
background: member.is_active ? '#dcfce7' : '#fee2e2',
color: member.is_active ? '#15803d' : '#dc2626',
}}>
{member.is_active ? 'Ενεργός' : 'Μπλοκαρ.'}
</span>
</td>
{/* Permissions (2.6e): count + "custom" when they differ from the role */}
<td style={{ padding: '0 12px', verticalAlign: 'middle' }} data-testid={`staff-perms-${member.id}`}>
<button type="button" onClick={() => setPermEditor(member)}
className="text-left text-label text-ink-2 hover:text-accent-ink inline-flex items-center gap-2">
{isSuperadmin
? t('permissions.all')
: t('permissions.count', { count: member.permissions?.length || 0 })}
{!isSuperadmin && catalog && differsFromRole(member.permissions || [], catalog.role_templates[member.role] || []) && (
<span className="rounded-full px-2 py-0.5 text-caption font-medium bg-warning-soft text-warning-ink">{t('permissions.custom')}</span>
)}
</button>
</td>
{/* Actions cell */}
<td style={{ textAlign: 'right', padding: '0 12px', verticalAlign: 'middle' }}>
<ActionsMenu
member={member}
isSuperadmin={isSuperadmin}
onEdit={() => 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')}
/>
</td>
</tr>
)
})}
</tbody>
</table>
)}
</div>
{/* ── Modals ── */}
{addModal && (
<AddStaffModal
form={newForm} setForm={setNewForm}
avatarFile={newAvatarFile} avatarPreview={newAvatarPreview}
setAvatarFile={setNewAvatarFile} setAvatarPreview={setNewAvatarPreview}
avatarInputRef={newAvatarInputRef}
isPending={createStaff.isPending}
onClose={() => { 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 && (
<EditStaffModal
member={editModal} form={editForm} setForm={setEditForm}
avatarInputRef={avatarInputRef}
isPending={updateStaff.isPending}
isUploadPending={uploadAvatar.isPending}
isDeletePending={deleteAvatar.isPending}
onClose={() => 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 && (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-xs p-6 space-y-4">
<h2 className="font-bold text-gray-800">Επαναφορά PIN — {staff.find(m => m.id === pinModal)?.username}</h2>
<PinInput value={newPin} onChange={setNewPin} />
<div className="flex gap-3 pt-2">
<button onClick={() => { setPinModal(null); setNewPin('') }} className="flex-1 btn btn-secondary">Ακύρωση</button>
<button onClick={() => resetPin.mutate({ id: pinModal, pin: newPin })} disabled={newPin.length < 4} className="flex-1 btn btn-primary">
Αποθήκευση
</button>
</div>
</div>
</div>
)}
{confirmDelete !== null && (
<ConfirmModal
title="Διαγραφή εργαζόμενου;"
message="Αυτή η ενέργεια δεν μπορεί να αναιρεθεί."
confirmLabel="Διαγραφή"
confirmVariant="danger"
onConfirm={() => deleteStaff.mutate(confirmDelete)}
onCancel={() => setConfirmDelete(null)}
/>
)}
{permEditor && <PermissionEditor member={permEditor} onClose={() => setPermEditor(null)} />}
{zoneModal && (
<ZoneModal member={zoneModal} groups={groups} onClose={() => setZoneModal(null)} />
)}
</div>
)
}
const thBase = {
fontSize: 11, fontWeight: 600, color: '#6b7280',
padding: '6px 4px', background: '#f9fafb',
position: 'sticky', top: 0, zIndex: 1,
}
// ── SVG icons ─────────────────────────────────────────────────────────────────
const editIcon = (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M12 20h9" /><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
</svg>
)
const zonesIcon = (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
</svg>
)
const pinIcon = (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" />
</svg>
)
const resetIcon = (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" /><path d="M3 3v5h5" />
</svg>
)
const blockIcon = (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10" /><line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
</svg>
)
const trashIcon = (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 6h18" /><path d="M8 6V4h8v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
</svg>
)
// ── 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 (
<div style={{
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
zIndex: 50, padding: 24,
}}>
<div style={{
background: '#fff', borderRadius: 20, boxShadow: '0 24px 72px rgba(0,0,0,0.18)',
width: '100%', maxWidth: 980,
maxHeight: '90vh', display: 'flex', flexDirection: 'column', overflow: 'hidden',
}}>
{/* Header */}
<div style={{ padding: '18px 26px 14px', borderBottom: '1px solid #f3f4f6', display: 'flex', alignItems: 'center', gap: 14, flexShrink: 0 }}>
{avatarPreview
? <img src={avatarPreview} alt="preview" style={{ width: 48, height: 48, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} />
: <div style={{ width: 48, height: 48, borderRadius: '50%', background: '#f3f4f6', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
<span style={{ fontSize: 22, color: '#9ca3af' }}>👤</span>
</div>
}
<div style={{ flex: 1, minWidth: 0 }}>
<h2 style={{ margin: 0, fontWeight: 700, fontSize: 16, color: '#111827' }}>Νέος εργαζόμενος</h2>
<p style={{ margin: '2px 0 0', fontSize: 12, color: '#9ca3af' }}>Συμπληρώστε τα στοιχεία του εργαζόμενου</p>
</div>
<div style={{ display: 'flex', gap: 6 }}>
<input ref={avatarInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={e => {
const file = e.target.files?.[0]
if (file) { setAvatarFile(file); setAvatarPreview(URL.createObjectURL(file)) }
e.target.value = ''
}} />
<button onClick={() => avatarInputRef.current?.click()} type="button"
style={{ fontSize: 12, padding: '5px 11px', border: '1px solid #e5e7eb', background: '#fff', borderRadius: 7, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>
{avatarPreview ? 'Αλλαγή φωτογραφίας' : 'Προσθήκη φωτογραφίας'}
</button>
{avatarPreview && (
<button type="button" onClick={() => { setAvatarFile(null); setAvatarPreview(null) }}
style={{ fontSize: 12, padding: '5px 11px', border: '1px solid #fecaca', background: '#fff5f5', borderRadius: 7, cursor: 'pointer', color: '#ef4444', fontWeight: 500 }}>
Αφαίρεση
</button>
)}
</div>
</div>
{/* Body — three columns */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', flex: 1, minHeight: 0, overflowY: 'auto' }}>
{/* Col 1: Identity + Account */}
<div style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16, borderRight: '1px solid #f3f4f6' }}>
<div>
<SectionLabel>Ταυτότητα</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<FormField label="Πλήρες Όνομα" required desc="Εμφανίζεται στα στατιστικά.">
<input style={inputStyle} placeholder="π.χ. Γιώργος Παπαδόπουλος" value={form.full_name} onChange={e => f('full_name', e.target.value)} autoFocus />
</FormField>
<FormField label="Παρατσούκλι" required desc="Εμφανίζεται στην εφαρμογή.">
<input style={inputStyle} placeholder="π.χ. Γιώργος" value={form.nickname} onChange={e => f('nickname', e.target.value)} />
</FormField>
</div>
</div>
<div>
<SectionLabel>Λογαριασμός</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<FormField label="Όνομα χρήστη" required desc="Χρησιμοποιείται για login.">
<input style={inputStyle} placeholder="π.χ. giorgos" value={form.username} onChange={e => f('username', e.target.value)} />
</FormField>
<FormField label="Ρόλος" required desc="Ορίζει προκαθορισμένα δικαιώματα.">
<select style={inputStyle} value={form.role} onChange={e => f('role', e.target.value)}>
{ALL_ROLES.map(r => <option key={r.value} value={r.value}>{r.label}</option>)}
</select>
</FormField>
</div>
</div>
</div>
{/* Col 2: Contact */}
<div style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16, borderRight: '1px solid #f3f4f6' }}>
<div>
<SectionLabel>Επικοινωνία</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<FormField label="Κινητό τηλέφωνο" desc="Εσωτερική αναφορά μόνο.">
<input style={inputStyle} placeholder="π.χ. 6901234567" value={form.mobile_phone} onChange={e => f('mobile_phone', e.target.value)} />
</FormField>
<FormField label="Email" desc="Εσωτερική χρήση μόνο.">
<input style={inputStyle} type="email" placeholder="π.χ. giorgos@restaurant.gr" value={form.email} onChange={e => f('email', e.target.value)} />
</FormField>
<FormField label="Σημείωση" desc="Οποιαδήποτε εσωτερική σημείωση.">
<textarea style={{ ...inputStyle, resize: 'none' }} placeholder="π.χ. Μερική απασχόληση" value={form.note} onChange={e => f('note', e.target.value)} rows={4} />
</FormField>
</div>
</div>
<div>
<SectionLabel>Μισθοδοσία</SectionLabel>
<FormField label="Ωριαία αμοιβή (€/ώρα)" desc="Μόνο για διαχειριστές.">
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<input type="number" step="0.50" min="0" style={{ ...inputStyle, width: 110 }}
placeholder="π.χ. 5.50" value={form.hourly_rate ?? ''}
onChange={e => f('hourly_rate', e.target.value)} />
{form.hourly_rate && parseFloat(form.hourly_rate) > 0
? <span style={{ fontSize: 11.5, color: '#16a34a', fontWeight: 500 }}>€{parseFloat(form.hourly_rate).toFixed(2)}/ώρα</span>
: <span style={{ fontSize: 11, color: '#9ca3af' }}>Δεν παρακολουθείται</span>
}
</div>
</FormField>
</div>
</div>
{/* Col 3: PIN */}
<div style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16, background: '#fafafa' }}>
<div>
<SectionLabel>Κωδικός PIN</SectionLabel>
<p style={{ margin: '0 0 16px', fontSize: 12, color: '#6b7280', lineHeight: 1.5 }}>
Ο 4ψήφιος κωδικός που θα χρησιμοποιεί ο εργαζόμενος για να ξεκλειδώσει την εφαρμογή.
</p>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<div style={{ width: '100%', maxWidth: 220 }}>
<PinInput value={form.pin} onChange={pin => f('pin', pin)} />
{form.pin.length > 0 && form.pin.length < 4 && (
<p style={{ textAlign: 'center', fontSize: 11.5, color: '#f59e0b', marginTop: 10 }}>
Χρειάζονται {4 - form.pin.length} ψηφία ακόμη
</p>
)}
{form.pin.length >= 4 && (
<p style={{ textAlign: 'center', fontSize: 11.5, color: '#22c55e', marginTop: 10, fontWeight: 600 }}>
✓ PIN ορίστηκε
</p>
)}
</div>
</div>
</div>
<div style={{ marginTop: 'auto', padding: 14, background: '#f0fdf4', borderRadius: 10, border: '1px solid #bbf7d0' }}>
<p style={{ margin: 0, fontSize: 11.5, color: '#15803d', lineHeight: 1.5 }}>
Τα δικαιώματα θα οριστούν αυτόματα βάσει του επιλεγμένου ρόλου και μπορείτε να τα τροποποιήσετε μετά τη δημιουργία.
</p>
</div>
</div>
</div>
{/* Footer */}
<div style={{ padding: '14px 26px', borderTop: '1px solid #f3f4f6', display: 'flex', justifyContent: 'flex-end', gap: 10, flexShrink: 0 }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: '#fff', borderRadius: 8, fontSize: 13.5, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>
Ακύρωση
</button>
<button onClick={onSubmit} disabled={isPending || !canSubmit}
style={{ padding: '8px 20px', border: 'none', background: canSubmit ? '#111827' : '#d1d5db', color: '#fff', borderRadius: 8, fontSize: 13.5, fontWeight: 600, cursor: canSubmit ? 'pointer' : 'not-allowed' }}>
{isPending ? 'Δημιουργία…' : 'Δημιουργία εργαζόμενου'}
</button>
</div>
</div>
</div>
)
}
// ── Edit Staff Modal ───────────────────────────────────────────────────────────
function EditStaffModal({ member, form, setForm, avatarInputRef, isPending, isUploadPending, isDeletePending, onClose, onSubmit, onUploadAvatar, onDeleteAvatar }) {
const f = (field, val) => setForm(p => ({ ...p, [field]: val }))
const canSubmit = form.username.trim() && form.full_name.trim() && form.nickname.trim()
const zoneLabel = !member.zone_assignments?.length ? 'Χωρίς ζώνες'
: member.zone_assignments.some(z => z.group_id === null) ? 'Όλες οι ζώνες'
: `${member.zone_assignments.length} ζών${member.zone_assignments.length === 1 ? 'η' : 'ες'}`
return (
<div style={{
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
zIndex: 50, padding: 24,
}}>
<div style={{
background: '#fff', borderRadius: 20, boxShadow: '0 24px 72px rgba(0,0,0,0.18)',
width: '100%', maxWidth: 980,
maxHeight: '90vh', display: 'flex', flexDirection: 'column', overflow: 'hidden',
}}>
{/* Header */}
<div style={{ padding: '18px 26px 14px', borderBottom: '1px solid #f3f4f6', display: 'flex', alignItems: 'center', gap: 14, flexShrink: 0 }}>
<WaiterAvatar waiter={member} size={48} />
<div style={{ flex: 1, minWidth: 0 }}>
<h2 style={{ margin: 0, fontWeight: 700, fontSize: 16, color: '#111827' }}>
Επεξεργασία — {member.full_name || member.username}
</h2>
<p style={{ margin: '2px 0 0', fontSize: 12, color: '#9ca3af' }}>Ενημέρωση στοιχείων εργαζόμενου</p>
</div>
<div style={{ display: 'flex', gap: 6 }}>
<input ref={avatarInputRef} type="file" accept="image/*" style={{ display: 'none' }}
onChange={e => { const file = e.target.files?.[0]; if (file) onUploadAvatar(file); e.target.value = '' }} />
<button onClick={() => avatarInputRef.current?.click()} disabled={isUploadPending}
style={{ fontSize: 12, padding: '5px 11px', border: '1px solid #e5e7eb', background: '#fff', borderRadius: 7, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>
{isUploadPending ? 'Μεταφόρτωση…' : member.avatar_url ? 'Αλλαγή φωτογραφίας' : 'Προσθήκη φωτογραφίας'}
</button>
{member.avatar_url && (
<button onClick={onDeleteAvatar} disabled={isDeletePending}
style={{ fontSize: 12, padding: '5px 11px', border: '1px solid #fecaca', background: '#fff5f5', borderRadius: 7, cursor: 'pointer', color: '#ef4444', fontWeight: 500 }}>
Αφαίρεση
</button>
)}
</div>
</div>
{/* Body — three columns */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', flex: 1, minHeight: 0, overflowY: 'auto' }}>
{/* Col 1: Identity + Account */}
<div style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16, borderRight: '1px solid #f3f4f6' }}>
<div>
<SectionLabel>Ταυτότητα</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<FormField label="Πλήρες Όνομα" required>
<input style={inputStyle} value={form.full_name} onChange={e => f('full_name', e.target.value)} autoFocus />
</FormField>
<FormField label="Παρατσούκλι" required>
<input style={inputStyle} value={form.nickname} onChange={e => f('nickname', e.target.value)} />
</FormField>
</div>
</div>
<div>
<SectionLabel>Λογαριασμός</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<FormField label="Όνομα χρήστη" required>
<input style={inputStyle} value={form.username} onChange={e => f('username', e.target.value)} />
</FormField>
<FormField label="Ρόλος" desc="Αλλαγή ρόλου δεν αλλάζει αυτόματα τα δικαιώματα.">
<select style={inputStyle} value={form.role} onChange={e => f('role', e.target.value)}>
{ALL_ROLES.map(r => <option key={r.value} value={r.value}>{r.label}</option>)}
</select>
</FormField>
</div>
</div>
</div>
{/* Col 2: Contact */}
<div style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16, borderRight: '1px solid #f3f4f6' }}>
<div>
<SectionLabel>Επικοινωνία</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<FormField label="Κινητό τηλέφωνο">
<input style={inputStyle} value={form.mobile_phone} onChange={e => f('mobile_phone', e.target.value)} />
</FormField>
<FormField label="Email">
<input style={inputStyle} type="email" value={form.email} onChange={e => f('email', e.target.value)} />
</FormField>
<FormField label="Σημείωση">
<textarea style={{ ...inputStyle, resize: 'none' }} value={form.note} onChange={e => f('note', e.target.value)} rows={4} />
</FormField>
</div>
</div>
</div>
{/* Col 3: Info + Payroll + PIN */}
<div style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16, background: '#fafafa' }}>
<div>
<SectionLabel>Πληροφορίες</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
<InfoBlock label="Εγγραφή"
value={member.created_at ? new Date(member.created_at).toLocaleDateString('el-GR') : null} />
<InfoBlock label="Κατάσταση"
value={member.is_active ? 'Ενεργός' : 'Αποκλεισμένος'}
valueColor={member.is_active ? '#16a34a' : '#ef4444'} />
</div>
<InfoBlock label="Ρόλος" value={ROLE_MAP[member.role]?.label || member.role} />
<InfoBlock label="Ζώνες" value={zoneLabel} />
</div>
</div>
<div>
<SectionLabel>Μισθοδοσία</SectionLabel>
<FormField label="Ωριαία αμοιβή (€/ώρα)" desc="Μόνο για διαχειριστές.">
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<input type="number" step="0.50" min="0" style={{ ...inputStyle, width: 110 }}
placeholder="π.χ. 5.50" value={form.hourly_rate}
onChange={e => f('hourly_rate', e.target.value)} />
{form.hourly_rate !== '' && parseFloat(form.hourly_rate) > 0
? <span style={{ fontSize: 11.5, color: '#16a34a', fontWeight: 500 }}>€{parseFloat(form.hourly_rate).toFixed(2)}/ώρα</span>
: <span style={{ fontSize: 11, color: '#9ca3af' }}>Δεν παρακολουθείται</span>
}
</div>
</FormField>
</div>
<div style={{ marginTop: 4, padding: 14, background: '#f3f4f6', borderRadius: 10 }}>
<p style={{ margin: '0 0 4px', fontSize: 11.5, fontWeight: 600, color: '#374151' }}>Κωδικός PIN</p>
<p style={{ margin: 0, fontSize: 11.5, color: '#6b7280', lineHeight: 1.5 }}>
Για αλλαγή PIN χρησιμοποιήστε την επιλογή <strong style={{ color: '#374151' }}>Επαναφορά PIN</strong> από το μενού Ενεργειών.
</p>
</div>
</div>
</div>
{/* Footer */}
<div style={{ padding: '14px 26px', borderTop: '1px solid #f3f4f6', display: 'flex', justifyContent: 'flex-end', gap: 10, flexShrink: 0 }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: '#fff', borderRadius: 8, fontSize: 13.5, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>
Ακύρωση
</button>
<button onClick={onSubmit} disabled={isPending || !canSubmit}
style={{ padding: '8px 20px', border: 'none', background: canSubmit ? '#111827' : '#d1d5db', color: '#fff', borderRadius: 8, fontSize: 13.5, fontWeight: 600, cursor: canSubmit ? 'pointer' : 'not-allowed' }}>
{isPending ? 'Αποθήκευση…' : 'Αποθήκευση αλλαγών'}
</button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,196 @@
// The week's schedule (plan step 6.11; replaces the v1 schedule page): who works when, for
// everyone who works here (the kitchen too). Two views: by person (a row each, a card per
// shift, + to add) and by hour (each day as a timeline, the opening hours shaded). A shift
// shows whether it was worked (the person's real shift started / ended) and its cost from the
// hourly pay; the week's hours and cost are at the top. The view's settings (first day of the
// week, the timeline's first hour, the opening hours) stay in this browser.
import { useMemo, useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ChevronLeft, ChevronRight, Plus, Settings2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import ShiftDialog from './ShiftDialog'
import ViewDialog from './ViewDialog'
import { addDays, gridOf, hourMarks, inOpening, loadView, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals } from './scheduleLogic'
const STATE = {
planned: 'border-info bg-info-soft text-info-ink',
working: 'border-success bg-success-soft text-success-ink',
worked: 'border-line bg-surface-2 text-ink-2',
}
const HOUR_PX = 44
export default function SchedulePage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const qc = useQueryClient()
const [view, setViewState] = useState(loadView)
const today = fmt.venueToday()
const [start, setStart] = useState(() => weekStartOf(today, loadView().mondayFirst))
const [editing, setEditing] = useState(null) // { date, userId, shift? }
const [settings, setSettings] = useState(false)
const setView = next => { setViewState(next); saveView(next) }
const { data, isPending } = useLiveQuery({
queryKey: ['schedule-week', start],
queryFn: () => client.get('/api/schedule/week', { params: { week_start: start } }).then(r => r.data),
})
const remove = useMutation({
mutationFn: id => client.delete(`/api/schedule/${id}`),
onSuccess: () => { toast.success(t('schedule.deleted')); qc.invalidateQueries({ queryKey: ['schedule-week'] }) },
onError: err => toast.error(errorMessage(err, t)),
})
const days = weekDays(start)
const people = data?.waiters ?? []
const scheduled = useMemo(() => data?.scheduled ?? [], [data])
const grid = useMemo(() => gridOf(scheduled), [scheduled])
const totals = weekTotals(scheduled)
const dayLabel = d => fmt.formatDateTime(`${d}T12:00:00Z`, { weekday: 'short' })
const dateLabel = d => fmt.formatDateTime(`${d}T12:00:00Z`, { day: '2-digit', month: '2-digit' })
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="schedule-page">
<div className="max-w-7xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('schedule.title')}</h1>
<p className="text-label text-ink-2" data-testid="schedule-totals">
{dateLabel(days[0])} – {dateLabel(days[6])} · {t('schedule.hours', { count: totals.hours })}
{totals.pay > 0 && ` · ${t('schedule.cost', { amount: fmt.formatMoney(totals.pay) })}`}
</p>
</div>
<div className="flex rounded-control border border-line overflow-hidden" role="group" aria-label={t('schedule.view')}>
{['people', 'hours'].map(v => (
<button key={v} type="button" aria-pressed={view.view === v} onClick={() => setView({ ...view, view: v })} data-testid={`schedule-view-${v}`}
className={cx('px-3 py-1.5 text-label font-medium', view.view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2')}>
{t(`schedule.views.${v}`)}
</button>
))}
</div>
<span className="flex items-center gap-1">
<IconButton variant="secondary" label={t('schedule.previous')} onClick={() => setStart(s => addDays(s, -7))}><ChevronLeft size={16} /></IconButton>
<Button variant="secondary" onClick={() => setStart(weekStartOf(today, view.mondayFirst))}>{t('schedule.thisWeek')}</Button>
<IconButton variant="secondary" label={t('schedule.next')} onClick={() => setStart(s => addDays(s, 7))} data-testid="schedule-next"><ChevronRight size={16} /></IconButton>
</span>
<IconButton variant="ghost" label={t('schedule.settings')} onClick={() => setSettings(true)}><Settings2 size={16} /></IconButton>
</header>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !people.length ? <EmptyState title={t('schedule.nobody')} />
: view.view === 'people' ? (
<div className="rounded-card border border-line bg-surface shadow-raised overflow-x-auto">
<table className="w-full min-w-[56rem] border-collapse text-label">
<thead>
<tr className="bg-surface-2">
<th className="text-left px-3 py-2 font-semibold text-ink-2 w-44">{t('schedule.person')}</th>
{days.map(d => (
<th key={d} className={cx('px-1 py-2 font-semibold', d === today ? 'text-accent-ink' : 'text-ink-2')}>
<span className="block capitalize">{dayLabel(d)}</span><span className="block text-caption font-normal">{dateLabel(d)}</span>
</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-line">
{people.map(p => (
<tr key={p.id} data-testid="schedule-person" data-name={p.name}>
<td className="px-3 py-2 align-top">
<span className="block font-semibold text-ink">{p.name}</span>
<span className="block text-caption text-ink-3">
{t(`roles.${p.role}`, { defaultValue: p.role ?? '' })}
{totals.people[p.id] ? ` · ${t('schedule.hours', { count: totals.people[p.id].hours })}` : ''}
</span>
</td>
{days.map(d => (
<td key={d} className={cx('px-1 py-1.5 align-top', d === today && 'bg-accent-soft/40')}>
<div className="grid gap-1 min-h-14">
{(grid[p.id]?.[d] ?? []).map(s => (
<button key={s.id} type="button" onClick={() => setEditing({ date: d, userId: p.id, shift: s })} data-testid="schedule-shift" data-state={shiftState(s)}
className={cx('text-left rounded-control border px-2 py-1', STATE[shiftState(s)])}>
<span className="block font-semibold tabular-nums">{s.start_time}–{s.end_time}</span>
<span className="block text-caption">
{t(`schedule.state.${shiftState(s)}`)}{s.estimated_pay != null ? ` · ${fmt.formatMoney(s.estimated_pay)}` : ''}
</span>
{s.notes && <span className="block text-caption italic truncate">{s.notes}</span>}
</button>
))}
<button type="button" onClick={() => setEditing({ date: d, userId: p.id })} aria-label={t('schedule.addFor', { name: p.name })}
className="h-6 rounded-control border border-dashed border-line text-ink-3 hover:border-accent hover:text-accent-ink grid place-items-center" data-testid="schedule-add">
<Plus size={14} />
</button>
</div>
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
) : (
<HoursView days={days} today={today} people={people} scheduled={scheduled} view={view} dayLabel={dayLabel} dateLabel={dateLabel}
onAdd={d => setEditing({ date: d, userId: null })} onOpen={(d, s) => setEditing({ date: d, userId: s.user_id, shift: s })} />
)}
<div className="flex flex-wrap gap-3 text-caption text-ink-2">
{['planned', 'working', 'worked'].map(s => (
<span key={s} className="inline-flex items-center gap-1.5"><span className={cx('w-4 h-3 rounded-sm border', STATE[s])} aria-hidden="true" />{t(`schedule.legend.${s}`)}</span>
))}
</div>
</div>
{editing && <ShiftDialog people={people} scheduled={scheduled} {...editing}
onClose={() => setEditing(null)} onDelete={id => { remove.mutate(id); setEditing(null) }}
onSaved={() => { setEditing(null); qc.invalidateQueries({ queryKey: ['schedule-week'] }) }} />}
{settings && <ViewDialog view={view} onClose={() => setSettings(false)}
onSave={next => { if (next.mondayFirst !== view.mondayFirst) setStart(weekStartOf(start, next.mondayFirst)); setView(next); setSettings(false) }} />}
</div>
)
}
function HoursView({ days, today, people, scheduled, view, dayLabel, dateLabel, onAdd, onOpen }) {
const { t } = useTranslation('manager')
const marks = hourMarks(view.firstHour)
const nameOf = id => people.find(p => p.id === id)?.nickname || people.find(p => p.id === id)?.name || `#${id}`
return (
<div className="rounded-card border border-line bg-surface shadow-raised overflow-x-auto" data-testid="schedule-hours">
<div className="flex min-w-[48rem]">
<div className="w-12 shrink-0 pt-10">
{marks.map(h => <div key={h} className="text-caption text-ink-3 text-right pr-1 -translate-y-2 tabular-nums" style={{ height: HOUR_PX }}>{String(h).padStart(2, '0')}:00</div>)}
</div>
{days.map(d => {
const shifts = scheduled.filter(s => s.scheduled_date === d)
const lanes = [...new Set(shifts.map(s => s.user_id))]
return (
<div key={d} className="flex-1 min-w-24 border-l border-line">
<div className={cx('h-10 grid place-items-center text-label font-semibold border-b border-line', d === today ? 'text-accent-ink bg-accent-soft' : 'text-ink-2 bg-surface-2')}>
<span className="capitalize leading-tight text-center">{dayLabel(d)}<span className="block text-caption font-normal">{dateLabel(d)}</span></span>
</div>
<div className="relative w-full cursor-copy" style={{ height: 24 * HOUR_PX }} onClick={() => onAdd(d)} title={t('schedule.addOn', { day: dayLabel(d) })} data-testid="schedule-day">
{marks.map((h, i) => (
<span key={h} className={cx('absolute inset-x-0 border-t', h === 0 ? 'border-info' : 'border-line', inOpening(h, view.open, view.close) && 'bg-accent-soft/40')}
style={{ top: i * HOUR_PX, height: HOUR_PX }} aria-hidden="true" />
))}
{shifts.map(s => {
const { top, height } = placeOnDay(s, view.firstHour)
const lane = lanes.indexOf(s.user_id)
const width = 100 / Math.max(lanes.length, 1)
return (
<button key={s.id} type="button" title={`${nameOf(s.user_id)} ${s.start_time}–${s.end_time}`}
onClick={e => { e.stopPropagation(); onOpen(d, s) }}
className={cx('absolute rounded-control border px-1 overflow-hidden text-caption font-semibold text-left', STATE[shiftState(s)])}
style={{ top: top * HOUR_PX, height: height * HOUR_PX, left: `calc(${lane * width}% + 2px)`, width: `calc(${width}% - 4px)` }}>
{nameOf(s.user_id)}
</button>
)
})}
</div>
</div>
)
})}
</div>
</div>
)
}
@@ -0,0 +1,58 @@
// A planned shift (plan step 6.11): who, from when to when (past midnight allowed), a note. A
// clash with the person's other shift that day is shown before saving (the server refuses it
// too). An existing shift can be changed or deleted; its person stays.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select } from '@xenia/ui'
import client from '../../api/client'
import { clashWith, hoursOf } from './scheduleLogic'
export default function ShiftDialog({ date, userId, shift, people, scheduled, onClose, onSaved, onDelete }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [person, setPerson] = useState(String(shift?.user_id ?? userId ?? people[0]?.id ?? ''))
const [start, setStart] = useState(shift?.start_time ?? '09:00')
const [end, setEnd] = useState(shift?.end_time ?? '17:00')
const [notes, setNotes] = useState(shift?.notes ?? '')
const clash = person && start && end ? clashWith(scheduled, { userId: Number(person), date, start, end, skipId: shift?.id ?? null }) : null
const rate = people.find(p => p.id === Number(person))?.hourly_rate
const save = useMutation({
mutationFn: () => (shift
? client.put(`/api/schedule/${shift.id}`, { start_time: start, end_time: end, notes: notes.trim() })
: client.post('/api/schedule/', { user_id: Number(person), scheduled_date: date, start_time: start, end_time: end, notes: notes.trim() || null })),
onSuccess: () => { toast.success(t(shift ? 'schedule.saved' : 'schedule.added')); onSaved() },
onError: err => toast.error(errorMessage(err, t)),
})
const hours = start && end ? hoursOf(start, end) : 0
return (
<Dialog open size="sm" onClose={onClose} title={t(shift ? 'schedule.editTitle' : 'schedule.newTitle')}
description={fmt.formatDateTime(`${date}T12:00:00Z`, { weekday: 'long', day: 'numeric', month: 'long' })}
footer={<>
{shift && <Button variant="ghost" icon={<Trash2 size={14} />} onClick={() => onDelete(shift.id)} data-testid="shift-delete">{t('schedule.delete')}</Button>}
<Button variant="secondary" onClick={onClose}>{t('schedule.back')}</Button>
<Button disabled={!person || !!clash} loading={save.isPending} onClick={() => save.mutate()} data-testid="shift-save">{t(shift ? 'schedule.save' : 'schedule.add')}</Button>
</>}>
<div className="grid gap-3" data-testid="shift-dialog">
<Field label={t('schedule.person')}>
<Select value={person} onChange={e => setPerson(e.target.value)} disabled={!!shift} data-testid="shift-person"
options={people.map(p => ({ value: String(p.id), label: p.name }))} />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field label={t('schedule.from')}><Input type="time" value={start} onChange={e => setStart(e.target.value)} data-testid="shift-start" /></Field>
<Field label={t('schedule.to')}><Input type="time" value={end} onChange={e => setEnd(e.target.value)} data-testid="shift-end" /></Field>
</div>
<p className="text-label text-ink-2">
{t('schedule.hours', { count: hours })}{rate ? ` · ${fmt.formatMoney(Math.round(hours * rate * 100) / 100)}` : ''}
{end && start && end <= start ? ` · ${t('schedule.overnight')}` : ''}
</p>
{clash && <p role="alert" className="rounded-control bg-danger-soft text-danger-ink text-label px-3 py-2" data-testid="shift-clash">{t('schedule.clash', { start: clash.start_time, end: clash.end_time })}</p>}
<Field label={t('schedule.note')}><Input value={notes} maxLength={200} onChange={e => setNotes(e.target.value)} placeholder={t('schedule.notePh')} /></Field>
</div>
</Dialog>
)
}
@@ -0,0 +1,33 @@
// How this browser shows the schedule (plan step 6.11): the week's first day, the timeline's
// first hour, the opening hours shaded on it. Nothing here changes the schedule itself.
import { useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select } from '@xenia/ui'
export default function ViewDialog({ view, onClose, onSave }) {
const { t } = useTranslation('manager')
const [v, setV] = useState(view)
const set = (k, val) => setV(x => ({ ...x, [k]: val }))
return (
<Dialog open size="sm" onClose={onClose} title={t('schedule.settings')} description={t('schedule.settingsHint')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('schedule.back')}</Button>
<Button onClick={() => onSave(v)}>{t('schedule.save')}</Button>
</>}>
<div className="grid gap-3">
<Field label={t('schedule.firstDay')}>
<Select value={v.mondayFirst ? 'mon' : 'sun'} onChange={e => set('mondayFirst', e.target.value === 'mon')}
options={[{ value: 'mon', label: t('schedule.monday') }, { value: 'sun', label: t('schedule.sunday') }]} />
</Field>
<Field label={t('schedule.firstHour')} hint={t('schedule.firstHourHint')}>
<Select value={String(v.firstHour)} onChange={e => set('firstHour', Number(e.target.value))}
options={Array.from({ length: 24 }, (_, h) => ({ value: String(h), label: `${String(h).padStart(2, '0')}:00` }))} />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field label={t('schedule.opens')} hint={t('schedule.openingHint')}><Input type="time" value={v.open} onChange={e => set('open', e.target.value)} /></Field>
<Field label={t('schedule.closes')}><Input type="time" value={v.close} onChange={e => set('close', e.target.value)} /></Field>
</div>
</div>
</Dialog>
)
}
@@ -0,0 +1,111 @@
// The weekly schedule as plain data (plan step 6.11), tested in tests/schedule.test.mjs. Dates
// are venue calendar days "YYYY-MM-DD"; times "HH:MM"; a shift that ends at or before its start
// runs past midnight (the backend reads them the same way).
const DAY_MS = 86_400_000
const parse = key => Date.UTC(Number(key.slice(0, 4)), Number(key.slice(5, 7)) - 1, Number(key.slice(8, 10)))
const keyOf = ms => new Date(ms).toISOString().slice(0, 10)
export const addDays = (key, n) => keyOf(parse(key) + n * DAY_MS)
/** 0 = Sunday … 6 = Saturday. */
export const dayOfWeek = key => new Date(parse(key)).getUTCDay()
/** The first day of the week holding `key` (Monday or Sunday first). */
export function weekStartOf(key, mondayFirst = true) {
const dow = dayOfWeek(key)
const back = mondayFirst ? (dow + 6) % 7 : dow
return addDays(key, -back)
}
export const weekDays = start => Array.from({ length: 7 }, (_, i) => addDays(start, i))
export function minutes(t) {
const [h, m] = String(t || '0:0').split(':').map(Number)
return h * 60 + m
}
/** [start, end] in minutes from the day's midnight; the end past 1440 when it runs overnight. */
export function span(start, end) {
const a = minutes(start)
let b = minutes(end)
if (b <= a) b += 1440
return [a, b]
}
export const hoursOf = (start, end) => { const [a, b] = span(start, end); return Math.round(((b - a) / 60) * 100) / 100 }
export function overlaps(s1, e1, s2, e2) {
const [a, b] = span(s1, e1)
const [c, d] = span(s2, e2)
return a < d && c < b
}
/** The shift a new or changed one would clash with (same person, same day), or null. */
export function clashWith(scheduled = [], { userId, date, start, end, skipId = null }) {
return scheduled.find(s => s.user_id === userId && s.scheduled_date === date && s.id !== skipId
&& overlaps(start, end, s.start_time, s.end_time)) ?? null
}
/** { userId: { date: [shifts by start] } } */
export function gridOf(scheduled = []) {
const g = {}
for (const s of scheduled) {
((g[s.user_id] ??= {})[s.scheduled_date] ??= []).push(s)
}
for (const days of Object.values(g)) for (const list of Object.values(days)) list.sort((a, b) => minutes(a.start_time) - minutes(b.start_time))
return g
}
/** 'planned' (not started) | 'working' (started, not ended) | 'worked' (started and ended). */
export function shiftState(shift) {
const actual = shift.actual_shifts ?? []
if (!actual.length) return 'planned'
return actual.some(a => a.is_active) ? 'working' : 'worked'
}
/** Hours and estimated pay per person for the week: { userId: { hours, pay } }, plus the totals. */
export function weekTotals(scheduled = []) {
const people = {}
let hours = 0
let pay = 0
for (const s of scheduled) {
const p = (people[s.user_id] ??= { hours: 0, pay: 0 })
const h = s.duration_hours ?? hoursOf(s.start_time, s.end_time)
p.hours += h
hours += h
if (s.estimated_pay != null) { p.pay += s.estimated_pay; pay += s.estimated_pay }
}
const r = n => Math.round(n * 100) / 100
for (const p of Object.values(people)) { p.hours = r(p.hours); p.pay = r(p.pay) }
return { people, hours: r(hours), pay: r(pay) }
}
/** Where a shift sits on a day's timeline drawn from `firstHour`: { top, height } in hours. */
export function placeOnDay(shift, firstHour = 6) {
const [a, b] = span(shift.start_time, shift.end_time)
const from = firstHour * 60
const top = ((a - from + 1440) % 1440) / 60
return { top, height: Math.max((b - a) / 60, 0.25) }
}
/** The 24 hour marks of a timeline starting at `firstHour`. */
export const hourMarks = firstHour => Array.from({ length: 24 }, (_, i) => (firstHour + i) % 24)
/** Is an hour mark inside the opening hours (start–end, past midnight allowed)? */
export function inOpening(hour, open, close) {
if (!open || !close) return false
const a = Math.floor(minutes(open) / 60)
const b = Math.floor(minutes(close) / 60)
return a <= b ? hour >= a && hour < b : hour >= a || hour < b
}
/** The schedule's view settings kept in this browser (a per-viewer convenience). */
export const VIEW_DEFAULTS = { view: 'people', mondayFirst: true, firstHour: 6, open: '', close: '' }
const VIEW_KEY = 'xenia:schedule:view'
export function loadView(storage = globalThis.localStorage) {
try { return { ...VIEW_DEFAULTS, ...JSON.parse(storage?.getItem(VIEW_KEY) || '{}') } } catch { return { ...VIEW_DEFAULTS } }
}
export function saveView(view, storage = globalThis.localStorage) {
try { storage?.setItem(VIEW_KEY, JSON.stringify(view)) } catch { /* private window: keep it for this visit */ }
}
@@ -3,13 +3,13 @@
// a sent item, change a price, a discount over the limit…). Backend: GET /api/access/overrides // a sent item, change a price, a discount over the limit…). Backend: GET /api/access/overrides
// (core.staff.manage), newest first, the latest 200. Rows are never deleted. // (core.staff.manage), newest first, the latest 200. Rows are never deleted.
// An approval is valid for 60 s, once: "Not used" = it expired before the action happened. // An approval is valid for 60 s, once: "Not used" = it expired before the action happened.
import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { ShieldCheck } from 'lucide-react' import { ShieldCheck } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation, useFormat } from '@xenia/i18n' import { useTranslation, useFormat } from '@xenia/i18n'
import { Button, EmptyState, Spinner } from '@xenia/ui' import { Button, EmptyState, Spinner } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { approvalState, approvalTarget, permLabelKey } from './permissionsLogic' import { approvalState, approvalTarget, permLabelKey } from './permissionsLogic'
const STATE_TONE = { const STATE_TONE = {
@@ -21,22 +21,11 @@ const STATE_TONE = {
export default function ApprovalsPage() { export default function ApprovalsPage() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const f = useFormat() const f = useFormat()
const [rows, setRows] = useState(null) // 6.11: loaded like the other v2 pages (react-query; a reconnect refreshes it)
const [error, setError] = useState(null) const { data: rows, error: failed, refetch } = useLiveQuery({ queryKey: ['approvals'], queryFn: () => client.get('/api/access/overrides').then(r => r.data) })
const error = failed ? errorMessage(failed, t) : null
const load = useCallback(async () => { if (error) return <div className="p-8"><EmptyState title={error} action={<Button variant="secondary" onClick={() => refetch()}>{t('common:actions.retry')}</Button>} /></div>
try {
const r = await client.get('/api/access/overrides')
setRows(r.data)
setError(null)
} catch (err) {
setError(errorMessage(err, t))
}
}, [t])
useEffect(() => { load() }, [load])
if (error) return <div className="p-8"><EmptyState title={error} action={<Button variant="secondary" onClick={load}>{t('common:actions.retry')}</Button>} /></div>
if (!rows) return <div className="p-8 flex justify-center"><Spinner /></div> if (!rows) return <div className="p-8 flex justify-center"><Spinner /></div>
return ( return (
@@ -0,0 +1,58 @@
// A new PIN, or a password, for someone (plan step 6.11). The PIN is 4 to 6 digits (the phones'
// and screens' PIN pad); the password at least 6 characters, for the password sign-in mode
// (KI-014). A password can also be taken away (PIN only). Typed twice; never shown back.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input } from '@xenia/ui'
import client from '../../api/client'
import { displayName, validPassword, validPin } from './staffLogic'
export default function SecretDialog({ kind, member, self, onClose, onSaved }) {
const { t } = useTranslation('manager')
const pin = kind === 'pin'
const [value, setValue] = useState('')
const [again, setAgain] = useState('')
const [tried, setTried] = useState(false)
const valid = pin ? validPin(value) : validPassword(value)
const same = value === again
const save = useMutation({
mutationFn: body => client.put(`/api/waiters/${member.id}/${kind}`, body),
onSuccess: (_r, body) => {
toast.success(t(pin ? 'staff.pinSaved' : body.password ? 'staff.passwordSaved' : 'staff.passwordRemoved', { name: displayName(member) }))
onSaved()
},
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (valid && same) save.mutate(pin ? { pin: value } : { password: value }) }
const clean = v => (pin ? v.replace(/\D/g, '').slice(0, 6) : v)
return (
<Dialog open size="sm" onClose={onClose}
title={t(pin ? 'staff.pinTitle' : 'staff.passwordTitle', { name: displayName(member) })}
description={pin ? t('staff.pinBody') : member.has_password ? t('staff.passwordBodyChange') : t('staff.passwordBodyNew')}
footer={<>
{!pin && member.has_password && !self && (
<Button variant="ghost" loading={save.isPending && save.variables?.password === null} onClick={() => save.mutate({ password: null })} data-testid="password-remove">
{t('staff.passwordRemove')}
</Button>
)}
<Button variant="secondary" onClick={onClose}>{t('staff.back')}</Button>
<Button loading={save.isPending && !!save.variables?.[kind]} onClick={submit} data-testid="secret-save">{t('staff.save')}</Button>
</>}>
<form className="grid gap-3" onSubmit={e => { e.preventDefault(); submit() }} data-testid="secret-dialog">
<Field label={t(pin ? 'staff.pinLabel' : 'staff.passwordLabel')} hint={t(pin ? 'staff.pinHint' : 'staff.passwordHint')}
error={tried && !valid ? t(pin ? 'staff.wrong.pin' : 'staff.wrong.password') : undefined}>
<Input type="password" autoFocus autoComplete="new-password" inputMode={pin ? 'numeric' : undefined} value={value}
onChange={e => setValue(clean(e.target.value))} data-testid="secret-value" />
</Field>
<Field label={t('staff.again')} error={tried && valid && !same ? t('staff.notSame') : undefined}>
<Input type="password" autoComplete="new-password" inputMode={pin ? 'numeric' : undefined} value={again}
onChange={e => setAgain(clean(e.target.value))} data-testid="secret-again" />
</Field>
</form>
</Dialog>
)
}
@@ -0,0 +1,103 @@
// A person's details (plan step 6.11): new (with their PIN, and a password if the venue signs in
// by password) or edit (and their photo). The role sets a new person's permissions; changing it
// later doesn't change them (the permissions button does). Hourly pay is for the schedule's costs.
import { useRef, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Camera, Trash2 } from 'lucide-react'
import { useAccess } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { LANGUAGE_NAMES, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { Avatar } from '../overview/parts'
import { ROLES, displayName, staffBody, staffForm, staffProblems } from './staffLogic'
export default function StaffDialog({ member, onClose, onSaved }) {
const { t } = useTranslation('manager')
const { languages, user: me } = useAccess()
const isNew = !member
const [form, setForm] = useState(() => staffForm(member))
const [photo, setPhoto] = useState(member?.avatar_url ?? null)
const [tried, setTried] = useState(false)
const fileRef = useRef(null)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const wrong = staffProblems(form, isNew)
const err = k => (tried && wrong.includes(k) ? t(`staff.wrong.${k}`) : undefined)
const roles = me?.role === 'superadmin' ? ['superadmin', ...ROLES] : ROLES
const save = useMutation({
mutationFn: body => (isNew ? client.post('/api/waiters/', body) : client.put(`/api/waiters/${member.id}`, body)),
onSuccess: () => { toast.success(t(isNew ? 'staff.added' : 'staff.saved', { name: form.full_name.trim() })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const upload = useMutation({
mutationFn: file => { const fd = new FormData(); fd.append('file', file); return client.post(`/api/waiters/${member.id}/avatar`, fd).then(r => r.data) },
onSuccess: m => { setPhoto(m.avatar_url); toast.success(t('staff.photoSaved')) },
onError: e => toast.error(errorMessage(e, t)),
})
const dropPhoto = useMutation({
mutationFn: () => client.delete(`/api/waiters/${member.id}/avatar`),
onSuccess: () => setPhoto(null), onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate(staffBody(form, isNew)) }
return (
<Dialog open size="lg" onClose={onClose} title={isNew ? t('staff.newTitle') : displayName(member)}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('staff.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="staff-save">{isNew ? t('staff.add') : t('staff.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="staff-dialog">
{!isNew && (
<div className="flex items-center gap-3">
<Avatar name={displayName(member)} url={photo} size="lg" />
<input ref={fileRef} type="file" accept="image/*" hidden onChange={e => { const f = e.target.files?.[0]; if (f) upload.mutate(f); e.target.value = '' }} />
<Button size="sm" variant="secondary" icon={<Camera size={14} />} loading={upload.isPending} onClick={() => fileRef.current?.click()}>{t('staff.photo')}</Button>
{photo && <Button size="sm" variant="ghost" icon={<Trash2 size={14} />} loading={dropPhoto.isPending} onClick={() => dropPhoto.mutate()}>{t('staff.photoRemove')}</Button>}
</div>
)}
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('staff.fullName')} required hint={t('staff.fullNameHint')} error={err('full_name')}>
<Input value={form.full_name} onChange={e => set('full_name', e.target.value)} data-testid="staff-full-name" />
</Field>
<Field label={t('staff.nickname')} required hint={t('staff.nicknameHint')} error={err('nickname')}>
<Input value={form.nickname} onChange={e => set('nickname', e.target.value)} data-testid="staff-nickname" />
</Field>
<Field label={t('staff.username')} required hint={t('staff.usernameHint')} error={err('username')}>
<Input value={form.username} autoCapitalize="none" onChange={e => set('username', e.target.value)} data-testid="staff-username" />
</Field>
<Field label={t('staff.role')} hint={isNew ? t('staff.roleHintNew') : t('staff.roleHintEdit')}>
<Select value={form.role} onChange={e => set('role', e.target.value)} data-testid="staff-role"
options={roles.map(r => ({ value: r, label: t(`roles.${r}`) }))} />
</Field>
</div>
{isNew && (
<div className="grid gap-3 sm:grid-cols-2 p-3 rounded-card bg-surface-2">
<Field label={t('staff.pinLabel')} required hint={t('staff.pinHint')} error={err('pin')}>
<Input type="password" inputMode="numeric" autoComplete="new-password" maxLength={6} value={form.pin}
onChange={e => set('pin', e.target.value.replace(/\D/g, ''))} data-testid="staff-new-pin" />
</Field>
<Field label={t('staff.passwordLabel')} hint={t('staff.passwordHintNew')} error={err('password')}>
<Input type="password" autoComplete="new-password" value={form.password} onChange={e => set('password', e.target.value)} data-testid="staff-new-password" />
</Field>
</div>
)}
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('staff.phone')}><Input type="tel" value={form.mobile_phone} onChange={e => set('mobile_phone', e.target.value)} /></Field>
<Field label={t('staff.email')}><Input type="email" value={form.email} onChange={e => set('email', e.target.value)} /></Field>
<Field label={t('staff.rate')} hint={t('staff.rateHint')} error={err('hourly_rate')}>
<Input inputMode="decimal" value={form.hourly_rate} onChange={e => set('hourly_rate', e.target.value)} data-testid="staff-rate" />
</Field>
<Field label={t('staff.language')} hint={t('staff.languageHint')}>
<Select value={form.language} onChange={e => set('language', e.target.value)}
options={[{ value: '', label: t('staff.venueLanguage') }, ...(languages || ['en', 'el']).map(l => ({ value: l, label: LANGUAGE_NAMES[l] || l }))]} />
</Field>
</div>
<Field label={t('staff.note')} hint={t('staff.noteHint')}>
<Textarea rows={2} value={form.note} onChange={e => set('note', e.target.value)} />
</Field>
</div>
</Dialog>
)
}
@@ -0,0 +1,147 @@
// Staff (plan step 6.11; replaces the v1 Management → Staff table): everyone who works here,
// with their role, whether they can sign in (blocked or not; PIN, password), what they may do
// (permission keys, "custom" when they differ from the role) and their zones. New person, edit
// (and photo), a new PIN, a password (KI-014: the password sign-in mode works for everyone now),
// zones, permissions, block / unblock, delete (only someone without history).
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Ban, CheckCircle2, KeyRound, LockKeyhole, MapPin, Pencil, Plus, Search, ShieldCheck, Trash2, Users } from 'lucide-react'
import { useAccess } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Select, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Avatar, Pill } from '../overview/parts'
import PermissionEditor from './PermissionEditor'
import SecretDialog from './SecretDialog'
import StaffDialog from './StaffDialog'
import ZonesDialog from './ZonesDialog'
import { GROUPS, ROLES, customKeys, displayName, filterStaff, groupCounts, zonesSummary } from './staffLogic'
export default function StaffPage() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const { user: me } = useAccess()
const [filter, setFilter] = useState({ role: '', status: '', q: '' })
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'pin' | 'password' | 'zones' | 'perms' | 'delete', member }
const { data: staff, isPending } = useLiveQuery({ queryKey: ['staff'], queryFn: () => client.get('/api/waiters/').then(r => r.data) })
const { data: catalog } = useLiveQuery({ queryKey: ['permission-catalog'], queryFn: () => client.get('/api/waiters/permission-catalog').then(r => r.data), staleTime: 300_000 })
const { data: groups = [] } = useLiveQuery({ queryKey: ['table-groups'], queryFn: () => client.get('/api/tables/groups').then(r => r.data), staleTime: 60_000 })
const changed = () => qc.invalidateQueries({ queryKey: ['staff'] })
const onError = err => toast.error(errorMessage(err, t))
const block = useMutation({
mutationFn: m => client.put(`/api/waiters/${m.id}/block`).then(r => r.data),
onSuccess: (r, m) => { toast.success(t(r.is_active ? 'staff.unblocked' : 'staff.blocked', { name: displayName(m) })); changed() }, onError,
})
const remove = useMutation({
mutationFn: m => client.delete(`/api/waiters/${m.id}`),
onSuccess: (_r, m) => { toast.success(t('staff.deleted', { name: displayName(m) })); setDialog(null); changed() }, onError,
})
const set = (k, v) => setFilter(f => ({ ...f, [k]: v }))
const shown = filterStaff(staff ?? [], filter)
const counts = groupCounts(staff ?? [])
const open = (kind, member = null) => setDialog({ kind, member })
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="staff-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('staff.title')}</h1>
<p className="text-label text-ink-2">
{GROUPS.filter(g => counts[g]).map(g => t(`staff.groups.${g}`, { count: counts[g] })).join(' · ')}
</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => open('new')} data-testid="staff-new">{t('staff.new')}</Button>
</header>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('staff.search')} aria-label={t('staff.search')} className="pl-9" data-testid="staff-search" />
</div>
<Select size="sm" value={filter.role} onChange={e => set('role', e.target.value)} aria-label={t('staff.role')}
options={[{ value: '', label: t('staff.allRoles') }, ...ROLES.map(r => ({ value: r, label: t(`roles.${r}`) }))]} />
<Select size="sm" value={filter.status} onChange={e => set('status', e.target.value)} aria-label={t('staff.status')}
options={[{ value: '', label: t('staff.anyStatus') }, { value: 'active', label: t('staff.active') }, { value: 'blocked', label: t('staff.blockedState') }]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !shown.length ? <EmptyState icon={<Users size={28} />} title={t('staff.none')} />
: (
<ul className="rounded-card border border-line bg-surface shadow-raised divide-y divide-line overflow-hidden">
{shown.map(m => {
const support = m.role === 'superadmin'
const zones = zonesSummary(m, groups)
return (
<li key={m.id} className={cx('px-4 py-3 flex flex-wrap items-center gap-3', !m.is_active && 'bg-surface-2')} data-testid="staff-row" data-username={m.username}>
<button type="button" className="flex items-center gap-3 flex-1 min-w-60 text-left" onClick={() => !support && open('edit', m)} disabled={support}>
<Avatar name={displayName(m)} url={m.avatar_url} />
<span className="grid min-w-0">
<span className={cx('text-body font-semibold truncate', m.is_active ? 'text-ink' : 'text-ink-3 line-through')}>{displayName(m)}</span>
<span className="flex flex-wrap items-center gap-1.5 text-caption text-ink-2">
<Pill tone="accent">{t(`roles.${m.role}`, { defaultValue: m.role })}</Pill>
<span>@{m.username}</span>
{m.nickname && m.nickname !== m.full_name && <span>· {m.nickname}</span>}
</span>
</span>
</button>
<span className="flex flex-wrap items-center gap-1.5 w-full sm:w-auto">
{!m.is_active && <Pill tone="danger">{t('staff.blockedState')}</Pill>}
<Pill tone={m.has_password ? 'success' : 'neutral'} title={t('staff.signInTip')}>{m.has_password ? t('staff.pinAndPassword') : t('staff.pinOnly')}</Pill>
{!support && (
<span data-testid={`staff-perms-${m.id}`}>
<button type="button" onClick={() => open('perms', m)} className="inline-flex items-center gap-1 text-caption text-ink-2 hover:text-accent-ink">
<ShieldCheck size={13} aria-hidden="true" />{t('permissions.count', { count: m.permissions?.length || 0 })}
{customKeys(m, catalog?.role_templates) && <Pill tone="warning">{t('permissions.custom')}</Pill>}
</button>
</span>
)}
{support && <span className="text-caption text-ink-3">{t('permissions.all')}</span>}
{(m.zone_assignments?.length > 0 || m.permissions?.includes('waiter_app.access')) && (
<span className="inline-flex items-center gap-1 text-caption text-ink-2" title={t('staff.zones')}>
<MapPin size={13} aria-hidden="true" />{zones === 'all' ? t('staff.allZones') : zones === 'none' ? t('staff.noZones') : zones}
</span>
)}
</span>
{!support && (
<span className="flex gap-0.5 ml-auto">
<IconButton size="sm" variant="ghost" label={t('staff.edit', { name: displayName(m) })} onClick={() => open('edit', m)}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('staff.pin', { name: displayName(m) })} onClick={() => open('pin', m)} data-testid="staff-pin"><KeyRound size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('staff.password', { name: displayName(m) })} onClick={() => open('password', m)} data-testid="staff-password"><LockKeyhole size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('staff.zonesOf', { name: displayName(m) })} onClick={() => open('zones', m)}><MapPin size={15} /></IconButton>
{m.id !== me?.id && (<>
<IconButton size="sm" variant="ghost" label={t(m.is_active ? 'staff.block' : 'staff.unblock', { name: displayName(m) })}
onClick={() => block.mutate(m)} data-testid="staff-block">{m.is_active ? <Ban size={15} /> : <CheckCircle2 size={15} />}</IconButton>
<IconButton size="sm" variant="ghost" label={t('staff.delete', { name: displayName(m) })} onClick={() => open('delete', m)}><Trash2 size={15} /></IconButton>
</>)}
</span>
)}
</li>
)
})}
</ul>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && (
<StaffDialog member={dialog.member} onClose={() => setDialog(null)} onSaved={() => { setDialog(null); changed() }} />
)}
{(dialog?.kind === 'pin' || dialog?.kind === 'password') && (
<SecretDialog kind={dialog.kind} member={dialog.member} self={dialog.member.id === me?.id} onClose={() => setDialog(null)} onSaved={() => { setDialog(null); changed() }} />
)}
{dialog?.kind === 'zones' && <ZonesDialog member={dialog.member} groups={groups} onClose={() => setDialog(null)} onSaved={() => { setDialog(null); changed() }} />}
{dialog?.kind === 'perms' && <PermissionEditor member={dialog.member} onClose={() => { setDialog(null); changed() }} />}
{dialog?.kind === 'delete' && (
<Dialog open size="sm" onClose={() => setDialog(null)} title={t('staff.deleteTitle', { name: displayName(dialog.member) })} description={t('staff.deleteBody')}
footer={<>
<Button variant="secondary" onClick={() => setDialog(null)}>{t('staff.back')}</Button>
{dialog.member.is_active && <Button variant="secondary" onClick={() => { block.mutate(dialog.member); setDialog(null) }}>{t('staff.blockInstead')}</Button>}
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.member)} data-testid="staff-delete-confirm">{t('staff.deleteYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,50 @@
// Which tables someone serves (plan step 6.11): every zone, or some of them. Their phone and the
// table map only show those tables; someone with no zone sees none.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Switch, cx } from '@xenia/ui'
import client from '../../api/client'
import { displayName, zonesBody, zonesOf } from './staffLogic'
export default function ZonesDialog({ member, groups, onClose, onSaved }) {
const { t } = useTranslation('manager')
const [zones, setZones] = useState(() => zonesOf(member))
const save = useMutation({
mutationFn: () => client.put(`/api/waiters/${member.id}/zones`, zonesBody(zones)),
onSuccess: () => { toast.success(t('staff.zonesSaved', { name: displayName(member) })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const toggle = id => setZones(z => ({ ...z, ids: z.ids.includes(id) ? z.ids.filter(x => x !== id) : [...z.ids, id] }))
return (
<Dialog open size="sm" onClose={onClose} title={t('staff.zonesOf', { name: displayName(member) })} description={t('staff.zonesBody')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('staff.back')}</Button>
<Button loading={save.isPending} onClick={() => save.mutate()}>{t('staff.save')}</Button>
</>}>
<div className="grid gap-3">
<label className="flex items-center gap-3 text-body font-medium text-ink">
<Switch checked={zones.all} onChange={v => setZones(z => ({ ...z, all: v }))} aria-label={t('staff.allZones')} />{t('staff.allZones')}
</label>
{!zones.all && (
groups.length === 0 ? <p className="text-label text-ink-3">{t('staff.noGroups')}</p> : (
<div className="flex flex-wrap gap-1.5">
{groups.map(g => {
const on = zones.ids.includes(g.id)
return (
<button key={g.id} type="button" aria-pressed={on} onClick={() => toggle(g.id)}
className={cx('px-3 py-1.5 rounded-full border text-label', on ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{g.name}
</button>
)
})}
</div>
)
)}
{!zones.all && !zones.ids.length && <p className="text-label text-warning-ink" role="note">{t('staff.noZonesWarn')}</p>}
</div>
</Dialog>
)
}
@@ -0,0 +1,110 @@
// The staff page as plain data (plan step 6.11), tested in tests/staff.test.mjs.
/** The roles in the order the page lists them (backend roles.py); names are i18n `roles.*`. */
export const ROLES = ['owner', 'store_manager', 'staff_manager', 'chef', 'assistant_chef', 'barista', 'barman', 'waiter', 'assistant_waiter', 'custom']
const GROUP = {
superadmin: 'management', owner: 'management', store_manager: 'management', staff_manager: 'management',
chef: 'kitchen', assistant_chef: 'kitchen', barista: 'kitchen', barman: 'kitchen',
waiter: 'service', assistant_waiter: 'service',
}
export const GROUPS = ['management', 'kitchen', 'service', 'other']
export const groupOf = role => GROUP[role] ?? 'other'
export const displayName = m => (m ? m.full_name || m.nickname || m.username : '')
/** How many people in each group (the page's header). */
export function groupCounts(staff = []) {
const out = Object.fromEntries(GROUPS.map(g => [g, 0]))
for (const m of staff) out[groupOf(m.role)] += 1
return out
}
const fold = s => String(s ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
/** Staff shown for a role ('' = all), a status ('' | 'active' | 'blocked') and a search
* (name, nickname, username, phone; accents ignored); active first, then by name. */
export function filterStaff(staff = [], { role = '', status = '', q = '' } = {}) {
const words = fold(q).split(/\s+/).filter(Boolean)
return staff
.filter(m => (!role || m.role === role) && (!status || (status === 'active') === !!m.is_active))
.filter(m => {
if (!words.length) return true
const text = fold([m.full_name, m.nickname, m.username, m.mobile_phone].join(' '))
return words.every(w => text.includes(w))
})
.sort((a, b) => Number(!!b.is_active) - Number(!!a.is_active) || displayName(a).localeCompare(displayName(b)))
}
// ── the person's form ───────────────────────────────────────────────────────
export const EMPTY_STAFF = {
full_name: '', nickname: '', username: '', role: 'waiter', mobile_phone: '', email: '', note: '',
hourly_rate: '', language: '', pin: '', password: '',
}
export function staffForm(m) {
if (!m) return { ...EMPTY_STAFF }
const out = { ...EMPTY_STAFF }
for (const k of Object.keys(EMPTY_STAFF)) if (m[k] != null && k !== 'pin' && k !== 'password') out[k] = String(m[k])
return out
}
export const validPin = pin => /^\d{4,6}$/.test(pin ?? '')
export const validPassword = pw => (pw ?? '').length >= 6
/** The fields that are wrong (empty = fine). A new person needs a PIN; a password is optional. */
export function staffProblems(form, isNew) {
const out = []
if (!form.full_name.trim()) out.push('full_name')
if (!form.nickname.trim()) out.push('nickname')
if (!/^[^\s]{2,}$/.test(form.username.trim())) out.push('username')
const rate = String(form.hourly_rate).trim().replace(',', '.')
if (rate && !(Number(rate) >= 0)) out.push('hourly_rate')
if (isNew && !validPin(form.pin)) out.push('pin')
if (isNew && form.password && !validPassword(form.password)) out.push('password')
return out
}
/** POST /api/waiters/ (new) or PUT /api/waiters/{id} (edit). */
export function staffBody(form, isNew) {
const text = v => (v ?? '').trim() || null
const rate = String(form.hourly_rate).trim().replace(',', '.')
const body = {
full_name: form.full_name.trim(), nickname: form.nickname.trim(), username: form.username.trim(), role: form.role,
mobile_phone: text(form.mobile_phone), email: text(form.email), note: text(form.note),
hourly_rate: rate ? Number(rate) : null, language: form.language || '',
}
if (isNew) {
body.pin = form.pin
body.is_active = true
body.language = form.language || null
if (form.password) body.password = form.password
}
return body
}
// ── zones ───────────────────────────────────────────────────────────────────
/** A person's zones: { all, ids } (all = every zone). */
export function zonesOf(member) {
const rows = member?.zone_assignments ?? []
return { all: rows.some(z => z.group_id == null), ids: rows.map(z => z.group_id).filter(id => id != null) }
}
/** 'all' | 'none' | the zones' names. */
export function zonesSummary(member, groups = []) {
const { all, ids } = zonesOf(member)
if (all) return 'all'
if (!ids.length) return 'none'
return ids.map(id => groups.find(g => g.id === id)?.name ?? `#${id}`).join(', ')
}
export const zonesBody = ({ all, ids }) => ({ all_zones: all, group_ids: all ? [] : ids })
/** Does the role's set of keys differ from the person's? (the "custom" mark) */
export function customKeys(member, templates) {
const role = templates?.[member.role]
if (!role || member.role === 'superadmin') return false
const a = new Set(member.permissions ?? [])
return a.size !== role.length || role.some(k => !a.has(k))
}
+91
View File
@@ -0,0 +1,91 @@
// The staff page and the weekly schedule as plain data (plan step 6.11).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
customKeys, filterStaff, groupCounts, groupOf, staffBody, staffForm, staffProblems, validPin, zonesBody, zonesOf, zonesSummary,
} from '../src/pages/staff/staffLogic.js'
import {
addDays, clashWith, gridOf, hourMarks, hoursOf, inOpening, loadView, overlaps, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals,
} from '../src/pages/schedule/scheduleLogic.js'
const staff = [
{ id: 1, full_name: 'Μαρία Κωνσταντίνου', nickname: 'Μαρία', username: 'maria', role: 'waiter', is_active: true, mobile_phone: '6901' },
{ id: 2, full_name: 'Nikos P', username: 'nikos', role: 'chef', is_active: false },
{ id: 3, full_name: 'Anna', username: 'anna', role: 'owner', is_active: true },
]
test('groups, filters (role, status, search without accents), active first', () => {
assert.equal(groupOf('barman'), 'kitchen')
assert.equal(groupOf('custom'), 'other')
assert.deepEqual(groupCounts(staff), { management: 1, kitchen: 1, service: 1, other: 0 })
assert.deepEqual(filterStaff(staff).map(m => m.id).at(-1), 2) // blocked last
assert.deepEqual(filterStaff(staff, { q: 'μαρια' }).map(m => m.id), [1])
assert.deepEqual(filterStaff(staff, { q: '6901' }).map(m => m.id), [1])
assert.deepEqual(filterStaff(staff, { status: 'blocked' }).map(m => m.id), [2])
assert.deepEqual(filterStaff(staff, { role: 'owner' }).map(m => m.id), [3])
})
test('the form: what is wrong for a new person and an edit, and the bodies', () => {
const f = { ...staffForm(null), full_name: ' Eleni ', nickname: 'Eleni', username: 'el eni', pin: '12', password: 'abc' }
assert.deepEqual(staffProblems(f, true), ['username', 'pin', 'password'])
assert.deepEqual(staffProblems({ ...f, username: 'eleni', pin: '1234', password: '' }, true), [])
assert.deepEqual(staffProblems({ ...f, username: 'eleni', hourly_rate: 'x' }, false), ['hourly_rate'])
assert.equal(validPin('123456'), true)
assert.equal(validPin('12345a'), false)
const body = staffBody({ ...f, username: 'eleni', pin: '1234', password: 'secret1', hourly_rate: '8,5' }, true)
assert.equal(body.full_name, 'Eleni')
assert.equal(body.hourly_rate, 8.5)
assert.equal(body.password, 'secret1')
assert.equal(body.language, null)
const edit = staffBody(staffForm({ ...staff[0], hourly_rate: 9, language: 'el' }), false)
assert.equal('pin' in edit, false)
assert.equal(edit.language, 'el')
assert.equal(staffBody(staffForm(staff[0]), false).language, '') // '' = as the venue
})
test('zones and the "custom keys" mark', () => {
const groups = [{ id: 1, name: 'Terrace' }, { id: 2, name: 'Inside' }]
assert.deepEqual(zonesOf({ zone_assignments: [{ group_id: null }] }), { all: true, ids: [] })
assert.equal(zonesSummary({ zone_assignments: [] }, groups), 'none')
assert.equal(zonesSummary({ zone_assignments: [{ group_id: 2 }, { group_id: 1 }] }, groups), 'Inside, Terrace')
assert.deepEqual(zonesBody({ all: true, ids: [1] }), { all_zones: true, group_ids: [] })
assert.equal(customKeys({ role: 'waiter', permissions: ['a', 'b'] }, { waiter: ['b', 'a'] }), false)
assert.equal(customKeys({ role: 'waiter', permissions: ['a'] }, { waiter: ['a', 'b'] }), true)
})
test('weeks: Monday or Sunday first, crossing months', () => {
assert.equal(weekStartOf('2026-11-19', true), '2026-11-16') // a Thursday
assert.equal(weekStartOf('2026-11-22', true), '2026-11-16') // Sunday belongs to the week before
assert.equal(weekStartOf('2026-11-22', false), '2026-11-22')
assert.deepEqual(weekDays('2026-11-30').slice(0, 3), ['2026-11-30', '2026-12-01', '2026-12-02'])
assert.equal(addDays('2026-03-28', 2), '2026-03-30') // across the clock change
})
test('shifts: hours past midnight, clashes, the grid, states, totals, the timeline', () => {
assert.equal(hoursOf('18:00', '02:00'), 8)
assert.equal(overlaps('22:00', '02:00', '01:00', '03:00'), false) // same day: 01:00 is the morning
assert.equal(overlaps('10:00', '14:00', '13:00', '19:00'), true)
const scheduled = [
{ id: 1, user_id: 7, scheduled_date: '2026-11-19', start_time: '18:00', end_time: '23:00', duration_hours: 5, estimated_pay: 40 },
{ id: 2, user_id: 7, scheduled_date: '2026-11-19', start_time: '09:00', end_time: '13:00', duration_hours: 4, estimated_pay: 32, actual_shifts: [{ is_active: true }] },
]
assert.equal(clashWith(scheduled, { userId: 7, date: '2026-11-19', start: '12:00', end: '15:00' })?.id, 2)
assert.equal(clashWith(scheduled, { userId: 7, date: '2026-11-19', start: '12:00', end: '15:00', skipId: 2 }), null)
assert.deepEqual(gridOf(scheduled)[7]['2026-11-19'].map(s => s.id), [2, 1])
assert.equal(shiftState(scheduled[0]), 'planned')
assert.equal(shiftState(scheduled[1]), 'working')
assert.deepEqual(weekTotals(scheduled), { people: { 7: { hours: 9, pay: 72 } }, hours: 9, pay: 72 })
assert.deepEqual(placeOnDay({ start_time: '02:00', end_time: '04:30' }, 6), { top: 20, height: 2.5 })
assert.equal(hourMarks(22)[2], 0)
assert.equal(inOpening(23, '18:00', '02:00'), true)
assert.equal(inOpening(3, '18:00', '02:00'), false)
})
test('the view settings stay in this browser and survive a broken store', () => {
const store = new Map()
const fake = { getItem: k => store.get(k) ?? null, setItem: (k, v) => store.set(k, v) }
saveView({ view: 'hours', mondayFirst: false }, fake)
assert.equal(loadView(fake).view, 'hours')
assert.equal(loadView(fake).firstHour, 6)
assert.equal(loadView({ getItem: () => '{bad' }).view, 'people')
})
+2 -2
View File
@@ -1,9 +1,9 @@
{ {
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
"paths": [ "paths": [
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing" "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule"
], ],
"strict": [ "strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing" "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule"
] ]
} }
+9 -2
View File
@@ -297,10 +297,17 @@
"role_invalid": "Δεν υπάρχει ρόλος {{role}}.", "role_invalid": "Δεν υπάρχει ρόλος {{role}}.",
"avatar_type": "Η φωτογραφία πρέπει να είναι αρχείο εικόνας.", "avatar_type": "Η φωτογραφία πρέπει να είναι αρχείο εικόνας.",
"assignment_exists": "Αυτή η ανάθεση υπάρχει ήδη.", "assignment_exists": "Αυτή η ανάθεση υπάρχει ήδη.",
"assignment_not_found": "Η ανάθεση δεν βρέθηκε." "assignment_not_found": "Η ανάθεση δεν βρέθηκε.",
"pin_invalid": "Το PIN είναι {{min}} έως {{max}} ψηφία.",
"password_own": "Τον δικό σας κωδικό τον αλλάζετε από το προφίλ σας.",
"delete_self": "Δεν μπορείτε να διαγράψετε τον εαυτό σας.",
"username_needed": "Κάθε άτομο χρειάζεται όνομα χρήστη.",
"has_history": "{{name}}: υπάρχουν παραγγελίες ή βάρδιες, οπότε δεν διαγράφεται. Μπλοκάρετέ τον: δεν θα συνδέεται και οι αναφορές κρατούν το όνομά του."
}, },
"schedule": { "schedule": {
"shift_not_found": "Η προγραμματισμένη βάρδια δεν βρέθηκε." "shift_not_found": "Η προγραμματισμένη βάρδια δεν βρέθηκε.",
"bad_time": "Οι ώρες γράφονται όπως 09:30.",
"overlap": "{{name}}: υπάρχει ήδη βάρδια {{start}} έως {{end}} εκείνη τη μέρα."
}, },
"setup": { "setup": {
"done": "Η αρχική ρύθμιση έχει γίνει: υπάρχει ήδη λογαριασμός διαχειριστή." "done": "Η αρχική ρύθμιση έχει γίνει: υπάρχει ήδη λογαριασμός διαχειριστή."
+149
View File
@@ -2566,5 +2566,154 @@
"testHint": "Ακούστε τον σε έναν εκτυπωτή.", "testHint": "Ακούστε τον σε έναν εκτυπωτή.",
"test": "Δοκιμή ήχου" "test": "Δοκιμή ήχου"
} }
},
"staff": {
"title": "Προσωπικό",
"new": "Νέο άτομο",
"none": "Κανείς δεν ταιριάζει.",
"search": "Αναζήτηση με όνομα, όνομα χρήστη ή τηλέφωνο…",
"role": "Ρόλος",
"allRoles": "Όλοι οι ρόλοι",
"status": "Κατάσταση",
"anyStatus": "Ενεργοί ή μπλοκαρισμένοι",
"active": "Ενεργοί",
"blockedState": "Μπλοκαρισμένος",
"groups": {
"management_one": "{{count}} στη διοίκηση",
"management_other": "{{count}} στη διοίκηση",
"kitchen_one": "{{count}} σε κουζίνα και μπαρ",
"kitchen_other": "{{count}} σε κουζίνα και μπαρ",
"service_one": "{{count}} στο σέρβις",
"service_other": "{{count}} στο σέρβις",
"other_one": "{{count}} άλλος",
"other_other": "{{count}} άλλοι"
},
"pinOnly": "PIN",
"pinAndPassword": "PIN + κωδικός",
"signInTip": "Πώς μπορεί να συνδεθεί: ο τρόπος σύνδεσης του καταστήματος ορίζει τι ζητείται.",
"zones": "Ζώνες",
"allZones": "Όλες οι ζώνες",
"noZones": "Καμία ζώνη",
"edit": "Επεξεργασία {{name}}",
"pin": "Νέο PIN για {{name}}",
"password": "Κωδικός για {{name}}",
"zonesOf": "Ζώνες: {{name}}",
"block": "Μπλοκάρισμα {{name}}",
"unblock": "Ξεμπλοκάρισμα {{name}}",
"delete": "Διαγραφή {{name}}",
"blocked": "{{name}}: μπλοκαρίστηκε και αποσυνδέθηκε παντού",
"unblocked": "{{name}}: μπορεί ξανά να συνδεθεί",
"deleteTitle": "Διαγραφή {{name}};",
"deleteBody": "Διαγράφεται μόνο κάποιος χωρίς παραγγελίες ή βάρδιες. Οι υπόλοιποι μπλοκάρονται: δεν συνδέονται και οι αναφορές κρατούν το όνομά τους.",
"deleteYes": "Διαγραφή",
"blockInstead": "Μπλοκάρισμα αντί γι' αυτό",
"deleted": "{{name}}: διαγράφηκε",
"back": "Πίσω",
"save": "Αποθήκευση",
"add": "Προσθήκη",
"newTitle": "Νέο άτομο",
"added": "{{name}}: προστέθηκε",
"saved": "Αποθηκεύτηκε",
"photo": "Φωτογραφία",
"photoRemove": "Αφαίρεση φωτογραφίας",
"photoSaved": "Η φωτογραφία αποθηκεύτηκε",
"fullName": "Ονοματεπώνυμο",
"fullNameHint": "Εμφανίζεται στις αναφορές.",
"nickname": "Όνομα στις εφαρμογές",
"nicknameHint": "Αυτό βλέπουν οι συνάδελφοι σε κινητά και οθόνες.",
"username": "Όνομα χρήστη",
"usernameHint": "Για τη σύνδεση· χωρίς κενά.",
"roleHintNew": "Ορίζει τι μπορεί να κάνει· προσαρμόζεται μετά από τα δικαιώματα.",
"roleHintEdit": "Η αλλαγή ρόλου δεν αλλάζει τα δικαιώματα: χρησιμοποιήστε το κουμπί δικαιωμάτων.",
"pinLabel": "PIN",
"pinHint": "4 έως 6 ψηφία, για το πληκτρολόγιο PIN σε κινητά και οθόνες.",
"passwordLabel": "Κωδικός",
"passwordHintNew": "Προαιρετικά: μόνο αν το κατάστημα συνδέεται με κωδικό. Τουλάχιστον 6 χαρακτήρες.",
"passwordHint": "Τουλάχιστον 6 χαρακτήρες.",
"phone": "Κινητό",
"email": "Email",
"rate": "Ωριαία αμοιβή (€)",
"rateHint": "Για το κόστος του προγράμματος. Τη βλέπουν μόνο οι διαχειριστές.",
"language": "Γλώσσα",
"languageHint": "Η γλώσσα των εφαρμογών για αυτό το άτομο.",
"venueLanguage": "Η γλώσσα του καταστήματος",
"note": "Σημείωση",
"noteHint": "Μόνο για τους διαχειριστές.",
"wrong": {
"full_name": "Γράψτε το ονοματεπώνυμο.",
"nickname": "Γράψτε το όνομα που δείχνουν οι εφαρμογές.",
"username": "Τουλάχιστον 2 χαρακτήρες, χωρίς κενά.",
"hourly_rate": "Ένας αριθμός, όπως 8,50.",
"pin": "4 έως 6 ψηφία.",
"password": "Τουλάχιστον 6 χαρακτήρες."
},
"pinTitle": "Νέο PIN για {{name}}",
"pinBody": "Συνδέεται με αυτό σε κινητά και οθόνες που ζητούν PIN.",
"passwordTitle": "Κωδικός για {{name}}",
"passwordBodyNew": "Με κωδικό συνδέεται όπου το κατάστημα ζητά κωδικό (κινητά, οθόνες, διαχείριση).",
"passwordBodyChange": "Έχει ήδη κωδικό: αυτός τον αντικαθιστά. Μένει συνδεδεμένος όπου είναι.",
"passwordRemove": "Αφαίρεση κωδικού",
"again": "Ξανά",
"notSame": "Τα δύο δεν ταιριάζουν.",
"pinSaved": "Νέο PIN για {{name}}",
"passwordSaved": "{{name}}: νέος κωδικός",
"passwordRemoved": "{{name}}: σύνδεση μόνο με PIN",
"zonesBody": "Το κινητό του και ο χάρτης τραπεζιών δείχνουν μόνο τα τραπέζια αυτών των ζωνών.",
"noGroups": "Δεν υπάρχουν ζώνες ακόμα (Διαχείριση → Τραπέζια).",
"noZonesWarn": "Χωρίς ζώνη δεν βλέπει κανένα τραπέζι.",
"zonesSaved": "Οι ζώνες αποθηκεύτηκαν: {{name}}"
},
"schedule": {
"title": "Πρόγραμμα",
"view": "Προβολή",
"views": {
"people": "Ανά άτομο",
"hours": "Ανά ώρα"
},
"previous": "Προηγούμενη εβδομάδα",
"next": "Επόμενη εβδομάδα",
"thisWeek": "Αυτή η εβδομάδα",
"settings": "Πώς φαίνεται το πρόγραμμα",
"hours_one": "{{count}} ώρα",
"hours_other": "{{count}} ώρες",
"cost": "περίπου {{amount}}",
"nobody": "Δεν υπάρχει προσωπικό ακόμα: προσθέστε στο Προσωπικό.",
"person": "Άτομο",
"addFor": "Νέα βάρδια για {{name}}",
"addOn": "Νέα βάρδια {{day}}",
"state": {
"planned": "Προγραμματισμένη",
"working": "Εργάζεται τώρα",
"worked": "Έγινε"
},
"legend": {
"planned": "Προγραμματισμένη, δεν ξεκίνησε",
"working": "Ξεκίνησε (εργάζεται τώρα)",
"worked": "Έγινε"
},
"newTitle": "Νέα βάρδια",
"editTitle": "Βάρδια",
"from": "Από",
"to": "Έως",
"overnight": "τελειώνει την επόμενη μέρα",
"clash": "Έχει ήδη βάρδια {{start}}–{{end}} εκείνη τη μέρα.",
"note": "Σημείωση",
"notePh": "π.χ. μόνο βράδυ",
"add": "Προσθήκη",
"save": "Αποθήκευση",
"back": "Πίσω",
"delete": "Διαγραφή",
"added": "Η βάρδια προστέθηκε",
"saved": "Η βάρδια αποθηκεύτηκε",
"deleted": "Η βάρδια διαγράφηκε",
"settingsHint": "Μόνο σε αυτόν τον υπολογιστή· το πρόγραμμα μένει ίδιο για όλους.",
"firstDay": "Η εβδομάδα ξεκινά",
"monday": "Δευτέρα",
"sunday": "Κυριακή",
"firstHour": "Ο άξονας ξεκινά στις",
"firstHourHint": "Για την προβολή «Ανά ώρα».",
"opens": "Ανοίγει",
"closes": "Κλείνει",
"openingHint": "Σκιασμένα στον άξονα."
} }
} }
+9 -2
View File
@@ -297,10 +297,17 @@
"role_invalid": "There is no role {{role}}.", "role_invalid": "There is no role {{role}}.",
"avatar_type": "The photo must be a picture file.", "avatar_type": "The photo must be a picture file.",
"assignment_exists": "That assignment already exists.", "assignment_exists": "That assignment already exists.",
"assignment_not_found": "Assignment not found." "assignment_not_found": "Assignment not found.",
"pin_invalid": "A PIN is {{min}} to {{max}} digits.",
"password_own": "Change your own password from your profile.",
"delete_self": "You can't delete yourself.",
"username_needed": "Every person needs a username.",
"has_history": "{{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."
}, },
"schedule": { "schedule": {
"shift_not_found": "Scheduled shift not found." "shift_not_found": "Scheduled shift not found.",
"bad_time": "Times are written like 09:30.",
"overlap": "{{name}} already has a shift from {{start}} to {{end}} that day."
}, },
"setup": { "setup": {
"done": "Setup is already done: a manager account exists." "done": "Setup is already done: a manager account exists."
+149
View File
@@ -2566,5 +2566,154 @@
"testHint": "Hear it on a printer.", "testHint": "Hear it on a printer.",
"test": "Test the beep" "test": "Test the beep"
} }
},
"staff": {
"title": "Staff",
"new": "Add a person",
"none": "Nobody matches.",
"search": "Search by name, username or phone…",
"role": "Role",
"allRoles": "All roles",
"status": "Status",
"anyStatus": "Active or blocked",
"active": "Active",
"blockedState": "Blocked",
"groups": {
"management_one": "{{count}} in management",
"management_other": "{{count}} in management",
"kitchen_one": "{{count}} in the kitchen and bar",
"kitchen_other": "{{count}} in the kitchen and bar",
"service_one": "{{count}} serving",
"service_other": "{{count}} serving",
"other_one": "{{count}} other",
"other_other": "{{count}} others"
},
"pinOnly": "PIN",
"pinAndPassword": "PIN + password",
"signInTip": "How they can sign in: the venue's sign-in mode decides which one is asked.",
"zones": "Zones",
"allZones": "All zones",
"noZones": "No zone",
"edit": "Edit {{name}}",
"pin": "New PIN for {{name}}",
"password": "Password for {{name}}",
"zonesOf": "Zones of {{name}}",
"block": "Block {{name}}",
"unblock": "Unblock {{name}}",
"delete": "Delete {{name}}",
"blocked": "{{name}} is blocked: signed out everywhere",
"unblocked": "{{name}} can sign in again",
"deleteTitle": "Delete {{name}}?",
"deleteBody": "Only someone with no orders or shifts can be deleted. Anyone else is blocked instead: they can't sign in, and the reports keep their name.",
"deleteYes": "Delete",
"blockInstead": "Block instead",
"deleted": "{{name}} deleted",
"back": "Back",
"save": "Save",
"add": "Add",
"newTitle": "Add a person",
"added": "{{name}} added",
"saved": "Saved",
"photo": "Photo",
"photoRemove": "Remove the photo",
"photoSaved": "Photo saved",
"fullName": "Full name",
"fullNameHint": "Shown in reports.",
"nickname": "Name in the apps",
"nicknameHint": "What colleagues see on the phones and screens.",
"username": "Username",
"usernameHint": "For signing in; no spaces.",
"roleHintNew": "Sets what they may do; adjust it later with the permissions.",
"roleHintEdit": "Changing the role doesn't change their permissions: use the permissions button.",
"pinLabel": "PIN",
"pinHint": "4 to 6 digits, for the PIN pad on phones and screens.",
"passwordLabel": "Password",
"passwordHintNew": "Optional: only needed if the venue signs in by password. At least 6 characters.",
"passwordHint": "At least 6 characters.",
"phone": "Mobile",
"email": "Email",
"rate": "Hourly pay (€)",
"rateHint": "For the schedule's costs. Only managers see it.",
"language": "Language",
"languageHint": "The apps' language for them.",
"venueLanguage": "The venue's language",
"note": "Note",
"noteHint": "For the managers only.",
"wrong": {
"full_name": "Write their full name.",
"nickname": "Write the name the apps show.",
"username": "At least 2 characters, no spaces.",
"hourly_rate": "A number, like 8,50.",
"pin": "4 to 6 digits.",
"password": "At least 6 characters."
},
"pinTitle": "New PIN for {{name}}",
"pinBody": "They sign in with it on the phones and screens that ask for a PIN.",
"passwordTitle": "Password for {{name}}",
"passwordBodyNew": "With a password they can sign in where the venue asks for one (phones, screens, the manager).",
"passwordBodyChange": "They already have a password: this replaces it. They stay signed in where they are.",
"passwordRemove": "Remove the password",
"again": "Again",
"notSame": "The two don't match.",
"pinSaved": "New PIN for {{name}}",
"passwordSaved": "{{name}} has a new password",
"passwordRemoved": "{{name}} signs in with a PIN only",
"zonesBody": "Their phone and the table map only show these zones' tables.",
"noGroups": "There are no zones yet (Management → Tables).",
"noZonesWarn": "With no zone they see no tables.",
"zonesSaved": "Zones of {{name}} saved"
},
"schedule": {
"title": "Schedule",
"view": "View",
"views": {
"people": "By person",
"hours": "By hour"
},
"previous": "Previous week",
"next": "Next week",
"thisWeek": "This week",
"settings": "How the schedule shows",
"hours_one": "{{count}} hour",
"hours_other": "{{count}} hours",
"cost": "about {{amount}}",
"nobody": "Nobody to schedule yet: add people in Staff.",
"person": "Person",
"addFor": "Add a shift for {{name}}",
"addOn": "Add a shift on {{day}}",
"state": {
"planned": "Planned",
"working": "Working now",
"worked": "Worked"
},
"legend": {
"planned": "Planned, not started",
"working": "Started (working now)",
"worked": "Worked"
},
"newTitle": "New shift",
"editTitle": "Shift",
"from": "From",
"to": "To",
"overnight": "ends the next day",
"clash": "They already have a shift {{start}}–{{end}} that day.",
"note": "Note",
"notePh": "e.g. evening only",
"add": "Add",
"save": "Save",
"back": "Back",
"delete": "Delete",
"added": "Shift added",
"saved": "Shift saved",
"deleted": "Shift deleted",
"settingsHint": "Only on this computer; the schedule stays the same for everyone.",
"firstDay": "The week starts on",
"monday": "Monday",
"sunday": "Sunday",
"firstHour": "The timeline starts at",
"firstHourHint": "For the \"By hour\" view.",
"opens": "Opens",
"closes": "Closes",
"openingHint": "Shaded on the timeline."
} }
} }
+61
View File
@@ -1100,6 +1100,67 @@ try {
if (savedZone) await api('DELETE', `/api/prep-zones/${savedZone.id}`, { token: boss }) if (savedZone) await api('DELETE', `/api/prep-zones/${savedZone.id}`, { token: boss })
if (grill) await api('DELETE', `/api/system/printers/${grill.id}`, { token: boss }) if (grill) await api('DELETE', `/api/system/printers/${grill.id}`, { token: boss })
// ── 6.11: staff on v2; a password given by the manager works on a paired screen (KI-014) ──
const st = 'staff:'
await page.goto(`${APP}/management/staff`)
await page.getByTestId('staff-new').click()
await page.getByTestId('staff-save').click()
r.check(`${st} a new person needs their names, a username and a PIN`, await page.getByTestId('staff-dialog').count() === 1
&& (await page.getByTestId('staff-dialog').textContent()).includes('4 to 6 digits'))
await page.getByTestId('staff-full-name').fill('Eleni E2E')
await page.getByTestId('staff-nickname').fill('Eleni')
await page.getByTestId('staff-username').fill('e2e_eleni')
await page.getByTestId('staff-new-pin').fill('2580')
await page.getByTestId('staff-rate').fill('8,5')
await page.getByTestId('staff-save').click()
const eleniRow = page.locator('[data-testid="staff-row"][data-username="e2e_eleni"]')
const eleniListed = await eleniRow.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
let eleni = (await api('GET', '/api/waiters/', { token: boss })).find(m => m.username === 'e2e_eleni')
r.check(`${st} added from the page: a waiter with a PIN, no password, pay 8.50`, eleniListed && eleni?.role === 'waiter' && eleni.has_password === false && eleni.hourly_rate === 8.5, JSON.stringify(eleni))
await eleniRow.getByTestId('staff-password').click()
await page.getByTestId('secret-value').fill('kalimera6')
await page.getByTestId('secret-again').fill('kalimera7')
await page.getByTestId('secret-save').click()
r.check(`${st} the two passwords must match`, (await page.getByTestId('secret-dialog').textContent()).includes("don't match"))
await page.getByTestId('secret-again').fill('kalimera6')
await page.getByTestId('secret-save').click()
await page.getByTestId('secret-dialog').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
await eleniRow.getByText('PIN + password').waitFor({ timeout: 8000 }).catch(() => {})
eleni = (await api('GET', '/api/waiters/', { token: boss })).find(m => m.username === 'e2e_eleni')
r.check(`${st} the manager gives her a password: the row says "PIN + password"`, eleni.has_password === true && (await eleniRow.textContent()).includes('PIN + password'))
await page.screenshot({ path: path.join(OUT, 'manager-staff-v2.png'), fullPage: true })
// a counter screen that signs in by password
await api('PUT', '/api/platform/modules/pos_counter', { token: boss, body: { enabled: true } }).catch(() => {})
const tillReq = await deviceRequestsPairing()
await api('POST', '/api/devices', { token: boss, body: { code: tillReq.code, app_key: 'pos_counter', name: 'E2E till', login_mode: 'password' } })
const tillToken = await devicePicksUpToken(tillReq)
const tillLogin = async password => fetch(`${backend.url}/api/auth/login`, {
method: 'POST', headers: { 'content-type': 'application/json', 'X-Xenia-Device': tillToken },
body: JSON.stringify({ client: 'terminal', username: 'e2e_eleni', password }),
}).then(async x => ({ status: x.status, body: await x.json() }))
const wrongPw = await tillLogin('wrong-one')
const rightPw = await tillLogin('kalimera6')
r.check(`${st} the done-when: she signs in with that password on a paired screen (a wrong one is refused)`,
wrongPw.body?.error?.code === 'auth.invalid_credentials' && rightPw.status === 200 && rightPw.body.user?.username === 'e2e_eleni', JSON.stringify(rightPw.body).slice(0, 200))
// the schedule: a shift for her, and a clash shown before saving
await page.goto(`${APP}/management/schedule`)
const eleniPlan = page.locator('[data-testid="schedule-person"][data-name="Eleni E2E"]')
await eleniPlan.waitFor({ timeout: 10_000 }).catch(() => {})
await eleniPlan.getByTestId('schedule-add').first().click()
await page.getByTestId('shift-start').fill('18:00')
await page.getByTestId('shift-end').fill('02:00')
await page.getByTestId('shift-save').click()
const planned = await eleniPlan.getByTestId('schedule-shift').first().waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
r.check(`${st} schedule: a shift 18:00–02:00 for her, 8 hours, costed at her pay`, planned
&& (await eleniPlan.getByTestId('schedule-shift').first().textContent()).includes('18:00–02:00')
&& (await eleniPlan.textContent()).includes('8 hours') && (await page.getByTestId('schedule-totals').textContent()).includes('€'))
await eleniPlan.getByTestId('schedule-add').first().click()
await page.getByTestId('shift-start').fill('20:00')
await page.getByTestId('shift-end').fill('22:00')
r.check(`${st} schedule: an overlapping shift is flagged and can't be saved`, await page.getByTestId('shift-clash').count() === 1 && await page.getByTestId('shift-save').isDisabled())
await page.screenshot({ path: path.join(OUT, 'manager-schedule.png'), fullPage: true })
await page.keyboard.press('Escape')
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
await page.goto(`${APP}/online-orders`) await page.goto(`${APP}/online-orders`)
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {}) await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})