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
This commit is contained in:
1 parent
04f3f55b78
commit
c980effddc
55 files changed
+7406
-29
No files matched your search
@@ -16,6 +16,7 @@ import type {
|
||||
PointsLogRow,
|
||||
PretixOptions,
|
||||
PretixSyncResult,
|
||||
PrintOverview,
|
||||
RafflePoolEntry,
|
||||
RaffleWinner,
|
||||
Registration,
|
||||
@@ -491,3 +492,34 @@ export const generateFeedbackSummary = (eventId: string, sessionId?: string) =>
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ event_id: eventId, scope: sessionId ? 'session' : 'event', ...(sessionId ? { session_id: sessionId } : {}) }),
|
||||
});
|
||||
|
||||
// ---- Badge printing (queue + printer stations) -------------------------------
|
||||
|
||||
/** Admin dashboard snapshot: stations, queue counters, recent jobs, dead letters. */
|
||||
export const getPrintOverview = () => rpc<PrintOverview>('get_print_overview', {});
|
||||
|
||||
/** Queue one attendee's badge for printing; resolves with the queue msg id. */
|
||||
export const enqueueBadgePrint = (registrationId: string) =>
|
||||
rpc<number>('enqueue_badge_print', { p_registration_id: registrationId });
|
||||
|
||||
/** Register a printer station. The token is returned only here, never again. */
|
||||
export async function createPrintStation(name: string): Promise<{ id: string; token: string }> {
|
||||
// create_print_station returns a one-row table (a JSON array of one object).
|
||||
const rows = await rpc<{ id: string; token: string }[]>('create_print_station', { p_name: name });
|
||||
if (!rows[0]) throw new ApiError('Station creation returned no token');
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
/** Retire a station; its token stops working immediately. */
|
||||
export const revokePrintStation = (id: string) => rpc<void>('revoke_print_station', { p_id: id });
|
||||
|
||||
/** Rename a station (revoked ones included); the Pi adopts the new name. */
|
||||
export const renamePrintStation = (id: string, name: string) =>
|
||||
rpc<void>('rename_print_station', { p_id: id, p_name: name });
|
||||
|
||||
/** Push a dead letter back onto the live queue; resolves with the new msg id. */
|
||||
export const requeueDeadBadgePrint = (msgId: number) =>
|
||||
rpc<number>('requeue_dead_badge_print', { p_msg_id: msgId });
|
||||
|
||||
/** Drop a dead letter without retrying it. */
|
||||
export const discardDeadBadgePrint = (msgId: number) => rpc<void>('discard_dead_badge_print', { p_msg_id: msgId });
|
||||
@@ -0,0 +1,136 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { getPrintOverview } from './api';
|
||||
import type { PrintOverview, PrintStation, PrintStationState } from './types';
|
||||
|
||||
const POLL_MS = 5000;
|
||||
|
||||
interface PrintStatusState {
|
||||
overview: PrintOverview | null;
|
||||
error: string | null;
|
||||
refresh: () => Promise<void>;
|
||||
}
|
||||
|
||||
const PrintStatusContext = createContext<PrintStatusState | null>(null);
|
||||
|
||||
/**
|
||||
* Single shared poller for the badge-print overview, mounted once for the
|
||||
* authenticated admin shell. Polls every 5 s while the document is visible,
|
||||
* pauses when hidden and refreshes immediately on visibilitychange. A failing
|
||||
* poll keeps the last overview and only exposes the error.
|
||||
*/
|
||||
export function PrintStatusProvider({ children }: { children: ReactNode }) {
|
||||
const [overview, setOverview] = useState<PrintOverview | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const inflight = useRef(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (inflight.current) return;
|
||||
inflight.current = true;
|
||||
try {
|
||||
const data = await getPrintOverview();
|
||||
setOverview(data);
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Printer status unavailable');
|
||||
} finally {
|
||||
inflight.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const tick = () => {
|
||||
if (!cancelled && document.visibilityState === 'visible') void refresh();
|
||||
};
|
||||
tick();
|
||||
const timer = window.setInterval(tick, POLL_MS);
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === 'visible') void refresh();
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearInterval(timer);
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [refresh]);
|
||||
|
||||
return <PrintStatusContext.Provider value={{ overview, error, refresh }}>{children}</PrintStatusContext.Provider>;
|
||||
}
|
||||
|
||||
export function usePrintStatus(): PrintStatusState {
|
||||
const ctx = useContext(PrintStatusContext);
|
||||
if (!ctx) throw new Error('usePrintStatus must be used within PrintStatusProvider');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// ---- Pure helpers (shared by the pill, the Printing view and Registrations) --
|
||||
|
||||
/** Stations that can still print; revoked ones are ignored everywhere. */
|
||||
export function activeStations(overview: PrintOverview | null): PrintStation[] {
|
||||
return (overview?.stations ?? []).filter((s) => s.state !== 'revoked' && !s.revoked_at);
|
||||
}
|
||||
|
||||
// Worst-state wins for the aggregated pill: error > offline > printing > ready.
|
||||
const SEVERITY: PrintStationState[] = ['error', 'offline', 'printing', 'ready'];
|
||||
|
||||
export function aggregateState(stations: PrintStation[]): PrintStationState | 'none' {
|
||||
for (const state of SEVERITY) if (stations.some((s) => s.state === state)) return state;
|
||||
return 'none';
|
||||
}
|
||||
|
||||
/** The station whose state drives the pill. */
|
||||
export function worstStation(stations: PrintStation[]): PrintStation | null {
|
||||
const state = aggregateState(stations);
|
||||
return stations.find((s) => s.state === state) ?? null;
|
||||
}
|
||||
|
||||
/** Compact age for last_seen_at: "45 s", "2 min", "3 h", "1 d". */
|
||||
export function timeAgo(iso: string | null | undefined): string {
|
||||
if (!iso) return 'never';
|
||||
const secs = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 1000));
|
||||
if (secs < 60) return `${secs} s`;
|
||||
const mins = Math.floor(secs / 60);
|
||||
if (mins < 60) return `${mins} min`;
|
||||
const hours = Math.floor(mins / 60);
|
||||
if (hours < 24) return `${hours} h`;
|
||||
return `${Math.floor(hours / 24)} d`;
|
||||
}
|
||||
|
||||
/** Trim Brother error strings to their core: 'No media when printing' → 'No media'. */
|
||||
export function shortError(err: string): string {
|
||||
return err.replace(/\s+when\s+printing/i, '').replace(/\s*\(.*\)\s*$/, '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Staff-facing instruction for a station's current problem ('' when fine).
|
||||
* The Pi has no screen, so this text is the only channel to the operator.
|
||||
*/
|
||||
export function printerHint(station: PrintStation): string {
|
||||
const st = station.last_status;
|
||||
const wifiHint = () => {
|
||||
const ssid = st?.network?.ssid?.trim();
|
||||
const network = ssid ? `“${ssid}”` : '“Convivo-Printer-XXXX”';
|
||||
return `The printer is not reachable. If it moved to a new Wi-Fi network, connect a phone to the open Wi-Fi ${network} and open http://10.41.0.1 to choose the network. Otherwise check the Raspberry Pi power.`;
|
||||
};
|
||||
if (station.state === 'offline') return wifiHint();
|
||||
if (station.state === 'error') {
|
||||
const printer = st?.printer;
|
||||
if (printer && printer.connected === false) {
|
||||
return 'Printer not detected — check the USB cable and that the printer is switched on.';
|
||||
}
|
||||
const errors = printer?.errors ?? [];
|
||||
for (const err of errors) {
|
||||
if (/wrong roll/i.test(err)) return err;
|
||||
if (/cover open/i.test(err)) return 'Close the printer cover.';
|
||||
if (/media/i.test(err)) return 'Load a new label roll.';
|
||||
if (/cutter jam/i.test(err)) return 'Clear the cutter jam.';
|
||||
}
|
||||
if (errors.length > 0) return errors.join(' · ');
|
||||
if (st?.last_error) return st.last_error;
|
||||
return 'The printer reports a problem — check the station card below.';
|
||||
}
|
||||
// HOTSPOT on a live heartbeat means the Pi just lost its network.
|
||||
if (st?.network?.state === 'HOTSPOT') return wifiHint();
|
||||
return '';
|
||||
}
|
||||
@@ -431,4 +431,104 @@ export interface BadgeSample {
|
||||
qr_token: string;
|
||||
event_name: string;
|
||||
company: string;
|
||||
/** Origin used to build check-in URLs; defaults to the current page origin. */
|
||||
checkin_origin?: string;
|
||||
}
|
||||
|
||||
/** The payload handed to the standalone print renderer (`window.renderBadge`). */
|
||||
export interface BadgePrintPayload {
|
||||
schema: 'convivo.badge-print/v1';
|
||||
kind: 'checkin' | 'reprint';
|
||||
requested_at: string;
|
||||
requested_by: string | null;
|
||||
event: { id: string; name: string; company: string | null };
|
||||
registration: { id: string; email: string; type: string };
|
||||
sample: BadgeSample;
|
||||
layout: {
|
||||
id: string;
|
||||
name: string;
|
||||
page_width_mm: number;
|
||||
page_height_mm: number;
|
||||
elements: BadgeElement[];
|
||||
};
|
||||
}
|
||||
|
||||
// ---- Badge printing (queue + stations, `get_print_overview`) ----------------
|
||||
|
||||
/** Derived station state (`get_print_overview` computes it server-side). */
|
||||
export type PrintStationState = 'ready' | 'printing' | 'error' | 'offline' | 'revoked';
|
||||
|
||||
/** The `last_status` heartbeat the Raspberry Pi worker writes every 10 s. */
|
||||
export interface PrintStationStatus {
|
||||
version?: string;
|
||||
station_name?: string;
|
||||
worker?: 'starting' | 'idle' | 'printing' | 'paused';
|
||||
job_msg_id?: number | null;
|
||||
printer?: {
|
||||
connected?: boolean;
|
||||
model?: string | null;
|
||||
ready?: boolean;
|
||||
media_type?: 'die-cut' | 'continuous' | null;
|
||||
label_id?: string | null;
|
||||
media_width_mm?: number | null;
|
||||
media_length_mm?: number | null;
|
||||
errors?: string[];
|
||||
};
|
||||
network?: {
|
||||
state?: 'CONNECTED' | 'CONNECTING' | 'HOTSPOT' | 'UNKNOWN';
|
||||
ssid?: string | null;
|
||||
ip?: string | null;
|
||||
};
|
||||
label?: string | null;
|
||||
last_error?: string | null;
|
||||
uptime_s?: number;
|
||||
}
|
||||
|
||||
export interface PrintStation {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
revoked_at: string | null;
|
||||
last_seen_at: string | null;
|
||||
last_status: PrintStationStatus | null;
|
||||
state: PrintStationState;
|
||||
}
|
||||
|
||||
export interface PrintQueueCounts {
|
||||
pending: number;
|
||||
in_flight: number;
|
||||
dead_letter: number;
|
||||
completed: number;
|
||||
}
|
||||
|
||||
/** A completed (archived) badge job, newest first. */
|
||||
export interface PrintRecentJob {
|
||||
msg_id: number;
|
||||
archived_at: string;
|
||||
kind: 'checkin' | 'reprint' | string;
|
||||
full_name: string | null;
|
||||
email: string | null;
|
||||
event_name: string | null;
|
||||
registration_id: string | null;
|
||||
}
|
||||
|
||||
/** A job that kept failing and was moved to the dead letter queue. */
|
||||
export interface PrintDeadLetter {
|
||||
msg_id: number;
|
||||
enqueued_at: string;
|
||||
failed_at: string | null;
|
||||
error: string | null;
|
||||
attempts: string | number | null;
|
||||
kind: 'checkin' | 'reprint' | string;
|
||||
full_name: string | null;
|
||||
email: string | null;
|
||||
event_name: string | null;
|
||||
registration_id: string | null;
|
||||
}
|
||||
|
||||
export interface PrintOverview {
|
||||
stations: PrintStation[];
|
||||
queue: PrintQueueCounts;
|
||||
recent: PrintRecentJob[];
|
||||
dead_letters: PrintDeadLetter[];
|
||||
}
|
||||
Reference in new issue
Block a user