- 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>
207 lines
13 KiB
React
207 lines
13 KiB
React
// 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>
|
|
)
|
|
}
|