feat: printing problems shown and handled; printing set-up on v2 (platform-v2 step 6.10)

- a ticket that doesn't print is a problem for whoever sent it and the managers:
  GET /api/print-problems (the order, table, dishes, printer, since when, tries,
  last error, who sent it) and three ways out: print again, send to another
  printer, handled (services/print_problems.py; print_jobs.resolved_by /
  redirected_to, Alembic 0036); live event print.problems from the print paths
- phone: the red printer button opens the problems sheet, the table page warns
  (usePrintProblems replaces the 8 s poll); counter POS: a red button under the
  modes with the shared panel (@xenia/ordering PrintProblemsPanel + pure rules);
  manager: a card on the overview (top), the Tables page and the order page
- manager: Settings -> Printing (printers with reachability, test print, network
  scan; ticket layout + test ticket, beep, fonts with previews, dot leader,
  dividers) and Management -> Prep zones (cards + zone dialog with the ticket
  language, printers, copies, sorting, category order, kitchen screen) rebuilt in
  src/pages/printing; v1 PrintFontsTab, PrepZonesConfigPage, PendingPrints and
  /api/orders/pending-prints removed
- access: printer add/edit/delete/scan need core.settings.manage, prep zone
  changes catalog.menu.manage (were any dashboard user)
- tests: test_print_problems.py, @xenia/ordering printProblems, manager
  printing.test.mjs, e2e print_problems.mjs (done-when) + manager.mjs printing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 01:40:07 +02:00
co-authored by Claude Opus 5.5
parent 070c9cf625
commit f31bdf42aa
57 changed files with 2557 additions and 2221 deletions
+1 -1
View File
@@ -37,7 +37,7 @@ import StaffPage from './pages/Management/StaffPage'
import SessionsPage from './pages/staff/SessionsPage'
import ApprovalsPage from './pages/staff/ApprovalsPage'
import ManagementSchedulePage from './pages/Management/SchedulePage'
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
import PrepZonesConfigPage from './pages/printing/PrepZonesPage'
import PricingPage from './pages/pricing/PricingPage'
// Inventory
@@ -1,810 +0,0 @@
import { useState, useRef, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import {
Plus, Pencil, Trash2, Printer, X, Check, ChevronDown,
Zap, Settings2, ArrowUpDown, Layers, CheckSquare, SkipForward,
GripVertical, ChevronUp, AlertTriangle, FlameKindling,
} from 'lucide-react'
import client from '../../api/client'
// ── API ───────────────────────────────────────────────────────────────────────
const fetchZones = () => client.get('/api/prep-zones').then(r => r.data)
const fetchPrinters = () => client.get('/api/system/printers').then(r => r.data)
const fetchCategories = () => client.get('/api/products/categories').then(r => r.data)
// ── Constants ─────────────────────────────────────────────────────────────────
const AUTO_PRINT_OPTIONS = [
{ value: 'none', label: 'Χωρίς εκτύπωση', desc: 'Μη αυτόματη εκτύπωση' },
{ value: 'master', label: 'Μόνο κύριος', desc: 'Εκτύπωση στον κύριο' },
{ value: 'all', label: 'Όλοι εκτυπωτές', desc: 'Master + δευτερεύοντες' },
]
const SORT_OPTIONS = [
{ value: 'order_time', label: 'Σειρά παραγγελίας', desc: 'Όπως προστέθηκαν στο καλάθι' },
{ value: 'item_count', label: 'Πλήθος (φθίνον)', desc: 'Πρώτα τα αντικείμενα με τη μεγαλύτερη ποσότητα' },
{ value: 'alpha', label: 'Αλφαβητικά', desc: 'Ταξινόμηση κατά όνομα' },
]
const EMPTY_ZONE = {
name: '', description: '', notification_name: '',
printer_ids: [], master_printer_id: null,
auto_print: 'none', master_copies: 1, secondary_copies: 1,
sort_items_by: 'order_time', group_by_category: false, category_order: [], print_checkboxes: false,
bypass_pending: false, bypass_kds: false, auto_ready_to_served: false,
}
// ── Helpers ───────────────────────────────────────────────────────────────────
function Toggle({ value, onChange, disabled }) {
return (
<button
type="button"
onClick={() => !disabled && onChange(!value)}
disabled={disabled}
className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors duration-200 focus:outline-none
${value ? 'bg-primary-600' : 'bg-gray-200'} ${disabled ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
>
<span className={`inline-block h-3.5 w-3.5 rounded-full bg-white shadow transition-transform duration-200
${value ? 'translate-x-4' : 'translate-x-0.5'}`} />
</button>
)
}
function CopySpinner({ value, onChange, min = 1, max = 9 }) {
return (
<div className="flex items-center gap-1.5">
<button
type="button"
onClick={() => onChange(Math.max(min, value - 1))}
className="w-8 h-8 rounded-lg border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-gray-100 hover:border-gray-400 transition-colors text-base font-medium"
>−</button>
<span className="w-9 text-center text-sm font-bold text-gray-800 tabular-nums">{value}×</span>
<button
type="button"
onClick={() => onChange(Math.min(max, value + 1))}
className="w-8 h-8 rounded-lg border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-gray-100 hover:border-gray-400 transition-colors text-base font-medium"
>+</button>
</div>
)
}
// ── Click-outside hook for dropdowns ─────────────────────────────────────────
function useClickOutside(ref, onClose) {
useEffect(() => {
function handle(e) {
if (ref.current && !ref.current.contains(e.target)) onClose()
}
document.addEventListener('mousedown', handle)
return () => document.removeEventListener('mousedown', handle)
}, [ref, onClose])
}
// ── Master printer single-select ──────────────────────────────────────────────
function MasterPrinterPicker({ printers, value, onChange }) {
const [open, setOpen] = useState(false)
const ref = useRef(null)
useClickOutside(ref, () => setOpen(false))
const selected = printers.find(p => p.id === value)
return (
<div className="relative" ref={ref}>
<button
type="button"
onClick={() => setOpen(v => !v)}
className="w-full flex items-center justify-between gap-2 px-3 py-2 border border-gray-300 rounded-lg bg-white text-sm text-left hover:border-gray-400 transition-colors"
>
<span className="flex items-center gap-2 flex-1 min-w-0">
{selected ? (
<>
<span className="w-2 h-2 rounded-full bg-green-500 shrink-0" />
<span className="font-medium text-gray-800 truncate">{selected.name}</span>
<span className="text-xs text-gray-400 font-mono ml-auto shrink-0">{selected.ip_address}:{selected.port}</span>
</>
) : (
<span className="text-gray-400">— Χωρίς κύριο —</span>
)}
</span>
<ChevronDown size={13} className={`text-gray-400 shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && (
<div className="absolute z-50 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-xl shadow-xl overflow-hidden">
<button
type="button"
onClick={() => { onChange(null); setOpen(false) }}
className={`w-full flex items-center gap-3 px-3 py-2.5 text-sm text-left transition-colors hover:bg-gray-50 ${!value ? 'bg-gray-50' : ''}`}
>
<span className="w-4 h-4 rounded border border-gray-300 flex items-center justify-center shrink-0">
{!value && <Check size={10} className="text-gray-600" />}
</span>
<span className="text-gray-400 italic text-xs">Χωρίς κύριο εκτυπωτή</span>
</button>
{printers.map(p => (
<button
key={p.id}
type="button"
onClick={() => { onChange(p.id); setOpen(false) }}
className={`w-full flex items-center gap-3 px-3 py-2.5 text-sm text-left transition-colors hover:bg-gray-50 ${value === p.id ? 'bg-primary-50' : ''}`}
>
<span className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${value === p.id ? 'bg-primary-600 border-primary-600' : 'border-gray-300'}`}>
{value === p.id && <Check size={10} className="text-white" />}
</span>
<Printer size={13} className="text-gray-400 shrink-0" />
<span className={`flex-1 ${value === p.id ? 'font-semibold text-primary-700' : 'text-gray-700'}`}>{p.name}</span>
<span className="text-xs text-gray-400 font-mono">{p.ip_address}:{p.port}</span>
</button>
))}
</div>
)}
</div>
)
}
// ── Secondary printers multi-select ──────────────────────────────────────────
function SecondaryPrinterPicker({ printers, selected, masterId, onChange }) {
const [open, setOpen] = useState(false)
const ref = useRef(null)
useClickOutside(ref, () => setOpen(false))
const selectedSet = new Set(selected)
const eligible = printers.filter(p => p.id !== masterId)
const selectedPrinters = eligible.filter(p => selectedSet.has(p.id))
const toggle = (id) => {
const next = new Set(selectedSet)
if (next.has(id)) next.delete(id); else next.add(id)
onChange([...next])
}
return (
<div className="relative" ref={ref}>
<button
type="button"
onClick={() => setOpen(v => !v)}
className="w-full flex items-center justify-between gap-2 px-3 py-2 border border-gray-300 rounded-lg bg-white text-sm text-left hover:border-gray-400 transition-colors min-h-[38px]"
>
<span className="flex flex-wrap gap-1 flex-1 min-w-0">
{selectedPrinters.length === 0 ? (
<span className="text-gray-400">— Χωρίς δευτερεύοντες —</span>
) : (
selectedPrinters.map(p => (
<span key={p.id} className="inline-flex items-center gap-1 bg-gray-100 text-gray-600 rounded px-1.5 py-0.5 text-xs font-medium">
<Printer size={10} />{p.name}
</span>
))
)}
</span>
<ChevronDown size={13} className={`text-gray-400 shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && (
<div className="absolute z-50 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-xl shadow-xl overflow-hidden">
{eligible.length === 0 ? (
<div className="px-3 py-4 text-sm text-gray-400 text-center italic">
{printers.length <= 1 ? 'Δεν υπάρχουν άλλοι εκτυπωτές' : 'Ο μόνος εκτυπωτής είναι ο κύριος'}
</div>
) : eligible.map(p => {
const on = selectedSet.has(p.id)
return (
<button
key={p.id}
type="button"
onClick={() => toggle(p.id)}
className={`w-full flex items-center gap-3 px-3 py-2.5 text-sm text-left transition-colors hover:bg-gray-50 ${on ? 'bg-gray-50' : ''}`}
>
<span className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${on ? 'bg-gray-700 border-gray-700' : 'border-gray-300'}`}>
{on && <Check size={10} className="text-white" />}
</span>
<Printer size={13} className="text-gray-400 shrink-0" />
<span className={`flex-1 ${on ? 'font-semibold text-gray-800' : 'text-gray-700'}`}>{p.name}</span>
<span className="text-xs text-gray-400 font-mono">{p.ip_address}:{p.port}</span>
</button>
)
})}
<div className="border-t border-gray-100 px-3 py-2 text-xs text-gray-400 italic">
Κλικ έξω για κλείσιμο
</div>
</div>
)}
</div>
)
}
// ── Category order modal ──────────────────────────────────────────────────────
function CategoryOrderModal({ categories, order, onSave, onClose }) {
const ranked = order.map(id => categories.find(c => c.id === id)).filter(Boolean)
const unranked = categories.filter(c => !order.includes(c.id))
const [list, setList] = useState([...ranked, ...unranked])
const dragIdx = useRef(null)
const onDragStart = (i) => { dragIdx.current = i }
const onDragOver = (e, i) => {
e.preventDefault()
if (dragIdx.current === null || dragIdx.current === i) return
const next = [...list]
const [moved] = next.splice(dragIdx.current, 1)
next.splice(i, 0, moved)
dragIdx.current = i
setList(next)
}
const onDragEnd = () => { dragIdx.current = null }
const move = (i, dir) => {
const j = i + dir
if (j < 0 || j >= list.length) return
const next = [...list];
[next[i], next[j]] = [next[j], next[i]]
setList(next)
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden">
<div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
<div>
<h2 className="text-sm font-bold text-gray-900">Σειρά Κατηγοριών Εκτύπωσης</h2>
<p className="text-xs text-gray-500 mt-0.5">Σύρετε για αλλαγή σειράς</p>
</div>
<button type="button" onClick={onClose} className="p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors">
<X size={16} />
</button>
</div>
<div className="px-3 py-3 max-h-80 overflow-y-auto space-y-1">
{list.map((cat, i) => (
<div
key={cat.id}
draggable
onDragStart={() => onDragStart(i)}
onDragOver={e => onDragOver(e, i)}
onDragEnd={onDragEnd}
className="flex items-center gap-2.5 px-3 py-2.5 bg-gray-50 rounded-xl border border-gray-100 cursor-grab active:cursor-grabbing select-none group hover:bg-white hover:border-gray-200 hover:shadow-sm transition-all"
>
<GripVertical size={14} className="text-gray-300 group-hover:text-gray-400 shrink-0" />
<span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: cat.color || '#94a3b8' }} />
<span className="text-sm text-gray-700 font-medium flex-1 min-w-0 truncate">{cat.name}</span>
<div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
<button type="button" onClick={() => move(i, -1)} disabled={i === 0}
className="p-1 rounded text-gray-400 hover:text-gray-600 disabled:opacity-20">
<ChevronUp size={13} />
</button>
<button type="button" onClick={() => move(i, 1)} disabled={i === list.length - 1}
className="p-1 rounded text-gray-400 hover:text-gray-600 disabled:opacity-20">
<ChevronDown size={13} />
</button>
</div>
<span className="text-xs text-gray-300 font-mono w-5 text-right shrink-0">{i + 1}</span>
</div>
))}
{list.length === 0 && (
<div className="py-8 text-center text-sm text-gray-400">Δεν υπάρχουν κατηγορίες</div>
)}
</div>
<div className="px-5 py-4 border-t border-gray-100 flex gap-2 justify-end">
<button type="button" onClick={onClose} className="btn btn-secondary">Ακύρωση</button>
<button
type="button"
onClick={() => { onSave(list.map(c => c.id)); onClose() }}
className="btn btn-primary flex items-center gap-2"
>
<Check size={14} /> Αποθήκευση σειράς
</button>
</div>
</div>
</div>
)
}
// ── Section header ────────────────────────────────────────────────────────────
function Section({ icon: Icon_, label, children }) {
return (
<div className="space-y-3">
<div className="flex items-center gap-2 pb-1.5 border-b border-gray-100">
<Icon_ size={13} className="text-gray-400" />
<span className="text-[11px] font-bold text-gray-400 uppercase tracking-widest">{label}</span>
</div>
{children}
</div>
)
}
// ── Toggle row ────────────────────────────────────────────────────────────────
function ToggleRow({ label, desc, value, onChange, disabled, children, warning }) {
return (
<div className={`rounded-xl border transition-colors ${value ? 'border-primary-200 bg-primary-50/40' : 'border-gray-200 bg-gray-50/40'} ${disabled ? 'opacity-60' : ''}`}>
<div className="flex items-center gap-3 px-4 py-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<span className="text-sm font-semibold text-gray-800">{label}</span>
{warning && <AlertTriangle size={12} className="text-amber-500 shrink-0" />}
</div>
{desc && <p className="text-xs text-gray-500 mt-0.5 leading-relaxed">{desc}</p>}
</div>
<Toggle value={value} onChange={onChange} disabled={disabled} />
</div>
{value && children && (
<div className="px-4 pb-3">{children}</div>
)}
</div>
)
}
// ── Zone Form ─────────────────────────────────────────────────────────────────
function ZoneForm({ initial, printers, categories, onSave, onCancel, saving }) {
const z = initial || EMPTY_ZONE
const [name, setName] = useState(z.name)
const [description, setDesc] = useState(z.description || '')
const [notifName, setNotifName] = useState(z.notification_name || '')
const [allPrinterIds, setAllPrinterIds] = useState(z.printer_ids || [])
const [masterId, setMasterId] = useState(z.master_printer_id ?? null)
const [autoPrint, setAutoPrint] = useState(z.auto_print || 'none')
const [masterCopies, setMasterCopies] = useState(z.master_copies || 1)
const [secondaryCopies, setSecondaryCopies] = useState(z.secondary_copies || 1)
const [sortBy, setSortBy] = useState(z.sort_items_by || 'order_time')
const [groupCat, setGroupCat] = useState(z.group_by_category || false)
const [catOrder, setCatOrder] = useState(z.category_order || [])
const [checkboxes, setCheckboxes] = useState(z.print_checkboxes || false)
const [bypassPending, setBypassPending] = useState(z.bypass_pending || false)
const [bypassKds, setBypassKds] = useState(z.bypass_kds || false)
const [autoReadyServed, setAutoReadyServed] = useState(z.auto_ready_to_served || false)
const [catModal, setCatModal] = useState(false)
const secondaryIds = allPrinterIds.filter(id => id !== masterId)
const handleMasterChange = (id) => {
setMasterId(id)
if (id && !allPrinterIds.includes(id)) setAllPrinterIds(prev => [...prev, id])
}
const handleSecondaryChange = (ids) => {
const next = new Set(ids)
if (masterId) next.add(masterId)
setAllPrinterIds([...next])
}
const handleBypassKds = (v) => { setBypassKds(v); if (v) setBypassPending(true) }
const handleBypassPending = (v) => { setBypassPending(v); if (!v) setBypassKds(false) }
const valid = name.trim().length > 0
const submit = (e) => {
e.preventDefault()
if (!valid) return
onSave({
name: name.trim(),
description: description.trim() || null,
notification_name: notifName.trim() || null,
printer_ids: allPrinterIds,
master_printer_id: masterId || null,
auto_print: autoPrint,
master_copies: masterCopies,
secondary_copies: secondaryCopies,
sort_items_by: sortBy,
group_by_category: groupCat,
category_order: catOrder,
print_checkboxes: checkboxes,
bypass_pending: bypassPending,
bypass_kds: bypassKds,
auto_ready_to_served: autoReadyServed,
})
}
return (
<>
<form onSubmit={submit} className="space-y-5">
{/* Identity */}
<Section icon={Settings2} label="Στοιχεία Ζώνης">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="label">Όνομα ζώνης *</label>
<input className="input" value={name} onChange={e => setName(e.target.value)}
placeholder="π.χ. Kitchen – Grill" autoFocus />
</div>
<div>
<label className="label">Όνομα ειδοποίησης</label>
<input className="input" value={notifName} onChange={e => setNotifName(e.target.value)}
placeholder="π.χ. Κουζίνα" />
</div>
</div>
<div>
<label className="label">Περιγραφή</label>
<input className="input" value={description} onChange={e => setDesc(e.target.value)}
placeholder="Προαιρετική περιγραφή" />
</div>
</Section>
{/* Printers */}
<Section icon={Printer} label="Εκτυπωτές">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="label">Κύριος εκτυπωτής</label>
<MasterPrinterPicker printers={printers} value={masterId} onChange={handleMasterChange} />
<p className="mt-1 text-xs text-gray-400">Ένας μόνο, υψηλή προτεραιότητα.</p>
</div>
<div>
<label className="label">Δευτερεύοντες εκτυπωτές</label>
<SecondaryPrinterPicker
printers={printers} selected={secondaryIds}
masterId={masterId} onChange={handleSecondaryChange}
/>
<p className="mt-1 text-xs text-gray-400">Μόνο στη λειτουργία «Όλοι».</p>
</div>
</div>
<div>
<label className="label">Αυτόματη εκτύπωση</label>
<div className="grid grid-cols-3 gap-2">
{AUTO_PRINT_OPTIONS.map(opt => (
<button key={opt.value} type="button" onClick={() => setAutoPrint(opt.value)}
className={`px-3 py-2.5 rounded-xl border text-left transition-all
${autoPrint === opt.value
? 'border-primary-500 bg-primary-50 ring-1 ring-primary-500'
: 'border-gray-200 hover:border-gray-300 bg-white'}`}>
<div className={`text-xs font-bold leading-tight ${autoPrint === opt.value ? 'text-primary-700' : 'text-gray-700'}`}>{opt.label}</div>
<div className="text-[11px] text-gray-400 mt-0.5">{opt.desc}</div>
</button>
))}
</div>
</div>
{autoPrint !== 'none' && (
<div className="grid grid-cols-2 gap-4">
<div>
<label className="label">Αντίτυπα κύριου</label>
<CopySpinner value={masterCopies} onChange={setMasterCopies} />
</div>
{autoPrint === 'all' && (
<div>
<label className="label">Αντίτυπα δευτερευόντων</label>
<CopySpinner value={secondaryCopies} onChange={setSecondaryCopies} />
</div>
)}
</div>
)}
</Section>
{/* Ticket formatting */}
<Section icon={ArrowUpDown} label="Μορφοποίηση Δελτίου">
<div>
<label className="label">Ταξινόμηση αντικειμένων</label>
<div className="grid grid-cols-3 gap-2">
{SORT_OPTIONS.map(opt => (
<button key={opt.value} type="button" onClick={() => setSortBy(opt.value)}
className={`px-3 py-2.5 rounded-xl border text-left transition-all
${sortBy === opt.value
? 'border-primary-500 bg-primary-50 ring-1 ring-primary-500'
: 'border-gray-200 hover:border-gray-300 bg-white'}`}>
<div className={`text-xs font-bold leading-tight ${sortBy === opt.value ? 'text-primary-700' : 'text-gray-700'}`}>{opt.label}</div>
<div className="text-[11px] text-gray-400 mt-0.5">{opt.desc}</div>
</button>
))}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<ToggleRow
label="Ομαδοποίηση κατά κατηγορία"
desc="Αντικείμενα ομαδοποιούνται ανά κατηγορία."
value={groupCat} onChange={setGroupCat}
>
<button type="button" onClick={() => setCatModal(true)}
className="mt-1 inline-flex items-center gap-1.5 text-xs font-semibold text-primary-600 hover:text-primary-700 bg-white border border-primary-200 rounded-lg px-3 py-1.5 hover:bg-primary-50 transition-colors">
<Layers size={12} />
Σειρά κατηγοριών
{catOrder.length > 0 && (
<span className="bg-primary-100 text-primary-700 rounded px-1 text-[10px] font-bold">{catOrder.length}</span>
)}
</button>
</ToggleRow>
<ToggleRow
label="Checkboxes"
desc="Προσθέτει [ ] πριν από κάθε αντικείμενο."
value={checkboxes} onChange={setCheckboxes}
/>
</div>
</Section>
{/* KDS Behavior */}
<Section icon={Zap} label="Συμπεριφορά KDS">
<div className="grid grid-cols-1 gap-3">
<ToggleRow
label="Παράκαμψη Pending & Prep"
desc="Αντικείμενα ξεκινούν απευθείας σε READY. Χρήσιμο για ποτά ή μπύρες."
value={bypassPending} onChange={handleBypassPending}
/>
<ToggleRow
label="Παράκαμψη KDS Status"
desc="Αντικείμενα πηγαίνουν κατευθείαν σε SERVED. Ενεργοποιεί αυτόματα και την Παράκαμψη Pending."
value={bypassKds} onChange={handleBypassKds} warning
/>
<ToggleRow
label="Αυτόματο Ready → Served"
desc="Όταν ο σεφ επισημαίνει READY στο KDS, αυτόματα αναβαθμίζεται και σε SERVED."
value={autoReadyServed} onChange={setAutoReadyServed}
/>
</div>
</Section>
{/* Actions */}
<div className="flex gap-3 justify-end pt-3 border-t border-gray-100">
<button type="button" onClick={onCancel} className="btn btn-secondary">
Ακύρωση
</button>
<button type="submit" disabled={!valid || saving} className="btn btn-primary flex items-center gap-2">
<Check size={15} />
{saving ? 'Αποθήκευση…' : 'Αποθήκευση'}
</button>
</div>
</form>
{catModal && (
<CategoryOrderModal
categories={categories} order={catOrder}
onSave={setCatOrder} onClose={() => setCatModal(false)}
/>
)}
</>
)
}
// ── Zone Card ─────────────────────────────────────────────────────────────────
function Badge({ children, variant = 'default' }) {
const cls = {
default: 'bg-gray-100 text-gray-600',
primary: 'bg-primary-100 text-primary-700',
green: 'bg-green-100 text-green-700',
amber: 'bg-amber-100 text-amber-700',
red: 'bg-red-100 text-red-700',
}[variant] || 'bg-gray-100 text-gray-600'
return (
<span className={`inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] font-semibold ${cls}`}>
{children}
</span>
)
}
function ZoneCard({ zone, printers, onEdit, onDelete }) {
const [confirmDelete, setConfirmDelete] = useState(false)
const printerMap = Object.fromEntries(printers.map(p => [p.id, p]))
const masterPrinter = printerMap[zone.master_printer_id]
const secondaryPrinters = (zone.secondary_printer_ids || []).map(id => printerMap[id]).filter(Boolean)
const printLabel = {
none: { text: 'Χωρίς εκτύπωση', variant: 'default' },
master: { text: 'Κύριος μόνο', variant: 'primary' },
all: { text: 'Όλοι', variant: 'primary' },
}[zone.auto_print] || { text: '—', variant: 'default' }
const sortLabel = {
order_time: 'Σειρά παρ.',
item_count: 'Κατά πλήθος',
alpha: 'Αλφαβητικά',
}[zone.sort_items_by] || zone.sort_items_by
return (
<div className="bg-white border border-gray-200 rounded-2xl shadow-sm overflow-hidden hover:shadow-md hover:border-gray-300 transition-all group">
<div className="px-4 pt-4 pb-3 flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<h3 className="font-bold text-gray-900 text-sm leading-tight">{zone.name}</h3>
{zone.bypass_kds && <Badge variant="red"><Zap size={10} />Bypass KDS</Badge>}
{!zone.bypass_kds && zone.bypass_pending && <Badge variant="amber"><SkipForward size={10} />Bypass Pending</Badge>}
{zone.auto_ready_to_served && <Badge variant="green"><Check size={10} />Auto Served</Badge>}
</div>
{zone.notification_name && (
<p className="text-xs text-primary-600 font-medium mt-0.5">{zone.notification_name}</p>
)}
{zone.description && <p className="text-xs text-gray-400 mt-0.5">{zone.description}</p>}
</div>
<div className="flex gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
<button onClick={() => onEdit(zone)}
className="p-1.5 rounded-lg text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-colors">
<Pencil size={13} />
</button>
{!confirmDelete ? (
<button onClick={() => setConfirmDelete(true)}
className="p-1.5 rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors">
<Trash2 size={13} />
</button>
) : (
<div className="flex gap-1 items-center">
<button onClick={() => setConfirmDelete(false)}
className="p-1.5 rounded-lg text-gray-400 hover:bg-gray-100 transition-colors">
<X size={13} />
</button>
<button onClick={() => onDelete(zone.id)}
className="px-2 py-1 rounded-lg text-xs font-bold bg-red-600 text-white hover:bg-red-700 transition-colors">
Διαγραφή
</button>
</div>
)}
</div>
</div>
<div className="px-4 pb-3 space-y-1.5">
<div className="flex items-center gap-2">
<span className="text-[10px] font-bold text-gray-400 uppercase tracking-wide w-14 shrink-0">Κύριος</span>
{masterPrinter ? (
<>
<span className="inline-flex items-center gap-1 bg-primary-50 text-primary-700 rounded-md px-2 py-0.5 text-xs font-medium">
<Printer size={10} />{masterPrinter.name}
</span>
{zone.auto_print !== 'none' && (
<span className="text-xs text-gray-400 font-mono">{zone.master_copies}×</span>
)}
</>
) : (
<span className="text-xs text-gray-400 italic">Χωρίς</span>
)}
</div>
{secondaryPrinters.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] font-bold text-gray-400 uppercase tracking-wide w-14 shrink-0">Δευτ.</span>
{secondaryPrinters.map(p => (
<span key={p.id} className="inline-flex items-center gap-1 bg-gray-100 text-gray-600 rounded-md px-2 py-0.5 text-xs font-medium">
<Printer size={10} />{p.name}
</span>
))}
{zone.auto_print === 'all' && (
<span className="text-xs text-gray-400 font-mono">{zone.secondary_copies}×</span>
)}
</div>
)}
</div>
<div className="px-4 py-2.5 border-t border-gray-100 bg-gray-50/60 flex flex-wrap gap-1.5 items-center">
<Badge variant={zone.auto_print !== 'none' ? 'primary' : 'default'}>{printLabel.text}</Badge>
<Badge>{sortLabel}</Badge>
{zone.group_by_category && <Badge><Layers size={10} />Κατά κατηγορία</Badge>}
{zone.print_checkboxes && <Badge><CheckSquare size={10} />Checkboxes</Badge>}
</div>
</div>
)
}
// ── Main Page ─────────────────────────────────────────────────────────────────
export default function PrepZonesConfigPage() {
const qc = useQueryClient()
const [showForm, setShowForm] = useState(false)
const [editing, setEditing] = useState(null)
const { data: zones = [], isLoading: lZ } = useQuery({ queryKey: ['prep-zones'], queryFn: fetchZones })
const { data: printers = [], isLoading: lP } = useQuery({ queryKey: ['printers'], queryFn: fetchPrinters })
const { data: categories = [], isLoading: lC } = useQuery({ queryKey: ['categories'], queryFn: fetchCategories })
const invalidate = () => qc.invalidateQueries({ queryKey: ['prep-zones'] })
const create = useMutation({
mutationFn: body => client.post('/api/prep-zones', body).then(r => r.data),
onSuccess: () => { invalidate(); setShowForm(false); toast.success('Ζώνη δημιουργήθηκε') },
onError: () => toast.error('Σφάλμα κατά τη δημιουργία'),
})
const update = useMutation({
mutationFn: ({ id, ...body }) => client.put(`/api/prep-zones/${id}`, body).then(r => r.data),
onSuccess: () => { invalidate(); setEditing(null); toast.success('Ζώνη ενημερώθηκε') },
onError: () => toast.error('Σφάλμα κατά την ενημέρωση'),
})
const remove = useMutation({
mutationFn: id => client.delete(`/api/prep-zones/${id}`),
onSuccess: () => { invalidate(); toast.success('Ζώνη διαγράφηκε') },
onError: () => toast.error('Σφάλμα κατά τη διαγραφή'),
})
if (lZ || lP || lC) {
return (
<div className="p-8 flex items-center gap-3 text-sm text-gray-400">
<div className="w-4 h-4 rounded-full border-2 border-gray-300 border-t-primary-500 animate-spin" />
Φόρτωση…
</div>
)
}
const flatCategories = categories.flatMap(c => [c, ...(c.subcategories || [])])
const formOpen = showForm || !!editing
return (
// h-full + overflow-y-auto makes this page scroll within the fixed AppLayout <main>
<div className="h-full overflow-y-auto">
<div className="p-6">
{/* Page header */}
<div className="flex items-start justify-between mb-6">
<div className="flex items-center gap-2.5">
<div className="w-8 h-8 rounded-xl bg-orange-100 flex items-center justify-center shrink-0">
<FlameKindling size={16} className="text-orange-600" />
</div>
<div>
<h1 className="text-xl font-bold text-gray-900 leading-tight">Ζώνες Προετοιμασίας</h1>
<p className="text-sm text-gray-500">Ζώνες, εκτυπωτές και συμπεριφορά KDS</p>
</div>
</div>
{!formOpen && (
<button onClick={() => setShowForm(true)} className="btn btn-primary flex items-center gap-2 shrink-0">
<Plus size={15} />
Νέα Ζώνη
</button>
)}
</div>
{/* Two-column layout when form is open */}
{formOpen ? (
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-6 items-start xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
{/* Form panel */}
<div className={`bg-white rounded-2xl p-6 shadow-sm border ${showForm ? 'border-primary-200' : 'border-amber-200'}`}>
<div className="flex items-center gap-2 mb-5">
<div className={`w-1 h-5 rounded-full ${showForm ? 'bg-primary-500' : 'bg-amber-400'}`} />
<h2 className="text-sm font-bold text-gray-800">
{showForm ? 'Νέα Ζώνη Προετοιμασίας' : `Επεξεργασία: ${editing?.name}`}
</h2>
</div>
<ZoneForm
initial={editing}
printers={printers}
categories={flatCategories}
onSave={showForm
? (body) => create.mutate(body)
: (body) => update.mutate({ id: editing.id, ...body })}
onCancel={() => { setShowForm(false); setEditing(null) }}
saving={create.isPending || update.isPending}
/>
</div>
{/* Zone list sidebar */}
<div className="space-y-3">
{zones.length === 0 ? (
<div className="text-center py-10 text-gray-400 bg-white rounded-2xl border border-gray-200">
<FlameKindling size={24} className="mx-auto mb-2 text-gray-300" />
<p className="text-sm">Δεν υπάρχουν ζώνες ακόμα</p>
</div>
) : zones.map(zone => (
<ZoneCard
key={zone.id}
zone={zone}
printers={printers}
onEdit={z => { setShowForm(false); setEditing(z) }}
onDelete={id => remove.mutate(id)}
/>
))}
</div>
</div>
) : (
/* Full-width zone grid when no form open */
zones.length === 0 ? (
<div className="text-center py-20 text-gray-400">
<div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gray-100 flex items-center justify-center">
<FlameKindling size={28} className="text-gray-300" />
</div>
<div className="font-semibold text-gray-600 mb-1">Δεν υπάρχουν ζώνες ακόμα</div>
<p className="text-sm">Δημιουργήστε την πρώτη ζώνη για να αρχίσετε.</p>
</div>
) : (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{zones.map(zone => (
<ZoneCard
key={zone.id}
zone={zone}
printers={printers}
onEdit={z => { setShowForm(false); setEditing(z) }}
onDelete={id => remove.mutate(id)}
/>
))}
</div>
)
)}
</div>
</div>
)
}
@@ -7,7 +7,7 @@ import VenueSettings from './sections/VenueSettings'
import AppInfoTab from './tabs/AppInfoTab'
import ColoursTab from './tabs/ColoursTab'
import OperationTab from './tabs/OperationTab'
import PrintFontsTab from './tabs/PrintFontsTab'
import PrintingSettings from '../printing/PrintingSettings'
import SecurityTab from './tabs/SecurityTab'
import DevelopmentTab from './tabs/DevelopmentTab'
import FiscalTab from './tabs/FiscalTab'
@@ -39,7 +39,7 @@ export default function SettingsPage() {
{activeTab === 'security' && <SecurityTab />}
{activeTab === 'operation' && <OperationTab />}
{activeTab === 'colours' && <ColoursTab />}
{activeTab === 'print-fonts' && <PrintFontsTab />}
{activeTab === 'print-fonts' && <PrintingSettings />}
{activeTab === 'fiscal' && <FiscalTab />}
{activeTab === 'development' && <DevelopmentTab />}
</div>
File diff suppressed because it is too large Load Diff
@@ -20,6 +20,7 @@ import AddItems from './AddItems'
import OrderLines from './OrderLines'
import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog'
import PrintProblemsCard from './PrintProblemsCard'
import { AuditList, PriceEventList } from './OrderHistory'
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
@@ -152,6 +153,8 @@ function OrderView({ orderId }) {
)}
</div>
<PrintProblemsCard orderId={order.id} />
{tab === 'order' && (
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
<div className="grid gap-4 min-w-0">
@@ -0,0 +1,43 @@
// Tickets that didn't print (plan step 6.10; replaces the overview's "waiting prints" card):
// on the overview, the Tables page (all of them) and an order's page (its own). Live: the list
// reloads on every `print.problems` event, so a ticket sent elsewhere or printed on a retry
// leaves every screen at once. The bell still tells managers away from these pages (print.failing).
import toast from 'react-hot-toast'
import { useQueryClient } from '@tanstack/react-query'
import { PrintProblemsPanel, actionRequest, problemsOf } from '@xenia/ordering'
import { useTranslation } from '@xenia/i18n'
import client from '../../api/client'
import { Card } from '../overview/parts'
import { usePrintProblems } from './usePrintProblems'
export default function PrintProblemsCard({ orderId = null, onOpen }) {
const { t } = useTranslation('manager')
const tc = useTranslation('common').t
const qc = useQueryClient()
const { data } = usePrintProblems()
const all = data?.problems ?? []
const shown = orderId == null ? all : problemsOf(all, orderId)
if (!shown.length) return null
async function run(kind, problem, printerId) {
const [url, body] = actionRequest(kind, problem, printerId)
const { data: res } = await client.post(url, body)
if (kind === 'retry' && !res.ok) toast.error(tc('printProblems.stillNot', { printer: res.printer }))
else toast.success(tc(`printProblems.done.${kind}`, { printer: res.printer }))
qc.invalidateQueries({ queryKey: ['print-problems'] })
qc.invalidateQueries({ queryKey: ['orders-active'] })
qc.invalidateQueries({ queryKey: ['order', problem.order_id] })
}
return (
<Card tone="danger" testId="print-problems-card"
title={<span className="grid">
<span>{tc('printProblems.title')}</span>
<span className="text-label font-normal">{tc('printProblems.count', { count: shown.length })}</span>
</span>}>
<PrintProblemsPanel problems={shown} printers={data?.printers ?? []} run={run} showPlace={orderId == null}
onOpen={onOpen ? p => onOpen(p.order_id, p.table_name) : undefined} />
<p className="px-4 pb-3 text-caption text-ink-3">{t('orders.printHelp')}</p>
</Card>
)
}
@@ -1,7 +1,8 @@
// The tables now, in the manager (plan step 6.9; the map since 6.8): each table's state, total,
// time open, waiters, flags and a booking kept for it soon (RESERVED). A table with an order
// opens its order page; a free one opens a new order there. Quick actions set the table's flags
// and can tell its waiters (or everyone) a message. Lines that didn't print are listed below.
// and can tell its waiters (or everyone) a message. Tickets that didn't print are listed below
// with what can be done about them (6.10).
// Everything stays current through the live events.
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
@@ -14,7 +15,7 @@ import LiveFloor from '../floor/LiveFloor'
import { useDuration } from '../overview/hooks'
import { TABLE_STATES, durationParts, orderTotal, tableCards, tableName } from '../overview/overviewLogic'
import { Money, Pill } from '../overview/parts'
import PendingPrints from '../overview/PendingPrints'
import PrintProblemsCard from './PrintProblemsCard'
import { BORDER, SOFT, SOLID } from '../overview/tones'
import QuickActions from './QuickActions'
import { NO_ZONE, cardTarget, filterCards, flagsByTable, personName } from './orderLogic'
@@ -94,7 +95,7 @@ export default function TablesPage() {
</div>
))}
<PendingPrints cards={cards.filter(c => c.pendingPrint)} onOpen={id => navigate(`/orders/${id}`)} />
<PrintProblemsCard onOpen={id => navigate(`/orders/${id}`)} />
{quick && <QuickActions card={quick} flagDefs={flagDefs} current={flags[quick.table.id] ?? []} onClose={() => setQuick(null)} />}
</div>
@@ -0,0 +1,14 @@
// The tickets that didn't print (plan step 6.10): GET /api/print-problems → { problems, printers },
// reloaded on the live event `print.problems` (and a closed order).
import { PRINT_EVENT } from '@xenia/ordering'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
export function usePrintProblems() {
return useLiveQuery({
queryKey: ['print-problems'],
queryFn: () => client.get('/api/print-problems').then(r => r.data),
events: [PRINT_EVENT, 'order_closed'],
refetchInterval: 60_000,
})
}
@@ -22,7 +22,8 @@ import DaySummaryDialog from './DaySummaryDialog'
import MessagesCard, { ComposeDialog } from './MessagesCard'
import NotesCard from './NotesCard'
import OrderDialog from './OrderDialog'
import PendingPrints from './PendingPrints'
import PrintProblemsCard from '../orders/PrintProblemsCard'
import { usePrintProblems } from '../orders/usePrintProblems'
import ShiftDialog from './ShiftDialog'
import ShiftsCard from './ShiftsCard'
import TablesCard from './TablesCard'
@@ -73,7 +74,7 @@ export default function OverviewPage() {
const dayOpen = !!day
const cards = tableCards(tables, orders)
const waiting = cards.filter(c => c.pendingPrint)
const waiting = usePrintProblems().data?.problems ?? [] // 6.10: tickets that didn't print
const today = dayOrders(orders, day?.opened_at)
const k = dayKpis({ cards, orders: today, shifts })
const idle = staff.filter(w => w.role === 'waiter' && !shifts.some(s => s.waiter_id === w.id))
@@ -160,6 +161,8 @@ export default function OverviewPage() {
<div className="grid gap-5 lg:grid-cols-[13fr_7fr] items-start">
<div className="grid gap-5 min-w-0">
{/* 6.10: tickets that didn't print come first: they need someone now */}
<PrintProblemsCard onOpen={(id, table) => setOrder({ id, table: table ?? `#${id}` })} />
<ShiftsCard shifts={shifts} idle={idle} dayOpen={dayOpen} hidden={hidden} canMessage={chatOn}
onStart={startShift}
onEnd={s => setShift({ shift: s, mode: 'close' })}
@@ -169,7 +172,6 @@ export default function OverviewPage() {
<Card title={t('overview.revenueByHour')} testId="revenue-chart">
<div className="p-4"><HourBars buckets={hourBuckets(orderPairs(today), hourOf)} current={nowHour} /></div>
</Card>
<PendingPrints cards={waiting} onOpen={(id, table) => setOrder({ id, table })} />
</div>
<div className="grid gap-5 min-w-0">
{notesOn && <NotesCard />}
@@ -1,74 +0,0 @@
// Orders with lines that haven't printed (plan step 6.2): which table, since when, how many
// retries, the lines waiting; print one again or all of them, or open the order.
import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button } from '@xenia/ui'
import client from '../../api/client'
import { printRetries, tableName } from './overviewLogic'
import { Card, Pill } from './parts'
export default function PendingPrints({ cards, onOpen }) {
const { t } = useTranslation('manager')
const { formatTime } = useFormat()
const qc = useQueryClient()
const [busy, setBusy] = useState(null) // an order id, or 'all'
if (cards.length === 0) return null
async function retry(orderId) {
try {
const res = await client.post(`/api/orders/${orderId}/retry-print`)
const failed = (res.data.print_results ?? []).filter(r => !r.success).map(r => r.printer_name)
if (failed.length) toast.error(t('overview.prints.failed', { printers: failed.join(', ') }))
else toast.success(t('overview.prints.done'))
} catch (err) {
toast.error(errorMessage(err, t))
}
}
async function run(id, fn) {
setBusy(id)
try { await fn() } finally {
setBusy(null)
qc.invalidateQueries({ queryKey: ['orders-active'] })
}
}
return (
<Card tone="warning" testId="pending-prints"
title={<span className="grid">
<span>{t('overview.prints.title')}</span>
<span className="text-label font-normal">{t('overview.prints.count', { count: cards.length })}</span>
</span>}
action={<Button size="sm" variant="secondary" icon={<Printer size={16} />} loading={busy === 'all'} disabled={busy != null}
onClick={() => run('all', async () => { for (const c of cards) await retry(c.order.id) })}>{t('overview.prints.all')}</Button>}>
<ul className="divide-y divide-line">
{cards.map(({ table, order }) => {
const waiting = order.items.filter(i => i.status === 'active' && !i.printed)
const retries = printRetries(order)
return (
<li key={order.id} className="flex items-center gap-3 px-4 py-2.5" data-testid="pending-print">
<span className="w-10 h-10 shrink-0 grid place-items-center rounded-control bg-warning-soft text-warning-ink text-label font-bold">{tableName(table)}</span>
<div className="flex-1 min-w-0">
<div className="flex flex-wrap items-center gap-2 text-label">
<span className="font-semibold text-ink">#{order.id}</span>
{order.opened_at && <span className="text-ink-2">{formatTime(order.opened_at)}</span>}
{retries > 0 && <Pill tone="warning">{t('overview.prints.retries', { count: retries })}</Pill>}
</div>
<div className="text-caption text-ink-2 truncate">
{t('overview.prints.lines', { count: waiting.length })} · {waiting.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
</div>
</div>
<Button size="sm" variant="ghost" onClick={() => onOpen(order.id, tableName(table))}>{t('overview.prints.open')}</Button>
<Button size="sm" variant="secondary" loading={busy === order.id} disabled={busy != null}
onClick={() => run(order.id, () => retry(order.id))}>{t('overview.prints.print')}</Button>
</li>
)
})}
</ul>
</Card>
)
}
@@ -203,12 +203,6 @@ export function notesPreview(notes = [], todos = []) {
].slice(0, 6)
}
/** The highest retry count among an order's waiting print jobs. */
export function printRetries(order) {
const waiting = (order.print_jobs ?? []).filter(j => j.status === 'pending').map(j => j.retry_count || 0)
return waiting.length ? Math.max(...waiting) : 0
}
/**
* The venue's wall clock for a moment, as a datetime-local value ("YYYY-MM-DDTHH:mm").
* Bookings are typed in venue time; the backend reads a time without an offset as venue time (D-11).
@@ -0,0 +1,103 @@
// Prep zones (plan step 6.10; replaces the v1 Management → Prep zones page): where each dish's
// ticket prints and how the kitchen screen treats it. A card per zone (its printers, whether it
// prints, the ticket's sorting, the kitchen screen's shortcuts); New / Edit open the zone's
// dialog, Delete asks first. Products are put in zones from the product editor.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { CookingPot, Pencil, Plus, Printer, Trash2 } from 'lucide-react'
import { useCan } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import ZoneDialog from './ZoneDialog'
export default function PrepZonesPage() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const canEdit = useCan('catalog.menu.manage')
const [editing, setEditing] = useState(null) // a zone, or {} for a new one
const [deleting, setDeleting] = useState(null)
const { data: zones, isPending } = useLiveQuery({ queryKey: ['prep-zones'], queryFn: () => client.get('/api/prep-zones').then(r => r.data) })
const { data: printers = [] } = useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000 })
const { data: categories = [] } = useLiveQuery({ queryKey: ['categories'], queryFn: () => client.get('/api/products/categories').then(r => r.data), staleTime: 60_000 })
const remove = useMutation({
mutationFn: id => client.delete(`/api/prep-zones/${id}`),
onSuccess: () => { toast.success(t('printing.zones.deleted')); setDeleting(null); qc.invalidateQueries({ queryKey: ['prep-zones'] }) },
onError: err => toast.error(errorMessage(err, t)),
})
const nameOf = id => printers.find(p => p.id === id)?.name ?? `#${id}`
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="prep-zones-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('printing.zones.title')}</h1>
<p className="text-label text-ink-2">{t('printing.zones.intro')}</p>
</div>
{canEdit && <Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="zone-new">{t('printing.zones.new')}</Button>}
</header>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !zones?.length ? <EmptyState icon={<CookingPot size={28} />} title={t('printing.zones.none')} description={t('printing.zones.noneHint')} />
: (
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(18rem,1fr))]">
{zones.map(z => (
<section key={z.id} className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-3 content-start" data-testid="zone-card" data-name={z.name}>
<header className="flex items-start gap-2">
<div className="flex-1 min-w-0">
<h2 className="text-body-lg font-semibold text-ink truncate">{z.name}</h2>
{z.notification_name && <p className="text-label text-accent-ink">{z.notification_name}</p>}
{z.description && <p className="text-caption text-ink-3">{z.description}</p>}
</div>
{canEdit && (<>
<IconButton size="sm" variant="ghost" label={t('printing.zones.edit', { name: z.name })} onClick={() => setEditing(z)} data-testid="zone-edit"><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('printing.zones.delete', { name: z.name })} onClick={() => setDeleting(z)}><Trash2 size={14} /></IconButton>
</>)}
</header>
<div className="grid gap-1 text-label">
<span className="flex flex-wrap items-center gap-1.5">
<span className="w-16 shrink-0 text-caption font-semibold uppercase tracking-wide text-ink-3">{t('printing.zones.main')}</span>
{z.master_printer_id ? <Pill tone="accent"><Printer size={12} aria-hidden="true" />{nameOf(z.master_printer_id)}{z.auto_print !== 'none' && z.master_copies > 1 ? ` ×${z.master_copies}` : ''}</Pill>
: <span className="text-ink-3">{t('printing.zones.noPrinter')}</span>}
</span>
{z.secondary_printer_ids?.length > 0 && (
<span className="flex flex-wrap items-center gap-1.5">
<span className="w-16 shrink-0 text-caption font-semibold uppercase tracking-wide text-ink-3">{t('printing.zones.also')}</span>
{z.secondary_printer_ids.map(id => <Pill key={id}><Printer size={12} aria-hidden="true" />{nameOf(id)}</Pill>)}
{z.auto_print === 'all' && z.secondary_copies > 1 && <span className="text-ink-3">×{z.secondary_copies}</span>}
</span>
)}
</div>
<footer className="flex flex-wrap gap-1.5 pt-2 border-t border-line">
<Pill tone={z.auto_print === 'none' ? 'warning' : 'success'}>{t(`printing.zones.autoShort.${z.auto_print}`)}</Pill>
<Pill>{t(`printing.zones.sortShort.${z.sort_items_by}`)}</Pill>
{z.group_by_category && <Pill>{t('printing.zones.byCategory')}</Pill>}
{z.print_checkboxes && <Pill>{t('printing.zones.checkboxes')}</Pill>}
{z.language && <Pill>{z.language.toUpperCase()}</Pill>}
{z.bypass_kds ? <Pill tone="danger">{t('printing.zones.skipKds')}</Pill> : z.bypass_pending && <Pill tone="warning">{t('printing.zones.startReady')}</Pill>}
{z.auto_ready_to_served && <Pill tone="info">{t('printing.zones.readyServed')}</Pill>}
</footer>
</section>
))}
</div>
)}
</div>
{editing && <ZoneDialog zone={editing.id ? editing : null} printers={printers} categories={categories}
onClose={() => setEditing(null)} onSaved={() => { setEditing(null); qc.invalidateQueries({ queryKey: ['prep-zones'] }) }} />}
{deleting && (
<Dialog open size="sm" onClose={() => setDeleting(null)} title={t('printing.zones.deleteTitle', { name: deleting.name })}
description={t('printing.zones.deleteBody')}
footer={<>
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('printing.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(deleting.id)} data-testid="zone-delete-confirm">{t('printing.zones.deleteYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,206 @@
// The venue's printers (plan step 6.10; was the top of Settings → Print fonts): each with its
// address, model and line width, whether it answers now, on/off, a test print, edit, remove;
// "Add a printer" and "Find printers" (a scan of the network for the printing port).
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Pencil, Plus, Printer, Radar, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Switch } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { SettingsCard } from '../Settings/sections/SettingsCard'
import { usePrinters } from './usePrinters'
import { EMPTY_PRINTER, PRINTER_MODELS, modelOf, printerBody, printerProblems } from './printingLogic'
export default function PrintersCard() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const { data: printers = [], isPending } = usePrinters()
const { data: status } = useLiveQuery({ queryKey: ['system-status'], queryFn: () => client.get('/api/system/status').then(r => r.data), refetchInterval: 30_000 })
const [editing, setEditing] = useState(null) // a printer, or a new one's starting values
const [finding, setFinding] = useState(false)
const [removing, setRemoving] = useState(null)
const changed = () => { qc.invalidateQueries({ queryKey: ['printers'] }); qc.invalidateQueries({ queryKey: ['system-status'] }) }
const onError = err => toast.error(errorMessage(err, t))
const toggle = useMutation({ mutationFn: p => client.put(`/api/system/printers/${p.id}`, { is_active: !p.is_active }), onSuccess: changed, onError })
const remove = useMutation({ mutationFn: id => client.delete(`/api/system/printers/${id}`), onSuccess: () => { setRemoving(null); toast.success(t('printing.printers.removed')); changed() }, onError })
const test = useMutation({
mutationFn: id => client.post('/api/system/printers/test', null, { params: { printer_id: id } }).then(r => r.data),
onSuccess: res => (res.success ? toast.success(t('printing.printers.testSent')) : toast.error(t('printing.printers.testFailed', { error: res.error }))),
onError,
})
const reachable = id => status?.printers?.find(p => p.id === id)?.reachable
return (
<SettingsCard title={t('printing.printers.title')} description={t('printing.printers.intro')} testId="printers-card">
<div className="px-5 py-3 flex flex-wrap gap-2">
<Button size="sm" icon={<Plus size={14} />} onClick={() => setEditing({ ...EMPTY_PRINTER })} data-testid="printer-new">{t('printing.printers.add')}</Button>
<Button size="sm" variant="secondary" icon={<Radar size={14} />} onClick={() => setFinding(true)}>{t('printing.printers.find')}</Button>
</div>
{!isPending && printers.length === 0 && <EmptyState compact icon={<Printer size={24} />} title={t('printing.printers.none')} />}
{printers.map(p => {
const r = p.is_active ? reachable(p.id) : null
return (
<div key={p.id} className="px-5 py-3 flex flex-wrap items-center gap-3" data-testid="printer-row" data-name={p.name}>
<Switch checked={p.is_active} onChange={() => toggle.mutate(p)} aria-label={t('printing.printers.on', { name: p.name })} />
<div className={`flex-1 min-w-48 ${p.is_active ? '' : 'opacity-60'}`}>
<div className="text-body font-semibold text-ink">{p.name}</div>
<div className="text-caption text-ink-2">
{p.ip_address}:{p.port} · {modelOf(p.codepage_n)?.label ?? t('printing.printers.codepage', { n: p.codepage_n })} · {t('printing.printers.chars', { count: p.line_width })}
</div>
</div>
{p.is_active && (r == null ? <Pill>{t('printing.printers.checking')}</Pill>
: r ? <Pill tone="success">{t('printing.printers.answers')}</Pill> : <Pill tone="danger">{t('printing.printers.noAnswer')}</Pill>)}
<Button size="sm" variant="secondary" loading={test.isPending && test.variables === p.id} onClick={() => test.mutate(p.id)}>{t('printing.printers.test')}</Button>
<IconButton size="sm" variant="ghost" label={t('printing.printers.edit', { name: p.name })} onClick={() => setEditing(p)}><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('printing.printers.remove', { name: p.name })} onClick={() => setRemoving(p)}><Trash2 size={14} /></IconButton>
</div>
)
})}
{editing && <PrinterDialog printer={editing} onClose={() => setEditing(null)} onSaved={() => { setEditing(null); changed() }} />}
{finding && <FindPrinters onClose={() => setFinding(false)} onPick={found => { setFinding(false); setEditing({ ...EMPTY_PRINTER, ...found }) }} />}
{removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t('printing.printers.removeTitle', { name: removing.name })}
description={t('printing.printers.removeBody')}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('printing.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing.id)}>{t('printing.printers.removeYes')}</Button>
</>} />
)}
</SettingsCard>
)
}
function PrinterDialog({ printer, onClose, onSaved }) {
const { t } = useTranslation('manager')
const [form, setForm] = useState(printer)
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const wrong = printerProblems(form)
const err = k => (tried && wrong.includes(k) ? t(`printing.printers.wrong.${k}`) : undefined)
const save = useMutation({
mutationFn: body => (printer.id ? client.put(`/api/system/printers/${printer.id}`, body) : client.post('/api/system/printers', body)),
onSuccess: () => { toast.success(t(printer.id ? 'printing.printers.saved' : 'printing.printers.added')); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate(printerBody(form)) }
const models = PRINTER_MODELS.some(m => m.codepage_n === Number(form.codepage_n)) ? PRINTER_MODELS
: [...PRINTER_MODELS, { label: t('printing.printers.codepage', { n: form.codepage_n }), codepage_n: Number(form.codepage_n) }]
return (
<Dialog open onClose={onClose} title={printer.id ? t('printing.printers.editTitle', { name: printer.name }) : t('printing.printers.addTitle')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('printing.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="printer-save">{t('printing.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="printer-dialog">
<Field label={t('printing.printers.name')} required error={err('name')}>
<Input value={form.name} onChange={e => set('name', e.target.value)} placeholder={t('printing.printers.namePh')} data-testid="printer-name" />
</Field>
<div className="grid gap-3 grid-cols-[1fr_7rem]">
<Field label={t('printing.printers.address')} required error={err('ip_address')} hint={t('printing.printers.addressHint')}>
<Input value={form.ip_address} inputMode="decimal" onChange={e => set('ip_address', e.target.value)} placeholder="192.168.1.50" data-testid="printer-ip" />
</Field>
<Field label={t('printing.printers.port')} error={err('port')}>
<Input value={form.port} inputMode="numeric" onChange={e => set('port', e.target.value)} data-testid="printer-port" />
</Field>
</div>
<div className="grid gap-3 grid-cols-[1fr_9rem]">
<Field label={t('printing.printers.model')} hint={t('printing.printers.modelHint')}>
<Select value={String(form.codepage_n)} onChange={e => set('codepage_n', Number(e.target.value))}
options={models.map(m => ({ value: String(m.codepage_n), label: m.label }))} />
</Field>
<Field label={t('printing.printers.width')} error={err('line_width')} hint={t('printing.printers.widthHint')}>
<Input value={form.line_width} inputMode="numeric" onChange={e => set('line_width', e.target.value)} />
</Field>
</div>
</div>
</Dialog>
)
}
/** A scan of the venue's network for devices answering on the printing port (streamed by the server). */
function FindPrinters({ onClose, onPick }) {
const { t } = useTranslation('manager')
const [subnet, setSubnet] = useState('')
const [port, setPort] = useState('9100')
const [scan, setScan] = useState({ running: false, found: [], done: 0, total: 0, error: null, ran: false })
const stop = useRef(null)
const { data: hints } = useLiveQuery({ queryKey: ['printer-scan-hints'], queryFn: () => client.get('/api/system/printers/scan-hints').then(r => r.data), staleTime: 60_000 })
const shownSubnet = subnet || hints?.subnets?.[0] || ''
useEffect(() => () => stop.current?.abort(), [])
async function start() {
stop.current?.abort()
const ctl = new AbortController()
stop.current = ctl
setScan({ running: true, found: [], done: 0, total: 0, error: null, ran: true })
try {
const res = await fetch(`/api/system/printers/scan?${new URLSearchParams({ subnet: shownSubnet, port })}`, {
headers: { Authorization: `Bearer ${localStorage.getItem('manager_token') || ''}` }, signal: ctl.signal,
})
if (!res.ok) throw new Error(String(res.status))
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
for (;;) {
const { done, value } = await reader.read()
if (done) break
buf += decoder.decode(value, { stream: true })
const lines = buf.split('\n')
buf = lines.pop()
for (const line of lines) {
if (!line.startsWith('data: ')) continue
let msg = null
try { msg = JSON.parse(line.slice(6)) } catch { continue }
if (msg.type === 'found') setScan(s => ({ ...s, found: [...s.found, { ip_address: msg.ip, port: msg.port }] }))
else if (msg.type === 'progress') setScan(s => ({ ...s, done: msg.done, total: msg.total }))
else if (msg.error) setScan(s => ({ ...s, error: msg.error }))
}
}
} catch (err) {
if (err.name !== 'AbortError') setScan(s => ({ ...s, error: t('printing.printers.scanFailed') }))
} finally {
setScan(s => ({ ...s, running: false }))
}
}
const pct = scan.total ? Math.round((scan.done / scan.total) * 100) : 0
return (
<Dialog open onClose={onClose} title={t('printing.printers.findTitle')} description={t('printing.printers.findBody')}
footer={<Button variant="secondary" onClick={onClose}>{t('printing.close')}</Button>}>
<div className="grid gap-3">
<div className="grid gap-3 grid-cols-[1fr_6rem_auto] items-end">
<Field label={t('printing.printers.subnet')} hint="192.168.1.0/24">
<Input value={shownSubnet} onChange={e => setSubnet(e.target.value)} disabled={scan.running} />
</Field>
<Field label={t('printing.printers.port')}>
<Input value={port} inputMode="numeric" onChange={e => setPort(e.target.value)} disabled={scan.running} />
</Field>
{scan.running
? <Button variant="danger" onClick={() => stop.current?.abort()}>{t('printing.printers.stop')}</Button>
: <Button onClick={start} disabled={!shownSubnet}>{t('printing.printers.scan')}</Button>}
</div>
{scan.running && (
<div className="grid gap-1">
<div className="h-1.5 rounded-full bg-surface-2 overflow-hidden"><div className="h-full bg-accent transition-[width] duration-base" style={{ width: `${pct}%` }} /></div>
<span className="text-caption text-ink-3">{t('printing.printers.scanned', { done: scan.done, total: scan.total })}</span>
</div>
)}
{scan.error && <p role="alert" className="text-label text-danger-ink">{scan.error}</p>}
<ul className="divide-y divide-line rounded-control border border-line min-h-16">
{scan.found.length === 0 && <li className="px-3 py-4 text-center text-label text-ink-3">{scan.ran && !scan.running ? t('printing.printers.foundNone') : t('printing.printers.scanStart')}</li>}
{scan.found.map(f => (
<li key={f.ip_address} className="px-3 py-2 flex items-center gap-3">
<span className="flex-1 text-body font-semibold tabular-nums">{f.ip_address}<span className="text-ink-3 font-normal">:{f.port}</span></span>
<Button size="sm" onClick={() => onPick(f)}>{t('printing.printers.use')}</Button>
</li>
))}
</ul>
</div>
</Dialog>
)
}
@@ -0,0 +1,15 @@
// Settings → Printing (plan step 6.10; replaces the v1 "Print fonts" tab): when managers are
// told about tickets that keep failing, the printers, and the tickets' look and beep.
import PrintAlertSetting from '../Settings/sections/PrintAlertSetting'
import PrintersCard from './PrintersCard'
import TicketSettings from './TicketSettings'
export default function PrintingSettings() {
return (
<div className="max-w-4xl grid gap-5" data-testid="printing-settings">
<PrintersCard />
<PrintAlertSetting />
<TicketSettings />
</div>
)
}
@@ -0,0 +1,197 @@
// How kitchen and bar tickets look and sound (plan step 6.10; was Settings → Print fonts): the
// layout (detailed / compact) with a test ticket, the printer's beep with a test, each part's
// font (size, bold, capitals) with a preview, the dot leader and the dividers. Every change is
// saved at once and used from the next ticket.
import { useId, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Bell, Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Input, Select, cx } from '@xenia/ui'
import client from '../../api/client'
import { SettingRow, SettingsCard } from '../Settings/sections/SettingsCard'
import { useSettings } from '../Settings/sections/useSettings'
import { usePrinters } from './usePrinters'
import {
BEEPS, DEFAULTS, DIVIDERS, DIVIDER_CHARS, DOT_PREVIEW, DOT_STYLES, FONT_GROUPS, FONT_SIZES, TICKET_MODES,
beepBytes, beepSettings, decodeBeep, decodeDots, decodeFont, encodeDots, encodeFont, isWide,
} from './printingLogic'
// how a size looks on paper: tall doubles the height, wide the width
const SCALE = { 0: 'scale-100', 16: 'scale-y-[1.8]', 32: 'scale-x-[1.8]', 48: 'scale-[1.8]' }
function Paper({ children, className }) {
return <span className={cx('w-44 h-12 shrink-0 rounded-control border border-line bg-surface grid place-items-center overflow-hidden font-mono text-ink', className)}>{children}</span>
}
function Pick({ options, value, onChange, label }) {
return (
<div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label={label}>
{options.map(o => (
<button key={o.value} type="button" role="radio" aria-checked={value === o.value} onClick={() => onChange(o.value)} data-value={o.value}
className={cx('px-3 py-1.5 rounded-control border text-label', value === o.value ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{o.label}
</button>
))}
</div>
)
}
function Check({ on, onChange, label }) {
return (
<button type="button" aria-pressed={on} onClick={() => onChange(!on)}
className={cx('px-2.5 py-1.5 rounded-control border text-label font-semibold', on ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{label}
</button>
)
}
function useTest() {
const { t } = useTranslation('manager')
return useMutation({
mutationFn: ({ url, params }) => client.post(url, null, { params }).then(r => r.data),
onSuccess: res => (res.success ? toast.success(t('printing.ticket.testSent')) : toast.error(t('printing.printers.testFailed', { error: res.error }))),
onError: err => toast.error(errorMessage(err, t)),
})
}
function PrinterPick({ printers, value, onChange }) {
const { t } = useTranslation('manager')
return (
<Select size="sm" value={value} onChange={e => onChange(e.target.value)} aria-label={t('printing.ticket.testOn')}
options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
)
}
export default function TicketSettings() {
const { t } = useTranslation('manager')
const s = useSettings()
const { data: printers = [] } = usePrinters()
const active = printers.filter(p => p.is_active)
const [testPrinter, setTestPrinter] = useState('')
const printerId = testPrinter || (active[0] ? String(active[0].id) : '')
const test = useTest()
const val = key => s.get(key, DEFAULTS[key])
if (s.loading) return null
return (
<div className="grid gap-5">
<SettingsCard title={t('printing.ticket.layout')} testId="ticket-layout">
<SettingRow label={t('printing.ticket.mode')} tip={t('printing.ticket.modeTip')}>
<Pick label={t('printing.ticket.mode')} value={val('print.ticket_mode')} onChange={v => s.save('print.ticket_mode', v)}
options={TICKET_MODES.map(m => ({ value: m, label: t(`printing.ticket.modes.${m}`) }))} />
</SettingRow>
{active.length > 0 && (
<div className="px-5 py-3 flex flex-wrap items-center gap-2">
<span className="flex-1 text-label text-ink-2">{t('printing.ticket.testHint')}</span>
<PrinterPick printers={active} value={printerId} onChange={setTestPrinter} />
<Button size="sm" variant="secondary" icon={<Printer size={14} />} loading={test.isPending && test.variables?.kind === 'order'}
onClick={() => test.mutate({ kind: 'order', url: '/api/system/printers/test-order', params: { printer_id: printerId } })}>{t('printing.ticket.testOrder')}</Button>
</div>
)}
</SettingsCard>
<Beep s={s} printers={active} printerId={printerId} onPrinter={setTestPrinter} test={test} />
<SettingsCard title={t('printing.ticket.fonts')} description={t('printing.ticket.fontsHint')} testId="ticket-fonts">
{FONT_GROUPS.map(g => (
<div key={g.key}>
<div className="px-5 pt-3 pb-1 text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`printing.ticket.groups.${g.key}`)}</div>
{g.fields.map(key => <FontRow key={key} field={key} value={val(key)} onSave={v => s.save(key, v)} />)}
{g.key === 'items' && <DotsRow value={val('print.dot_style')} onSave={v => s.save('print.dot_style', v)} />}
</div>
))}
<SettingRow label={t('printing.ticket.divider')} hint={t('printing.ticket.dividerHint')}>
<div className="flex items-center gap-3">
<Select value={val('print.divider_style')} onChange={e => s.save('print.divider_style', e.target.value)} aria-label={t('printing.ticket.divider')}
options={DIVIDERS.map(d => ({ value: d, label: t(`printing.ticket.dividers.${d}`) }))} />
</div>
</SettingRow>
<div className="px-5 pb-4 -mt-1">
<Paper className="w-full">{DIVIDER_CHARS[val('print.divider_style')] ? DIVIDER_CHARS[val('print.divider_style')].repeat(32) : <span className="text-ink-3 text-caption">{t('printing.ticket.emptyLine')}</span>}</Paper>
</div>
</SettingsCard>
</div>
)
}
function FontRow({ field, value, onSave }) {
const { t } = useTranslation('manager')
const id = useId()
const f = decodeFont(value)
const set = patch => onSave(encodeFont({ ...f, ...patch }))
const name = field.replace('print.font_', '')
return (
<div className="px-5 py-3 flex flex-wrap items-center gap-3" data-testid={`font-${name}`}>
<label htmlFor={id} className="flex-1 min-w-48 grid">
<span className="text-body font-medium text-ink">{t(`printing.ticket.parts.${name}`)}</span>
<span className="text-caption text-ink-2">{t(`printing.ticket.partsHint.${name}`)}</span>
</label>
<Select id={id} value={f.size} onChange={e => set({ size: e.target.value })} className="w-40"
options={FONT_SIZES.map(z => ({ value: z, label: t(`printing.ticket.sizes.${z}`) }))} />
<Check on={f.bold} onChange={v => set({ bold: v })} label={t('printing.ticket.bold')} />
<Check on={f.caps} onChange={v => set({ caps: v })} label={t('printing.ticket.caps')} />
<Paper><span className={cx('inline-block', SCALE[f.size], f.bold ? 'font-extrabold' : 'font-normal')}>{f.caps ? 'SAMPLE' : 'Sample'}</span></Paper>
{isWide(f.size) && <span className="w-full text-caption text-warning-ink">{t('printing.ticket.wideNote')}</span>}
</div>
)
}
function DotsRow({ value, onSave }) {
const { t } = useTranslation('manager')
const d = decodeDots(value)
const set = patch => onSave(encodeDots({ ...d, ...patch }))
return (
<div className="px-5 py-3 flex flex-wrap items-center gap-3" data-testid="font-dots">
<span className="flex-1 min-w-48 grid">
<span className="text-body font-medium text-ink">{t('printing.ticket.dots')}</span>
<span className="text-caption text-ink-2">{t('printing.ticket.dotsHint')}</span>
</span>
<Select value={d.style} onChange={e => set({ style: e.target.value })} className="w-40" aria-label={t('printing.ticket.dots')}
options={DOT_STYLES.map(x => ({ value: x, label: t(`printing.ticket.dotStyles.${x}`) }))} />
<Select value={d.size} onChange={e => set({ size: e.target.value })} className="w-40" aria-label={t('printing.ticket.dotsSize')}
options={FONT_SIZES.map(z => ({ value: z, label: t(`printing.ticket.sizes.${z}`) }))} />
<Check on={d.bold} onChange={v => set({ bold: v })} label={t('printing.ticket.bold')} />
<Paper><span className={cx('inline-block whitespace-nowrap', SCALE[d.size], d.bold && 'font-extrabold')}>{t('printing.ticket.dotsSample', { dots: DOT_PREVIEW[d.style] })}</span></Paper>
</div>
)
}
function Beep({ s, printers, printerId, onPrinter, test }) {
const { t } = useTranslation('manager')
const saved = decodeBeep(s.get('print.beep_pattern', 'double'), s.get('print.beep_on_ticket', 'true'))
const [custom, setCustom] = useState({ n1: saved.n1, n2: saved.n2, n3: saved.n3 })
const save = beep => beepSettings(beep).forEach(([k, v]) => s.save(k, v))
const choose = preset => save(preset === 'custom' ? { preset, ...custom } : { preset })
const setPart = (k, v) => setCustom(c => ({ ...c, [k]: v }))
const savePart = () => save({ preset: 'custom', ...custom }) // on leaving the box, not on every key
const bytes = beepBytes(saved.preset === 'custom' ? { preset: 'custom', ...custom } : saved)
return (
<SettingsCard title={t('printing.beep.title')} description={t('printing.beep.intro')} testId="ticket-beep">
<div className="px-5 py-3">
<Pick label={t('printing.beep.title')} value={saved.preset} onChange={choose} options={BEEPS.map(b => ({ value: b, label: t(`printing.beep.presets.${b}`) }))} />
</div>
{saved.preset === 'custom' && (
<div className="px-5 py-3 grid gap-3 sm:grid-cols-3">
{['n1', 'n2', 'n3'].map(k => (
<label key={k} className="grid gap-1 text-label text-ink-2">
{t(`printing.beep.${k}`)}
<Input type="number" min={1} max={30} value={custom[k]} onChange={e => setPart(k, e.target.value)} onBlur={savePart} />
<span className="text-caption text-ink-3">{t(`printing.beep.${k}Hint`)}</span>
</label>
))}
</div>
)}
{printers.length > 0 && saved.preset !== 'off' && (
<div className="px-5 py-3 flex flex-wrap items-center gap-2">
<span className="flex-1 text-label text-ink-2">{t('printing.beep.testHint')}</span>
<PrinterPick printers={printers} value={printerId} onChange={onPrinter} />
<Button size="sm" variant="secondary" icon={<Bell size={14} />} loading={test.isPending && test.variables?.kind === 'beep'}
onClick={() => test.mutate({ kind: 'beep', url: '/api/system/printers/test-beep', params: { printer_id: printerId, ...bytes } })}>{t('printing.beep.test')}</Button>
</div>
)}
</SettingsCard>
)
}
@@ -0,0 +1,180 @@
// A prep zone's settings (plan step 6.10): its name (and the name staff see in messages), the
// ticket's language, the printers (a main one, more for "all printers") and copies, how the
// ticket lists dishes, and the kitchen screen's shortcuts. Each choice has an (i) tip.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp } from 'lucide-react'
import { useAccess } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { LANGUAGE_NAMES, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, InfoTip, Input, Select, Stepper, Switch, cx } from '@xenia/ui'
import client from '../../api/client'
import { AUTO_PRINT, SORT_BY, move, orderedCategories, setBypass, setMain, toggleSecond, zoneBody, zoneForm, zoneProblem } from './printingLogic'
function Section({ title, children }) {
return (
<section className="grid gap-3">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{title}</h3>
{children}
</section>
)
}
function Choice({ options, value, onChange, label, testId }) {
return (
<div className="grid gap-2 sm:grid-cols-3" role="radiogroup" aria-label={label} data-testid={testId}>
{options.map(o => (
<button key={o.value} type="button" role="radio" aria-checked={value === o.value} onClick={() => onChange(o.value)} data-value={o.value}
className={cx('text-left px-3 py-2 rounded-control border transition-colors duration-fast',
value === o.value ? 'border-accent bg-accent-soft' : 'border-line bg-surface hover:bg-surface-2')}>
<span className={cx('block text-label font-semibold', value === o.value ? 'text-accent-ink' : 'text-ink')}>{o.label}</span>
<span className="block text-caption text-ink-2">{o.hint}</span>
</button>
))}
</div>
)
}
function Toggle({ label, tip, checked, onChange, testId }) {
return (
<div className="flex items-center gap-3">
<Switch checked={checked} onChange={onChange} aria-label={label} data-testid={testId} />
<span className="flex-1 text-body text-ink flex items-center gap-1">{label}{tip && <InfoTip>{tip}</InfoTip>}</span>
</div>
)
}
export default function ZoneDialog({ zone, printers, categories, onClose, onSaved }) {
const { t } = useTranslation('manager')
const { languages } = useAccess()
const [form, setForm] = useState(() => zoneForm(zone))
const [ordering, setOrdering] = useState(false)
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const problem = zoneProblem(form)
const save = useMutation({
mutationFn: body => (zone ? client.put(`/api/prep-zones/${zone.id}`, body) : client.post('/api/prep-zones', body)),
onSuccess: () => { toast.success(t(zone ? 'printing.zones.saved' : 'printing.zones.created')); onSaved() },
onError: err => toast.error(errorMessage(err, t)),
})
const submit = () => { setTried(true); if (!problem) save.mutate(zoneBody(form)) }
const flat = categories.flatMap(c => [c, ...(c.subcategories ?? [])])
return (
<Dialog open size="lg" onClose={onClose} title={zone ? t('printing.zones.editTitle', { name: zone.name }) : t('printing.zones.newTitle')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('printing.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="zone-save">{t('printing.save')}</Button>
</>}>
<div className="grid gap-6" data-testid="zone-dialog">
<Section title={t('printing.zones.about')}>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('printing.zones.name')} required error={tried && problem === 'name' ? t('printing.zones.nameNeeded') : undefined}>
<Input value={form.name} onChange={e => set('name', e.target.value)} placeholder={t('printing.zones.namePh')} data-testid="zone-name" />
</Field>
<Field label={t('printing.zones.shown')} hint={t('printing.zones.shownHint')}>
<Input value={form.notification_name} onChange={e => set('notification_name', e.target.value)} />
</Field>
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_14rem]">
<Field label={t('printing.zones.description')}>
<Input value={form.description} onChange={e => set('description', e.target.value)} />
</Field>
<Field label={t('printing.zones.language')} hint={t('printing.zones.languageHint')}>
<Select value={form.language} onChange={e => set('language', e.target.value)} data-testid="zone-language"
options={[{ value: '', label: t('printing.zones.venueLanguage') }, ...(languages || ['en', 'el']).map(l => ({ value: l, label: LANGUAGE_NAMES[l] || l }))]} />
</Field>
</div>
</Section>
<Section title={t('printing.zones.printers')}>
<Choice label={t('printing.zones.auto')} value={form.auto_print} onChange={v => set('auto_print', v)} testId="zone-auto"
options={AUTO_PRINT.map(v => ({ value: v, label: t(`printing.zones.autoShort.${v}`), hint: t(`printing.zones.autoHint.${v}`) }))} />
{printers.length === 0 ? <p className="text-label text-warning-ink">{t('printing.zones.noPrinters')}</p> : (
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('printing.zones.mainPrinter')} hint={t('printing.zones.mainHint')}
error={tried && problem === 'printer' ? t('printing.zones.printerNeeded') : undefined}>
<Select value={form.master_printer_id ?? ''} onChange={e => setForm(f => setMain(f, e.target.value ? Number(e.target.value) : null))} data-testid="zone-main"
options={[{ value: '', label: t('printing.zones.noPrinter') }, ...printers.map(p => ({ value: String(p.id), label: p.name }))]} />
</Field>
<div className="grid gap-1.5">
<span className="text-label font-medium text-ink flex items-center gap-1">{t('printing.zones.secondPrinters')}<InfoTip>{t('printing.zones.secondTip')}</InfoTip></span>
<div className="flex flex-wrap gap-1.5">
{printers.filter(p => p.id !== form.master_printer_id).map(p => {
const on = form.printer_ids.includes(p.id)
return (
<button key={p.id} type="button" aria-pressed={on} onClick={() => setForm(f => toggleSecond(f, p.id))}
className={cx('px-3 py-1 rounded-full border text-label', on ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{p.name}
</button>
)
})}
</div>
</div>
</div>
)}
{form.auto_print !== 'none' && (
<div className="flex flex-wrap gap-6">
<label className="grid gap-1 text-label text-ink-2">{t('printing.zones.mainCopies')}
<Stepper value={form.master_copies} min={1} max={9} onChange={v => set('master_copies', v)} label={t('printing.zones.mainCopies')} />
</label>
{form.auto_print === 'all' && (
<label className="grid gap-1 text-label text-ink-2">{t('printing.zones.secondCopies')}
<Stepper value={form.secondary_copies} min={1} max={9} onChange={v => set('secondary_copies', v)} label={t('printing.zones.secondCopies')} />
</label>
)}
</div>
)}
</Section>
<Section title={t('printing.zones.ticket')}>
<Choice label={t('printing.zones.sort')} value={form.sort_items_by} onChange={v => set('sort_items_by', v)}
options={SORT_BY.map(v => ({ value: v, label: t(`printing.zones.sortShort.${v}`), hint: t(`printing.zones.sortHint.${v}`) }))} />
<Toggle label={t('printing.zones.byCategory')} tip={t('printing.zones.byCategoryTip')} checked={form.group_by_category} onChange={v => set('group_by_category', v)} />
{form.group_by_category && (
<div className="pl-12">
<Button size="sm" variant="secondary" onClick={() => setOrdering(true)}>
{t('printing.zones.categoryOrder')}{form.category_order.length ? ` (${form.category_order.length})` : ''}
</Button>
</div>
)}
<Toggle label={t('printing.zones.checkboxes')} tip={t('printing.zones.checkboxesTip')} checked={form.print_checkboxes} onChange={v => set('print_checkboxes', v)} />
</Section>
<Section title={t('printing.zones.kds')}>
<Toggle label={t('printing.zones.startReady')} tip={t('printing.zones.startReadyTip')} checked={form.bypass_pending} onChange={v => setForm(f => setBypass(f, 'bypass_pending', v))} />
<Toggle label={t('printing.zones.skipKds')} tip={t('printing.zones.skipKdsTip')} checked={form.bypass_kds} onChange={v => setForm(f => setBypass(f, 'bypass_kds', v))} />
<Toggle label={t('printing.zones.readyServed')} tip={t('printing.zones.readyServedTip')} checked={form.auto_ready_to_served} onChange={v => set('auto_ready_to_served', v)} />
</Section>
</div>
{ordering && <CategoryOrder categories={flat} order={form.category_order} onClose={() => setOrdering(false)}
onSave={ids => { set('category_order', ids); setOrdering(false) }} />}
</Dialog>
)
}
function CategoryOrder({ categories, order, onClose, onSave }) {
const { t } = useTranslation('manager')
const [list, setList] = useState(() => orderedCategories(categories, order))
return (
<Dialog open size="sm" onClose={onClose} title={t('printing.zones.categoryOrder')} description={t('printing.zones.categoryOrderHint')}
footer={<>
<Button variant="ghost" onClick={() => onSave([])}>{t('printing.zones.categoryOrderReset')}</Button>
<Button variant="secondary" onClick={onClose}>{t('printing.back')}</Button>
<Button onClick={() => onSave(list.map(c => c.id))}>{t('printing.save')}</Button>
</>}>
<ol className="grid gap-1">
{list.map((c, i) => (
<li key={c.id} className="flex items-center gap-2 px-3 py-1.5 rounded-control bg-surface-2">
<span className="w-6 text-caption text-ink-3 tabular-nums">{i + 1}</span>
<span className="flex-1 text-label text-ink">{c.name}</span>
<IconButton size="sm" variant="ghost" label={t('printing.up')} disabled={i === 0} onClick={() => setList(l => move(l, i, -1))}><ArrowUp size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('printing.down')} disabled={i === list.length - 1} onClick={() => setList(l => move(l, i, 1))}><ArrowDown size={14} /></IconButton>
</li>
))}
</ol>
</Dialog>
)
}
@@ -0,0 +1,180 @@
// Printing set-up as plain data (plan step 6.10), tested in tests/printing.test.mjs. The ticket
// settings are strings the backend reads (services/printer_service.py):
// fonts "SIZE:BOLD:CAPS" SIZE = ESC ! base byte 0 | 16 (tall) | 32 (wide) | 48 (both)
// dot leader "STYLE:SIZE:BOLD" STYLE = dot_space | dot | dash_space | underscore
// beep print.beep_on_ticket 'true'|'false' + print.beep_pattern single|double|triple|long|custom:n1:n2:n3
export const FONT_SIZES = ['0', '16', '32', '48']
export const DIVIDERS = ['dash', 'equals', 'star', 'empty']
export const DIVIDER_CHARS = { dash: '-', equals: '=', star: '*', empty: '' }
export const DOT_STYLES = ['dot_space', 'dot', 'dash_space', 'underscore']
export const DOT_PREVIEW = { dot_space: '. . . . .', dot: '.........', dash_space: '- - - - -', underscore: '_________' }
export const TICKET_MODES = ['detailed', 'compact']
export const BEEPS = ['off', 'single', 'double', 'triple', 'long', 'custom']
const BEEP_BYTES = { single: [2, 2, 1], double: [1, 1, 2], triple: [1, 1, 3], long: [5, 2, 1] }
/** The ticket's parts with a font of their own, grouped as on the ticket. */
export const FONT_GROUPS = [
{ key: 'header', fields: ['print.font_order_number', 'print.font_meta'] },
{ key: 'items', fields: ['print.font_item_name', 'print.font_quick', 'print.font_pref', 'print.font_extra', 'print.font_ingredient'] },
{ key: 'notes', fields: ['print.font_item_note', 'print.font_order_note'] },
]
export const DEFAULTS = {
'print.font_order_number': '48:1:0', 'print.font_meta': '0:0:0', 'print.font_item_name': '16:1:0',
'print.font_quick': '0:0:0', 'print.font_pref': '0:0:0', 'print.font_extra': '0:0:0', 'print.font_ingredient': '0:0:0',
'print.font_item_note': '0:0:0', 'print.font_order_note': '0:1:0', 'print.divider_style': 'dash',
'print.dot_style': 'dot_space:0:0', 'print.ticket_mode': 'detailed', 'print.beep_on_ticket': 'true', 'print.beep_pattern': 'double',
}
export function decodeFont(value) {
const [size, bold, caps] = String(value || '0:0:0').split(':')
return { size: FONT_SIZES.includes(size) ? size : '0', bold: bold === '1', caps: caps === '1' }
}
export const encodeFont = ({ size, bold, caps }) => `${size}:${bold ? 1 : 0}:${caps ? 1 : 0}`
export function decodeDots(value) {
const [style, size, bold] = String(value || 'dot_space:0:0').split(':')
return { style: DOT_STYLES.includes(style) ? style : 'dot_space', size: FONT_SIZES.includes(size) ? size : '0', bold: bold === '1' }
}
export const encodeDots = ({ style, size, bold }) => `${style}:${size}:${bold ? 1 : 0}`
/** A wide font fits about half as many characters on a line. */
export const isWide = size => size === '32' || size === '48'
/** The two beep settings → { preset, n1, n2, n3 } (n* the printer's beep bytes). */
export function decodeBeep(pattern, enabled) {
if (enabled === 'false') return { preset: 'off', n1: 1, n2: 1, n3: 2 }
const p = pattern || 'double'
if (p.startsWith('custom:')) {
const [, a, b, c] = p.split(':').map(Number)
return { preset: 'custom', n1: a || 2, n2: b || 2, n3: c || 1 }
}
const [n1, n2, n3] = BEEP_BYTES[p] ?? BEEP_BYTES.double
return { preset: BEEP_BYTES[p] ? p : 'double', n1, n2, n3 }
}
/** A beep choice → the settings to save, as [key, value] pairs. */
export function beepSettings({ preset, n1, n2, n3 }) {
if (preset === 'off') return [['print.beep_on_ticket', 'false']]
const clamp = v => Math.max(1, Math.min(30, Math.round(Number(v) || 1)))
const pattern = preset === 'custom' ? `custom:${clamp(n1)}:${clamp(n2)}:${clamp(n3)}` : preset
return [['print.beep_on_ticket', 'true'], ['print.beep_pattern', pattern]]
}
/** The bytes the "Test beep" button sends for a choice. */
export function beepBytes(beep) {
if (beep.preset === 'custom') return { n1: beep.n1, n2: beep.n2, n3: beep.n3 }
const [n1, n2, n3] = BEEP_BYTES[beep.preset] ?? BEEP_BYTES.double
return { n1, n2, n3 }
}
// ── printers ────────────────────────────────────────────────────────────────
/** Printer models by the Greek code page each needs (ESC t n): one choice per code page. */
export const PRINTER_MODELS = [
{ label: 'Jolimark TP850UE / S4MAS Giant 100', codepage_n: 29 },
{ label: 'NETUM NT8330L', codepage_n: 24 },
]
export const modelOf = codepage => PRINTER_MODELS.find(m => m.codepage_n === codepage) ?? null
export const EMPTY_PRINTER = { name: '', ip_address: '', port: 9100, protocol: 'escpos_tcp', line_width: 48, codepage_n: 29, is_active: true }
const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
/** The fields of a printer form that are wrong (empty = fine). */
export function printerProblems(form) {
const out = []
if (!form.name?.trim()) out.push('name')
if (!IPV4.test(String(form.ip_address ?? '').trim())) out.push('ip_address')
const port = Number(form.port)
if (!Number.isInteger(port) || port < 1 || port > 65535) out.push('port')
const width = Number(form.line_width)
if (!Number.isInteger(width) || width < 20 || width > 80) out.push('line_width')
return out
}
export function printerBody(form) {
return {
name: form.name.trim(), ip_address: String(form.ip_address).trim(), port: Number(form.port),
protocol: form.protocol || 'escpos_tcp', line_width: Number(form.line_width), codepage_n: Number(form.codepage_n ?? 29),
is_active: form.is_active !== false,
}
}
// ── prep zones ──────────────────────────────────────────────────────────────
export const AUTO_PRINT = ['none', 'master', 'all']
export const SORT_BY = ['order_time', 'item_count', 'alpha']
export const EMPTY_ZONE = {
name: '', description: '', notification_name: '', language: '',
printer_ids: [], master_printer_id: null, auto_print: 'master', master_copies: 1, secondary_copies: 1,
sort_items_by: 'order_time', group_by_category: false, category_order: [], print_checkboxes: false,
bypass_pending: false, bypass_kds: false, auto_ready_to_served: false,
}
/** A zone from the API as the form edits it. */
export function zoneForm(zone) {
const out = { ...EMPTY_ZONE }
if (!zone) return out
for (const k of Object.keys(EMPTY_ZONE)) if (zone[k] != null) out[k] = zone[k]
out.language = zone.language || ''
for (const k of ['group_by_category', 'print_checkboxes', 'bypass_pending', 'bypass_kds', 'auto_ready_to_served']) out[k] = !!zone[k]
return out
}
/** The main printer changes: it's always one of the zone's printers. */
export function setMain(form, printerId) {
const ids = printerId != null && !form.printer_ids.includes(printerId) ? [...form.printer_ids, printerId] : form.printer_ids
return { ...form, master_printer_id: printerId, printer_ids: ids }
}
/** Tick or untick a second printer (the main one stays). */
export function toggleSecond(form, printerId) {
if (printerId === form.master_printer_id) return form
const ids = form.printer_ids.includes(printerId) ? form.printer_ids.filter(i => i !== printerId) : [...form.printer_ids, printerId]
return { ...form, printer_ids: ids }
}
/** "Skip the kitchen screen" implies "start as ready"; turning that off turns the other off. */
export function setBypass(form, key, value) {
if (key === 'bypass_kds') return { ...form, bypass_kds: value, bypass_pending: value ? true : form.bypass_pending }
if (key === 'bypass_pending') return { ...form, bypass_pending: value, bypass_kds: value ? form.bypass_kds : false }
return { ...form, [key]: value }
}
/** What's missing before saving: 'name' | 'printer' (printing on, no printer) | null. */
export function zoneProblem(form) {
if (!form.name.trim()) return 'name'
if (form.auto_print !== 'none' && !form.master_printer_id && !form.printer_ids.length) return 'printer'
return null
}
export function zoneBody(form) {
const text = v => (v ?? '').trim() || null
return {
...form,
name: form.name.trim(), description: text(form.description), notification_name: text(form.notification_name),
language: form.language || null,
master_copies: Math.max(1, Math.min(9, Number(form.master_copies) || 1)),
secondary_copies: Math.max(1, Math.min(9, Number(form.secondary_copies) || 1)),
}
}
/** The categories in the zone's order: ranked ones first, then the rest by their own order. */
export function orderedCategories(categories, order = []) {
const byId = new Map(categories.map(c => [c.id, c]))
const ranked = order.map(id => byId.get(id)).filter(Boolean)
const rest = categories.filter(c => !order.includes(c.id))
return [...ranked, ...rest]
}
/** Move one entry of a list up (-1) or down (+1). */
export function move(list, index, step) {
const to = index + step
if (to < 0 || to >= list.length) return list
const out = [...list]
;[out[index], out[to]] = [out[to], out[index]]
return out
}
@@ -0,0 +1,7 @@
// The venue's printers (GET /api/system/printers), shared by the printing settings and the zones.
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
export function usePrinters() {
return useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 15_000 })
}
+1 -3
View File
@@ -3,7 +3,7 @@ import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
bookingBody, cashCheck, dayKpis, dayOrders, durationParts, hourBuckets, initials, itemKind, itemShown,
messageAcks, messageTargets, notesPreview, orderPairs, orderTotal, paymentTotals, printRetries, quickAmounts,
messageAcks, messageTargets, notesPreview, orderPairs, orderTotal, paymentTotals, quickAmounts,
shiftCounts, shiftMoney, tableCards, tableName, tablesByZone, toneOf, TONES, venueWallClock,
} from '../src/pages/overview/overviewLogic.js'
import { onlineKind, onlineNextStep } from '../src/pages/online/onlineOrdersLogic.js'
@@ -110,8 +110,6 @@ test('the day\'s payments, messages, notes, print retries', () => {
const notes = [{ id: 1, is_pinned: true }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }]
const todos = [{ id: 9, priority: 'high' }, { id: 8, priority: 'high', is_done: true }, { id: 7, priority: 'low' }]
assert.deepEqual(notesPreview(notes, todos).map(x => `${x.kind}${x.id}`), ['note1', 'todo9', 'note2', 'note3', 'note4'])
assert.equal(printRetries({ print_jobs: [{ status: 'pending', retry_count: 2 }, { status: 'done', retry_count: 9 }] }), 2)
assert.equal(printRetries({}), 0)
})
test('bookings are typed in venue time', () => {
+60
View File
@@ -0,0 +1,60 @@
// Printing set-up as plain data (plan step 6.10).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
beepBytes, beepSettings, decodeBeep, decodeDots, decodeFont, encodeDots, encodeFont, move, orderedCategories, printerBody,
printerProblems, setBypass, setMain, toggleSecond, zoneBody, zoneForm, zoneProblem,
} from '../src/pages/printing/printingLogic.js'
test('fonts and the dot leader round-trip; bad values fall back', () => {
assert.deepEqual(decodeFont('48:1:0'), { size: '48', bold: true, caps: false })
assert.equal(encodeFont({ size: '16', bold: false, caps: true }), '16:0:1')
assert.deepEqual(decodeFont('99:x'), { size: '0', bold: false, caps: false })
assert.equal(encodeDots(decodeDots('dash_space:32:1')), 'dash_space:32:1')
assert.deepEqual(decodeDots(''), { style: 'dot_space', size: '0', bold: false })
})
test('beep: presets, custom, off, and what the test sends', () => {
assert.deepEqual(decodeBeep('triple', 'true'), { preset: 'triple', n1: 1, n2: 1, n3: 3 })
assert.deepEqual(decodeBeep('custom:3:2:4', 'true'), { preset: 'custom', n1: 3, n2: 2, n3: 4 })
assert.equal(decodeBeep('double', 'false').preset, 'off')
assert.deepEqual(beepSettings({ preset: 'off' }), [['print.beep_on_ticket', 'false']])
assert.deepEqual(beepSettings({ preset: 'custom', n1: 99, n2: 0, n3: 2.4 }), [['print.beep_on_ticket', 'true'], ['print.beep_pattern', 'custom:30:1:2']])
assert.deepEqual(beepBytes({ preset: 'long' }), { n1: 5, n2: 2, n3: 1 })
})
test('printer form: what is wrong, and the body', () => {
assert.deepEqual(printerProblems({ name: ' ', ip_address: '10.0.0.300', port: 0, line_width: 48 }), ['name', 'ip_address', 'port'])
assert.deepEqual(printerProblems({ name: 'Bar', ip_address: '192.168.1.20', port: '9100', line_width: '42' }), [])
assert.deepEqual(printerBody({ name: ' Bar ', ip_address: '192.168.1.20 ', port: '9100', line_width: '42', codepage_n: '24' }),
{ name: 'Bar', ip_address: '192.168.1.20', port: 9100, protocol: 'escpos_tcp', line_width: 42, codepage_n: 24, is_active: true })
})
test('zones: main and second printers, the kitchen screen switches, what is missing, the body', () => {
let f = zoneForm(null)
assert.equal(zoneProblem(f), 'name')
f = { ...f, name: ' Grill ' }
assert.equal(zoneProblem(f), 'printer')
f = setMain(f, 3)
assert.deepEqual(f.printer_ids, [3])
f = toggleSecond(toggleSecond(f, 5), 3) // the main one can't be unticked
assert.deepEqual(f.printer_ids, [3, 5])
assert.equal(zoneProblem(f), null)
f = setBypass(f, 'bypass_kds', true)
assert.equal(f.bypass_pending, true)
f = setBypass(f, 'bypass_pending', false)
assert.equal(f.bypass_kds, false)
const body = zoneBody({ ...f, description: ' ', master_copies: 20 })
assert.equal(body.name, 'Grill')
assert.equal(body.description, null)
assert.equal(body.language, null)
assert.equal(body.master_copies, 9)
assert.equal(zoneForm({ name: 'Bar', group_by_category: 1, language: null }).group_by_category, true)
})
test('category order: ranked first, then the rest; moving within bounds', () => {
const cats = [{ id: 1 }, { id: 2 }, { id: 3 }]
assert.deepEqual(orderedCategories(cats, [3, 9]).map(c => c.id), [3, 1, 2])
assert.deepEqual(move([1, 2, 3], 0, -1), [1, 2, 3])
assert.deepEqual(move([1, 2, 3], 2, -1), [1, 3, 2])
})
+2 -2
View File
@@ -1,9 +1,9 @@
{
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
"paths": [
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders"
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing"
],
"strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders"
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing"
]
}