feat: bump client-services (accumulated feature work + deploy fixes)

Snapshot of in-progress work across local_backend, manager_dashboard,
and waiter_pwa (pricing, chat, fiscal, prep zones, recovery codes, CRM,
inventory, permissions), plus the nginx/docker-compose deploy fixes for
the Unraid + NPM reverse-proxy setup.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-19 10:00:14 +03:00
co-authored by Claude Sonnet 5
parent 02ec1aa28f
commit 34ae328b0d
182 changed files with 34874 additions and 3556 deletions
File diff suppressed because it is too large Load Diff
+468
View File
@@ -0,0 +1,468 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import client from '../api/client'
import useAuthStore from '../store/authStore'
import useChatStore from '../store/chatStore'
// ─── Relative time (Greek) ────────────────────────────────────────────────────
function relativeTime(dateStr) {
if (!dateStr) return ''
const date = new Date(dateStr)
const now = new Date()
const diffMs = now - date
const diffMin = Math.floor(diffMs / 60_000)
const diffHours = Math.floor(diffMs / 3_600_000)
if (diffMin < 1) return 'τώρα'
if (diffMin < 60) return `${diffMin}λ`
if (diffHours < 24) return `${diffHours}ω`
const yesterday = new Date(now)
yesterday.setDate(yesterday.getDate() - 1)
if (
date.getDate() === yesterday.getDate() &&
date.getMonth() === yesterday.getMonth() &&
date.getFullYear() === yesterday.getFullYear()
) return 'χθες'
return date.toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit' })
}
// ─── Avatar ───────────────────────────────────────────────────────────────────
function Avatar({ label, size = 44, isGroup = false }) {
const initials = isGroup
? '👥'
: (label || '?').slice(0, 2).toUpperCase()
return (
<div style={{
width: size, height: size, borderRadius: '50%', flexShrink: 0,
background: isGroup ? 'var(--bg3)' : 'var(--accent)',
color: isGroup ? 'var(--text)' : 'var(--accent-fg)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: isGroup ? 20 : 16, fontWeight: 700,
}}>
{initials}
</div>
)
}
// ─── Conversation row ─────────────────────────────────────────────────────────
function ConvRow({ conv, currentUserId, onClick }) {
const isGroup = conv.type === 'group'
const isDirect = conv.type === 'direct'
const title = isGroup
? (conv.name || 'Ομάδα')
: (conv.participants?.find(p => p.user_id !== currentUserId)?.username || 'Άγνωστος')
const lastMsg = conv.last_message
const preview = lastMsg
? lastMsg.is_deleted
? 'Το μήνυμα διαγράφηκε'
: lastMsg.body
: 'Δεν υπάρχουν μηνύματα'
const timestamp = lastMsg?.sent_at || conv.created_at
const hasUnread = (conv.unread_count || 0) > 0
return (
<button
onClick={onClick}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '14px 16px', borderBottom: '1px solid var(--border)',
background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
width: '100%', textAlign: 'left', cursor: 'pointer',
}}
>
<Avatar label={isGroup ? null : title} isGroup={isGroup} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
<span style={{
fontSize: 15, fontWeight: hasUnread ? 700 : 600,
color: 'var(--text)', flex: 1,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>
{title}
</span>
<span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>
{relativeTime(timestamp)}
</span>
</div>
<div style={{
fontSize: 13, color: 'var(--muted)', marginTop: 2,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
fontStyle: lastMsg?.is_deleted ? 'italic' : 'normal',
fontWeight: hasUnread ? 600 : 400,
}}>
{isGroup && lastMsg && !lastMsg.is_deleted && lastMsg.sender_name
? `${lastMsg.sender_name}: ${preview}`
: preview
}
</div>
</div>
{hasUnread && (
<div style={{
background: 'var(--danger)', color: '#fff',
borderRadius: '50%', minWidth: 20, height: 20,
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 11, fontWeight: 800, flexShrink: 0,
padding: conv.unread_count > 9 ? '0 6px' : '0',
}}>
{conv.unread_count > 99 ? '99+' : conv.unread_count}
</div>
)}
</button>
)
}
// ─── New Chat bottom drawer ───────────────────────────────────────────────────
function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
const [staff, setStaff] = useState([])
const [loading, setLoading] = useState(true)
const [mode, setMode] = useState('picker') // 'picker' | 'group_name' | 'group_pick'
const [groupName, setGroupName] = useState('')
const [selectedIds, setSelectedIds] = useState([])
const [creating, setCreating] = useState(false)
const [error, setError] = useState(null)
useEffect(() => {
client.get('/api/chat/users')
.then(r => setStaff((r.data || []).filter(u => u.id !== currentUserId)))
.catch(() => setError('Αποτυχία φόρτωσης χρηστών'))
.finally(() => setLoading(false))
}, [currentUserId])
async function startDirect(userId) {
setCreating(true)
setError(null)
try {
const res = await client.post('/api/chat/conversations', {
type: 'direct',
participant_ids: [userId],
})
onConversationCreated(res.data)
} catch (e) {
setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας συνομιλίας')
setCreating(false)
}
}
async function createGroup() {
if (!groupName.trim()) return
setCreating(true)
setError(null)
try {
const res = await client.post('/api/chat/conversations', {
type: 'group',
name: groupName.trim(),
participant_ids: selectedIds,
})
onConversationCreated(res.data)
} catch (e) {
setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας ομάδας')
setCreating(false)
}
}
function toggleSelect(id) {
setSelectedIds(prev =>
prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
)
}
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ maxHeight: '80svh' }}>
<div className="modal-handle" />
{mode === 'picker' && (
<>
<h2 className="modal-title" style={{ marginBottom: 16 }}>Νέα Συνομιλία</h2>
{/* New Group option */}
<button
onClick={() => setMode('group_name')}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 4px', background: 'none', border: 'none',
borderBottom: '1px solid var(--border)', width: '100%',
cursor: 'pointer', textAlign: 'left', marginBottom: 4,
}}
>
<div style={{
width: 44, height: 44, borderRadius: '50%', flexShrink: 0,
background: 'var(--accent)', display: 'flex', alignItems: 'center',
justifyContent: 'center', fontSize: 20,
}}>
👥
</div>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}>Νέα Ομάδα</span>
</button>
<div style={{ flex: 1, overflowY: 'auto', marginTop: 4 }}>
{loading && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}>
Φόρτωση…
</p>
)}
{!loading && staff.length === 0 && !error && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}>
Δεν υπάρχει άλλο προσωπικό
</p>
)}
{staff.map(u => (
<button
key={u.id}
onClick={() => startDirect(u.id)}
disabled={creating}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 4px', background: 'none', border: 'none',
borderBottom: '1px solid var(--border)', width: '100%',
cursor: creating ? 'not-allowed' : 'pointer', textAlign: 'left',
opacity: creating ? 0.6 : 1,
}}
>
<Avatar label={u.username || u.full_name} />
<div>
<div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>
{u.full_name || u.username}
</div>
{u.full_name && (
<div style={{ fontSize: 12, color: 'var(--muted)' }}>{u.username}</div>
)}
</div>
</button>
))}
</div>
</>
)}
{mode === 'group_name' && (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
<button
onClick={() => setMode('picker')}
style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text)', padding: 0 }}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
<h2 className="modal-title" style={{ margin: 0 }}>Όνομα Ομάδας</h2>
</div>
<input
autoFocus
value={groupName}
onChange={e => setGroupName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && groupName.trim() && setMode('group_pick')}
placeholder="π.χ. Βραδινή βάρδια"
style={{
width: '100%', padding: '12px 14px',
background: 'var(--bg3)', border: '1px solid var(--border)',
borderRadius: 12, color: 'var(--text)', fontSize: 16, outline: 'none',
boxSizing: 'border-box', marginBottom: 16,
}}
/>
<button
className="btn"
style={{ width: '100%' }}
disabled={!groupName.trim()}
onClick={() => groupName.trim() && setMode('group_pick')}
>
Επόμενο
</button>
</>
)}
{mode === 'group_pick' && (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
<button
onClick={() => setMode('group_name')}
style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text)', padding: 0 }}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
<h2 className="modal-title" style={{ margin: 0 }}>Επιλογή Μελών</h2>
</div>
<p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 12 }}>
Ομάδα: <strong style={{ color: 'var(--text)' }}>{groupName}</strong>
</p>
<div style={{ flex: 1, overflowY: 'auto', marginBottom: 12 }}>
{staff.map(u => {
const selected = selectedIds.includes(u.id)
return (
<button
key={u.id}
onClick={() => toggleSelect(u.id)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '11px 4px', background: 'none', border: 'none',
borderBottom: '1px solid var(--border)', width: '100%',
cursor: 'pointer', textAlign: 'left',
}}
>
<div style={{
width: 24, height: 24, borderRadius: 6, flexShrink: 0,
border: `2px solid ${selected ? 'var(--accent)' : 'var(--border)'}`,
background: selected ? 'var(--accent)' : 'transparent',
display: 'flex', alignItems: 'center', justifyContent: 'center',
transition: 'background 0.12s, border-color 0.12s',
}}>
{selected && (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path d="M2.5 7l3 3 6-6" stroke="var(--accent-fg)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
)}
</div>
<Avatar label={u.username || u.full_name} size={40} />
<div>
<div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>
{u.full_name || u.username}
</div>
{u.full_name && (
<div style={{ fontSize: 12, color: 'var(--muted)' }}>{u.username}</div>
)}
</div>
</button>
)
})}
</div>
<button
className="btn"
style={{ width: '100%' }}
disabled={creating}
onClick={createGroup}
>
{creating ? 'Δημιουργία…' : `Δημιουργία Ομάδας${selectedIds.length > 0 ? ` (${selectedIds.length})` : ''}`}
</button>
</>
)}
{error && (
<p style={{ fontSize: 13, color: 'var(--danger)', marginTop: 10, textAlign: 'center' }}>{error}</p>
)}
</div>
</div>
)
}
// ─── Main page ────────────────────────────────────────────────────────────────
export default function ChatListPage() {
const navigate = useNavigate()
const { user } = useAuthStore()
const { conversations, setConversations, upsertConversation } = useChatStore()
const [showNewChat, setShowNewChat] = useState(false)
const [loading, setLoading] = useState(true)
// ── Load conversations ───────────────────────────────────────────────────────
useEffect(() => {
client.get('/api/chat/conversations')
.then(r => setConversations(r.data || []))
.catch(() => {})
.finally(() => setLoading(false))
}, [])
function handleConversationCreated(conv) {
upsertConversation(conv)
setShowNewChat(false)
navigate(`/messages/${conv.id}`)
}
// Separate system group (pinned) from regular conversations
const systemConv = conversations.find(c => c.is_system)
const regularConvs = conversations.filter(c => !c.is_system)
return (
<>
{/* Conversation list */}
<div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
{/* ── New conversation row (always first) ─────────────────────── */}
<button
onClick={() => setShowNewChat(true)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '14px 16px', width: '100%',
background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
cursor: 'pointer', textAlign: 'left',
}}
>
<div style={{
width: 44, height: 44, borderRadius: '50%', flexShrink: 0,
background: 'var(--accent)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="var(--accent-fg)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="var(--accent-fg)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</div>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}>
Νέα Συνομιλία
</span>
</button>
{/* ── System group (pinned second) ────────────────────────────── */}
{systemConv && (
<ConvRow
conv={systemConv}
currentUserId={user?.id}
onClick={() => navigate(`/messages/${systemConv.id}`)}
/>
)}
{/* ── Regular conversations ────────────────────────────────────── */}
{loading && (
<div style={{ textAlign: 'center', padding: 40, color: 'var(--muted)', fontSize: 14 }}>
Φόρτωση…
</div>
)}
{!loading && regularConvs.length === 0 && !systemConv && (
<div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
flex: 1, padding: 40, gap: 12, minHeight: 200,
}}>
<span style={{ fontSize: 40 }}>💬</span>
<p style={{ fontSize: 15, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5, margin: 0 }}>
Πατήστε «Νέα Συνομιλία» για να ξεκινήσετε μια συζήτηση.
</p>
</div>
)}
{!loading && regularConvs.map(conv => (
<ConvRow
key={conv.id}
conv={conv}
currentUserId={user?.id}
onClick={() => navigate(`/messages/${conv.id}`)}
/>
))}
</div>
{showNewChat && (
<NewChatDrawer
currentUserId={user?.id}
onClose={() => setShowNewChat(false)}
onConversationCreated={handleConversationCreated}
/>
)}
</>
)
}
+573
View File
@@ -0,0 +1,573 @@
import { useEffect, useRef, useState, useCallback } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import client from '../api/client'
import useAuthStore from '../store/authStore'
import useChatStore from '../store/chatStore'
// ─── Helpers ──────────────────────────────────────────────────────────────────
function formatTime(dateStr) {
if (!dateStr) return ''
return new Date(dateStr).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}
function formatDateLabel(dateStr) {
const date = new Date(dateStr)
const now = new Date()
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const yesterday = new Date(today)
yesterday.setDate(yesterday.getDate() - 1)
const d = new Date(date.getFullYear(), date.getMonth(), date.getDate())
if (d.getTime() === today.getTime()) return 'Σήμερα'
if (d.getTime() === yesterday.getTime()) return 'Χθες'
return date.toLocaleDateString('el-GR', { weekday: 'long', day: 'numeric', month: 'long' })
}
function sameDay(a, b) {
const da = new Date(a), db = new Date(b)
return da.getFullYear() === db.getFullYear() &&
da.getMonth() === db.getMonth() &&
da.getDate() === db.getDate()
}
// ─── Message bubble ───────────────────────────────────────────────────────────
function MessageBubble({ msg, isOwn, showSender, isGroup }) {
if (msg.is_deleted) {
return (
<div style={{
alignSelf: isOwn ? 'flex-end' : 'flex-start',
maxWidth: '75%',
padding: '8px 14px',
borderRadius: isOwn ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
background: 'var(--bg3)',
}}>
<span style={{ fontSize: 13, color: 'var(--muted)', fontStyle: 'italic' }}>
Το μήνυμα διαγράφηκε
</span>
</div>
)
}
return (
<div style={{
alignSelf: isOwn ? 'flex-end' : 'flex-start',
maxWidth: '75%',
display: 'flex', flexDirection: 'column',
alignItems: isOwn ? 'flex-end' : 'flex-start',
gap: 3,
}}>
{isGroup && showSender && !isOwn && (
<span style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', paddingLeft: 4 }}>
{msg.sender_name}
</span>
)}
<div style={{
padding: '10px 14px',
borderRadius: isOwn ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
background: isOwn ? 'var(--accent)' : 'var(--bg2)',
color: isOwn ? 'var(--accent-fg)' : 'var(--text)',
fontSize: 15, lineHeight: 1.45, wordBreak: 'break-word',
}}>
{msg.body}
</div>
<span style={{ fontSize: 11, color: 'var(--muted)', paddingLeft: 2, paddingRight: 2 }}>
{formatTime(msg.sent_at)}
</span>
</div>
)
}
// ─── Date separator ───────────────────────────────────────────────────────────
function DateSeparator({ label }) {
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
margin: '16px 0 8px',
}}>
<div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
<span style={{
fontSize: 12, fontWeight: 700, color: 'var(--muted)',
letterSpacing: 0.5, whiteSpace: 'nowrap',
}}>
{label}
</span>
<div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
</div>
)
}
// ─── Auto-resize textarea ─────────────────────────────────────────────────────
function AutoTextarea({ value, onChange, onSubmit, placeholder }) {
const ref = useRef(null)
useEffect(() => {
if (!ref.current) return
ref.current.style.height = 'auto'
const scrollH = ref.current.scrollHeight
const lineH = 22 // approx line height
const maxH = lineH * 3 + 16 // 3 lines + padding
ref.current.style.height = Math.min(scrollH, maxH) + 'px'
}, [value])
function handleKeyDown(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
onSubmit()
}
}
return (
<textarea
ref={ref}
value={value}
onChange={onChange}
onKeyDown={handleKeyDown}
placeholder={placeholder}
rows={1}
style={{
flex: 1, resize: 'none', background: 'var(--bg3)',
border: '1px solid var(--border)', borderRadius: 22,
padding: '10px 16px', color: 'var(--text)', fontSize: 15,
outline: 'none', lineHeight: 1.4, fontFamily: 'inherit',
maxHeight: 82, overflowY: 'auto',
}}
/>
)
}
// ─── Leave confirmation modal ─────────────────────────────────────────────────
function LeaveModal({ onConfirm, onCancel }) {
return (
<div className="modal-overlay" onClick={onCancel}>
<div
className="modal-sheet"
onClick={e => e.stopPropagation()}
style={{ maxHeight: 'auto' }}
>
<div className="modal-handle" />
<h2 className="modal-title" style={{ marginBottom: 8 }}>Αποχώρηση από ομάδα;</h2>
<p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 20 }}>
Δεν θα λαμβάνετε πλέον μηνύματα από αυτή την ομάδα.
</p>
<div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onCancel}>Ακύρωση</button>
<button
style={{
flex: 1, height: 44, borderRadius: 12, border: 'none',
background: 'var(--danger)', color: '#fff',
fontSize: 15, fontWeight: 700, cursor: 'pointer',
}}
onClick={onConfirm}
>
Αποχώρηση
</button>
</div>
</div>
</div>
)
}
// ─── Main page ────────────────────────────────────────────────────────────────
export default function ChatThreadPage() {
const { conversationId } = useParams()
const navigate = useNavigate()
const { user } = useAuthStore()
const {
conversations, messages: allMessages,
upsertConversation, markConvRead, addMessage,
setMessages, prependMessages, updateLastRead,
} = useChatStore()
const [inputText, setInputText] = useState('')
const [sending, setSending] = useState(false)
const [loadingMore, setLoadingMore] = useState(false)
const [hasMore, setHasMore] = useState(true)
const [showLeave, setShowLeave] = useState(false)
const [initialLoad, setInitialLoad] = useState(true)
const messagesEl = useRef(null)
const bottomAnchor = useRef(null)
const offsetRef = useRef(0)
const PAGE_SIZE = 50
const conv = conversations.find(c => c.id === conversationId)
const rawMessages = allMessages[conversationId] || []
// API returns newest-first, we display oldest-first
const displayMessages = [...rawMessages].reverse()
const isGroup = conv?.type === 'group'
const isDirect = conv?.type === 'direct'
const title = isGroup
? (conv?.name || 'Ομάδα')
: (conv?.participants?.find(p => p.user_id !== user?.id)?.username || 'Συνομιλία')
// ── Mark as read ─────────────────────────────────────────────────────────────
const markRead = useCallback(async () => {
try {
await client.post(`/api/chat/conversations/${conversationId}/read`)
markConvRead(conversationId)
} catch {}
}, [conversationId, markConvRead])
// ── Initial load ─────────────────────────────────────────────────────────────
useEffect(() => {
let cancelled = false
async function init() {
// Load conversation metadata if we don't have it
if (!conv) {
try {
const r = await client.get(`/api/chat/conversations/${conversationId}`)
if (!cancelled) upsertConversation(r.data)
} catch {}
}
// Load first page of messages
try {
const r = await client.get(
`/api/chat/conversations/${conversationId}/messages?offset=0&limit=${PAGE_SIZE}`
)
if (!cancelled) {
const msgs = r.data || []
setMessages(conversationId, msgs)
offsetRef.current = msgs.length
setHasMore(msgs.length === PAGE_SIZE)
setInitialLoad(false)
}
} catch {
if (!cancelled) setInitialLoad(false)
}
markRead()
}
init()
return () => { cancelled = true }
}, [conversationId])
// ── Scroll to bottom after initial load ───────────────────────────────────────
useEffect(() => {
if (!initialLoad && bottomAnchor.current) {
bottomAnchor.current.scrollIntoView({ behavior: 'instant' })
}
}, [initialLoad])
// ── Infinite scroll upward ────────────────────────────────────────────────────
async function loadMore() {
if (loadingMore || !hasMore) return
const el = messagesEl.current
const prevScrollHeight = el?.scrollHeight || 0
const prevScrollTop = el?.scrollTop || 0
setLoadingMore(true)
try {
const r = await client.get(
`/api/chat/conversations/${conversationId}/messages?offset=${offsetRef.current}&limit=${PAGE_SIZE}`
)
const older = r.data || []
prependMessages(conversationId, older)
offsetRef.current += older.length
setHasMore(older.length === PAGE_SIZE)
// Restore scroll position after prepend
requestAnimationFrame(() => {
if (el) {
el.scrollTop = el.scrollHeight - prevScrollHeight + prevScrollTop
}
})
} catch {}
setLoadingMore(false)
}
function handleScroll(e) {
if (e.target.scrollTop < 60 && hasMore && !loadingMore) {
loadMore()
}
}
// ── SSE wiring ────────────────────────────────────────────────────────────────
useEffect(() => {
function onSSE(e) {
const { type, data } = e.detail
// conversationId from useParams is a string; SSE payload has an integer
if (type === 'chat_message' && String(data.conversation_id) === conversationId) {
// Own messages are handled optimistically in sendMessage — skip the SSE echo
// to avoid showing the message twice before the optimistic replace completes.
if (data.sender_id === user?.id) return
const msg = {
id: data.message_id,
conversation_id: data.conversation_id,
sender_id: data.sender_id,
sender_name: data.sender_name,
body: data.body,
sent_at: data.sent_at,
is_deleted: false,
}
addMessage(conversationId, msg)
offsetRef.current += 1
markRead()
// Scroll to bottom if near bottom
const el = messagesEl.current
if (el && el.scrollHeight - el.scrollTop - el.clientHeight < 120) {
requestAnimationFrame(() => {
bottomAnchor.current?.scrollIntoView({ behavior: 'smooth' })
})
}
// Update last_message in conv list
const existingConv = useChatStore.getState().conversations.find(c => c.id === conversationId)
if (existingConv) {
upsertConversation({
...existingConv,
last_message: { ...msg },
})
}
} else if (type === 'chat_read' && String(data.conversation_id) === conversationId) {
updateLastRead(data.conversation_id, data.user_id, data.read_at)
}
}
window.addEventListener('sse-event', onSSE)
return () => window.removeEventListener('sse-event', onSSE)
}, [conversationId, addMessage, markRead, upsertConversation, updateLastRead])
// ── Send message ──────────────────────────────────────────────────────────────
async function sendMessage() {
const body = inputText.trim()
if (!body || sending) return
setInputText('')
setSending(true)
// Optimistic
const optimisticMsg = {
id: `opt-${Date.now()}`,
conversation_id: conversationId,
sender_id: user?.id,
sender_name: user?.username,
body,
sent_at: new Date().toISOString(),
is_deleted: false,
_optimistic: true,
}
addMessage(conversationId, optimisticMsg)
offsetRef.current += 1
requestAnimationFrame(() => {
bottomAnchor.current?.scrollIntoView({ behavior: 'smooth' })
})
try {
const r = await client.post(`/api/chat/conversations/${conversationId}/messages`, { body })
// Replace optimistic with real
useChatStore.setState(state => {
const msgs = (state.messages[conversationId] || []).map(m =>
m.id === optimisticMsg.id ? r.data : m
)
return { messages: { ...state.messages, [conversationId]: msgs } }
})
const existingConv = useChatStore.getState().conversations.find(c => c.id === conversationId)
if (existingConv) {
upsertConversation({ ...existingConv, last_message: r.data })
}
} catch {
// Remove optimistic on failure, restore input
useChatStore.setState(state => {
const msgs = (state.messages[conversationId] || []).filter(m => m.id !== optimisticMsg.id)
return { messages: { ...state.messages, [conversationId]: msgs } }
})
setInputText(body)
offsetRef.current = Math.max(0, offsetRef.current - 1)
}
setSending(false)
}
// ── Leave group ───────────────────────────────────────────────────────────────
async function leaveGroup() {
try {
await client.post(`/api/chat/conversations/${conversationId}/leave`)
useChatStore.setState(state => ({
conversations: state.conversations.filter(c => c.id !== conversationId),
totalUnread: state.conversations
.filter(c => c.id !== conversationId)
.reduce((s, c) => s + (c.unread_count || 0), 0),
}))
navigate('/messages', { replace: true })
} catch {}
setShowLeave(false)
}
// ── Render messages with date separators ──────────────────────────────────────
function renderMessages() {
const items = []
for (let i = 0; i < displayMessages.length; i++) {
const msg = displayMessages[i]
const prev = displayMessages[i - 1]
if (!prev || !sameDay(prev.sent_at, msg.sent_at)) {
items.push(
<DateSeparator key={`date-${msg.id}`} label={formatDateLabel(msg.sent_at)} />
)
}
const isOwn = msg.sender_id === user?.id
// Show sender name on every incoming group message
const showSender = isGroup && !isOwn
items.push(
<MessageBubble
key={msg.id}
msg={msg}
isOwn={isOwn}
showSender={showSender}
isGroup={isGroup}
/>
)
}
return items
}
const canLeave = isGroup && !conv?.is_system
return (
<div className="page" style={{ background: 'var(--bg)' }}>
{/* Top bar */}
<header className="top-bar">
<button
onClick={() => navigate('/messages')}
style={{
display: 'flex', alignItems: 'center', gap: 6,
background: 'none', border: 'none', cursor: 'pointer',
color: 'var(--text)', fontSize: 15, fontWeight: 600,
padding: '0 4px', minHeight: 44, borderRadius: 8,
flexShrink: 0,
}}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
Πίσω
</button>
<div style={{ flex: 1, textAlign: 'center', minWidth: 0 }}>
<span className="top-bar__title" style={{
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
display: 'block',
}}>
{title}
</span>
{isGroup && (
<span style={{ fontSize: 11, color: 'var(--muted)', display: 'block', marginTop: -2 }}>
{(conv?.participants || []).length} μέλη
</span>
)}
</div>
{canLeave ? (
<button
onClick={() => setShowLeave(true)}
style={{
background: 'none', border: 'none', cursor: 'pointer',
color: 'var(--danger)', fontSize: 13, fontWeight: 700,
padding: '0 4px', minHeight: 44, borderRadius: 8, flexShrink: 0,
}}
>
Αποχώρηση
</button>
) : (
<div style={{ width: 72, flexShrink: 0 }} />
)}
</header>
{/* Messages area */}
<div
ref={messagesEl}
onScroll={handleScroll}
style={{
flex: 1, overflowY: 'auto', minHeight: 0,
padding: '12px 16px',
display: 'flex', flexDirection: 'column', gap: 6,
overscrollBehavior: 'contain',
}}
>
{loadingMore && (
<div style={{ textAlign: 'center', padding: '8px 0', color: 'var(--muted)', fontSize: 13 }}>
Φόρτωση παλαιότερων…
</div>
)}
{initialLoad && (
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<span style={{ color: 'var(--muted)', fontSize: 14 }}>Φόρτωση…</span>
</div>
)}
{!initialLoad && displayMessages.length === 0 && (
<div style={{
flex: 1, display: 'flex', flexDirection: 'column',
alignItems: 'center', justifyContent: 'center', gap: 10,
}}>
<span style={{ fontSize: 40 }}>💬</span>
<p style={{ fontSize: 15, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5 }}>
Δεν υπάρχουν μηνύματα ακόμα.{'\n'}Πείτε γεια!
</p>
</div>
)}
{!initialLoad && renderMessages()}
<div ref={bottomAnchor} />
</div>
{/* Send bar */}
<div style={{
background: 'var(--bg2)', borderTop: '1px solid var(--border)',
padding: '10px 12px',
display: 'flex', alignItems: 'flex-end', gap: 10,
flexShrink: 0,
}}>
<AutoTextarea
value={inputText}
onChange={e => setInputText(e.target.value)}
onSubmit={sendMessage}
placeholder="Γράψτε μήνυμα…"
/>
<button
onClick={sendMessage}
disabled={!inputText.trim() || sending}
style={{
width: 44, height: 44, borderRadius: '50%', border: 'none',
background: inputText.trim() ? 'var(--accent)' : 'var(--bg3)',
color: inputText.trim() ? 'var(--accent-fg)' : 'var(--muted)',
cursor: inputText.trim() ? 'pointer' : 'not-allowed',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0, transition: 'background 0.15s, color 0.15s',
}}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path d="M22 2L11 13" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M22 2L15 22L11 13L2 9L22 2Z" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
</div>
{showLeave && (
<LeaveModal onConfirm={leaveGroup} onCancel={() => setShowLeave(false)} />
)}
</div>
)
}
+512
View File
@@ -0,0 +1,512 @@
import { useState, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useProductCache } from '../hooks/useProductCache'
import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
// ── Heart icon ────────────────────────────────────────────────────────────────
function Heart({ filled, size = 22 }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? '#ef4444' : 'none'} stroke={filled ? '#ef4444' : 'currentColor'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
</svg>
)
}
// ── Thumb (product image or initials) ─────────────────────────────────────────
function Thumb({ product, size = 42, radius = 10 }) {
return (
<div style={{
width: size, height: size, borderRadius: radius, flexShrink: 0,
background: 'var(--bg3)', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{product.image_url
? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: Math.round(size * 0.33), fontWeight: 700, color: 'var(--muted)' }}>
{product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()}
</span>
}
</div>
)
}
// ── Item Favorites Modal ───────────────────────────────────────────────────────
// Shows all attribute sections with heart toggles.
// The waiter picks which items appear in that product's Favorites tab.
function AttrSection({ title, items, favIds, onToggle }) {
if (!items || items.length === 0) return null
return (
<div style={{ marginBottom: 20 }}>
<div style={{
fontSize: 11, fontWeight: 700, color: 'var(--muted)',
textTransform: 'uppercase', letterSpacing: 0.8,
padding: '0 0 8px',
}}>
{title}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
{items.map(item => {
const isFav = favIds.includes(item.id)
return (
<div
key={item.id}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '10px 14px',
background: isFav ? 'rgba(239,68,68,0.07)' : 'var(--bg2)',
border: `1px solid ${isFav ? 'rgba(239,68,68,0.25)' : 'var(--border)'}`,
borderRadius: 10,
transition: 'background 120ms, border-color 120ms',
}}
>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.name}
</div>
{item.extra_cost != null && item.extra_cost !== 0 && (
<div style={{ fontSize: 12, color: 'var(--muted)' }}>+{Number(item.extra_cost).toFixed(2)} €</div>
)}
{item.price != null && item.price !== 0 && (
<div style={{ fontSize: 12, color: 'var(--muted)' }}>+{Number(item.price).toFixed(2)} €</div>
)}
</div>
<button
onClick={() => onToggle(item.id)}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, flexShrink: 0, color: isFav ? '#ef4444' : 'var(--muted)' }}
>
<Heart filled={isFav} size={20} />
</button>
</div>
)
})}
</div>
</div>
)
}
function ItemFavoritesModal({ product, waiterAttrFavs, onSave, onClose }) {
// Local state: { quick: id[], ingredients: id[], options: id[], prefs: id[] }
// Start from waiter overrides if they exist, otherwise seed from manager's is_favorite flags
function seedFromManager() {
return {
quick: (product.quick_options || []).filter(x => x.is_favorite).map(x => x.id),
ingredients: (product.ingredients || []).filter(x => x.is_favorite).map(x => x.id),
options: (product.options || []).filter(x => x.is_favorite).map(x => x.id),
prefs: (product.preference_sets|| []).filter(x => x.is_favorite).map(x => x.id),
}
}
const [local, setLocal] = useState(() => waiterAttrFavs ?? seedFromManager())
const hasAnything = (
(product.quick_options || []).length > 0 ||
(product.ingredients || []).length > 0 ||
(product.options || []).length > 0 ||
(product.preference_sets || []).length > 0
)
function toggle(section, id) {
setLocal(prev => {
const arr = prev[section] || []
return {
...prev,
[section]: arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id],
}
})
}
const totalSelected = (local.quick?.length || 0) + (local.ingredients?.length || 0) + (local.options?.length || 0) + (local.prefs?.length || 0)
function handleSave() {
// If nothing selected, clear the override (fall back to manager)
const isEmpty = totalSelected === 0
onSave(isEmpty ? null : local)
onClose()
}
function handleClear() {
setLocal({ quick: [], ingredients: [], options: [], prefs: [] })
}
return (
<>
{/* Backdrop */}
<div
onClick={onClose}
style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100 }}
/>
{/* Sheet */}
<div style={{
position: 'fixed', left: 0, right: 0, bottom: 0,
zIndex: 101,
background: 'var(--bg)',
borderRadius: '20px 20px 0 0',
maxHeight: '88vh',
display: 'flex', flexDirection: 'column',
boxShadow: '0 -8px 40px rgba(0,0,0,0.2)',
}}>
{/* Handle bar */}
<div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 0' }}>
<div style={{ width: 36, height: 4, borderRadius: 2, background: 'var(--border)' }} />
</div>
{/* Header */}
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '14px 16px 12px', borderBottom: '1px solid var(--border)', flexShrink: 0,
}}>
<Thumb product={product} size={38} radius={9} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product.name}
</div>
<div style={{ fontSize: 12, color: 'var(--muted)' }}>
{waiterAttrFavs ? 'Προσωπικές ρυθμίσεις ενεργές' : 'Χρήση ρυθμίσεων διαχειριστή'}
</div>
</div>
<button
onClick={onClose}
style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', padding: 4, fontSize: 20, lineHeight: 1 }}
>
✕
</button>
</div>
{/* Body */}
<div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 0' }}>
{!hasAnything ? (
<p style={{ color: 'var(--muted)', fontSize: 14, textAlign: 'center', padding: '32px 0' }}>
Αυτό το προϊόν δεν έχει επιλογές, υλικά ή προτιμήσεις.
</p>
) : (
<>
<p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 16, lineHeight: 1.5 }}>
Επίλεξε ποιες επιλογές θα εμφανίζονται στην καρτέλα <strong style={{ color: '#ef4444' }}>♥ Αγαπημένα</strong> για αυτό το προϊόν. Αν δεν επιλέξεις τίποτα, θα χρησιμοποιηθούν οι ρυθμίσεις του διαχειριστή.
</p>
<AttrSection
title="Γρήγορες Επιλογές"
items={product.quick_options}
favIds={local.quick || []}
onToggle={id => toggle('quick', id)}
/>
<AttrSection
title="Υλικά"
items={product.ingredients}
favIds={local.ingredients || []}
onToggle={id => toggle('ingredients', id)}
/>
<AttrSection
title="Extras"
items={product.options}
favIds={local.options || []}
onToggle={id => toggle('options', id)}
/>
<AttrSection
title="Προτιμήσεις"
items={product.preference_sets}
favIds={local.prefs || []}
onToggle={id => toggle('prefs', id)}
/>
</>
)}
</div>
{/* Footer */}
<div style={{
display: 'flex', gap: 10, padding: '12px 16px',
borderTop: '1px solid var(--border)', flexShrink: 0,
paddingBottom: 'max(12px, env(safe-area-inset-bottom))',
}}>
{waiterAttrFavs && (
<button
onClick={handleClear}
style={{
padding: '0 16px', height: 44, borderRadius: 12,
border: '1.5px solid var(--border)',
background: 'var(--bg2)', color: 'var(--muted)',
fontSize: 13, fontWeight: 600, cursor: 'pointer',
}}
>
Επαναφορά
</button>
)}
<button
onClick={handleSave}
style={{
flex: 1, height: 44, borderRadius: 12, border: 'none',
background: totalSelected > 0 ? '#ef4444' : 'var(--accent)',
color: '#fff',
fontSize: 15, fontWeight: 700, cursor: 'pointer',
}}
>
{totalSelected > 0 ? `Αποθήκευση (${totalSelected} επιλογές)` : 'Αποθήκευση'}
</button>
</div>
</div>
</>
)
}
// ── Product row (ALL tab) ─────────────────────────────────────────────────────
function ProductRow({ product, isFav, hasAttrOverride, onToggleFav, onEditAttrs }) {
const hasAttrs = (
(product.quick_options || []).length > 0 ||
(product.ingredients || []).length > 0 ||
(product.options || []).length > 0 ||
(product.preference_sets || []).length > 0
)
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '10px 16px', borderBottom: '1px solid var(--border)',
}}>
<Thumb product={product} />
{/* Tappable area — opens attr editor */}
<div
onClick={hasAttrs ? () => onEditAttrs(product) : undefined}
style={{ flex: 1, minWidth: 0, cursor: hasAttrs ? 'pointer' : 'default' }}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product.name}
</div>
{hasAttrOverride && (
<Heart filled size={12} />
)}
</div>
<div style={{ fontSize: 12, color: hasAttrs ? 'var(--accent)' : 'var(--muted)' }}>
{hasAttrs ? 'Επιλογές αγαπημένων →' : `${Number(product.base_price).toFixed(2)} €`}
</div>
</div>
{/* Heart — toggles product in/out of favorites list */}
<button
onClick={() => onToggleFav(product.id)}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 6, color: isFav ? '#ef4444' : 'var(--muted)', flexShrink: 0 }}
>
<Heart filled={isFav} />
</button>
</div>
)
}
// ── Draggable favorites list (pointer-events — works on touch + mouse) ─────────
function FavoritesList({ items, products, onReorder }) {
const [dragging, setDragging] = useState(null)
const [dropIndex, setDropIndex] = useState(null)
const containerRef = useRef(null)
const stateRef = useRef({ dragging: null, dropIndex: null })
function getProductById(id) { return products.find(p => p.id === id) }
function computeDropIndex(clientY) {
if (!containerRef.current) return null
const rows = [...containerRef.current.querySelectorAll('[data-drag-row]')]
for (let i = 0; i < rows.length; i++) {
const rect = rows[i].getBoundingClientRect()
if (clientY < rect.top + rect.height * 0.51) return i
}
return rows.length
}
const onPointerDown = useCallback((e, idx) => {
e.currentTarget.setPointerCapture(e.pointerId)
stateRef.current = { dragging: idx, dropIndex: null }
setDragging(idx)
function onMove(ev) {
const di = computeDropIndex(ev.clientY)
if (di !== stateRef.current.dropIndex) {
stateRef.current.dropIndex = di
setDropIndex(di)
}
}
function onUp() {
const { dragging: from, dropIndex: to } = stateRef.current
if (from != null && to != null) {
const next = [...items]
const [moved] = next.splice(from, 1)
const insertAt = to > from ? to - 1 : to
next.splice(insertAt, 0, moved)
onReorder(next)
}
stateRef.current = { dragging: null, dropIndex: null }
setDragging(null)
setDropIndex(null)
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', onUp)
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
}, [items, onReorder])
if (items.length === 0) {
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flex: 1, padding: 32, gap: 12 }}>
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.4 }}>
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
</svg>
<p style={{ fontSize: 14, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.6 }}>
Δεν έχεις προσθέσει αγαπημένα ακόμα.<br />Πήγαινε στην καρτέλα ΌΛΑ και πάτα την καρδιά δίπλα στα προϊόντα.
</p>
</div>
)
}
return (
<div ref={containerRef} style={{ flex: 1, overflowY: 'auto', touchAction: 'pan-x' }}>
{dropIndex === 0 && dragging != null && (
<div style={{ height: 3, background: '#22c55e', margin: '0 16px', borderRadius: 2 }} />
)}
{items.map((productId, idx) => {
const product = getProductById(productId)
if (!product) return null
const isDragging = dragging === idx
return (
<div key={productId}>
<div
data-drag-row
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '11px 16px',
borderBottom: '1px solid var(--border)',
background: isDragging ? 'var(--bg3)' : 'var(--bg)',
opacity: isDragging ? 0.45 : 1,
transition: 'opacity 120ms',
userSelect: 'none', WebkitUserSelect: 'none',
}}
>
<div
onPointerDown={e => onPointerDown(e, idx)}
style={{
color: 'var(--muted)', flexShrink: 0,
display: 'flex', flexDirection: 'column', gap: 2.5, padding: '6px 4px',
cursor: 'grab', touchAction: 'none',
}}
>
{[0,1,2].map(i => <span key={i} style={{ display: 'block', width: 16, height: 2.5, background: 'currentColor', borderRadius: 1 }} />)}
</div>
<Thumb product={product} size={38} radius={9} />
<span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product.name}
</span>
<span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>{Number(product.base_price).toFixed(2)} €</span>
</div>
{dropIndex === idx + 1 && dragging != null && dragging !== idx && (
<div style={{ height: 3, background: '#22c55e', margin: '0 16px', borderRadius: 2 }} />
)}
</div>
)
})}
</div>
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function FavoritesSetupPage() {
const navigate = useNavigate()
const { products, categories } = useProductCache()
const { favorites, toggleFavorite, reorderFavorites, itemFavorites, setItemFavorites } = useWaiterFavoritesStore()
const [tab, setTab] = useState('all')
const [editingProduct, setEditingProduct] = useState(null) // product object for ItemFavoritesModal
const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)
return (
<div className="page" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{/* Header */}
<header className="top-bar">
<button className="icon-btn" onClick={() => navigate(-1)}>←</button>
<span className="top-bar__title">Ρύθμιση Αγαπημένων</span>
<div style={{ width: 40 }} />
</header>
{/* Tabs */}
<div style={{ display: 'flex', borderBottom: '1px solid var(--border)', flexShrink: 0, background: 'var(--bg)' }}>
{[
{ key: 'all', label: 'ΌΛΑ' },
{ key: 'favorites', label: `ΑΓΑΠΗΜΈΝΑ (${favorites.length})` },
].map(t => (
<button
key={t.key}
onClick={() => setTab(t.key)}
style={{
flex: 1, padding: '12px 8px',
background: 'none', border: 'none', cursor: 'pointer',
fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
color: tab === t.key ? 'var(--accent)' : 'var(--muted)',
borderBottom: `2.5px solid ${tab === t.key ? 'var(--accent)' : 'transparent'}`,
transition: 'color 120ms, border-color 120ms',
}}
>
{t.label}
</button>
))}
</div>
{/* Content */}
<div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
{tab === 'all' ? (
topLevel.map(cat => {
const subcats = categories.filter(c => c.parent_id === cat.id)
const directProds = products.filter(p => p.category_id === cat.id && p.is_available)
const subProds = subcats.flatMap(sc => products.filter(p => p.category_id === sc.id && p.is_available))
const allProds = [...directProds, ...subProds]
if (allProds.length === 0) return null
return (
<div key={cat.id}>
<div style={{
padding: '8px 16px', fontSize: 11, fontWeight: 700,
color: cat.color || 'var(--muted)',
textTransform: 'uppercase', letterSpacing: 0.8,
background: 'var(--bg2)', borderBottom: '1px solid var(--border)',
position: 'sticky', top: 0, zIndex: 1,
}}>
{cat.name}
</div>
{allProds.map(p => (
<ProductRow
key={p.id}
product={p}
isFav={favorites.includes(p.id)}
hasAttrOverride={!!itemFavorites[p.id]}
onToggleFav={toggleFavorite}
onEditAttrs={setEditingProduct}
/>
))}
</div>
)
})
) : (
<FavoritesList
items={favorites}
products={products}
onReorder={reorderFavorites}
/>
)}
</div>
{/* Item attribute favorites modal */}
{editingProduct && (
<ItemFavoritesModal
product={editingProduct}
waiterAttrFavs={itemFavorites[editingProduct.id] ?? null}
onSave={attrFavs => setItemFavorites(editingProduct.id, attrFavs)}
onClose={() => setEditingProduct(null)}
/>
)}
</div>
)
}
+1 -1
View File
@@ -104,7 +104,7 @@ export default function LoginPage() {
// We send waiter id as identifier; backend matches by id+pin
const { data } = await client.post('/api/auth/login-by-id', { waiter_id: selectedWaiter.id, pin })
login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token)
navigate('/tables')
navigate('/tables', { replace: true })
} catch (err) {
setError(err.response?.data?.detail || 'Λανθασμένο PIN')
} finally {
+789
View File
@@ -0,0 +1,789 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { useSearchParams } from 'react-router-dom'
import AppShell from '../components/AppShell'
import client from '../api/client'
// ── helpers ───────────────────────────────────────────────────────────────────
function fmtTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}
function fmtDateTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleString('el-GR', {
day: '2-digit', month: '2-digit',
hour: '2-digit', minute: '2-digit',
})
}
function fmtPrice(n) {
return '€' + parseFloat(n || 0).toFixed(2)
}
// ── icons ─────────────────────────────────────────────────────────────────────
function PrintOkIcon() {
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none">
<path d="M6 9V2h12v7" stroke="#22c55e" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" stroke="#22c55e" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<rect x="6" y="14" width="12" height="8" rx="1" stroke="#22c55e" strokeWidth="2"/>
</svg>
)
}
function PrintFailIcon() {
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none">
<path d="M6 9V2h12v7" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<rect x="6" y="14" width="12" height="8" rx="1" stroke="#ef4444" strokeWidth="2"/>
<path d="M10 17l4 4M14 17l-4 4" stroke="#ef4444" strokeWidth="1.5" strokeLinecap="round"/>
</svg>
)
}
// Receipt SVG from ASSETS/ICONS/receipt.svg, coloured by fiscal status
function FiscalStatusIcon({ status }) {
if (!status) return null
const color = status === 'success' ? '#22c55e' : status === 'pending' ? '#f59e0b' : '#ef4444'
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17 13H21V19C21 20.1046 20.1046 21 19 21M17 13V19C17 20.1046 17.8954 21 19 21M17 13V5.75707C17 4.85168 17 4.39898 16.8098 4.13646C16.6439 3.90746 16.3888 3.75941 16.1076 3.72897C15.7853 3.69408 15.3923 3.91868 14.6062 4.36788L14.2938 4.54637C14.0045 4.7117 13.8598 4.79438 13.7062 4.82675C13.5702 4.85539 13.4298 4.85539 13.2938 4.82675C13.1402 4.79438 12.9955 4.7117 12.7062 4.54637L10.7938 3.45359C10.5045 3.28826 10.3598 3.20559 10.2062 3.17322C10.0702 3.14457 9.92978 3.14457 9.79383 3.17322C9.64019 3.20559 9.49552 3.28826 9.20618 3.4536L7.29382 4.54637C7.00448 4.71171 6.85981 4.79438 6.70617 4.82675C6.57022 4.85539 6.42978 4.85539 6.29383 4.82675C6.14019 4.79438 5.99552 4.71171 5.70618 4.54637L5.39382 4.36788C4.60772 3.91868 4.21467 3.69408 3.89237 3.72897C3.61123 3.75941 3.35611 3.90746 3.1902 4.13646C3 4.39898 3 4.85168 3 5.75707V16.2C3 17.8801 3 18.7202 3.32698 19.362C3.6146 19.9264 4.07354 20.3854 4.63803 20.673C5.27976 21 6.11984 21 7.8 21H19M12 10.5C11.5 10.376 10.6851 10.3714 10 10.376C9.77091 10.3775 9.90941 10.3678 9.6 10.376C8.79258 10.4012 8.00165 10.7368 8 11.6875C7.99825 12.7003 9 13 10 13C11 13 12 13.2312 12 14.3125C12 15.1251 11.1925 15.4812 10.1861 15.5991C9.3861 15.5991 9 15.625 8 15.5M10 16V17M10 8.99998V9.99998" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
)
}
function CompactIcon({ active }) {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none">
<rect x="3" y="5" width="18" height="3" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
<rect x="3" y="11" width="18" height="3" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
<rect x="3" y="17" width="18" height="3" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
</svg>
)
}
function DetailedIcon({ active }) {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none">
<rect x="3" y="3" width="18" height="7" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
<rect x="3" y="13" width="18" height="7" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
</svg>
)
}
function FilterIcon() {
return (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path d="M3 6h18M7 12h10M11 18h2" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
</svg>
)
}
// ── action sheet — long-press on detailed cards ───────────────────────────────
function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
return (
<div
onClick={onClose}
style={{
position: 'fixed', inset: 0, zIndex: 200,
background: 'rgba(0,0,0,0.55)',
display: 'flex', alignItems: 'flex-end',
}}
>
<div
onClick={e => e.stopPropagation()}
style={{
width: '100%', background: 'var(--bg)',
borderRadius: '20px 20px 0 0',
padding: '12px 16px 32px',
boxShadow: '0 -4px 20px rgba(0,0,0,0.4)',
}}
>
<div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 16px' }} />
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 4 }}>
Πρόβλημα Εκτύπωσης
</div>
<div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 20 }}>
Παραγγελία #{order.id} · {order.table_name} · {fmtTime(order.opened_at)}
{order.print_retry_count > 0 && (
<span style={{ marginLeft: 8, color: '#f59e0b' }}>
{order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'}
</span>
)}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<button
onClick={onRetry}
disabled={busy}
style={{
padding: '14px', borderRadius: 12, border: 'none',
background: 'var(--accent)', color: '#fff',
fontSize: 15, fontWeight: 700, cursor: busy ? 'default' : 'pointer',
opacity: busy ? 0.6 : 1,
}}
>
{busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'}
</button>
<button
onClick={onCancel}
disabled={busy}
style={{
padding: '14px', borderRadius: 12,
border: '1px solid #fee2e2', background: '#fff5f5',
fontSize: 15, fontWeight: 600, color: '#dc2626',
cursor: busy ? 'default' : 'pointer',
opacity: busy ? 0.6 : 1,
}}
>
Ακύρωση Εκτύπωσης
</button>
<button
onClick={onClose}
style={{
padding: '14px', borderRadius: 12,
border: '1px solid var(--border)', background: 'var(--bg2)',
fontSize: 15, color: 'var(--muted)', cursor: 'pointer',
}}
>
Κλείσιμο
</button>
</div>
</div>
</div>
)
}
// ── filter sheet ──────────────────────────────────────────────────────────────
function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
const [localFilter, setLocalFilter] = useState(filter)
const [localFrom, setLocalFrom] = useState(dateFrom)
const [localTo, setLocalTo] = useState(dateTo)
return (
<div
onClick={onClose}
style={{
position: 'fixed', inset: 0, zIndex: 200,
background: 'rgba(0,0,0,0.55)',
display: 'flex', alignItems: 'flex-end',
}}
>
<div
onClick={e => e.stopPropagation()}
style={{
width: '100%', background: 'var(--bg)',
borderRadius: '20px 20px 0 0',
padding: '12px 16px 40px',
boxShadow: '0 -4px 20px rgba(0,0,0,0.4)',
}}
>
<div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 20px' }} />
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>Φίλτρα</div>
{/* Status filter */}
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
Κατάσταση
</div>
<div style={{ display: 'flex', gap: 8 }}>
{[
{ value: 'all', label: 'Όλες' },
{ value: 'success', label: 'Επιτυχής' },
{ value: 'failed', label: 'Αποτυχημένη' },
].map(opt => (
<button
key={opt.value}
onClick={() => setLocalFilter(opt.value)}
style={{
flex: 1, padding: '10px 4px', borderRadius: 10,
border: `1px solid ${localFilter === opt.value ? 'var(--accent)' : 'var(--border)'}`,
background: localFilter === opt.value ? 'rgba(var(--accent-rgb,59,130,246),0.12)' : 'var(--bg2)',
color: localFilter === opt.value ? 'var(--accent)' : 'var(--text)',
fontSize: 13, fontWeight: localFilter === opt.value ? 700 : 500,
cursor: 'pointer',
}}
>
{opt.label}
</button>
))}
</div>
</div>
{/* Date range */}
<div style={{ marginBottom: 24 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
Εύρος ημερομηνίας/ώρας
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>Από</span>
<input
type="datetime-local"
value={localFrom}
onChange={e => setLocalFrom(e.target.value)}
style={{
flex: 1, height: 38, borderRadius: 10,
border: '1px solid var(--border)', background: 'var(--bg2)',
padding: '0 10px', fontSize: 13, color: 'var(--text)',
fontFamily: 'inherit', outline: 'none',
}}
/>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>Έως</span>
<input
type="datetime-local"
value={localTo}
onChange={e => setLocalTo(e.target.value)}
style={{
flex: 1, height: 38, borderRadius: 10,
border: '1px solid var(--border)', background: 'var(--bg2)',
padding: '0 10px', fontSize: 13, color: 'var(--text)',
fontFamily: 'inherit', outline: 'none',
}}
/>
</div>
{(localFrom || localTo) && (
<button
onClick={() => { setLocalFrom(''); setLocalTo('') }}
style={{
alignSelf: 'flex-start', fontSize: 12, color: 'var(--muted)',
background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0',
}}
>
Καθαρισμός ημερομηνίας
</button>
)}
</div>
</div>
<button
onClick={() => onApply(localFilter, localFrom, localTo)}
style={{
width: '100%', padding: '14px', borderRadius: 12, border: 'none',
background: 'var(--accent)', color: '#fff',
fontSize: 15, fontWeight: 700, cursor: 'pointer',
}}
>
Εφαρμογή
</button>
</div>
</div>
)
}
// ── compact card (click = expand inline, expanded shows action buttons) ────────
function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
const isPending = order.print_status === 'pending'
return (
<div
style={{
background: 'var(--bg2)',
border: `1px solid ${isPending ? 'rgba(239,68,68,0.4)' : 'var(--border)'}`,
borderRadius: 12,
cursor: 'pointer',
transition: 'border-color 0.15s',
}}
onClick={() => onToggle(order.id)}
>
{/* Always-visible summary row */}
<div style={{ padding: '10px 14px' }}>
{/* 3-column grid: table name | centered order# | print icon */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 4 }}>
<span style={{
fontSize: 14, fontWeight: 700, color: 'var(--text)',
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>
{order.table_name || '—'}
</span>
<span style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center' }}>
#{order.id}
</span>
<span style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 4 }}>
<FiscalStatusIcon status={order.fiscal_status} />
{isPending ? <PrintFailIcon /> : <PrintOkIcon />}
</span>
</div>
{/* Row 2: item count | total */}
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 5 }}>
<span style={{ fontSize: 12, color: 'var(--muted)' }}>
{order.items.length} αντ.
</span>
<span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)' }}>
{fmtPrice(order.total)}
</span>
</div>
</div>
{/* Expanded section — items + action buttons for pending */}
{expanded && (
<>
<div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />
<div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 3 }}>
{order.items.map(item => (
<div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--text)', flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.product_name}
</span>
<span style={{ color: 'var(--muted)', marginLeft: 8, flexShrink: 0 }}>
×{item.quantity % 1 === 0 ? item.quantity : item.quantity.toFixed(2)}
</span>
</div>
))}
</div>
{/* Total + fiscal info */}
<div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />
<div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 4 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontSize: 14, fontWeight: 600, color: 'var(--muted)' }}>Σύνολο</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
{isPending && order.print_retry_count > 0 && (
<span style={{ fontSize: 11, color: '#f59e0b' }}>
{order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'}
</span>
)}
<span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{fmtPrice(order.total)}</span>
</div>
</div>
{order.fiscal_status && (
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Φορολογική εκτύπωση</span>
<span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}>
{order.fiscal_status === 'success' ? 'Επιτυχής' : order.fiscal_status === 'pending' ? 'Εκκρεμεί…' : 'Αποτυχία'}
</span>
</div>
)}
</div>
{isPending && (
<>
<div style={{ borderTop: '1px solid var(--border)', margin: '0 14px' }} />
<div style={{ padding: '10px 14px', display: 'flex', gap: 8 }} onClick={e => e.stopPropagation()}>
<button
onClick={() => onRetry(order)}
disabled={busy}
style={{
flex: 1, padding: '10px 8px', borderRadius: 10, border: 'none',
background: 'var(--accent)', color: '#fff',
fontSize: 13, fontWeight: 700, cursor: busy ? 'default' : 'pointer',
opacity: busy ? 0.6 : 1,
}}
>
{busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'}
</button>
<button
onClick={() => onCancel(order)}
disabled={busy}
style={{
flex: 1, padding: '10px 8px', borderRadius: 10,
border: '1px solid #fee2e2', background: '#fff5f5',
fontSize: 13, fontWeight: 600, color: '#dc2626',
cursor: busy ? 'default' : 'pointer',
opacity: busy ? 0.6 : 1,
}}
>
Ακύρωση
</button>
</div>
</>
)}
</>
)}
</div>
)
}
// ── detailed card (long-press = action sheet) ─────────────────────────────────
function DetailedCard({ order, onLongPress }) {
const isPending = order.print_status === 'pending'
const pressTimer = useRef(null)
function startPress() {
if (!isPending) return
pressTimer.current = setTimeout(() => onLongPress(order), 600)
}
function cancelPress() {
clearTimeout(pressTimer.current)
}
return (
<div
onPointerDown={startPress}
onPointerUp={cancelPress}
onPointerLeave={cancelPress}
style={{
background: 'var(--bg2)',
border: `1px solid ${isPending ? 'rgba(239,68,68,0.4)' : 'var(--border)'}`,
borderRadius: 14,
cursor: isPending ? 'pointer' : 'default',
userSelect: 'none',
WebkitUserSelect: 'none',
}}
>
{/* Header */}
<div style={{
display: 'flex', alignItems: 'center', gap: 10,
padding: '11px 14px',
background: isPending ? 'rgba(239,68,68,0.06)' : 'var(--bg3)',
borderBottom: '1px solid var(--border)',
borderRadius: '14px 14px 0 0',
}}>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', flex: 1 }}>
{order.table_name || '—'}
</span>
<span style={{ fontSize: 12, color: 'var(--muted)' }}>#{order.id}</span>
<span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<FiscalStatusIcon status={order.fiscal_status} />
{isPending ? <PrintFailIcon /> : <PrintOkIcon />}
</span>
</div>
{/* Meta rows */}
<div style={{ padding: '10px 14px', display: 'flex', flexDirection: 'column', gap: 5 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Παραγγέλθηκε</span>
<span style={{ color: 'var(--text)', fontWeight: 500 }}>{fmtDateTime(order.opened_at)}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Εκτύπωση</span>
<span style={{ fontWeight: 600, color: isPending ? '#ef4444' : '#22c55e' }}>
{isPending
? `Εκκρεμεί (${order.print_retry_count} επαν.)`
: `OK ${fmtTime(order.print_attempted_at)}`}
</span>
</div>
{order.fiscal_status && (
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
<span style={{ color: 'var(--muted)' }}>Φορολογική εκτύπωση</span>
<span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}>
{order.fiscal_status === 'success' ? 'Επιτυχής' : order.fiscal_status === 'pending' ? 'Εκκρεμεί…' : 'Αποτυχία'}
</span>
</div>
)}
</div>
{/* Divider */}
<div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />
{/* Items — no fixed height, auto-sizes to content */}
<div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 4 }}>
{order.items.map(item => (
<div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
<span style={{ color: 'var(--text)', flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.product_name}
</span>
<span style={{ color: 'var(--muted)', marginLeft: 8, flexShrink: 0 }}>
×{item.quantity % 1 === 0 ? item.quantity : item.quantity.toFixed(2)}
</span>
</div>
))}
</div>
{/* Divider */}
<div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />
{/* Total */}
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 14px', fontSize: 14 }}>
<span style={{ color: 'var(--muted)', fontWeight: 600 }}>Σύνολο</span>
<span style={{ color: 'var(--text)', fontWeight: 700 }}>{fmtPrice(order.total)}</span>
</div>
{isPending && (
<div style={{ padding: '0 14px 10px', textAlign: 'center' }}>
<span style={{ fontSize: 11, color: 'var(--muted)' }}>Κρατήστε πατημένο για επιλογές</span>
</div>
)}
</div>
)
}
// ── main page ─────────────────────────────────────────────────────────────────
export default function OrderLogPage() {
const [searchParams] = useSearchParams()
const initialFilter = searchParams.get('filter') === 'failed' ? 'failed' : 'all'
const [orders, setOrders] = useState([])
const [loading, setLoading] = useState(true)
const [view, setView] = useState('compact')
const [search, setSearch] = useState('')
const [filter, setFilter] = useState(initialFilter)
const [dateFrom, setDateFrom] = useState('')
const [dateTo, setDateTo] = useState('')
const [showFilter, setShowFilter] = useState(false)
const [expandedId, setExpandedId] = useState(null)
const [actionOrder, setActionOrder] = useState(null)
const [actionBusy, setActionBusy] = useState(false)
const load = useCallback(async () => {
try {
const res = await client.get('/api/orders/shift-log')
setOrders(res.data?.orders ?? [])
} catch {
// keep stale data
} finally {
setLoading(false)
}
}, [])
useEffect(() => { load() }, [load])
useEffect(() => {
const id = setInterval(load, 10000)
return () => clearInterval(id)
}, [load])
function toggleExpand(id) {
setExpandedId(prev => prev === id ? null : id)
}
const q = search.trim().toLowerCase()
let filtered = q
? orders.filter(o =>
(o.table_name || '').toLowerCase().includes(q) ||
String(o.id).includes(q) ||
o.items.some(i => i.product_name.toLowerCase().includes(q))
)
: [...orders]
if (filter === 'failed') {
filtered = filtered.filter(o => o.print_status === 'pending')
} else if (filter === 'success') {
filtered = filtered.filter(o => o.print_status !== 'pending')
}
if (dateFrom) {
const from = new Date(dateFrom)
filtered = filtered.filter(o => new Date(o.opened_at) >= from)
}
if (dateTo) {
const to = new Date(dateTo)
filtered = filtered.filter(o => new Date(o.opened_at) <= to)
}
async function handleRetry(order) {
setActionBusy(true)
try {
await client.post(`/api/orders/${order.id}/retry-print`)
await load()
setActionOrder(null)
setExpandedId(null)
} catch {
// stay open so user can try again
} finally {
setActionBusy(false)
}
}
async function handleCancelJobs(order) {
setActionBusy(true)
try {
const pendingJobs = order.print_jobs.filter(j => j.status === 'pending')
for (const job of pendingJobs) {
await client.post(`/api/orders/${order.id}/print-jobs/${job.id}/cancel`)
}
await load()
setActionOrder(null)
setExpandedId(null)
} catch {
// stay open
} finally {
setActionBusy(false)
}
}
const pendingCount = orders.filter(o => o.print_status === 'pending').length
const hasActiveFilters = filter !== 'all' || !!dateFrom || !!dateTo
return (
<AppShell title="Αρχ. Παραγγ.">
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>
{/* Toolbar */}
<div style={{
display: 'flex', gap: 8, alignItems: 'center',
padding: '10px 14px',
borderBottom: '1px solid var(--border)',
flexShrink: 0,
}}>
<input
type="search"
placeholder="Τραπέζι, #παραγγελία, αντικείμενο…"
value={search}
onChange={e => setSearch(e.target.value)}
style={{
flex: 1, height: 38, borderRadius: 10,
border: '1px solid var(--border)', background: 'var(--bg2)',
padding: '0 12px', fontSize: 14, color: 'var(--text)',
fontFamily: 'inherit', outline: 'none',
}}
/>
<button
onClick={() => setView(v => v === 'compact' ? 'detailed' : 'compact')}
style={{
width: 38, height: 38, borderRadius: 10,
border: `1px solid ${view === 'detailed' ? 'var(--accent)' : 'var(--border)'}`,
background: view === 'detailed' ? 'var(--accent)18' : 'var(--bg2)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer',
}}
title={view === 'compact' ? 'Λεπτομερής προβολή' : 'Συμπαγής προβολή'}
>
{view === 'compact' ? <DetailedIcon active={false} /> : <CompactIcon active={false} />}
</button>
</div>
{/* Pending banner */}
{pendingCount > 0 && (
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '8px 14px',
background: 'rgba(239,68,68,0.08)',
borderBottom: '1px solid rgba(239,68,68,0.2)',
flexShrink: 0,
}}>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="10" stroke="#ef4444" strokeWidth="2"/>
<path d="M12 8v4M12 16h.01" stroke="#ef4444" strokeWidth="2" strokeLinecap="round"/>
</svg>
<span style={{ fontSize: 13, color: '#ef4444', fontWeight: 600 }}>
{pendingCount} παραγγελί{pendingCount !== 1 ? 'ες' : 'α'} με πρόβλημα εκτύπωσης
</span>
</div>
)}
{/* Active filter chips */}
{hasActiveFilters && (
<div style={{
display: 'flex', gap: 6, alignItems: 'center',
padding: '6px 14px',
borderBottom: '1px solid var(--border)',
flexShrink: 0, flexWrap: 'wrap',
}}>
{filter !== 'all' && (
<span style={{
fontSize: 12, padding: '3px 10px', borderRadius: 999,
background: filter === 'failed' ? 'rgba(239,68,68,0.12)' : 'rgba(34,197,94,0.12)',
color: filter === 'failed' ? '#ef4444' : '#22c55e',
fontWeight: 600,
}}>
{filter === 'failed' ? 'Αποτυχημένη εκτύπωση' : 'Επιτυχής εκτύπωση'}
</span>
)}
{dateFrom && (
<span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}>
Από {new Date(dateFrom).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
</span>
)}
{dateTo && (
<span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}>
Έως {new Date(dateTo).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
</span>
)}
<button
onClick={() => { setFilter('all'); setDateFrom(''); setDateTo('') }}
style={{ fontSize: 12, color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer', padding: '3px 6px' }}
>
✕ Καθαρισμός
</button>
</div>
)}
{/* List */}
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px 80px', display: 'flex', flexDirection: 'column', gap: 8 }}>
{loading && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}>Φόρτωση…</p>
)}
{!loading && filtered.length === 0 && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}>
{search || hasActiveFilters ? 'Δεν βρέθηκαν παραγγελίες' : 'Δεν υπάρχουν παραγγελίες σε αυτή τη βάρδια'}
</p>
)}
{filtered.map(order =>
view === 'compact'
? (
<CompactCard
key={order.id}
order={order}
expanded={expandedId === order.id}
onToggle={toggleExpand}
onRetry={handleRetry}
onCancel={handleCancelJobs}
busy={actionBusy}
/>
)
: (
<DetailedCard
key={order.id}
order={order}
onLongPress={setActionOrder}
/>
)
)}
</div>
{/* Floating filter button */}
<button
onClick={() => setShowFilter(true)}
style={{
position: 'absolute', bottom: 20, right: 20,
width: 52, height: 52, borderRadius: '50%',
border: 'none', cursor: 'pointer',
background: hasActiveFilters ? 'var(--accent)' : 'var(--bg3)',
color: hasActiveFilters ? '#fff' : 'var(--text)',
boxShadow: '0 4px 16px rgba(0,0,0,0.25)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
zIndex: 10,
}}
title="Φίλτρα"
>
<FilterIcon />
{hasActiveFilters && (
<span style={{
position: 'absolute', top: -2, right: -2,
width: 14, height: 14, borderRadius: '50%',
background: '#ef4444',
border: '2px solid var(--bg)',
}} />
)}
</button>
</div>
{/* Action sheet — long-press on detailed cards */}
{actionOrder && (
<PrintActionSheet
order={actionOrder}
busy={actionBusy}
onRetry={() => handleRetry(actionOrder)}
onCancel={() => handleCancelJobs(actionOrder)}
onClose={() => setActionOrder(null)}
/>
)}
{/* Filter sheet */}
{showFilter && (
<FilterSheet
filter={filter}
dateFrom={dateFrom}
dateTo={dateTo}
onApply={(f, from, to) => {
setFilter(f)
setDateFrom(from)
setDateTo(to)
setShowFilter(false)
}}
onClose={() => setShowFilter(false)}
/>
)}
</AppShell>
)
}
File diff suppressed because it is too large Load Diff
+271
View File
@@ -0,0 +1,271 @@
import { useQuery } from '@tanstack/react-query'
import AppShell from '../components/AppShell'
import client from '../api/client'
// ── helpers ───────────────────────────────────────────────────────────────────
function fmtTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}
function fmtDuration(seconds) {
if (seconds == null || seconds < 0) return '—'
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
if (h === 0) return `${m}λ`
if (m === 0) return `${h}ω`
return `${h}ω ${m}λ`
}
function fmtEuro(n) {
return '€' + parseFloat(n || 0).toFixed(2)
}
function sinceSeconds(isoStart) {
if (!isoStart) return 0
return Math.floor((Date.now() - new Date(isoStart).getTime()) / 1000)
}
function breakDurationSeconds(b) {
if (!b.started_at) return 0
const end = b.ended_at ? new Date(b.ended_at) : new Date()
return Math.floor((end - new Date(b.started_at)) / 1000)
}
// ── stat card ─────────────────────────────────────────────────────────────────
function StatCard({ label, value, sub, accent }) {
return (
<div style={{
background: 'var(--bg2)', border: '1px solid var(--border)',
borderRadius: 16, padding: '16px 18px',
display: 'flex', flexDirection: 'column', gap: 4,
}}>
<div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.7 }}>{label}</div>
<div style={{
fontSize: 28, fontWeight: 700, lineHeight: 1.1,
color: accent || 'var(--text)',
fontFamily: "'ui-monospace','SFMono-Regular',monospace",
}}>{value}</div>
{sub && <div style={{ fontSize: 12, color: 'var(--muted)' }}>{sub}</div>}
</div>
)
}
// ── horizontal bar chart (per-hour) ──────────────────────────────────────────
function PerHourChart({ title, data, accent = 'var(--accent)' }) {
const hours = Object.keys(data).map(Number).sort((a, b) => a - b)
if (hours.length === 0) return null
const maxValue = Math.max(...hours.map(h => data[h]), 1)
return (
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>{title}</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{hours.map(h => {
const pct = (data[h] / maxValue) * 100
return (
<div key={h} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ width: 32, fontSize: 11, fontWeight: 700, color: 'var(--muted)', textAlign: 'right', flexShrink: 0 }}>
{String(h).padStart(2, '0')}:00
</div>
<div style={{ flex: 1, height: 20, background: 'var(--bg3)', borderRadius: 4, overflow: 'hidden' }}>
<div style={{
height: '100%', borderRadius: 4,
width: `${Math.max(pct, data[h] > 0 ? 2 : 0)}%`,
background: accent,
transition: 'width 300ms ease',
display: 'flex', alignItems: 'center',
}}>
{pct > 18 && (
<span style={{ fontSize: 10, fontWeight: 800, color: 'var(--accent-fg)', paddingLeft: 6 }}>
{data[h]}
</span>
)}
</div>
</div>
<div style={{ width: 20, fontSize: 11, fontWeight: 700, color: 'var(--text)', flexShrink: 0 }}>
{pct <= 18 ? data[h] : ''}
</div>
</div>
)
})}
</div>
</div>
)
}
// ── breaks timeline ───────────────────────────────────────────────────────────
function BreakRow({ brk, index }) {
const dur = breakDurationSeconds(brk)
const active = !brk.ended_at
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '10px 14px', borderRadius: 10,
background: active ? 'rgba(251,146,60,0.1)' : 'var(--bg2)',
border: `1px solid ${active ? '#f97316' : 'var(--border)'}`,
}}>
<div style={{
width: 28, height: 28, borderRadius: 8, flexShrink: 0,
background: active ? '#f97316' : 'var(--bg3)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 12, fontWeight: 700, color: active ? 'white' : 'var(--muted)',
}}>{index + 1}</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
{fmtTime(brk.started_at)} – {active ? 'Τώρα' : fmtTime(brk.ended_at)}
</div>
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>
{fmtDuration(dur)}
</div>
</div>
{active && (
<span style={{
fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999,
background: '#f97316', color: 'white',
}}>ΕΝΕΡΓΟ</span>
)}
</div>
)
}
// ── main page ─────────────────────────────────────────────────────────────────
export default function ShiftOverviewPage() {
const { data: shift, isLoading: shiftLoading } = useQuery({
queryKey: ['my-shift'],
queryFn: () => client.get('/api/shifts/my').then(r => r.data),
refetchInterval: 30_000,
})
const { data: settings } = useQuery({
queryKey: ['pos-settings'],
queryFn: () => client.get('/api/settings/').then(r => r.data),
staleTime: 60_000,
})
const hideRevenue = settings?.['shifts.hide_revenue_from_waiters']?.value === 'true'
// /api/orders/my returns only open orders belonging to this waiter —
// enough for per-hour chart of current open tables
const { data: openOrders = [] } = useQuery({
queryKey: ['my-orders-shift'],
queryFn: () => client.get('/api/orders/my').then(r => r.data),
refetchInterval: 30_000,
enabled: !!shift,
})
if (shiftLoading) {
return (
<AppShell title="Shift Overview">
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 14 }}>
Φόρτωση…
</div>
</AppShell>
)
}
if (!shift) {
return (
<AppShell title="Shift Overview">
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, padding: 24, textAlign: 'center' }}>
<div style={{ fontSize: 40 }}>⏸</div>
<div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>Δεν υπάρχει ενεργή βάρδια</div>
<div style={{ fontSize: 13, color: 'var(--muted)' }}>Ξεκινήστε βάρδια για να δείτε στατιστικά.</div>
</div>
</AppShell>
)
}
// ── Compute stats ────────────────────────────────────────────────────────────
const totalShiftSec = sinceSeconds(shift.started_at)
const totalBreakSec = (shift.breaks || []).reduce((s, b) => s + breakDurationSeconds(b), 0)
const workedSec = Math.max(0, totalShiftSec - totalBreakSec)
// Per-hour buckets from currently-open orders
const ordersByHour = {}
const itemsByHour = {}
openOrders.forEach(o => {
const h = new Date(o.opened_at).getHours()
ordersByHour[h] = (ordersByHour[h] || 0) + 1
itemsByHour[h] = (itemsByHour[h] || 0) +
(o.items || []).filter(i => i.status !== 'cancelled').reduce((s, i) => s + i.quantity, 0)
})
const totalItems = openOrders.reduce((s, o) =>
s + (o.items || []).filter(i => i.status !== 'cancelled').reduce((is, i) => is + i.quantity, 0), 0)
const activeBreak = (shift.breaks || []).find(b => !b.ended_at)
return (
<AppShell title="Shift Overview">
<div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 24px' }}>
{/* Active break banner */}
{activeBreak && (
<div style={{
margin: '0 0 16px',
padding: '12px 16px',
borderRadius: 12,
background: 'rgba(251,146,60,0.12)',
border: '1px solid #f97316',
display: 'flex', alignItems: 'center', gap: 10,
}}>
<span style={{ fontSize: 20 }}>☕</span>
<div>
<div style={{ fontSize: 14, fontWeight: 700, color: '#f97316' }}>Σε διάλειμμα</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>
από {fmtTime(activeBreak.started_at)} · {fmtDuration(breakDurationSeconds(activeBreak))} μέχρι τώρα
</div>
</div>
</div>
)}
{/* Hero stats grid */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 20 }}>
<StatCard label="Έναρξη" value={fmtTime(shift.started_at)} />
<StatCard label="Ώρες Εργασίας" value={fmtDuration(workedSec)} sub={`${fmtDuration(totalBreakSec)} διαλείμματα`} />
<StatCard label="Αρχ. Μετρητά" value={fmtEuro(shift.starting_cash)} />
{!hideRevenue && (
<StatCard label="Είσπραξη" value={fmtEuro(shift.total_collected)} accent="var(--success, #22c55e)" />
)}
{!hideRevenue && (
<StatCard label="Παραδ. Ποσό" value={fmtEuro(shift.net_to_deliver)} sub="Αρχ. + Είσπραξη" accent="var(--accent)" />
)}
<StatCard label="Ανοιχτά Τραπέζια" value={String(openOrders.length)} sub="τρέχουσες παραγγελίες" />
<StatCard label="Είδη (ανοιχτά)" value={String(totalItems)} />
<StatCard label="Διαλείμματα" value={String((shift.breaks || []).length)} sub={`${fmtDuration(totalBreakSec)} σύνολο`} />
</div>
{/* Per-hour charts */}
{openOrders.length > 0 && (
<div style={{
background: 'var(--bg2)', border: '1px solid var(--border)',
borderRadius: 16, padding: '16px 18px', marginBottom: 20,
}}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>Ανά Ώρα</div>
<PerHourChart title="Παραγγελίες" data={ordersByHour} />
<PerHourChart title="Είδη" data={itemsByHour} />
</div>
)}
{/* Breaks */}
{(shift.breaks || []).length > 0 && (
<div>
<div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>
Διαλείμματα ({shift.breaks.length})
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{shift.breaks.map((b, i) => <BreakRow key={b.id} brk={b} index={i} />)}
</div>
</div>
)}
</div>
</AppShell>
)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff