Files
Convivo/apps/admin/src/views/Printing.tsx
T
00c89c1b48 feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view
- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations,
  token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs,
  welcome_checkin enqueue; badge_print_tests.sql (101 assertions)
- apps/printer: Python worker (Playwright render -> brother_ql via pyusb),
  comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token),
  arm64 image build + idempotent Pi setup/install scripts, 77 pytest
- apps/admin: Printing view, station management/DLQ, global printer status
  pill, Print button on Registrations, standalone print renderer entry
  (print.html -> dist-print) with bundled fonts
- docs: printing.md + architecture/schema/rpcs/tests/admin-app updates,
  apps/printer/AGENT.md operating manual
- e2e: printing.spec.ts

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-18 22:25:38 +02:00

426 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState } from 'react';
import {
createPrintStation,
discardDeadBadgePrint,
enqueueBadgePrint,
renamePrintStation,
requeueDeadBadgePrint,
revokePrintStation,
} from '../lib/api';
import type { PrintDeadLetter, PrintRecentJob, PrintStation, PrintStationState } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner } from '../components/ui';
import { activeStations, printerHint, timeAgo, usePrintStatus } from '../lib/printStatus';
const STATE_LABEL: Record<PrintStationState, string> = {
ready: 'ready',
printing: 'printing',
error: 'error',
offline: 'offline',
revoked: 'revoked',
};
const STATE_PILL: Record<PrintStationState, string> = {
ready: 'green',
printing: 'session',
error: 'red',
offline: 'attendee',
revoked: 'attendee',
};
const kindLabel = (kind: string) => (kind === 'checkin' ? 'check-in' : kind === 'reprint' ? 'reprint' : kind);
function fmtUptime(secs: number | undefined): string {
if (secs == null || !Number.isFinite(secs)) return '—';
const h = Math.floor(secs / 3600);
const m = Math.floor((secs % 3600) / 60);
return h > 0 ? `${h}h ${m}m` : `${m}m`;
}
function fmtTime(iso: string | null): string {
if (!iso) return '—';
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();
}
export function Printing() {
const { push } = useToast();
const { overview, error, refresh } = usePrintStatus();
const [adding, setAdding] = useState(false);
const [stationName, setStationName] = useState('');
const [creating, setCreating] = useState(false);
const [issuedToken, setIssuedToken] = useState<{ name: string; token: string } | null>(null);
const [copied, setCopied] = useState(false);
const [busyId, setBusyId] = useState<string | number | null>(null);
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState('');
const [renaming, setRenaming] = useState(false);
if (error && !overview) {
return <Empty icon="⚠️" text={error} />;
}
if (!overview) {
return (
<div className="loading-screen">
<Spinner />
</div>
);
}
const stations = overview.stations;
const live = activeStations(overview);
const { queue } = overview;
async function addStation() {
const name = stationName.trim();
if (!name || creating) return;
setCreating(true);
try {
const { token } = await createPrintStation(name);
setIssuedToken({ name, token });
setStationName('');
setAdding(false);
await refresh();
} catch (e) {
push('error', e instanceof Error ? e.message : 'Could not create the station');
} finally {
setCreating(false);
}
}
async function revoke(station: PrintStation) {
if (!confirm(`Revoke "${station.name}"? Its token stops working immediately and the Raspberry Pi can no longer print.`)) return;
setBusyId(station.id);
try {
await revokePrintStation(station.id);
await refresh();
push('success', `Station "${station.name}" revoked`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Revoke failed');
} finally {
setBusyId(null);
}
}
function startRename(station: PrintStation) {
setRenamingId(station.id);
setRenameValue(station.name);
}
function cancelRename() {
setRenamingId(null);
setRenameValue('');
}
async function saveRename(station: PrintStation) {
const name = renameValue.trim();
if (!name || renaming) return;
setRenaming(true);
try {
await renamePrintStation(station.id, name);
await refresh();
push('success', `Station renamed to "${name}"`);
cancelRename();
} catch (e) {
push('error', e instanceof Error ? e.message : 'Rename failed');
} finally {
setRenaming(false);
}
}
async function requeue(dl: PrintDeadLetter) {
setBusyId(dl.msg_id);
try {
await requeueDeadBadgePrint(dl.msg_id);
await refresh();
push('success', 'Job requeued — the station will pick it up');
} catch (e) {
push('error', e instanceof Error ? e.message : 'Requeue failed');
} finally {
setBusyId(null);
}
}
async function discard(dl: PrintDeadLetter) {
if (!confirm(`Discard this dead job${dl.full_name ? ` for ${dl.full_name}` : ''}? It will not be printed.`)) return;
setBusyId(dl.msg_id);
try {
await discardDeadBadgePrint(dl.msg_id);
await refresh();
push('success', 'Dead job discarded');
} catch (e) {
push('error', e instanceof Error ? e.message : 'Discard failed');
} finally {
setBusyId(null);
}
}
async function reprint(job: PrintRecentJob) {
if (!job.registration_id) {
push('error', 'This job has no registration to reprint');
return;
}
setBusyId(job.msg_id);
try {
await enqueueBadgePrint(job.registration_id);
await refresh();
push('success', `Reprint queued for ${job.full_name ?? job.email ?? 'attendee'}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Reprint failed');
} finally {
setBusyId(null);
}
}
async function copyToken() {
if (!issuedToken) return;
try {
await navigator.clipboard.writeText(issuedToken.token);
setCopied(true);
} catch {
push('error', 'Copy failed — select the token and copy it manually');
}
}
return (
<div className="printing">
<div className="page-head">
<div>
<h1>Printing</h1>
<div className="sub">Badge queue and printer stations. {error ? <span className="feedback-error">Status update failed: {error}</span> : null}</div>
</div>
<div className="row" style={{ gap: 10 }}>
{adding ? (
<>
<input
className="input"
style={{ maxWidth: 220 }}
placeholder="Station name…"
value={stationName}
autoFocus
onChange={(e) => setStationName(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addStation()}
/>
<button className="btn primary small" disabled={!stationName.trim() || creating} onClick={addStation}>
{creating ? 'Creating…' : 'Create'}
</button>
<button className="btn small" onClick={() => { setAdding(false); setStationName(''); }}>
Cancel
</button>
</>
) : (
<button className="btn" onClick={() => setAdding(true)}>+ Add station</button>
)}
</div>
</div>
<div className="print-counters">
<div className="card print-counter"><div className="n">{queue.pending}</div><div className="l">pending</div></div>
<div className="card print-counter"><div className="n">{queue.in_flight}</div><div className="l">in progress</div></div>
<div className="card print-counter"><div className="n">{queue.completed}</div><div className="l">done</div></div>
<div className="card print-counter"><div className="n">{queue.dead_letter}</div><div className="l">dead letter</div></div>
</div>
<div className="section-head"><h2 className="h2">Stations</h2></div>
{live.length === 0 && stations.length === 0 && (
<div className="card">
<Empty icon="🖨️" text='No printer stations yet. Add one, then put its token on the Raspberry Pi.' />
</div>
)}
{live.length === 0 && stations.length > 0 && (
<div className="card"><Empty icon="🖨️" text='All stations are revoked. Add a station to print again.' /></div>
)}
{live.map((s) => {
const st = s.last_status;
const hint = printerHint(s);
const printer = st?.printer;
const roll = printer?.label_id
? `${printer.label_id}${printer.media_type ? ` · ${printer.media_type}` : ''}${
printer.media_width_mm ? ` · ${printer.media_width_mm}×${printer.media_length_mm ?? '∞'} mm` : ''
}`
: '—';
return (
<div className="card print-station" key={s.id} data-testid={`station-${s.id}`}>
<div className="row between" style={{ flexWrap: 'wrap', gap: 8 }}>
<div className="row" style={{ gap: 10 }}>
{renamingId === s.id ? (
<span className="row" style={{ gap: 8 }}>
<input
className="input"
style={{ maxWidth: 220 }}
aria-label="Station name"
value={renameValue}
autoFocus
onChange={(e) => setRenameValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void saveRename(s);
if (e.key === 'Escape') cancelRename();
}}
/>
<button className="btn primary small" disabled={!renameValue.trim() || renaming} onClick={() => void saveRename(s)}>
{renaming ? 'Saving…' : 'Save'}
</button>
<button className="btn small" disabled={renaming} onClick={cancelRename}>
Cancel
</button>
</span>
) : (
<>
<strong>{s.name}</strong>
<span className={`pill ${STATE_PILL[s.state]}`}>{STATE_LABEL[s.state]}</span>
</>
)}
</div>
<div className="row" style={{ gap: 10 }}>
<span className="muted small">last seen {timeAgo(s.last_seen_at)} ago</span>
{renamingId !== s.id && (
<button className="btn small" disabled={busyId === s.id || renaming} onClick={() => startRename(s)}>
Rename
</button>
)}
<button className="btn danger small" disabled={busyId === s.id} onClick={() => revoke(s)}>
Revoke
</button>
</div>
</div>
{hint && <div className="print-hint" role="note">{hint}</div>}
<dl className="print-details">
<div><dt>Worker</dt><dd>{st?.worker ?? '—'}</dd></div>
<div><dt>Current job</dt><dd>{st?.job_msg_id ? `#${st.job_msg_id}` : '—'}</dd></div>
<div><dt>Printer</dt><dd>{printer?.model ?? '—'}</dd></div>
<div><dt>Roll</dt><dd>{roll}</dd></div>
<div>
<dt>Errors</dt>
<dd>{printer?.errors?.length ? printer.errors.join(' · ') : '—'}</dd>
</div>
<div>
<dt>Network</dt>
<dd>{st?.network ? `${st.network.state ?? '—'}${st.network.ssid ? ` · ${st.network.ssid}` : ''}${st.network.ip ? ` · ${st.network.ip}` : ''}` : '—'}</dd>
</div>
<div><dt>Version</dt><dd>{st?.version ?? '—'}</dd></div>
<div><dt>Uptime</dt><dd>{fmtUptime(st?.uptime_s)}</dd></div>
<div><dt>Last error</dt><dd className="print-last-error">{st?.last_error ?? '—'}</dd></div>
</dl>
</div>
);
})}
{stations.filter((s) => s.state === 'revoked').map((s) => (
<div className="card print-station revoked" key={s.id}>
<div className="row between">
<div className="row" style={{ gap: 10 }}>
<strong>{s.name}</strong>
<span className="pill attendee">revoked</span>
</div>
<span className="muted small">revoked {fmtTime(s.revoked_at)}</span>
</div>
</div>
))}
<div className="section-head"><h2 className="h2">Dead letters</h2></div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Attendee</th>
<th>Event</th>
<th>Error</th>
<th>Attempts</th>
<th>Failed at</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{overview.dead_letters.map((dl) => (
<tr key={dl.msg_id}>
<td>
<div className="cell-person">
<div>
<div className="n">{dl.full_name ?? '—'}</div>
<div className="e">{dl.email ?? ''}</div>
</div>
</div>
</td>
<td>{dl.event_name ?? '—'}</td>
<td className="small">{dl.error ?? '—'}</td>
<td>{dl.attempts ?? '—'}</td>
<td className="muted small">{fmtTime(dl.failed_at)}</td>
<td style={{ textAlign: 'right' }}>
<div className="row" style={{ gap: 8, justifyContent: 'flex-end' }}>
<button className="btn small" disabled={busyId === dl.msg_id} onClick={() => requeue(dl)}>
Requeue
</button>
<button className="btn danger small" disabled={busyId === dl.msg_id} onClick={() => discard(dl)}>
Discard
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{overview.dead_letters.length === 0 && (
<div style={{ padding: 16 }}><Empty icon="✅" text="No failed jobs — everything printed or is still queued." /></div>
)}
</div>
<div className="section-head"><h2 className="h2">Recently printed</h2></div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Attendee</th>
<th>Kind</th>
<th>Time</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{overview.recent.map((job) => (
<tr key={job.msg_id}>
<td>
<div className="cell-person">
<div>
<div className="n">{job.full_name ?? '—'}</div>
<div className="e">{job.email ?? ''}</div>
</div>
</div>
</td>
<td><span className="pill">{kindLabel(job.kind)}</span></td>
<td className="muted small">{fmtTime(job.archived_at)}</td>
<td style={{ textAlign: 'right' }}>
<button className="btn small" disabled={busyId === job.msg_id || !job.registration_id} onClick={() => reprint(job)}>
Reprint
</button>
</td>
</tr>
))}
</tbody>
</table>
{overview.recent.length === 0 && (
<div style={{ padding: 16 }}><Empty icon="🖨️" text="Nothing has been printed yet." /></div>
)}
</div>
{issuedToken && (
<Modal
open
title={`Station token — ${issuedToken.name}`}
onClose={() => { setIssuedToken(null); setCopied(false); }}
footer={
<button className="btn primary" onClick={() => { setIssuedToken(null); setCopied(false); }}>
Done
</button>
}
>
<p className="feedback-error" style={{ fontWeight: 700 }}>
Store it in the Raspberry Pi setup now — it cannot be shown again.
</p>
<div className="row" style={{ gap: 8 }}>
<input className="input mono" readOnly value={issuedToken.token} onFocus={(e) => e.target.select()} aria-label="Station token" />
<button className="btn" onClick={copyToken}>{copied ? 'Copied' : 'Copy'}</button>
</div>
</Modal>
)}
</div>
);
}