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 (
)
}
const parts = displayName.trim().split(' ')
const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
return (
{initials}
)
}
// ── PIN input ──────────────────────────────────────────────────────────────────
const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']
function PinInput({ value, onChange }) {
function press(d) {
if (d === '⌫') { onChange(value.slice(0, -1)); return }
if (d === '' || value.length >= 6) return
onChange(value + d)
}
return (
{Array.from({ length: 4 }).map((_, i) => (
))}
{DIGITS.map((d, i) => (
))}
)
}
// ── Actions dropdown ───────────────────────────────────────────────────────────
function ActionsMenu({ member, onEdit, onZones, onResetPin, onBlock, onDelete, onPermissions, permissionsLabel, isSuperadmin }) {
const [open, setOpen] = useState(false)
const ref = useRef(null)
useEffect(() => {
if (!open) return
function handler(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false) }
document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler)
}, [open])
const items = [
{ label: 'Επεξεργασία', icon: editIcon, onClick: onEdit },
{ label: 'Πρόσβαση σε Ζώνες', icon: zonesIcon, onClick: onZones },
{ label: 'Επαναφορά PIN', icon: pinIcon, onClick: onResetPin },
{ label: permissionsLabel, icon: resetIcon, onClick: onPermissions },
!isSuperadmin && { label: member.is_active ? 'Μπλοκάρισμα' : 'Ξεμπλοκάρισμα', icon: blockIcon, onClick: onBlock, color: member.is_active ? '#f97316' : '#22c55e' },
!isSuperadmin && { label: 'Διαγραφή', icon: trashIcon, onClick: onDelete, color: '#ef4444' },
].filter(Boolean)
return (
{open && (
{items.map((item, i) => (
))}
)}
)
}
// ── ZoneModal ──────────────────────────────────────────────────────────────────
function ZoneModal({ member, groups, onClose }) {
const qc = useQueryClient()
const hasAllZones = member.zone_assignments.some(z => z.group_id === null)
const assignedIds = new Set(member.zone_assignments.map(z => z.group_id).filter(id => id !== null))
const [allZones, setAllZones] = useState(hasAllZones)
const [selected, setSelected] = useState(new Set(assignedIds))
const saveZones = useMutation({
mutationFn: (body) => client.put(`/api/waiters/${member.id}/zones`, body),
onSuccess: () => { toast.success('Zones ενημερώθηκαν'); qc.invalidateQueries({ queryKey: ['staff'] }); onClose() },
onError: () => toast.error('Σφάλμα'),
})
function toggleGroup(gid) {
setSelected(prev => { const next = new Set(prev); next.has(gid) ? next.delete(gid) : next.add(gid); return next })
}
return (
Ζώνες — {member.username}
{!allZones && (
{groups.length === 0 &&
Δεν υπάρχουν ομάδες τραπεζιών.
}
{groups.map(g => (
))}
)}
{!allZones && selected.size === 0 && (
Χωρίς επιλογή ο σερβιτόρος δεν βλέπει κανένα τραπέζι.
)}
)
}
// ── Shared form primitives ─────────────────────────────────────────────────────
function FormField({ label, required, desc, children }) {
return (
{children}
{desc &&
{desc}
}
)
}
function SectionLabel({ children }) {
return (
{children}
)
}
function InfoBlock({ label, value, valueColor }) {
return (
{label}
{value || '—'}
)
}
const inputStyle = {
width: '100%', padding: '7px 10px', border: '1px solid #e5e7eb', borderRadius: 7,
fontSize: 13, outline: 'none', color: '#111827', background: '#fff', boxSizing: 'border-box',
}
const EMPTY_FORM = {
username: '', full_name: '', nickname: '', mobile_phone: '', email: '', note: '',
role: 'waiter', pin: '', hourly_rate: '',
}
// ── Main page ──────────────────────────────────────────────────────────────────
export default function StaffPage() {
const qc = useQueryClient()
const [addModal, setAddModal] = useState(false)
const [pinModal, setPinModal] = useState(null)
const [zoneModal, setZoneModal] = useState(null)
const [confirmDelete, setConfirmDelete] = useState(null)
const [newPin, setNewPin] = useState('')
const [newForm, setNewForm] = useState(EMPTY_FORM)
const [newAvatarFile, setNewAvatarFile] = useState(null)
const [newAvatarPreview, setNewAvatarPreview] = useState(null)
const [editModal, setEditModal] = useState(null)
const [editForm, setEditForm] = useState({ username: '', full_name: '', nickname: '', mobile_phone: '', email: '', note: '', role: 'waiter', hourly_rate: '' })
const [filterRole, setFilterRole] = useState('all')
const [permEditor, setPermEditor] = useState(null)
const { t } = useTranslation('manager')
const avatarInputRef = useRef(null)
const newAvatarInputRef = useRef(null)
const { data: staff = [], isLoading } = useQuery({
queryKey: ['staff'],
queryFn: () => client.get('/api/waiters/').then(r => r.data),
})
const { data: catalog } = useQuery({
queryKey: ['permission-catalog'],
queryFn: () => client.get('/api/waiters/permission-catalog').then(r => r.data),
})
const { data: groups = [] } = useQuery({
queryKey: ['table-groups'],
queryFn: () => client.get('/api/tables/groups').then(r => r.data),
})
const invalidate = () => qc.invalidateQueries({ queryKey: ['staff'] })
const createStaff = useMutation({
mutationFn: async (body) => {
const res = await client.post('/api/waiters/', body)
if (newAvatarFile) {
const fd = new FormData()
fd.append('file', newAvatarFile)
await client.post(`/api/waiters/${res.data.id}/avatar`, fd, { headers: { 'Content-Type': 'multipart/form-data' } })
}
return res
},
onSuccess: () => {
toast.success('Εργαζόμενος δημιουργήθηκε')
setAddModal(false); setNewForm(EMPTY_FORM); setNewAvatarFile(null); setNewAvatarPreview(null)
invalidate()
},
onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
})
const updateStaff = useMutation({
mutationFn: ({ id, ...body }) => client.put(`/api/waiters/${id}`, body),
onSuccess: () => { toast.success('Στοιχεία ενημερώθηκαν'); setEditModal(null); invalidate() },
onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
})
const uploadAvatar = useMutation({
mutationFn: ({ id, file }) => {
const fd = new FormData(); fd.append('file', file)
return client.post(`/api/waiters/${id}/avatar`, fd, { headers: { 'Content-Type': 'multipart/form-data' } })
},
onSuccess: (res) => { toast.success('Avatar ανέβηκε'); setEditModal(res.data); invalidate() },
onError: () => toast.error('Σφάλμα μεταφόρτωσης'),
})
const deleteAvatar = useMutation({
mutationFn: (id) => client.delete(`/api/waiters/${id}/avatar`),
onSuccess: (res) => { toast.success('Avatar αφαιρέθηκε'); setEditModal(res.data); invalidate() },
onError: () => toast.error('Σφάλμα'),
})
const toggleBlock = useMutation({
mutationFn: (id) => client.put(`/api/waiters/${id}/block`),
onSuccess: () => invalidate(),
onError: () => toast.error('Σφάλμα'),
})
const resetPin = useMutation({
mutationFn: ({ id, pin }) => client.put(`/api/waiters/${id}/reset-pin?pin=${encodeURIComponent(pin)}`),
onSuccess: () => { toast.success('PIN ανανεώθηκε'); setPinModal(null); setNewPin('') },
onError: () => toast.error('Σφάλμα'),
})
const deleteStaff = useMutation({
mutationFn: (id) => client.delete(`/api/waiters/${id}`),
onSuccess: () => { toast.success('Διαγράφηκε'); setConfirmDelete(null); invalidate() },
onError: () => toast.error('Σφάλμα'),
})
if (isLoading) return Φόρτωση…
function openEdit(m) {
setEditModal(m)
setEditForm({
username: m.username || '', full_name: m.full_name || '',
nickname: m.nickname || '', mobile_phone: m.mobile_phone || '',
email: m.email || '', note: m.note || '',
role: m.role || 'waiter', hourly_rate: m.hourly_rate ?? '',
})
}
// Group counts for header badges
const groupedCounts = staff.reduce((acc, m) => {
const g = m.role in { superadmin: 1, owner: 1, store_manager: 1, staff_manager: 1 } ? 'Διοίκηση'
: m.role in { chef: 1, assistant_chef: 1, barista: 1, barman: 1 } ? 'Κουζίνα / Bar'
: 'Σέρβις'
acc[g] = (acc[g] || 0) + 1
return acc
}, {})
const filtered = filterRole === 'all' ? staff : staff.filter(m => m.role === filterRole)
return (
{/* ── Header bar ── */}
{Object.entries(groupedCounts).map(([group, count]) => (
{count} {group}
))}
{/* Role filter */}
{/* ── Scrollable table area ── */}
{filtered.length === 0 ? (
Δεν βρέθηκαν εργαζόμενοι.
) : (
{/* Column label row */}
|
Εργαζόμενος
|
Κατάσταση |
{t('permissions.column')}
|
Ενέργειες
|
{filtered.map((member, rowIdx) => {
const role = ROLE_MAP[member.role]
const isSuperadmin = member.role === 'superadmin'
const rowBg = rowIdx % 2 === 0 ? '#fff' : '#fafafa'
return (
e.currentTarget.style.background = '#f0f9ff'}
onMouseLeave={e => e.currentTarget.style.background = rowBg}
>
{/* Identity cell */}
{member.full_name || member.username}
{role?.label || member.role}
{member.nickname && (
{member.nickname}
)}
|
{/* Status cell */}
{member.is_active ? 'Ενεργός' : 'Μπλοκαρ.'}
|
{/* Permissions (2.6e): count + "custom" when they differ from the role */}
|
{/* Actions cell */}
openEdit(member)}
onZones={() => setZoneModal(member)}
onResetPin={() => setPinModal(member.id)}
onBlock={() => toggleBlock.mutate(member.id)}
onDelete={() => setConfirmDelete(member.id)}
onPermissions={() => setPermEditor(member)}
permissionsLabel={t('permissions.open')}
/>
|
)
})}
)}
{/* ── Modals ── */}
{addModal && (
{ setAddModal(false); setNewForm(EMPTY_FORM); setNewAvatarFile(null); setNewAvatarPreview(null) }}
onSubmit={() => createStaff.mutate({
username: newForm.username, full_name: newForm.full_name || null,
nickname: newForm.nickname || null, mobile_phone: newForm.mobile_phone || null,
email: newForm.email || null, note: newForm.note || null,
pin: newForm.pin, role: newForm.role, is_active: true,
hourly_rate: newForm.hourly_rate !== '' ? parseFloat(newForm.hourly_rate) : null,
})}
/>
)}
{editModal && (
setEditModal(null)}
onSubmit={() => updateStaff.mutate({
id: editModal.id,
username: editForm.username.trim() || undefined,
full_name: editForm.full_name || null, nickname: editForm.nickname || null,
mobile_phone: editForm.mobile_phone || null, email: editForm.email || null,
note: editForm.note || null, role: editForm.role,
hourly_rate: editForm.hourly_rate !== '' ? parseFloat(editForm.hourly_rate) : null,
})}
onUploadAvatar={file => uploadAvatar.mutate({ id: editModal.id, file })}
onDeleteAvatar={() => deleteAvatar.mutate(editModal.id)}
/>
)}
{pinModal !== null && (
Επαναφορά PIN — {staff.find(m => m.id === pinModal)?.username}
)}
{confirmDelete !== null && (
deleteStaff.mutate(confirmDelete)}
onCancel={() => setConfirmDelete(null)}
/>
)}
{permEditor && setPermEditor(null)} />}
{zoneModal && (
setZoneModal(null)} />
)}
)
}
const thBase = {
fontSize: 11, fontWeight: 600, color: '#6b7280',
padding: '6px 4px', background: '#f9fafb',
position: 'sticky', top: 0, zIndex: 1,
}
// ── SVG icons ─────────────────────────────────────────────────────────────────
const editIcon = (
)
const zonesIcon = (
)
const pinIcon = (
)
const resetIcon = (
)
const blockIcon = (
)
const trashIcon = (
)
// ── Add Staff Modal ────────────────────────────────────────────────────────────
function AddStaffModal({ form, setForm, avatarFile, avatarPreview, setAvatarFile, setAvatarPreview, avatarInputRef, isPending, onClose, onSubmit }) {
const f = (field, val) => setForm(p => ({ ...p, [field]: val }))
const canSubmit = form.username.trim() && form.full_name.trim() && form.nickname.trim() && form.pin.length >= 4
return (
{/* Header */}
{avatarPreview
?

:
👤
}
Νέος εργαζόμενος
Συμπληρώστε τα στοιχεία του εργαζόμενου
{
const file = e.target.files?.[0]
if (file) { setAvatarFile(file); setAvatarPreview(URL.createObjectURL(file)) }
e.target.value = ''
}} />
{avatarPreview && (
)}
{/* Body — three columns */}
{/* Col 1: Identity + Account */}
{/* Col 2: Contact */}
{/* Col 3: PIN */}
Κωδικός PIN
Ο 4ψήφιος κωδικός που θα χρησιμοποιεί ο εργαζόμενος για να ξεκλειδώσει την εφαρμογή.
f('pin', pin)} />
{form.pin.length > 0 && form.pin.length < 4 && (
Χρειάζονται {4 - form.pin.length} ψηφία ακόμη
)}
{form.pin.length >= 4 && (
✓ PIN ορίστηκε
)}
Τα δικαιώματα θα οριστούν αυτόματα βάσει του επιλεγμένου ρόλου και μπορείτε να τα τροποποιήσετε μετά τη δημιουργία.
{/* Footer */}
)
}
// ── 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 (
{/* Header */}
{/* Body — three columns */}
{/* Col 1: Identity + Account */}
{/* Col 2: Contact */}
{/* Col 3: Info + Payroll + PIN */}
Κωδικός PIN
Για αλλαγή PIN χρησιμοποιήστε την επιλογή Επαναφορά PIN από το μενού Ενεργειών.
{/* Footer */}
)
}