import { useRef, useState } from 'react' import useTableViewStore from '../store/tableViewStore' import { money } from '../i18n' import { useTranslation } from '@xenia/i18n' import { fade } from '../logic/colour' import OneMore from './OneMore' import { canOneMore } from '../logic/lines' import { countsInTotal, isPart, isSettled } from '../logic/split' const fmtPrice = money const UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' } function fmtQty(qty, unitType) { const label = UNIT_LABELS[unitType] if (!label) return `×${qty}` if (unitType === 'kg' || unitType === 'liter') return `${Number(qty).toFixed(1)}${label}` return `${qty}${label}` } function fmtDateTime(iso) { if (!iso) return null try { const d = new Date(iso) return d.toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) } catch { return null } } // ── Icons ───────────────────────────────────────────────────────────────────── function SectionIcon({ type }) { const icons = { prefs: , quick: , extras: , removed: , note: , } return {icons[type] ?? null} } function ExpandArrow({ expanded, onClick }) { return ( ) } // ── Parse selected_options into grouped sections ────────────────────────────── function buildSections(item) { const sections = [] const opts = (() => { try { return item.selected_options ? JSON.parse(item.selected_options) : [] } catch { return [] } })() const removed = (() => { try { return item.removed_ingredients ? JSON.parse(item.removed_ingredients) : [] } catch { return [] } })() const prefGroups = [] const extraGroups = [] const quickLines = [] const idCount = {} opts.forEach(o => { if (o.id != null) idCount[o.id] = (idCount[o.id] || 0) + 1 }) const consumedAsSubAtIndex = new Set() let i = 0 while (i < opts.length) { const o = opts[i] if (consumedAsSubAtIndex.has(i)) { i++; continue } if (o.id == null) { const existing = quickLines.find(x => x.name === o.name) if (existing) existing._qty = (existing._qty || 1) + 1 else quickLines.push({ name: o.name, _qty: 1 }) i++ continue } let subName = null if (i + 1 < opts.length && opts[i + 1].id == null) { subName = opts[i + 1].name consumedAsSubAtIndex.add(i + 1) } if (idCount[o.id] > 1) { const existing = extraGroups.find(g => g.id === o.id && g.subName === subName) if (existing) existing.qty++ else extraGroups.push({ id: o.id, name: o.name, subName, qty: 1 }) } else { const value = subName ? `${o.name} · ${subName}` : o.name prefGroups.push({ setName: null, values: [value] }) } i++ } if (prefGroups.length > 0) sections.push({ type: 'prefs', lines: prefGroups }) if (quickLines.length > 0) sections.push({ type: 'quick', lines: quickLines }) if (extraGroups.length > 0) sections.push({ type: 'extras', lines: extraGroups }) if (removed.length > 0) sections.push({ type: 'removed', lines: removed.map(n => ({ name: n })) }) if (item.notes) sections.push({ type: 'note', lines: [{ name: item.notes }] }) return sections } // ── KDS colour strip ────────────────────────────────────────────────────────── const KDS_COLORS = { pending: { textColor: 'var(--x-warning)', label: 'kds.pending', icon: '⏳', dot: 'var(--x-warning)' }, preparing: { textColor: 'var(--x-info)', label: 'kds.preparing', icon: '🔥', dot: 'var(--x-info)' }, done: { textColor: 'var(--x-success)', label: 'kds.ready', icon: '✓', dot: 'var(--x-success)' }, served: { textColor: null, label: null, icon: null, dot: null }, } // ── Shared expanded details panel ───────────────────────────────────────────── function OptionsPanel({ sections }) { const { t } = useTranslation('waiter') return (
{sections.map((sec, si) => (
{sec.type === 'prefs' && sec.lines.map((line, li) => (
{line.setName && ( {line.setName} )} {line.values.join(' · ')}
))} {sec.type === 'quick' && sec.lines.map((line, li) => (
{line.name} {line._qty > 1 && ×{line._qty}}
))} {sec.type === 'extras' && sec.lines.map((line, li) => (
{line.name} {line.subName && · {line.subName}} {line.qty > 1 && ×{line.qty}}
))} {sec.type === 'removed' && sec.lines.map((line, li) => (
{t('drawer.without', { name: line.name })}
))} {sec.type === 'note' && sec.lines.map((line, li) => (
{line.name}
))}
))}
) } // ── KDS badge/icon renderer ─────────────────────────────────────────────────── function KdsBadge({ kdsColor, kdsDisplayStyle }) { const { t } = useTranslation('waiter') if (!kdsColor?.label) return null if (kdsDisplayStyle === 'icon' && kdsColor.dot) { return ( ) } return ( {t(kdsColor.label)} ) } // ── Price event label helpers ───────────────────────────────────────────────── const PRICING_EVENT_STYLE = { modifier_applied: { color: 'var(--x-info)', label: null }, // label comes from modifier_name waiter_discount: { color: 'var(--x-special-ink)', label: 'summary.discount' }, free_item_added: { color: 'var(--x-success)', label: 'summary.free' }, deal_offer_accepted: { color: 'var(--x-success)', label: null }, // label from deal_name } function PricingRows({ events, _layout, nameIndent = 12 }) { const { t } = useTranslation('waiter') const rows = events.filter(ev => ev.event_type === 'modifier_applied' || ev.event_type === 'waiter_discount' || ev.event_type === 'free_item_added' ) if (rows.length === 0) return null // Match OptionsPanel container padding: section divider + inner padding return (
{rows.map((ev, i) => { const evStyle = PRICING_EVENT_STYLE[ev.event_type] || { color: 'var(--x-ink-2)', label: ev.event_type } const label = ev.modifier_name || ev.deal_name || (evStyle.label && t(evStyle.label)) || ev.event_type const delta = ev.delta_amount return (
{label} {delta != null && ( {delta > 0 ? '+' : ''}{money(delta)} )}
) })}
) } // Small badge shown on the main item row to hint that pricing changes exist function PricingBadge({ events }) { const { t } = useTranslation('waiter') if (!events || events.length === 0) return null const hasDiscount = events.some(ev => ev.event_type === 'waiter_discount') const hasModifier = events.some(ev => ev.event_type === 'modifier_applied') const hasFree = events.some(ev => ev.event_type === 'free_item_added') const icons = [] if (hasModifier) icons.push( ) if (hasDiscount) icons.push( ) if (hasFree) icons.push( ) if (icons.length === 0) return null return ( {icons} ) } // Deal badge on items that triggered or were added by a deal function DealBadge({ item }) { const { t } = useTranslation('waiter') if (item.deal_id) { return ( {t('summary.freeCaps')} ) } return null } function MergedBadge({ item }) { if (!item._isMerged) return null return ( ∑{item._sourceIds?.length} ) } // ── ItemRow ─────────────────────────────────────────────────────────────────── function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kdsDisplayStyle, orderItemLayout, waiterMap, courses, priceEvents, moved = false }) { const { t } = useTranslation('waiter') const isPaid = item.status === 'paid' const isCancelled = item.status === 'cancelled' const effectiveKds = item.kds_status || 'pending' const isServed = effectiveKds === 'served' const kdsColor = !isCancelled && !isServed ? KDS_COLORS[effectiveKds] : null const sections = buildSections(item) const hasDetails = sections.length > 0 const [expanded, setExpanded] = useState(false) const pressTimer = useRef(null) const didLongPress = useRef(false) const touchStartPos = useRef({ x: 0, y: 0 }) const canSelect = selectable && !isCancelled function handleTouchStart(e) { if (!canSelect || !onLongPress) return didLongPress.current = false touchStartPos.current = { x: e.touches[0].clientX, y: e.touches[0].clientY } pressTimer.current = setTimeout(() => { didLongPress.current = true onLongPress(item) }, 500) } function handleTouchMove(e) { const dx = Math.abs(e.touches[0].clientX - touchStartPos.current.x) const dy = Math.abs(e.touches[0].clientY - touchStartPos.current.y) if (dx > 8 || dy > 8) clearTimeout(pressTimer.current) } function handleTouchEnd() { clearTimeout(pressTimer.current) } function handleBodyClick() { if (didLongPress.current) { didLongPress.current = false; return } if (canSelect) onToggle(item.id) } const nameColor = !isCancelled && !isServed ? kdsColor?.textColor : null const totalPrice = fmtPrice(((item.unit_price ?? 0) + (item.price_adjustment ?? 0)) * item.quantity) const unitPriceAdjusted = (item.unit_price ?? 0) + (item.price_adjustment ?? 0) // Cast to boolean so JSX never renders the raw number 0 const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0) const courseBadge = item.course_id != null && courses?.length > 0 ? (() => { const course = courses.find(c => c.id === item.course_id) if (!course) return null return ( {courses.indexOf(course) + 1} ) })() : null // Lines the guests sent themselves (QR menu at the table) or an online order (plan step 4.8) const sourceBadge = item.source === 'qr' || item.source === 'online' ? ( {item.source === 'qr' ? '📱 QR' : `🌐 ${t('summary.source.onlineShort')}`} ) : null const nameEl = ( {(isPart(item) ? item.product_name : item.product?.name) || `#${item.product_id}`} {isSettled(item) && ( ➗ {t('split.settled')} )} {courseBadge} {sourceBadge} {moved && ( ↪ {t('moves.movedShort')} )} ) const paidBadge = isPaid && !isServed ? {t('summary.paidBadge')} : null const cancelledBadge = isCancelled ? {t('summary.cancelledBadge')} : null const draftBadge = !isPaid && !isCancelled && !item.printed ? ⏳ : null // Whole-card click+touch handlers on the outer wrapper const cardHandlers = { onClick: handleBodyClick, onTouchStart: handleTouchStart, onTouchMove: handleTouchMove, onTouchEnd: handleTouchEnd, onTouchCancel: handleTouchEnd, } const cardClass = [ 'order-item', isPaid && isServed ? 'order-item--paid' : '', isCancelled ? 'order-item--cancelled' : '', selectable && selected ? 'order-item--selected' : '', isLast ? 'order-item--last' : '', ].filter(Boolean).join(' ') // Indent of secondary rows — lines up with the start of the item name const nameIndent = selectable && !isCancelled ? 44 : 12 // ── COMPACT ────────────────────────────────────────────────────────────────── const hasPricingRows = priceEvents && priceEvents.some(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type)) const [pricingExpanded, setPricingExpanded] = useState(false) if (orderItemLayout === 'compact') { return (
{selectable && !isCancelled && ( {selected ? '☑' : '☐'} )}
{nameEl} {(hasDetails || hasPricingRows) && ( { const next = !(expanded || pricingExpanded) if (hasDetails) setExpanded(next) if (hasPricingRows) setPricingExpanded(next) }} /> )} {paidBadge} {cancelledBadge} {draftBadge}
{fmtQty(item.quantity, item.unit_type)} {totalPrice}
{(expanded || pricingExpanded) && hasPricingRows && ( )} {expanded && hasDetails && }
) } // ── EXPANDED ───────────────────────────────────────────────────────────────── if (orderItemLayout === 'expanded') { return (
{/* Row 1: checkbox · name · badges · expand arrow · KDS badge */}
{selectable && !isCancelled && ( {selected ? '☑' : '☐'} )}
{nameEl} {(hasDetails || hasPricingRows) && ( { const next = !(expanded || pricingExpanded) if (hasDetails) setExpanded(next) if (hasPricingRows) setPricingExpanded(next) }} /> )} {paidBadge} {cancelledBadge} {draftBadge}
{/* Row 2: unit price · qty · total */}
{hasPriceAdj ? <>{fmtPrice(item.unit_price)}{fmtPrice(unitPriceAdjusted)} : fmtPrice(unitPriceAdjusted) } {fmtQty(item.quantity, item.unit_type)} {totalPrice}
{(pricingExpanded || expanded) && hasPricingRows && } {expanded && hasDetails && }
) } // ── FULLY DETAILED ──────────────────────────────────────────────────────────── const addedByName = waiterMap?.[item.added_by] ?? null const paidByName = waiterMap?.[item.paid_by] ?? null const addedAtFmt = fmtDateTime(item.added_at) const paidAtFmt = fmtDateTime(item.paid_at) return (
{/* Row 1 */}
{selectable && !isCancelled && ( {selected ? '☑' : '☐'} )}
{nameEl} {paidBadge} {cancelledBadge} {draftBadge}
{/* Row 2 — pricing */}
{hasPriceAdj ? <>{fmtPrice(item.unit_price)}{fmtPrice(unitPriceAdjusted)} : fmtPrice(unitPriceAdjusted) } {fmtQty(item.quantity, item.unit_type)} {totalPrice}
{hasPricingRows && } {/* Detail rows */}
{/* Ordered by */}
{t('summary.ordered')} {addedByName && addedAtFmt ? `${addedByName} · ${addedAtFmt}` : addedByName || addedAtFmt || '—'}
{/* Paid by — only if paid */} {isPaid && (
{t('summary.paidAt')} {paidByName && paidAtFmt ? `${paidByName} · ${paidAtFmt}` : paidByName || paidAtFmt || '—'}
)} {/* Options — inline, no expand needed */} {hasDetails && (
{sections.map((sec, si) => (
{sec.type === 'prefs' && sec.lines.map((line, li) => (
{line.setName && {line.setName}: } {line.values.join(' · ')}
))} {sec.type === 'quick' && sec.lines.map((line, li) => (
{line.name} {line._qty > 1 && ×{line._qty}}
))} {sec.type === 'extras' && sec.lines.map((line, li) => (
{line.name} {line.subName && · {line.subName}} {line.qty > 1 && ×{line.qty}}
))} {sec.type === 'removed' && sec.lines.map((line, li) => (
{t('drawer.without', { name: line.name })}
))} {sec.type === 'note' && sec.lines.map((line, li) => (
{line.name}
))}
))}
)}
) } export default function OrderSummary({ order, selectable = false, selectedIds = [], onToggle, onLongPressItem, waiterMap, courses = [], priceEventsMap = {}, movedItems = {}, onOneMore }) { const { t } = useTranslation('waiter') const kdsDisplayStyle = useTableViewStore(s => s.kdsDisplayStyle || 'badge') const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact') const activeItems = order.items?.filter(i => i.status !== 'cancelled') || [] const total = activeItems .filter(countsInTotal) // 6F.6: a split bill's settled lines are counted through its parts .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0) const paidTotal = activeItems .filter(i => i.status === 'paid') .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0) return (
{activeItems.length === 0 &&

{t('summary.noItems')}

} {activeItems.map((item, idx) => ( // 6F.5: "+1" beside a line whose product allows it, outside the line's own tap area
{onOneMore && canOneMore(item) && onOneMore(item, qty)} />}
))}
{t('common.total')} {fmtPrice(total)}
{paidTotal > 0 && paidTotal < total && (
{t('tables.quick.paid')} {fmtPrice(paidTotal)}
)} {paidTotal > 0 && paidTotal < total && (
{t('summary.due')} {fmtPrice(total - paidTotal)}
)}
) }