import { useState } from 'react' import { useParams, useNavigate } from 'react-router-dom' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import toast from 'react-hot-toast' import client from '../api/client' import { Percent } from 'lucide-react' import Badge from '../ui/Badge' import { ConfirmModal } from '../ui/Modal' import PaymentMethodModal from '../ui/PaymentMethodModal' import DesktopOrderingTab from './DesktopOrderingTab' function PrintOrderModal({ onClose, onPrint, printers }) { const [printerId, setPrinterId] = useState(printers[0]?.id ?? '') function submit() { if (!printerId) { toast.error('Επιλέξτε εκτυπωτή'); return } onPrint(Number(printerId)) onClose() } return (

Εκτύπωση παραγγελίας

) } function effPrice(item) { return (item.unit_price ?? 0) + (item.price_adjustment ?? 0) } function itemTotal(item) { return (effPrice(item) * item.quantity).toFixed(2) } const PAYMENT_METHOD_STYLES = { cash: { label: 'ΜΕΤΡΗΤΑ', color: '#15803d', bg: '#f0fdf4', border: '#86efac' }, card: { label: 'ΚΑΡΤΑ', color: '#1d4ed8', bg: '#eff6ff', border: '#93c5fd' }, transfer: { label: 'ΤΡΑΠΕΖΙΚΗ', color: '#6d28d9', bg: '#f5f3ff', border: '#c4b5fd' }, treat: { label: 'ΚΕΡΑΣΤΗΚΕ', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' }, comp: { label: 'ΚΕΡΑΣΤΗΚΕ', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' }, } function PayMethodChip({ method }) { if (!method) return null const s = PAYMENT_METHOD_STYLES[method] || { label: method.toUpperCase(), color: '#374151', bg: '#f3f4f6', border: '#d1d5db' } return ( {s.label} ) } function formatDate(dt) { if (!dt) return '—' return new Date(dt).toLocaleString('el-GR', { dateStyle: 'short', timeStyle: 'short' }) } const EVENT_LABELS = { ORDER_OPENED: 'Άνοιγμα', ITEMS_ADDED: 'Προσθήκη', PAYMENT: 'Πληρωμή', PAYMENT_OFFLINE: 'Πληρωμή (Offline)', ORDER_CLOSED: 'Κλείσιμο', ORDER_CANCELLED: 'Ακύρωση', ITEM_CANCELLED: 'Ακύρωση αντ.', } function AuditTab({ order, waiterMap }) { if (!order.audit_logs || order.audit_logs.length === 0) { return

Δεν υπάρχουν εγγραφές.

} const itemsById = Object.fromEntries((order.items || []).map(i => [i.id, i])) return (
{order.audit_logs.map(log => { const isDuplicate = log.is_duplicate === 1 || log.is_duplicate === true const isPayment = log.event_type === 'PAYMENT' || log.event_type === 'PAYMENT_OFFLINE' const badgeClass = isDuplicate ? 'bg-red-100 text-red-700' : isPayment ? 'bg-green-100 text-green-700' : log.event_type.includes('CANCEL') ? 'bg-red-100 text-red-600' : log.event_type === 'ORDER_CLOSED' ? 'bg-gray-100 text-gray-600' : 'bg-blue-100 text-blue-700' const displayTime = log.offline_at ? formatDate(log.offline_at) : formatDate(log.created_at) // Resolve item names for ITEMS_ADDED and ITEM_CANCELLED events let itemNames = [] if (log.item_ids && (log.event_type === 'ITEMS_ADDED' || log.event_type === 'ITEM_CANCELLED')) { try { const ids = JSON.parse(log.item_ids) itemNames = ids.map(id => { const item = itemsById[id] return item ? `${item.product?.name ?? `#${item.product_id}`} ×${item.quantity}` : null }).filter(Boolean) } catch { /* ignore */ } } return (
{EVENT_LABELS[log.event_type] ?? log.event_type} {isDuplicate && ( ΔΙΠΛΗ )}
{log.waiter_name ?? waiterMap[log.waiter_id] ?? `#${log.waiter_id}`} {log.amount != null && ( €{log.amount.toFixed(2)} )} {log.payment_method && ( )} {itemNames.length > 0 && (
{itemNames.map((name, i) => ( {name} ))}
)}
{displayTime} {log.offline_at && ( offline )}
) })}
) } // ─── Price Events Tab ──────────────────────────────────────────────────────── const PRICE_EVENT_LABELS = { modifier_applied: 'Τροποποιητής', deal_triggered: 'Προσφορά', deal_offer_shown: 'Προσφορά (εμφανίστηκε)', deal_offer_accepted: 'Προσφορά (αποδεκτή)', deal_offer_dismissed:'Προσφορά (απορρίφθηκε)', waiter_discount: 'Έκπτωση σερβιτόρου', free_item_added: 'Δωρεάν αντικείμενο', } const PRICE_EVENT_COLORS = { modifier_applied: { bg: '#eff6ff', color: '#1d4ed8', border: '#93c5fd' }, deal_triggered: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' }, deal_offer_shown: { bg: '#fefce8', color: '#a16207', border: '#fde68a' }, deal_offer_accepted: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' }, deal_offer_dismissed:{ bg: '#fef2f2', color: '#b91c1c', border: '#fca5a5' }, waiter_discount: { bg: '#fdf4ff', color: '#7e22ce', border: '#d8b4fe' }, free_item_added: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' }, } function PriceEventsTab({ orderId }) { const { data: events = [], isLoading } = useQuery({ queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), }) if (isLoading) return (
) if (events.length === 0) return (

Δεν υπάρχουν συμβάντα τιμολόγησης για αυτή την παραγγελία.

) return (
{events.map(ev => { const label = PRICE_EVENT_LABELS[ev.event_type] ?? ev.event_type const style = PRICE_EVENT_COLORS[ev.event_type] ?? { bg: '#f8fafc', color: '#334155', border: '#cbd5e1' } const hasDelta = ev.price_before != null && ev.price_after != null return (
{label}
{ev.modifier_name && {ev.modifier_name}} {ev.deal_name && {ev.deal_name}} {ev.applied_by_username && ( από {ev.applied_by_username} )} {hasDelta && ( {ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount?.toFixed(2)}€ ({ev.price_before?.toFixed(2)} → {ev.price_after?.toFixed(2)}) )}
{ev.waiter_note && (

"{ev.waiter_note}"

)} {ev.conditions_snapshot && Object.keys(ev.conditions_snapshot).length > 0 && (
Συνθήκες
                    {JSON.stringify(ev.conditions_snapshot, null, 2)}
                  
)}
{formatDate(ev.applied_at)}
) })}
) } export default function OrderDetailPage({ orderId: propOrderId, readOnly = false }) { const { orderId: paramOrderId } = useParams() const orderId = propOrderId ?? paramOrderId const navigate = useNavigate() const qc = useQueryClient() const [tab, setTab] = useState('overview') const [confirmAction, setConfirmAction] = useState(null) // { type, payload } const [showPrintModal, setShowPrintModal] = useState(false) const [payPending, setPayPending] = useState(null) // item_ids waiting for method selection const [customerSearch, setCustomerSearch] = useState('') const [showCustomerDropdown, setShowCustomerDropdown] = useState(false) const { data: order, isLoading } = useQuery({ queryKey: ['order', orderId], queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data), enabled: !!orderId, }) const { data: waiters = [] } = useQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000, }) const { data: printers = [] } = useQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000, }) const { data: rawPriceEvents = [] } = useQuery({ queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), enabled: !!orderId, staleTime: 30_000, }) const priceEventsMap = rawPriceEvents.reduce((acc, ev) => { if (!acc[ev.order_item_id]) acc[ev.order_item_id] = [] acc[ev.order_item_id].push(ev) return acc }, {}) const printOrder = useMutation({ mutationFn: (printerId) => client.post(`/api/orders/${orderId}/print`, { printer_id: printerId }), onSuccess: () => toast.success('Αποστολή στον εκτυπωτή…'), onError: () => toast.error('Σφάλμα εκτύπωσης'), }) const waiterMap = Object.fromEntries(waiters.map(w => [w.id, w.nickname || w.full_name || w.username])) const assignedIds = new Set((order?.waiters ?? []).map(w => w.waiter_id)) const invalidate = () => { qc.invalidateQueries({ queryKey: ['order', orderId] }) qc.invalidateQueries({ queryKey: ['orders-active'] }) } const cancelItem = useMutation({ mutationFn: (itemId) => client.delete(`/api/orders/${orderId}/items/${itemId}`), onSuccess: () => { toast.success('Αντικείμενο ακυρώθηκε'); invalidate() }, onError: () => toast.error('Σφάλμα ακύρωσης αντικειμένου'), }) const cancelOrder = useMutation({ mutationFn: () => client.delete(`/api/orders/${orderId}`), onSuccess: () => { toast.success('Παραγγελία ακυρώθηκε'); navigate('/tables') }, onError: () => toast.error('Σφάλμα ακύρωσης παραγγελίας'), }) const closeOrder = useMutation({ mutationFn: () => client.post(`/api/orders/${orderId}/close`), onSuccess: () => { toast.success('Παραγγελία έκλεισε'); navigate('/tables') }, onError: () => toast.error('Σφάλμα κλεισίματος'), }) const assignWaiter = useMutation({ mutationFn: (waiter_id) => client.put(`/api/orders/${orderId}/assign-waiter`, { waiter_id }), onSuccess: () => { toast.success('Σερβιτόρος προστέθηκε'); invalidate() }, onError: () => toast.error('Σφάλμα'), }) const removeWaiter = useMutation({ mutationFn: (wid) => client.delete(`/api/orders/${orderId}/waiters/${wid}`), onSuccess: () => { toast.success('Σερβιτόρος αφαιρέθηκε'); invalidate() }, onError: () => toast.error('Σφάλμα'), }) const { data: customersData = [] } = useQuery({ queryKey: ['customers', customerSearch], queryFn: () => client.get('/api/customers/', { params: customerSearch ? { search: customerSearch } : {} }).then(r => r.data), staleTime: 30_000, enabled: showCustomerDropdown, }) const assignCustomer = useMutation({ mutationFn: (customer_id) => client.put(`/api/orders/${orderId}/customer`, { customer_id }), onSuccess: (_, customer_id) => { toast.success(customer_id ? 'Πελάτης ανατέθηκε' : 'Πελάτης αφαιρέθηκε'); invalidate(); setShowCustomerDropdown(false); setCustomerSearch('') }, onError: () => toast.error('Σφάλμα'), }) const payItems = useMutation({ mutationFn: ({ item_ids, payment_method }) => client.post(`/api/orders/${orderId}/pay`, { item_ids, payment_method }), onSuccess: () => { toast.success('Πληρώθηκε'); invalidate() }, onError: () => toast.error('Σφάλμα πληρωμής'), }) const tabItem = useMutation({ mutationFn: (itemId) => client.post(`/api/orders/${orderId}/items/${itemId}/tab`), onSuccess: () => { toast.success('Αντικείμενο μεταφέρθηκε στην καρτέλα'); invalidate() }, onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'), }) function requestPay(item_ids) { setPayPending(item_ids) } function confirmPay(method) { if (!payPending) return payItems.mutate({ item_ids: payPending, payment_method: method }) setPayPending(null) } function handleConfirm() { if (!confirmAction) return const { type, payload } = confirmAction if (type === 'cancelItem') cancelItem.mutate(payload) if (type === 'cancelOrder') cancelOrder.mutate() if (type === 'closeOrder') closeOrder.mutate() setConfirmAction(null) } if (isLoading) return
Φόρτωση…
if (!order) return
Παραγγελία δεν βρέθηκε.
const activeItems = order.items.filter(i => i.status === 'active') const total = order.items .filter(i => i.status !== 'cancelled') .reduce((s, i) => s + effPrice(i) * i.quantity, 0) const isOpen = ['open', 'partially_paid'].includes(order.status) // The ordering tab needs full height and no outer padding if (tab === 'order') { return (
{/* Compact header strip */}
{!propOrderId && ( )}
Τραπέζι {order.table_name || order.table_id}
€{total.toFixed(2)}
{/* Tab strip inline */}
{[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό']].map(([key, label]) => ( ))}
{/* Full-height ordering terminal */}
) } return (
{!propOrderId && ( )} {/* Header */}

Τραπέζι {order.table_name || order.table_id} · Ανοίχτηκε {formatDate(order.opened_at)} {order.closed_at && ` · Έκλεισε ${formatDate(order.closed_at)}`}

€{total.toFixed(2)}
{/* Customer assignment */}

Πελάτης

{order.customer_id && isOpen && !readOnly && ( )}
{order.customer_id ? (
👤
{order.customer_name || `Πελάτης #${order.customer_id}`}
{order.customer_phone &&
{order.customer_phone}
}
) : isOpen && !readOnly ? (
{!showCustomerDropdown ? ( ) : (
setCustomerSearch(e.target.value)} placeholder="Αναζήτηση πελάτη…" style={{ width: '100%', padding: '7px 11px', border: '1.5px solid #3b82f6', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
{customersData.length === 0 && (
Δεν βρέθηκαν πελάτες
)} {customersData.map(c => ( ))}
)}
) : (
Χωρίς πελάτη
)}
{/* Tabs */}
{[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό Συναλλαγών']].map(([key, label]) => ( ))}
{tab === 'overview' && <> {/* Waiters */}

Προσωπικό

{order.waiters.map(w => (
{waiterMap[w.waiter_id] || `#${w.waiter_id}`} {isOpen && !readOnly && ( )}
))} {isOpen && !readOnly && ( )}
{/* Items */}

Αντικείμενα

{order.items.length === 0 && (

Κανένα αντικείμενο.

)} {order.items.map(item => { const isCancelled = item.status === 'cancelled' const isClosedItem = item.status === 'closed' const badgeStatus = isClosedItem ? 'closed_item' : item.status const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0) const isDealItem = !!item.deal_id const itemPriceEvents = (priceEventsMap[item.id] ?? []).filter(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type)) const EVENT_COLORS_ODP = { modifier_applied: '#2563eb', waiter_discount: '#7c3aed', free_item_added: '#16a34a' } return (

{item.product?.name ?? `#${item.product_id}`} {item.course_id != null && ( {item.course_id} )} {isDealItem && ΔΩΡΕΑΝ}

{item.notes &&

{item.notes}

}

x{item.quantity} · €{effPrice(item).toFixed(2)}/τμχ {hasPriceAdj && ( €{(item.unit_price ?? 0).toFixed(2)} )}

{itemPriceEvents.map((ev, ei) => { const evColor = EVENT_COLORS_ODP[ev.event_type] || '#8a9099' const evLabel = ev.modifier_name || ev.deal_name || (ev.event_type === 'waiter_discount' ? 'Έκπτωση' : ev.event_type === 'free_item_added' ? 'Δωρεάν' : ev.event_type) return (

↳ {evLabel} {ev.delta_amount != null && {ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount.toFixed(2)} €}

) })} {item.paid_by && (

Πληρώθηκε: {item.paid_by_name ?? waiterMap[item.paid_by] ?? `#${item.paid_by}`} {item.paid_at ? ` · ${formatDate(item.paid_at)}` : ''} {item.payment_method && ( {' · '}{(PAYMENT_METHOD_STYLES[item.payment_method] || { label: item.payment_method.toUpperCase() }).label} )}

)} {isClosedItem && (

Απλήρωτο — κλείστηκε από manager

)}
€{itemTotal(item)} {isOpen && !readOnly && item.status === 'active' && ( <> {order.customer_id && ( )} )} {item.status === 'tabbed' && ( 📋 Καρτέλα )}
) })}
{/* Actions */}
{isOpen && !readOnly && activeItems.length > 0 && ( )} {isOpen && !readOnly && ( <> )}
} {tab === 'pricing' && (
)} {tab === 'audit' && (
)} {payPending && ( setPayPending(null)} title={payPending.length === 1 ? 'Τρόπος Πληρωμής;' : `Πληρωμή ${payPending.length} αντικειμένων;`} /> )} {confirmAction && ( setConfirmAction(null)} /> )} {showPrintModal && printers.length > 0 && ( setShowPrintModal(false)} onPrint={(printerId) => printOrder.mutate(printerId)} /> )} {showPrintModal && printers.length === 0 && (

Δεν βρέθηκαν ενεργοί εκτυπωτές.

)}
) }