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:
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
// (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.
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { ShieldCheck } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation, useFormat } from '@xenia/i18n'
|
||||
import { Button, EmptyState, Spinner } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import { approvalState, approvalTarget, permLabelKey } from './permissionsLogic'
|
||||
|
||||
const STATE_TONE = {
|
||||
@@ -21,22 +21,11 @@ const STATE_TONE = {
|
||||
export default function ApprovalsPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
const f = useFormat()
|
||||
const [rows, setRows] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
// 6.11: loaded like the other v2 pages (react-query; a reconnect refreshes it)
|
||||
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 () => {
|
||||
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 (error) return <div className="p-8"><EmptyState title={error} action={<Button variant="secondary" onClick={() => refetch()}>{t('common:actions.retry')}</Button>} /></div>
|
||||
if (!rows) return <div className="p-8 flex justify-center"><Spinner /></div>
|
||||
|
||||
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))
|
||||
}
|
||||
Reference in New Issue
Block a user