// 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 (
{!isPending && printers.length === 0 && } title={t('printing.printers.none')} />} {printers.map(p => { const r = p.is_active ? reachable(p.id) : null return (
toggle.mutate(p)} aria-label={t('printing.printers.on', { name: p.name })} />
{p.name}
{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 })}
{p.is_active && (r == null ? {t('printing.printers.checking')} : r ? {t('printing.printers.answers')} : {t('printing.printers.noAnswer')})} setEditing(p)}> setRemoving(p)}>
) })} {editing && setEditing(null)} onSaved={() => { setEditing(null); changed() }} />} {finding && setFinding(false)} onPick={found => { setFinding(false); setEditing({ ...EMPTY_PRINTER, ...found }) }} />} {removing && ( setRemoving(null)} title={t('printing.printers.removeTitle', { name: removing.name })} description={t('printing.printers.removeBody')} footer={<> } /> )}
) } 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 ( }>
set('name', e.target.value)} placeholder={t('printing.printers.namePh')} data-testid="printer-name" />
set('ip_address', e.target.value)} placeholder="192.168.1.50" data-testid="printer-ip" /> set('port', e.target.value)} data-testid="printer-port" />
set('line_width', e.target.value)} />
) } /** 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 ( {t('printing.close')}}>
setSubnet(e.target.value)} disabled={scan.running} /> setPort(e.target.value)} disabled={scan.running} /> {scan.running ? : }
{scan.running && (
{t('printing.printers.scanned', { done: scan.done, total: scan.total })}
)} {scan.error &&

{scan.error}

}
    {scan.found.length === 0 &&
  • {scan.ran && !scan.running ? t('printing.printers.foundNone') : t('printing.printers.scanStart')}
  • } {scan.found.map(f => (
  • {f.ip_address}:{f.port}
  • ))}
) }