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]>
This commit is contained in:
1 parent
0f3720d48a
commit
00c89c1b48
55 files changed
+7406
-29
No files matched your search
@@ -5,6 +5,7 @@ node_modules/
|
|||||||
dist/
|
dist/
|
||||||
build/
|
build/
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
|
apps/admin/dist-print/
|
||||||
|
|
||||||
# Generated types (regenerate with `npm run db:types`)
|
# Generated types (regenerate with `npm run db:types`)
|
||||||
packages/shared/src/database.types.ts
|
packages/shared/src/database.types.ts
|
||||||
@@ -15,6 +16,10 @@ packages/shared/src/database.types.ts
|
|||||||
!.env.example
|
!.env.example
|
||||||
SMTP.md
|
SMTP.md
|
||||||
|
|
||||||
|
# Printer Pi: filled setup (station token) + exported worker image
|
||||||
|
apps/printer/pi/setup.local.sh
|
||||||
|
apps/printer/pi/*.tar.gz
|
||||||
|
|
||||||
# Supabase CLI local state (generated on `supabase start`)
|
# Supabase CLI local state (generated on `supabase start`)
|
||||||
supabase/.temp/
|
supabase/.temp/
|
||||||
supabase/.branches/
|
supabase/.branches/
|
||||||
@@ -37,3 +42,7 @@ e2e/node_modules/
|
|||||||
e2e/reports/
|
e2e/reports/
|
||||||
e2e/test-results/
|
e2e/test-results/
|
||||||
test-results/
|
test-results/
|
||||||
|
|
||||||
|
# Python bytecode
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
Generated
+55
@@ -16,6 +16,11 @@
|
|||||||
"react-dom": "^18.3.1"
|
"react-dom": "^18.3.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@fontsource/arimo": "^5.3.0",
|
||||||
|
"@fontsource/cousine": "^5.3.0",
|
||||||
|
"@fontsource/gelasio": "^5.3.0",
|
||||||
|
"@fontsource/open-sans": "^5.3.0",
|
||||||
|
"@fontsource/tinos": "^5.3.0",
|
||||||
"@types/canvas-confetti": "1.6.4",
|
"@types/canvas-confetti": "1.6.4",
|
||||||
"@types/react": "^18.3.5",
|
"@types/react": "^18.3.5",
|
||||||
"@types/react-dom": "^18.3.0",
|
"@types/react-dom": "^18.3.0",
|
||||||
@@ -697,6 +702,56 @@
|
|||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@fontsource/arimo": {
|
||||||
|
"version": "5.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@fontsource/arimo/-/arimo-5.3.0.tgz",
|
||||||
|
"integrity": "sha512-nhxZ2sTVZYX8DJBgLuyX360B5vE4mxqpmjlKTRfucIqfcWRVx9vOYzWBc1IgEX0ist48VMC10PRKbFyH+4QFvQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "OFL-1.1",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ayuhito"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@fontsource/cousine": {
|
||||||
|
"version": "5.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@fontsource/cousine/-/cousine-5.3.0.tgz",
|
||||||
|
"integrity": "sha512-EhVes1KpHrmPwGVCoVxYpdiIi/L2LRGxbAuv07m3TdY76f9Vmwyhd/TNqi2RC0NOvMCNt2FtYPJcAfFfkK9DoQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "OFL-1.1",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ayuhito"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@fontsource/gelasio": {
|
||||||
|
"version": "5.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@fontsource/gelasio/-/gelasio-5.3.0.tgz",
|
||||||
|
"integrity": "sha512-V95Jr9GxtSCkigiWKEDTIqajefhJHk8251aQYrMBmrdSeYnjgbKRYxLjGpr3/NjpOAf2bejIiZPwtzJ9Bcpsgw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "OFL-1.1",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ayuhito"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@fontsource/open-sans": {
|
||||||
|
"version": "5.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@fontsource/open-sans/-/open-sans-5.3.0.tgz",
|
||||||
|
"integrity": "sha512-V1bdMlGNyZrJwzrdusshMOw2YR0aqYDL7kOo9dkxUEKl8dFv66A9HLckOOXl572sG/7ohhDQrCrTFGSn9LZcSw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "OFL-1.1",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ayuhito"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@fontsource/tinos": {
|
||||||
|
"version": "5.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@fontsource/tinos/-/tinos-5.3.0.tgz",
|
||||||
|
"integrity": "sha512-VVDyyZdbcsLKxo/W7rClAvacD/7DsGc7J5xzzp51Tndib8kDkEe/0bqbb3Xb3iH6+IUjt07aRsvtQ9MGeGGi4w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "OFL-1.1",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ayuhito"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@jridgewell/gen-mapping": {
|
"node_modules/@jridgewell/gen-mapping": {
|
||||||
"version": "0.3.13",
|
"version": "0.3.13",
|
||||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
|
"build:print": "vite build --config vite.print.config.ts",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -17,6 +18,11 @@
|
|||||||
"react-dom": "^18.3.1"
|
"react-dom": "^18.3.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@fontsource/arimo": "^5.3.0",
|
||||||
|
"@fontsource/cousine": "^5.3.0",
|
||||||
|
"@fontsource/gelasio": "^5.3.0",
|
||||||
|
"@fontsource/open-sans": "^5.3.0",
|
||||||
|
"@fontsource/tinos": "^5.3.0",
|
||||||
"@types/canvas-confetti": "1.6.4",
|
"@types/canvas-confetti": "1.6.4",
|
||||||
"@types/react": "^18.3.5",
|
"@types/react": "^18.3.5",
|
||||||
"@types/react-dom": "^18.3.0",
|
"@types/react-dom": "^18.3.0",
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Convivo badge print renderer</title>
|
||||||
|
<style>
|
||||||
|
/* Tiny reset: the screenshot must be the pure badge, no editor chrome. */
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
html, body, #badge-root { background: #fff; }
|
||||||
|
#badge-root .badge-page { box-shadow: none !important; border: 0 !important; border-radius: 0 !important; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="badge-root"></div>
|
||||||
|
<script type="module" src="/src/print/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -10,12 +10,15 @@ import { Schedule } from './views/Schedule';
|
|||||||
import { Activity } from './views/Activity';
|
import { Activity } from './views/Activity';
|
||||||
import { Raffle } from './views/Raffle';
|
import { Raffle } from './views/Raffle';
|
||||||
import { BadgeEditor } from './views/BadgeEditor';
|
import { BadgeEditor } from './views/BadgeEditor';
|
||||||
|
import { Printing } from './views/Printing';
|
||||||
import { Events } from './views/Events';
|
import { Events } from './views/Events';
|
||||||
import { Interfaces } from './views/Interfaces';
|
import { Interfaces } from './views/Interfaces';
|
||||||
import { Reports } from './views/Reports';
|
import { Reports } from './views/Reports';
|
||||||
import { Settings } from './views/Settings';
|
import { Settings } from './views/Settings';
|
||||||
import { Settings as SettingsIcon } from 'lucide-react';
|
import { Settings as SettingsIcon } from 'lucide-react';
|
||||||
import { Spinner } from './components/ui';
|
import { Spinner } from './components/ui';
|
||||||
|
import { PrinterStatusPill } from './components/PrinterStatusPill';
|
||||||
|
import { PrintStatusProvider } from './lib/printStatus';
|
||||||
|
|
||||||
export type View =
|
export type View =
|
||||||
| 'dashboard'
|
| 'dashboard'
|
||||||
@@ -26,6 +29,7 @@ export type View =
|
|||||||
| 'activity'
|
| 'activity'
|
||||||
| 'raffle'
|
| 'raffle'
|
||||||
| 'badges'
|
| 'badges'
|
||||||
|
| 'printing'
|
||||||
| 'events'
|
| 'events'
|
||||||
| 'interfaces'
|
| 'interfaces'
|
||||||
| 'reports'
|
| 'reports'
|
||||||
@@ -40,6 +44,7 @@ const NAV: { id: View; label: string; ico: string }[] = [
|
|||||||
{ id: 'activity', label: 'Activity', ico: '⚡' },
|
{ id: 'activity', label: 'Activity', ico: '⚡' },
|
||||||
{ id: 'raffle', label: 'Raffle', ico: '🎯' },
|
{ id: 'raffle', label: 'Raffle', ico: '🎯' },
|
||||||
{ id: 'badges', label: 'Badges', ico: '🎫' },
|
{ id: 'badges', label: 'Badges', ico: '🎫' },
|
||||||
|
{ id: 'printing', label: 'Printing', ico: '🖨️' },
|
||||||
{ id: 'events', label: 'Events', ico: '📅' },
|
{ id: 'events', label: 'Events', ico: '📅' },
|
||||||
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
|
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
|
||||||
{ id: 'reports', label: 'Reports', ico: '📤' },
|
{ id: 'reports', label: 'Reports', ico: '📤' },
|
||||||
@@ -61,6 +66,7 @@ function Shell() {
|
|||||||
if (!contact) return <Login />;
|
if (!contact) return <Login />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<PrintStatusProvider>
|
||||||
<div className="app">
|
<div className="app">
|
||||||
<aside className="sidebar">
|
<aside className="sidebar">
|
||||||
<div className="brand">
|
<div className="brand">
|
||||||
@@ -82,6 +88,8 @@ function Shell() {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</nav>
|
</nav>
|
||||||
|
{/* Outside .sidebar-foot so it also shows on mobile (the Pi has no screen). */}
|
||||||
|
<PrinterStatusPill onNavigate={setView} />
|
||||||
<div className="sidebar-foot">
|
<div className="sidebar-foot">
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<span className="avatar" style={{ width: 36, height: 36, fontSize: 13, background: '#d50000' }}>
|
<span className="avatar" style={{ width: 36, height: 36, fontSize: 13, background: '#d50000' }}>
|
||||||
@@ -112,12 +120,14 @@ function Shell() {
|
|||||||
{view === 'activity' && <Activity />}
|
{view === 'activity' && <Activity />}
|
||||||
{view === 'raffle' && <Raffle />}
|
{view === 'raffle' && <Raffle />}
|
||||||
{view === 'badges' && <BadgeEditor />}
|
{view === 'badges' && <BadgeEditor />}
|
||||||
|
{view === 'printing' && <Printing />}
|
||||||
{view === 'events' && <Events />}
|
{view === 'events' && <Events />}
|
||||||
{view === 'interfaces' && <Interfaces />}
|
{view === 'interfaces' && <Interfaces />}
|
||||||
{view === 'reports' && <Reports />}
|
{view === 'reports' && <Reports />}
|
||||||
{view === 'settings' && <Settings />}
|
{view === 'settings' && <Settings />}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
</PrintStatusProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { QRCodeSVG } from 'qrcode.react';
|
import { QRCodeSVG } from 'qrcode.react';
|
||||||
import type { BadgeElement, BadgeQrElement, BadgeSample, BadgeTextElement } from '../lib/types';
|
import type { BadgeElement, BadgeQrElement, BadgeSample, BadgeTextElement } from '../lib/types';
|
||||||
|
import './badge-render.css';
|
||||||
|
|
||||||
// CSS 96 dpi: 1mm = 3.7795px. Shared by the editor canvas and read-only previews.
|
// CSS 96 dpi: 1mm = 3.7795px. Shared by the editor canvas and read-only previews.
|
||||||
export const MM = 3.7795275591;
|
export const MM = 3.7795275591;
|
||||||
@@ -45,7 +46,7 @@ export function resolveText(el: BadgeTextElement, sample: BadgeSample): string {
|
|||||||
export function resolveQr(el: BadgeQrElement, sample: BadgeSample): string {
|
export function resolveQr(el: BadgeQrElement, sample: BadgeSample): string {
|
||||||
switch (el.value) {
|
switch (el.value) {
|
||||||
case 'qr_token': return sample.qr_token || 'CONVIVO-QR';
|
case 'qr_token': return sample.qr_token || 'CONVIVO-QR';
|
||||||
case 'checkin_url': return `${window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`;
|
case 'checkin_url': return `${sample.checkin_origin ?? window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`;
|
||||||
case 'email': return sample.email || '[email protected]';
|
case 'email': return sample.email || '[email protected]';
|
||||||
case 'attendee_name': return sample.full_name || 'Attendee';
|
case 'attendee_name': return sample.full_name || 'Attendee';
|
||||||
default: return el.static_value || 'https://example.com';
|
default: return el.static_value || 'https://example.com';
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import type { View } from '../App';
|
||||||
|
import { Tooltip } from './ui';
|
||||||
|
import { activeStations, aggregateState, printerHint, timeAgo, shortError, usePrintStatus, worstStation } from '../lib/printStatus';
|
||||||
|
import type { PrintStation, PrintStationState } from '../lib/types';
|
||||||
|
|
||||||
|
// Pill label per aggregated state; the worst station refines error/offline text.
|
||||||
|
function pillText(state: PrintStationState | 'none', station: PrintStation | null): string {
|
||||||
|
if (state === 'none') return 'No printer';
|
||||||
|
if (state === 'ready') return 'Printer ready';
|
||||||
|
if (state === 'printing') return 'Printing…';
|
||||||
|
if (state === 'offline') return `Printer offline · ${timeAgo(station?.last_seen_at)}`;
|
||||||
|
const err = station?.last_status?.printer?.errors?.[0];
|
||||||
|
return err ? `Printer: ${shortError(err)}` : 'Printer error';
|
||||||
|
}
|
||||||
|
|
||||||
|
function tooltipContent(stations: PrintStation[]): string {
|
||||||
|
return stations
|
||||||
|
.map((s) => {
|
||||||
|
const st = s.last_status;
|
||||||
|
const roll = st?.printer?.label_id ?? 'unknown roll';
|
||||||
|
const net = st?.network;
|
||||||
|
const netText = net?.ssid ? `${net.ssid}${net.ip ? ` · ${net.ip}` : ''}` : net?.state ?? 'unknown';
|
||||||
|
const hint = printerHint(s);
|
||||||
|
return `${s.name} (${s.state}) — roll: ${roll} · network: ${netText} · last seen: ${timeAgo(s.last_seen_at)}${hint ? ` · ${hint}` : ''}`;
|
||||||
|
})
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Always-visible printer status for the sidebar (desktop and mobile). The Pi
|
||||||
|
* has no screen, so staff must see the printer state from every admin view.
|
||||||
|
*/
|
||||||
|
export function PrinterStatusPill({ onNavigate }: { onNavigate: (view: View) => void }) {
|
||||||
|
const { overview } = usePrintStatus();
|
||||||
|
const stations = activeStations(overview);
|
||||||
|
const state = aggregateState(stations);
|
||||||
|
const station = worstStation(stations);
|
||||||
|
const label = pillText(state, station);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tooltip title="Printer status" content={<span style={{ whiteSpace: 'pre-line' }}>{tooltipContent(stations)}</span>}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`printer-pill ${state}`}
|
||||||
|
data-testid="printer-pill"
|
||||||
|
data-state={state}
|
||||||
|
onClick={() => onNavigate('printing')}
|
||||||
|
>
|
||||||
|
<span className="printer-pill-dot" aria-hidden="true" />
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,586 @@
|
|||||||
|
/*
|
||||||
|
* Badge rendering: the read-only badge rules shared by the admin preview and the
|
||||||
|
* standalone print renderer (apps/admin/print.html). Imported by BadgeRender.tsx,
|
||||||
|
* so the admin app loads this before styles.css.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Bundled fonts. The editor family names below are the ones BadgeEditor offers;
|
||||||
|
each maps to an open-licensed metric-compatible face so rendering never depends
|
||||||
|
on the fonts installed on the viewer's OS (admin laptop vs. the Pi). */
|
||||||
|
/* Open Sans latin 400 normal (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 400 normal (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin 700 normal (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 700 normal (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin 400 italic (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 400 italic (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin 700 italic (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 700 italic (editor family "Open Sans") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Open Sans';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 400 normal (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 400 normal (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 700 normal (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 700 normal (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 400 italic (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 400 italic (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 700 italic (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 700 italic (editor family "Helvetica") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 400 normal (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 400 normal (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 700 normal (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 700 normal (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 400 italic (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 400 italic (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin 700 italic (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arimo latin-ext 700 italic (editor family "Arial") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Arial';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/arimo/files/arimo-latin-ext-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin 400 normal (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin-ext 400 normal (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-ext-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin 700 normal (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin-ext 700 normal (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-ext-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin 400 italic (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin-ext 400 italic (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-ext-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin 700 italic (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gelasio latin-ext 700 italic (editor family "Georgia") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Georgia';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/gelasio/files/gelasio-latin-ext-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin 400 normal (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin-ext 400 normal (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-ext-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin 700 normal (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin-ext 700 normal (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-ext-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin 400 italic (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin-ext 400 italic (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-ext-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin 700 italic (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tinos latin-ext 700 italic (editor family "Times New Roman") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Times New Roman';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/tinos/files/tinos-latin-ext-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin 400 normal (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin-ext 400 normal (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-ext-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin 700 normal (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin-ext 700 normal (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-ext-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin 400 italic (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin-ext 400 italic (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-ext-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin 700 italic (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cousine latin-ext 700 italic (editor family "Courier New") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Courier New';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/cousine/files/cousine-latin-ext-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin 400 normal (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 400 normal (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin 700 normal (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 700 normal (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-normal.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin 400 italic (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 400 italic (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin 700 italic (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Open Sans latin-ext 700 italic (editor family "system-ui") */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'system-ui';
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-display: block;
|
||||||
|
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-italic.woff2) format('woff2');
|
||||||
|
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- badge page (read-only rendering) ---------- */
|
||||||
|
.badge-page {
|
||||||
|
position: relative; background: #fff; flex: none;
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
.badge-page-static { flex: none; }
|
||||||
|
.badge-el { position: absolute; overflow: visible; }
|
||||||
|
.badge-text-body { width: 100%; height: 100%; display: flex; overflow: hidden; }
|
||||||
|
.badge-text-body > span { width: 100%; overflow-wrap: anywhere; }
|
||||||
|
.badge-el-placeholder { color: #cbd5e1; font-style: italic; }
|
||||||
|
.badge-qr-body { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
|
||||||
|
.badge-qr-body svg { width: 100%; height: 100%; }
|
||||||
|
.badge-image-body { width: 100%; height: 100%; display: block; }
|
||||||
|
.badge-image-empty {
|
||||||
|
display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 12px;
|
||||||
|
border: 1px dashed #cbd5e1; background: #f8fafc;
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import type {
|
|||||||
PointsLogRow,
|
PointsLogRow,
|
||||||
PretixOptions,
|
PretixOptions,
|
||||||
PretixSyncResult,
|
PretixSyncResult,
|
||||||
|
PrintOverview,
|
||||||
RafflePoolEntry,
|
RafflePoolEntry,
|
||||||
RaffleWinner,
|
RaffleWinner,
|
||||||
Registration,
|
Registration,
|
||||||
@@ -491,3 +492,34 @@ export const generateFeedbackSummary = (eventId: string, sessionId?: string) =>
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ event_id: eventId, scope: sessionId ? 'session' : 'event', ...(sessionId ? { session_id: sessionId } : {}) }),
|
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;
|
qr_token: string;
|
||||||
event_name: string;
|
event_name: string;
|
||||||
company: 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[];
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { flushSync } from 'react-dom';
|
||||||
|
import { createRoot, type Root } from 'react-dom/client';
|
||||||
|
import { BadgePagePreview, MM } from '../components/BadgeRender';
|
||||||
|
import type { BadgePrintPayload } from '../lib/types';
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
/** Render one badge; resolves with its size in CSS pixels. */
|
||||||
|
renderBadge: (
|
||||||
|
payload: BadgePrintPayload,
|
||||||
|
options?: { checkinOrigin?: string },
|
||||||
|
) => Promise<{ width_px: number; height_px: number }>;
|
||||||
|
__badgeReady: boolean;
|
||||||
|
__badgeError: string | null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SCHEMA = 'convivo.badge-print/v1';
|
||||||
|
|
||||||
|
let root: Root | null = null;
|
||||||
|
|
||||||
|
function nextFrame(): Promise<void> {
|
||||||
|
return new Promise((resolve) => requestAnimationFrame(() => resolve()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait until every image inside the badge is decoded (rejects on a broken src). */
|
||||||
|
async function waitForImages(host: HTMLElement): Promise<void> {
|
||||||
|
const images = Array.from(host.querySelectorAll('img'));
|
||||||
|
for (const img of images) {
|
||||||
|
try {
|
||||||
|
await img.decode();
|
||||||
|
} catch {
|
||||||
|
throw new Error(`image failed to load: ${img.src || img.getAttribute('src') || ''}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderBadge(
|
||||||
|
payload: BadgePrintPayload,
|
||||||
|
options?: { checkinOrigin?: string },
|
||||||
|
): Promise<{ width_px: number; height_px: number }> {
|
||||||
|
window.__badgeReady = false;
|
||||||
|
window.__badgeError = null;
|
||||||
|
try {
|
||||||
|
if (!payload || payload.schema !== SCHEMA) {
|
||||||
|
throw new Error(`unsupported print payload schema: ${payload?.schema}`);
|
||||||
|
}
|
||||||
|
const host = document.getElementById('badge-root');
|
||||||
|
if (!host) throw new Error('badge-root element not found');
|
||||||
|
if (!root) root = createRoot(host);
|
||||||
|
flushSync(() => {
|
||||||
|
root?.render(
|
||||||
|
<BadgePagePreview
|
||||||
|
layout={payload.layout}
|
||||||
|
sample={{ ...payload.sample, checkin_origin: options?.checkinOrigin }}
|
||||||
|
pxPerMm={MM}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await document.fonts.ready;
|
||||||
|
await waitForImages(host);
|
||||||
|
await nextFrame();
|
||||||
|
await nextFrame();
|
||||||
|
const page = host.querySelector<HTMLElement>('.badge-page');
|
||||||
|
if (!page) throw new Error('badge page did not render');
|
||||||
|
const box = page.getBoundingClientRect();
|
||||||
|
window.__badgeReady = true;
|
||||||
|
return { width_px: box.width, height_px: box.height };
|
||||||
|
} catch (err) {
|
||||||
|
window.__badgeError = err instanceof Error ? err.message : String(err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.renderBadge = renderBadge;
|
||||||
|
window.__badgeReady = false;
|
||||||
|
window.__badgeError = null;
|
||||||
+49
-16
@@ -462,33 +462,20 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
|
|||||||
overflow: auto; background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px;
|
overflow: auto; background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px;
|
||||||
padding: 28px; display: flex; justify-content: center; align-items: flex-start; min-height: 360px;
|
padding: 28px; display: flex; justify-content: center; align-items: flex-start; min-height: 360px;
|
||||||
}
|
}
|
||||||
.badge-page {
|
/* Editor-only look; the shared read-only badge rules live in components/badge-render.css. */
|
||||||
position: relative; background: #fff; box-shadow: 0 10px 30px rgba(0,0,0,.12); flex: none;
|
.badge-page { box-shadow: 0 10px 30px rgba(0,0,0,.12); }
|
||||||
touch-action: none;
|
|
||||||
}
|
|
||||||
.badge-page-empty {
|
.badge-page-empty {
|
||||||
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
|
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
|
||||||
color: #94a3b8; font-size: 13px; text-align: center; padding: 20px; pointer-events: none;
|
color: #94a3b8; font-size: 13px; text-align: center; padding: 20px; pointer-events: none;
|
||||||
}
|
}
|
||||||
.badge-el { position: absolute; overflow: visible; cursor: move; }
|
.badge-el { cursor: move; }
|
||||||
.badge-el.selected { outline: 1.5px solid var(--accent); }
|
.badge-el.selected { outline: 1.5px solid var(--accent); }
|
||||||
.badge-text-body { width: 100%; height: 100%; display: flex; overflow: hidden; }
|
|
||||||
.badge-text-body > span { width: 100%; overflow-wrap: anywhere; }
|
|
||||||
.badge-el-placeholder { color: #cbd5e1; font-style: italic; }
|
|
||||||
.badge-align-group { margin-top: 8px; }
|
.badge-align-group { margin-top: 8px; }
|
||||||
.badge-align-group-label { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
|
.badge-align-group-label { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
|
||||||
.badge-preview-stage {
|
.badge-preview-stage {
|
||||||
display: flex; justify-content: center; align-items: center; padding: 16px;
|
display: flex; justify-content: center; align-items: center; padding: 16px;
|
||||||
background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px; min-height: 180px;
|
background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px; min-height: 180px;
|
||||||
}
|
}
|
||||||
.badge-page-static { flex: none; }
|
|
||||||
.badge-qr-body { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
|
|
||||||
.badge-qr-body svg { width: 100%; height: 100%; }
|
|
||||||
.badge-image-body { width: 100%; height: 100%; display: block; }
|
|
||||||
.badge-image-empty {
|
|
||||||
display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 12px;
|
|
||||||
border: 1px dashed #cbd5e1; background: #f8fafc;
|
|
||||||
}
|
|
||||||
.badge-handle {
|
.badge-handle {
|
||||||
position: absolute; width: 9px; height: 9px; background: #fff; border: 1.5px solid var(--accent);
|
position: absolute; width: 9px; height: 9px; background: #fff; border: 1.5px solid var(--accent);
|
||||||
border-radius: 2px; transform: translate(-50%, -50%); z-index: 2;
|
border-radius: 2px; transform: translate(-50%, -50%); z-index: 2;
|
||||||
@@ -534,3 +521,49 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
|
|||||||
.badge-guide-v { width: 0; border-left: 1px dashed #ff2d95; }
|
.badge-guide-v { width: 0; border-left: 1px dashed #ff2d95; }
|
||||||
.badge-guide-h { height: 0; border-top: 1px dashed #ff2d95; }
|
.badge-guide-h { height: 0; border-top: 1px dashed #ff2d95; }
|
||||||
.badge-guide-space { border-color: #0ea5e9; }
|
.badge-guide-space { border-color: #0ea5e9; }
|
||||||
|
|
||||||
|
/* Printing */
|
||||||
|
.printer-pill {
|
||||||
|
display: flex; align-items: center; gap: 8px; width: 100%; margin-top: 14px;
|
||||||
|
padding: 9px 12px; border-radius: 12px; border: 1px solid rgba(255,255,255,.16);
|
||||||
|
background: var(--sidebar-2); color: rgba(255,255,255,.85);
|
||||||
|
font-size: 12.5px; font-weight: 700; font-family: inherit; cursor: pointer;
|
||||||
|
white-space: nowrap; flex-shrink: 0; text-align: left; transition: background .12s;
|
||||||
|
}
|
||||||
|
.printer-pill:hover { background: rgba(255,255,255,.1); color: #fff; }
|
||||||
|
.printer-pill-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--muted); flex-shrink: 0; }
|
||||||
|
.printer-pill.ready { border-color: rgba(5,150,105,.55); }
|
||||||
|
.printer-pill.ready .printer-pill-dot { background: #10b981; box-shadow: 0 0 8px rgba(16,185,129,.7); }
|
||||||
|
.printer-pill.printing { border-color: rgba(14,165,233,.55); }
|
||||||
|
.printer-pill.printing .printer-pill-dot { background: #0ea5e9; box-shadow: 0 0 8px rgba(14,165,233,.7); animation: printer-pulse 1.1s ease-in-out infinite; }
|
||||||
|
.printer-pill.error { border-color: rgba(213,0,0,.6); }
|
||||||
|
.printer-pill.error .printer-pill-dot { background: var(--red); box-shadow: 0 0 8px rgba(213,0,0,.7); }
|
||||||
|
.printer-pill.offline .printer-pill-dot, .printer-pill.none .printer-pill-dot { background: #6b7280; }
|
||||||
|
@keyframes printer-pulse { 50% { opacity: .35; } }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.printer-pill.printing .printer-pill-dot { animation: none; }
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
/* First in the scrolling top bar, so it never hides behind the wide nav.
|
||||||
|
The Tooltip wrapper (span.tip-anchor) is the real flex child. */
|
||||||
|
.sidebar > .tip-anchor:has(.printer-pill) { order: -1; flex-shrink: 0; }
|
||||||
|
.printer-pill { width: auto; margin-top: 0; padding: 8px 12px; }
|
||||||
|
}
|
||||||
|
.printing { display: grid; gap: 16px; align-content: start; }
|
||||||
|
.print-counters { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
|
||||||
|
.print-counter { text-align: center; padding: 14px 10px; }
|
||||||
|
.print-counter .n { font-size: 24px; font-weight: 800; }
|
||||||
|
.print-counter .l { color: var(--muted); font-size: 12.5px; font-weight: 600; }
|
||||||
|
.print-station { display: grid; gap: 12px; }
|
||||||
|
.print-station.revoked { opacity: .65; }
|
||||||
|
.print-hint {
|
||||||
|
padding: 10px 12px; border-radius: 12px; font-size: 13.5px; line-height: 1.5;
|
||||||
|
background: rgba(213,0,0,.07); border: 1px solid rgba(213,0,0,.3); color: var(--red);
|
||||||
|
}
|
||||||
|
.print-details { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 8px 16px; margin: 0; }
|
||||||
|
.print-details dt { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
|
||||||
|
.print-details dd { font-size: 13.5px; overflow-wrap: anywhere; margin: 0; }
|
||||||
|
.print-last-error { color: var(--red); }
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.print-counters { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
|
|||||||
import {
|
import {
|
||||||
createRegistration,
|
createRegistration,
|
||||||
deleteContacts,
|
deleteContacts,
|
||||||
|
enqueueBadgePrint,
|
||||||
getBadgeLayouts,
|
getBadgeLayouts,
|
||||||
getAllContacts,
|
getAllContacts,
|
||||||
getAllEvents,
|
getAllEvents,
|
||||||
@@ -18,6 +19,7 @@ import { useToast } from '../context/ToastContext';
|
|||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { Avatar, ColumnFilter, Empty, Modal, QrImage, Spinner, Toggle, Tooltip, TypeBadge, type ColumnFilterOption } from '../components/ui';
|
import { Avatar, ColumnFilter, Empty, Modal, QrImage, Spinner, Toggle, Tooltip, TypeBadge, type ColumnFilterOption } from '../components/ui';
|
||||||
import { BadgePagePreview, fitScale } from '../components/BadgeRender';
|
import { BadgePagePreview, fitScale } from '../components/BadgeRender';
|
||||||
|
import { activeStations, aggregateState, usePrintStatus } from '../lib/printStatus';
|
||||||
|
|
||||||
const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor'];
|
const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor'];
|
||||||
// Multi-select column filters are Excel-style: an empty selection means "all".
|
// Multi-select column filters are Excel-style: an empty selection means "all".
|
||||||
@@ -44,6 +46,10 @@ export function Registrations() {
|
|||||||
const [mergeFor, setMergeFor] = useState<Registration | null>(null);
|
const [mergeFor, setMergeFor] = useState<Registration | null>(null);
|
||||||
const [badgeFor, setBadgeFor] = useState<Registration | null>(null);
|
const [badgeFor, setBadgeFor] = useState<Registration | null>(null);
|
||||||
const [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]);
|
const [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]);
|
||||||
|
const [printingIds, setPrintingIds] = useState<Set<string>>(new Set());
|
||||||
|
const { overview: printOverview } = usePrintStatus();
|
||||||
|
// Aggregated printer state, used only to phrase the enqueue toast honestly.
|
||||||
|
const printerState = aggregateState(activeStations(printOverview));
|
||||||
const [fType, setFType] = useState<string[]>([]);
|
const [fType, setFType] = useState<string[]>([]);
|
||||||
const [fTicket, setFTicket] = useState<string[]>([]);
|
const [fTicket, setFTicket] = useState<string[]>([]);
|
||||||
const [fCheckedIn, setFCheckedIn] = useState<string[]>([]);
|
const [fCheckedIn, setFCheckedIn] = useState<string[]>([]);
|
||||||
@@ -201,6 +207,25 @@ export function Registrations() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Queue this attendee's badge. Works while the printer is offline/error —
|
||||||
|
// the job simply prints once the station is back.
|
||||||
|
async function printBadge(r: Registration) {
|
||||||
|
if (printingIds.has(r.id)) return;
|
||||||
|
setPrintingIds((ids) => new Set(ids).add(r.id));
|
||||||
|
try {
|
||||||
|
await enqueueBadgePrint(r.id);
|
||||||
|
push('success', printerState === 'offline' || printerState === 'error' ? `Queued — printer is ${printerState}` : 'Sent to printer');
|
||||||
|
} catch (e) {
|
||||||
|
push('error', e instanceof Error ? e.message : 'Print failed');
|
||||||
|
} finally {
|
||||||
|
setPrintingIds((ids) => {
|
||||||
|
const next = new Set(ids);
|
||||||
|
next.delete(r.id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (error) return <Empty icon="⚠️" text={error} />;
|
if (error) return <Empty icon="⚠️" text={error} />;
|
||||||
if (!loaded)
|
if (!loaded)
|
||||||
return (
|
return (
|
||||||
@@ -327,6 +352,17 @@ export function Registrations() {
|
|||||||
</button>
|
</button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
|
{badgeConfigured ? (
|
||||||
|
<button className="btn small" disabled={printingIds.has(r.id)} onClick={() => printBadge(r)} title="Send this attendee's badge to the printer">
|
||||||
|
{printingIds.has(r.id) ? 'Printing…' : 'Print'}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<Tooltip title="No badge yet" content="A badge needs to be configured for this event first. Design one in the Badges view.">
|
||||||
|
<button className="btn small" disabled>
|
||||||
|
Print
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
{!r.qr_token?.trim() && r.import_source === 'sessionize' && (
|
{!r.qr_token?.trim() && r.import_source === 'sessionize' && (
|
||||||
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
|
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
|
||||||
Merge tickets
|
Merge tickets
|
||||||
|
|||||||
@@ -9,5 +9,5 @@
|
|||||||
"strict": true,
|
"strict": true,
|
||||||
"noEmit": true
|
"noEmit": true
|
||||||
},
|
},
|
||||||
"include": ["vite.config.ts"]
|
"include": ["vite.config.ts", "vite.print.config.ts"]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
// Standalone print renderer bundle (print.html -> dist-print). No dev proxy:
|
||||||
|
// the Pi serves the static files itself and drives it through window.renderBadge.
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
base: './',
|
||||||
|
build: {
|
||||||
|
outDir: 'dist-print',
|
||||||
|
emptyOutDir: true,
|
||||||
|
rollupOptions: { input: 'print.html' },
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
# Convivo Badge Printer — Pi Operating Manual
|
||||||
|
|
||||||
|
Operating instructions for an AI agent (or human) who must **change, deploy or troubleshoot**
|
||||||
|
the Convivo Raspberry Pi badge printer. Everything here was verified against the code and on
|
||||||
|
real hardware (2026-10-18). Parts marked *in progress* are being built by a concurrent agent —
|
||||||
|
**verify against the code before relying on them.**
|
||||||
|
|
||||||
|
Backend architecture contract: [docs/backend/printing.md](../../docs/backend/printing.md)
|
||||||
|
(link only, don't duplicate). Repo-wide rules: [root AGENT.MD](../../AGENT.MD).
|
||||||
|
|
||||||
|
## 1. Purpose & architecture
|
||||||
|
|
||||||
|
Staff check in an attendee → the DB transaction enqueues a self-contained badge document
|
||||||
|
(`convivo.badge-print/v1`) on a pgmq queue → a headless Raspberry Pi station claims it,
|
||||||
|
renders the badge with the admin's own React renderer inside headless Chromium, composes it
|
||||||
|
onto the loaded roll and prints on a Brother QL-1110NWB over raw USB. Admins watch a status
|
||||||
|
pill + Printing view in the admin console.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
SCAN[Welcome check-in / admin Print] -->|pgmq.send| Q[(badge_print queue)]
|
||||||
|
Q -->|printer_claim_badge_job RPC| W[worker: apps/printer/worker]
|
||||||
|
W -->|renderBadge in Chromium| R[dist-print renderer]
|
||||||
|
W -->|brother_ql_next pyusb| P[Brother QL-1110NWB]
|
||||||
|
W -->|printer_heartbeat| S[(print_stations)]
|
||||||
|
S -->|get_print_overview 5s poll| A[Admin pill + Printing view]
|
||||||
|
C[comitup + portal] -->|/run/convivo/network.json| W
|
||||||
|
```
|
||||||
|
|
||||||
|
Delivery is **at-least-once**: if `complete` keeps failing (>60 s) the job may be redelivered
|
||||||
|
and print a duplicate. That is by design — don't "fix" it silently.
|
||||||
|
|
||||||
|
## 2. Repo map
|
||||||
|
|
||||||
|
| Path | Role |
|
||||||
|
|---|---|
|
||||||
|
| `apps/printer/worker/` | Python worker: `main.py` loop, `rpc.py` PostgREST client, `printer.py` brother_ql USB, `render.py` Chromium, `label.py` Pillow compose, `network.py` comitup state, `status_labels.py`, `config.py` env |
|
||||||
|
| `apps/printer/tests/` | pytest unit tests (fakes — no hardware, no DB) |
|
||||||
|
| `apps/printer/Dockerfile` | arm64 image; **build context = repo root**; node renderer stage on `BUILDPLATFORM`, runtime = `mcr.microsoft.com/playwright/python:v1.55.0-noble` |
|
||||||
|
| `apps/printer/Dockerfile.dockerignore` | per-Dockerfile ignore (supabase/, e2e/, docs/, pi/, tests excluded from context) |
|
||||||
|
| `apps/printer/pi/install.sh` | dev-machine side: buildx build → tar.gz → scp → run setup.sh over SSH |
|
||||||
|
| `apps/printer/pi/setup.sh` | Pi provisioning, idempotent, runs as root on the Pi |
|
||||||
|
| `apps/printer/pi/setup.local.sh` | filled copy with URL + station token — **git-ignored, secret-bearing, never open/print/commit** |
|
||||||
|
| `apps/printer/pi/convivo-printer-image.tar.gz` | exported image (~950 MB gz) — git-ignored |
|
||||||
|
| `apps/printer/portal/portal.py` | captive-portal config page — *in progress by another agent*, see §8 |
|
||||||
|
| `supabase/migrations/20261018170000_badge_print_queue.sql` | queues, `print_stations`, all RPCs (idempotent/re-runnable) |
|
||||||
|
| `supabase/tests/badge_print_tests.sql` | rollback-only regression suite (~101 asserts); run command in its header |
|
||||||
|
| `apps/admin/print.html`, `src/print/main.tsx` | standalone renderer page; exposes `window.renderBadge(payload, opts)` |
|
||||||
|
| `apps/admin/vite.print.config.ts` | builds `print.html` → `apps/admin/dist-print/` (`npm run build:print`) |
|
||||||
|
| `apps/admin/src/components/BadgeRender.tsx` | shared badge layout renderer (editor preview + print page) |
|
||||||
|
| `apps/admin/src/views/Printing.tsx` | stations, queue counts, dead letters (Requeue/Discard), recent (Reprint), Add/Rename/Revoke station |
|
||||||
|
| `apps/admin/src/lib/printStatus.tsx` | 5 s poller of `get_print_overview()` + `printerHint()` operator text |
|
||||||
|
| `e2e/tests/printing.spec.ts` | Playwright: pill states, token-once, rename, requeue/discard, reprint (RPCs mocked) |
|
||||||
|
|
||||||
|
## 3. Hardware facts (verified on the real Pi)
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|---|---|
|
||||||
|
| Board | Raspberry Pi 4 (2 GB), Raspberry Pi OS / Debian 13 trixie, aarch64 |
|
||||||
|
| Printer | Brother QL-1110NWB(c), USB id `04f9:20a8`, identifier `usb://0x04f9:0x20a8`, pyusb backend |
|
||||||
|
| Model string | `QL-1110NWB` (brother_ql_next 0.12.0); device self-reports `QL-1100NWB` — normal |
|
||||||
|
| Die-cut roll | `103x164` (1200×1822 px @300 dpi). **Die-cut labels cannot be cut shorter** than the pitch |
|
||||||
|
| Continuous roll | DK-22246 → id `103` (1200 px wide), cut to layout length |
|
||||||
|
| `BROTHER_LABEL` | `auto` (default): print on whatever roll is detected |
|
||||||
|
| Print speed | ≈ 8 s/label. `/tmp` on the Pi is a ≈923 MB tmpfs — never stage the image there |
|
||||||
|
|
||||||
|
## 4. Golden rules
|
||||||
|
|
||||||
|
1. **Never write or print secrets.** No passwords in files, commands, logs, or memory —
|
||||||
|
refer to "the Pi sudo password, ask the operator". No station tokens, no server
|
||||||
|
credentials, ever. The Supabase anon key is public (not a secret) but don't paste it
|
||||||
|
anywhere new: it comes from `apps/printer/pi/setup.sh` (default `CONVIVO_ANON_KEY`,
|
||||||
|
same value baked into the web apps).
|
||||||
|
2. **sudo on the Pi needs a password.** Pipe it on stdin only:
|
||||||
|
`printf '%s\n' "$PI_SUDO_PASSWORD" | ssh convivo-pi "sudo -S -p '' …"`, with
|
||||||
|
`PI_SUDO_PASSWORD` read from a private 0600 file outside the repo (or exported by the
|
||||||
|
operator). Never on a command line (`sudo … <pw>`), never in the repo.
|
||||||
|
3. **SSH access**: alias `convivo-pi` in `~/.ssh/config` (key `~/.ssh/convivo_pi`,
|
||||||
|
`StrictHostKeyChecking yes`). The Pi's LAN IP changes at venues — always use the alias.
|
||||||
|
4. **Idempotency**: `setup.sh` must stay safe to re-run on a working station. It restarts
|
||||||
|
services **only when their config changed** (§6). Violating this caused two real
|
||||||
|
incidents (bounced worker printed a label mid-deploy; hotspot without DHCP).
|
||||||
|
5. **Risky network change over Wi-Fi SSH? Arm a rollback first** (§7).
|
||||||
|
6. **Never log tokens or `qr_token` payload values.** `Config` keeps `station_token` out of
|
||||||
|
`repr` — keep it that way.
|
||||||
|
7. **Ask before destructive or production actions** (revoke station, DB writes on prod,
|
||||||
|
rebooting a station mid-event). Prod deploys follow
|
||||||
|
[docs/deployment.md](../../docs/deployment.md): backup, drift guard, build-before-up,
|
||||||
|
never touch prod data/secrets.
|
||||||
|
8. **Sub-agents must not run local docker builds** — docker veth churn can kill the session
|
||||||
|
(ERR_NETWORK_CHANGED). The supervisor runs builds, in async terminals. Also: `pkill -f`
|
||||||
|
patterns can match your own shell — avoid them.
|
||||||
|
|
||||||
|
## 5. Changing the code
|
||||||
|
|
||||||
|
### Worker (`apps/printer/worker/`)
|
||||||
|
- Loop: `tick()` → printer ready? → `claim(wait_seconds)` → `handle_job()` →
|
||||||
|
render → compose → `print_image` → `complete`/`fail`. Errors never escape the loop.
|
||||||
|
- A post-print error (roll ran out mid-job) must **not** dead-letter a badge that did print
|
||||||
|
(`did_print` wins). Retryable failures re-claim up to 3 reads, then dead-letter.
|
||||||
|
- Env knobs live in `config.py` (`CONVIVO_URL`, `CONVIVO_ANON_KEY`, `PRINTER_STATION_TOKEN`,
|
||||||
|
`STATION_NAME`, `BROTHER_*`, `WAIT_SECONDS`, `HEARTBEAT_SECONDS`, `VT_SECONDS`,
|
||||||
|
`STATUS_LABELS`, `DRY_RUN`, `THRESHOLD`, `DITHER`).
|
||||||
|
- `DRY_RUN=1` writes PNGs to `/tmp/dryrun` instead of printing — use it for bench tests.
|
||||||
|
|
||||||
|
Tests (pure fakes, no hardware/DB):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd apps/printer && python -m venv /tmp/convivo-printer-venv
|
||||||
|
/tmp/convivo-printer-venv/bin/pip install -r requirements-dev.txt brother_ql_next==0.12.0 pillow httpx
|
||||||
|
/tmp/convivo-printer-venv/bin/python -m pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
### Renderer (`apps/admin`)
|
||||||
|
The badge look is `BadgeRender.tsx` shared with the editor; the print page is
|
||||||
|
`src/print/main.tsx` (`window.renderBadge`). Change layout code there, then:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build:print --prefix apps/admin # produces dist-print/ (what the Pi image embeds)
|
||||||
|
npm run build --prefix apps/admin # the admin app itself must still build
|
||||||
|
CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- printing.spec.ts
|
||||||
|
```
|
||||||
|
(the e2e spec needs the admin dev server on 127.0.0.1:3001; RPCs are mocked in the spec).
|
||||||
|
The Dockerfile renderer stage rebuilds `dist-print` inside the image — a stale local
|
||||||
|
`dist-print/` never leaks in (it's docker-ignored).
|
||||||
|
|
||||||
|
### Database (`supabase/`)
|
||||||
|
Edit the migration `20261018170000_badge_print_queue.sql` (it is idempotent/re-runnable)
|
||||||
|
and extend `supabase/tests/badge_print_tests.sql`. RPC surface:
|
||||||
|
`welcome_checkin` (enqueues on first check-in; no layout → no job), `enqueue_badge_print`
|
||||||
|
(admin reprint), `create_print_station` / `rename_print_station` / `revoke_print_station`,
|
||||||
|
`get_print_overview`, `requeue_dead_badge_print`, `discard_dead_badge_print`, and the four
|
||||||
|
token-gated `printer_*` RPCs (claim/complete/fail/heartbeat).
|
||||||
|
|
||||||
|
Run the rollback suite (works before AND after apply; nothing persists):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
(echo 'begin;'; \
|
||||||
|
cat supabase/migrations/20261018170000_badge_print_queue.sql; \
|
||||||
|
sed '/^begin;$/d' supabase/tests/badge_print_tests.sql) \
|
||||||
|
| docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -v ON_ERROR_STOP=1
|
||||||
|
```
|
||||||
|
|
||||||
|
Hard constraint: the anon role has `statement_timeout = 3 s` — every anon RPC must finish
|
||||||
|
under that. The claim long-poll is clamped server-side to `p_wait_seconds ≤ 2`
|
||||||
|
(worker default `WAIT_SECONDS=2`). A 10 s poll → HTTP 500 `57014`.
|
||||||
|
|
||||||
|
### Image
|
||||||
|
`apps/printer/Dockerfile`: build context is the **repo root**; the node renderer stage runs
|
||||||
|
on `--platform=$BUILDPLATFORM` (native, fast) while the runtime stage is arm64. Runtime deps
|
||||||
|
are pinned in `requirements.txt` (brother_ql_next, pillow, httpx, playwright). Container
|
||||||
|
runs as root on purpose (raw USB, Chromium `--no-sandbox`). Healthcheck =
|
||||||
|
`/tmp/heartbeat-ok` touched every heartbeat, 120 s start-period.
|
||||||
|
|
||||||
|
## 6. Deploy to a Pi
|
||||||
|
|
||||||
|
### First install on a fresh Pi
|
||||||
|
1. Flash Raspberry Pi OS (64-bit, trixie) with **Raspberry Pi Imager → OS customisation:
|
||||||
|
enable SSH (key auth), set hostname `convivo-printer`**. Connect **Ethernet** if at all
|
||||||
|
possible for the first deploy (Wi-Fi over-SSH deploys need the rollback dance, §7).
|
||||||
|
2. Add the ssh alias (`convivo-pi`) with key `~/.ssh/convivo_pi`, `StrictHostKeyChecking yes`;
|
||||||
|
copy your key to the Pi; have the operator supply the sudo password when needed.
|
||||||
|
3. Create the station in **Admin → Printing → Add station** — the token (`cvp_…`) is shown
|
||||||
|
**once** (only its SHA-256 is stored). Lost it → revoke + re-add.
|
||||||
|
4. Create `apps/printer/pi/setup.local.sh` (git-ignored, mode 0600):
|
||||||
|
`cp apps/printer/pi/setup.sh apps/printer/pi/setup.local.sh` then set the defaults —
|
||||||
|
either edit the `: "${VAR:=…}"` lines or `sed` them: `CONVIVO_URL`,
|
||||||
|
`PRINTER_STATION_TOKEN`, `STATION_NAME`. Never commit or print this file.
|
||||||
|
5. Run the installer (supervisor's terminal, expect: build a few minutes, upload minutes,
|
||||||
|
`docker load` on the SD card several minutes):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PI_SUDO_PASSWORD="$(cat <private-0600-file>)" bash apps/printer/pi/install.sh # default target convivo-pi
|
||||||
|
PI_SUDO_PASSWORD=… bash apps/printer/pi/install.sh user@other-pi # any other Pi
|
||||||
|
```
|
||||||
|
|
||||||
|
`install.sh` flags: `SKIP_BUILD=1` (reuse the existing tar), `SKIP_IMAGE=1` (env-only
|
||||||
|
change — don't even upload the tar; *being added, verify against the code*),
|
||||||
|
`STAGE_APP=0` / `STAGE_WIFI_PORTAL=0` (skip stages), `REBOOT=1` (reboot if kernel update
|
||||||
|
pending). It builds arm64 with buildx (installs QEMU binfmt if missing), gzips to
|
||||||
|
`apps/printer/pi/convivo-printer-image.tar.gz`, scp's setup (prefers `setup.local.sh`) +
|
||||||
|
image to **`/var/tmp/convivo-setup`** (NOT `/tmp` — 923 MB tmpfs), then runs setup.sh as
|
||||||
|
root via `sudo -S`.
|
||||||
|
|
||||||
|
### `setup.sh` stages and idempotency rules (do not break these)
|
||||||
|
- **base_system / reliability**: hostname, timezone, apt, hardware watchdog, journald cap,
|
||||||
|
Wi-Fi powersave off, auto-upgrade timers disabled. `daemon-reexec` **only when the
|
||||||
|
watchdog conf changed**, and then comitup is restarted too — a re-exec without that
|
||||||
|
restart leaves comitup with a stale D-Bus proxy → hotspot up but **no DHCP/portal**.
|
||||||
|
- **docker**: installed from docker.com repo; restart **only when `daemon.json` changed** —
|
||||||
|
a restart bounces the worker on its old image (it would re-claim and print).
|
||||||
|
- **usb**: blacklist `usblp`; **mask `ipp-usb`** (it grabs the printer's interfaces →
|
||||||
|
"Resource busy").
|
||||||
|
- **app**: writes `/opt/convivo-printer/.env` (0600) + `docker-compose.yml`, `docker load`,
|
||||||
|
tags whatever load reports as `convivo-printer:latest`, `compose up -d`, image prune.
|
||||||
|
Compose: host network, `/dev/bus/usb` + `device_cgroup_rules: c 189:* rmw` (replugged
|
||||||
|
printer works without restart), `/run/convivo:ro`, tmpfs `/tmp`, `restart: always`.
|
||||||
|
*In progress:* setup.sh will always rewrite `.env` while **preserving portal-set
|
||||||
|
values** — verify against the code.
|
||||||
|
- **comitup**: restart **only when `/etc/comitup.conf` changed** (a restart renegotiates
|
||||||
|
Wi-Fi and can drop your SSH mid-script).
|
||||||
|
|
||||||
|
### Updates
|
||||||
|
Code change → re-run `install.sh` (rebuild + upload + setup). Env-only change → edit
|
||||||
|
`setup.local.sh` (or `.env` on the Pi + `docker compose up -d`), with `SKIP_BUILD=1
|
||||||
|
SKIP_IMAGE=1` if supported. Then verify (§10 checklist).
|
||||||
|
|
||||||
|
## 7. Risky network changes over Wi-Fi SSH
|
||||||
|
|
||||||
|
Arm a rollback **before** the change, run the work detached, cancel the timer after:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. snapshot the current profile, then arm a timer (e.g. 8 min):
|
||||||
|
ssh convivo-pi "sudo -S systemd-run --on-active=8min --unit=convivo-net-rollback \
|
||||||
|
sh -c 'cp /tmp/net-backup.yaml /etc/netplan/ && netplan generate && nmcli connection reload && systemctl restart comitup'"
|
||||||
|
# 2. long steps detached so an SSH drop can't kill them:
|
||||||
|
ssh convivo-pi "sudo -S systemd-run --unit=convivo-setup --collect bash /var/tmp/convivo-setup/setup.sh"
|
||||||
|
# 3. verify connectivity (comitup-cli i shows CONNECTED), then:
|
||||||
|
ssh convivo-pi "sudo -S systemctl stop convivo-net-rollback"
|
||||||
|
```
|
||||||
|
|
||||||
|
If SSH drops, the timer restores the old config automatically.
|
||||||
|
|
||||||
|
## 8. Wi-Fi provisioning & captive portal
|
||||||
|
|
||||||
|
- comitup 1.43 (Debian trixie package). With no known network the Pi broadcasts the **open**
|
||||||
|
AP `Convivo-Printer-<nnnn>` (`<nnnn>` persistent per device; this Pi: `Convivo-Printer-6372`).
|
||||||
|
Connect a phone, open **http://10.41.0.1**, pick a network. Comitup remembers any number
|
||||||
|
of networks and reuses existing NM/netplan profiles. **Open AP = anyone nearby can
|
||||||
|
reconfigure the station — accepted risk.**
|
||||||
|
- `external_callback = /usr/local/lib/convivo/netstate.sh` writes
|
||||||
|
`/run/convivo/network.json` (`HOTSPOT|CONNECTING|CONNECTED` + ssid/ip) → mounted
|
||||||
|
read-only into the worker → heartbeats → the admin pill knows the network state.
|
||||||
|
- **Config portal (in progress, another agent):** `apps/printer/portal/portal.py` will
|
||||||
|
replace the comitup web UI by overriding `comitup-web.service` `ExecStart` through a
|
||||||
|
systemd drop-in. Staff will be able to pick **any** Wi-Fi and optionally set
|
||||||
|
`CONVIVO_URL` / `CONVIVO_ANON_KEY` / `PRINTER_STATION_TOKEN` — the portal rewrites
|
||||||
|
`/opt/convivo-printer/.env` and recreates the container. Companion changes:
|
||||||
|
`install.sh SKIP_IMAGE=1`, and `setup.sh` always rewriting `.env` while preserving
|
||||||
|
portal-set values. **Verify all of this against the code before documenting or relying
|
||||||
|
on it.** `STAGE_WIFI_PORTAL=0` skips the comitup/portal stage (wired bench).
|
||||||
|
|
||||||
|
## 9. Configuring: local test vs production
|
||||||
|
|
||||||
|
| | Local test | Production |
|
||||||
|
|---|---|---|
|
||||||
|
| `CONVIVO_URL` | `http://<dev-machine-LAN-IP>:54321` (Kong; reachable from the Pi on the same LAN — verified: `192.168.178.x`) | `https://admin.appe.at` (same-origin PostgREST proxy) |
|
||||||
|
| Station token | create via SQL on the local DB (below) | Admin → Printing → Add station (shown once) |
|
||||||
|
| Migrations/admin | local `supabase_db_Convivo` | per docs/deployment.md (backup, drift guard, build-before-up) |
|
||||||
|
|
||||||
|
Local station via SQL (token to a 0600 file, **never print it**):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -tA -c \
|
||||||
|
"select set_config('request.jwt.claims','{\"email\":\"<admin @appe.at email>\",\"role\":\"authenticated\"}', false);
|
||||||
|
select token from public.create_print_station('Welcome desk (local test)');" > /tmp/.local-station-token
|
||||||
|
chmod 600 /tmp/.local-station-token
|
||||||
|
```
|
||||||
|
|
||||||
|
Queue a test badge: `select public.enqueue_badge_print('<registration-id>');` (admin only)
|
||||||
|
or the admin Print button on Registrations (works while the printer is offline — the job
|
||||||
|
waits). The event needs a badge layout whose page fits the loaded roll (die-cut 103×164 or
|
||||||
|
continuous 103 mm wide).
|
||||||
|
|
||||||
|
## 10. Operating at an event
|
||||||
|
|
||||||
|
- **Roll change**: swap physically; `BROTHER_LABEL=auto` picks up the new media on the next
|
||||||
|
status poll. Worker pauses (no claims) while the printer reports errors — queue waits.
|
||||||
|
Want short badges (e.g. 101×30)? You need the **continuous DK-22246** roll; a die-cut
|
||||||
|
roll always prints the full 164 mm label.
|
||||||
|
- **Wi-Fi change**: phone → open AP `Convivo-Printer-<nnnn>` → http://10.41.0.1 → pick the
|
||||||
|
venue network (or the new portal page once it lands, §8). Watch the pill come back.
|
||||||
|
- **Admin pill states** (worst-state wins across active stations, polls every 5 s):
|
||||||
|
- `ready` — heartbeat <45 s old, printer ready, no errors.
|
||||||
|
- `printing` — worker currently on a job.
|
||||||
|
- `error` — printer disconnected / errors (no media, cover open, cutter jam, wrong roll)
|
||||||
|
— hover text comes from `printerHint()`, written for operators.
|
||||||
|
- `offline` — no heartbeat for >45 s (Pi off, Wi-Fi lost, wrong `CONVIVO_URL`).
|
||||||
|
- `revoked` stations are excluded from the pill.
|
||||||
|
- Queue counts, dead letters (Requeue/Discard) and Recent jobs (Reprint) live in
|
||||||
|
**Admin → Printing**. Rename a station there (inline); the worker adopts the new name
|
||||||
|
from the heartbeat response.
|
||||||
|
- Status labels ("ready" / "need Wi-Fi" printed on the printer) are **off by default**
|
||||||
|
(`STATUS_LABELS=1` enables; costs media). The pill is the default channel.
|
||||||
|
|
||||||
|
## 11. Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Cause | Fix |
|
||||||
|
|---|---|---|
|
||||||
|
| USB open "Resource busy" | `ipp-usb` (or `usblp`) claimed the printer | `sudo systemctl mask --now ipp-usb`; replug USB; setup.sh enforces both |
|
||||||
|
| Claims HTTP 500 `57014` | anon `statement_timeout` 3 s exceeded | keep `p_wait_seconds ≤ 2`; nobody raised `WAIT_SECONDS` |
|
||||||
|
| Hotspot up, clients get no IP | comitup stale D-Bus proxy after `daemon-reexec` | `sudo systemctl restart comitup` |
|
||||||
|
| DLQ "layout … does not fit label" | badge bigger than loaded roll (both rotations) | load 103 mm roll / shrink layout / Requeue after fix |
|
||||||
|
| Short badge wastes a full die-cut label | die-cut can't cut shorter | load continuous DK-22246 (`103`) |
|
||||||
|
| Pill **offline** | Pi powered off / Wi-Fi lost / wrong `CONVIVO_URL` | power, `comitup-cli i`, `cat /run/convivo/network.json`, re-provision Wi-Fi |
|
||||||
|
| RPC 401 / SQLSTATE `28000`, log "station token rejected" | token revoked/wrong | Add station again (new token, once), update `.env` via portal or redeploy |
|
||||||
|
| Pill error "wrong roll" | `BROTHER_LABEL` pinned, different roll loaded | swap roll or set `BROTHER_LABEL=auto` |
|
||||||
|
| Duplicate badge after worker restart | `complete` failed >60 s earlier | expected at-least-once; fix network to DB |
|
||||||
|
| Container unhealthy | `/tmp/heartbeat-ok` stale >1 min | `docker logs --since 10m convivo-printer`; usually DB unreachable |
|
||||||
|
| Printer not detected (USB gone) | cable/power/replug | check printer power; `lsusb -d 04f9:`; cgroup rule means no container restart needed |
|
||||||
|
| Pi unreachable by IP | venue changed the network | use `convivo-pi` alias / mDNS; re-provision via portal/AP |
|
||||||
|
|
||||||
|
Log & state commands (read-only, safe during an event):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh convivo-pi "sudo -n docker logs --since 10m convivo-printer"
|
||||||
|
ssh convivo-pi "sudo -n docker ps --filter name=convivo-printer" # Status: healthy
|
||||||
|
ssh convivo-pi "comitup-cli i"
|
||||||
|
ssh convivo-pi "cat /run/convivo/network.json"
|
||||||
|
docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -c \
|
||||||
|
"select name, last_seen_at, last_status->'printer'->>'ready' as ready from public.print_stations"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 12. Checklists
|
||||||
|
|
||||||
|
**Pre-deploy**
|
||||||
|
- [ ] `cd apps/printer && python -m pytest -q` green.
|
||||||
|
- [ ] SQL rollback suite green (command in §5) if DB touched.
|
||||||
|
- [ ] `npm run build --prefix apps/admin && npm run build:print --prefix apps/admin` green if renderer/admin touched.
|
||||||
|
- [ ] `printing.spec.ts` green if admin UI touched.
|
||||||
|
- [ ] `git status` shows no secret files staged (`setup.local.sh`, `*.tar.gz` are git-ignored — keep it that way).
|
||||||
|
- [ ] Station exists (Admin → Printing) and its token is in `setup.local.sh` / portal, not in any log.
|
||||||
|
|
||||||
|
**Post-deploy verification**
|
||||||
|
- [ ] `docker ps` → `convivo-printer` **healthy** (allow 120 s start-period).
|
||||||
|
- [ ] Logs show heartbeats / `worker idle`, no token errors.
|
||||||
|
- [ ] Admin pill shows the station **ready** with the right name and roll.
|
||||||
|
- [ ] Physical: check in an unchecked attendee → badge prints ≤ ~15 s → job in Recent (archived).
|
||||||
|
- [ ] Reprint from Printing view works.
|
||||||
|
- [ ] (If network work was done) rollback timer cancelled: `systemctl is-active convivo-net-rollback` → inactive.
|
||||||
|
|
||||||
|
**Production (first real deployment — not done yet as of 2026-10-18)**
|
||||||
|
- [ ] Verify `pgmq` is installable on prod Postgres (local: works as `postgres` role; prod unverified).
|
||||||
|
- [ ] Apply the migration via docs/deployment.md (backup, single transaction, migration ledger).
|
||||||
|
- [ ] Build + deploy admin app (Printing view, pill). The renderer ships **inside the Pi image**, not the web app.
|
||||||
|
- [ ] Add station (prod) → one-time token → `setup.local.sh` with `CONVIVO_URL=https://admin.appe.at`.
|
||||||
|
- [ ] `install.sh` against the prod Pi; run the post-deploy checklist with a real check-in.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Convivo badge-printer worker.
|
||||||
|
# Build context = REPO ROOT:
|
||||||
|
# docker buildx build --platform linux/arm64 -f apps/printer/Dockerfile -t convivo-printer:latest .
|
||||||
|
|
||||||
|
# --- badge print renderer (built on the native build platform for speed) ------
|
||||||
|
FROM --platform=$BUILDPLATFORM node:20-bookworm-slim AS renderer
|
||||||
|
WORKDIR /build
|
||||||
|
COPY apps/admin/package.json apps/admin/package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY apps/admin/ ./
|
||||||
|
RUN npx vite build --config vite.print.config.ts
|
||||||
|
|
||||||
|
# --- runtime: Playwright Chromium + brother_ql + worker ------------------------
|
||||||
|
FROM mcr.microsoft.com/playwright/python:v1.55.0-noble
|
||||||
|
|
||||||
|
ARG APP_VERSION=dev
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends libusb-1.0-0 fonts-dejavu-core \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY apps/printer/requirements.txt ./requirements.txt
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY apps/printer/worker/ /app/worker/
|
||||||
|
COPY --from=renderer /build/dist-print /app/renderer/
|
||||||
|
|
||||||
|
ENV PYTHONUNBUFFERED=1 \
|
||||||
|
APP_VERSION=${APP_VERSION}
|
||||||
|
|
||||||
|
# Root on purpose: raw USB access for the Brother printer (no privileged mode).
|
||||||
|
# The image's Chromium runs with --no-sandbox (set in render.py).
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=120s \
|
||||||
|
CMD find /tmp/heartbeat-ok -mmin -1 | grep -q . || exit 1
|
||||||
|
|
||||||
|
CMD ["python", "-m", "worker"]
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Per-Dockerfile ignore (BuildKit: <Dockerfile>.dockerignore). Context = repo root.
|
||||||
|
.git
|
||||||
|
**/.git
|
||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
**/dist-print
|
||||||
|
**/test-results
|
||||||
|
assets
|
||||||
|
docs
|
||||||
|
e2e
|
||||||
|
mockup
|
||||||
|
packages
|
||||||
|
src
|
||||||
|
supabase
|
||||||
|
apps/convivo
|
||||||
|
apps/printer/pi
|
||||||
|
apps/printer/tests
|
||||||
|
*.md
|
||||||
|
docker-compose.yml
|
||||||
Executable
+57
@@ -0,0 +1,57 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Copy setup (+ worker image when present) to the Pi and run it as root.
|
||||||
|
# Usage: apps/printer/pi/install.sh [ssh-target] (default: convivo-pi)
|
||||||
|
# Env: PI_SUDO_PASSWORD (prompted if unset), STAGE_APP / STAGE_WIFI_PORTAL / REBOOT forwarded to setup.sh.
|
||||||
|
# SKIP_BUILD=1 reuses an existing image tar instead of rebuilding it.
|
||||||
|
# SKIP_IMAGE=1 does not upload the image tar (reuse the image already on the Pi).
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
TARGET="${1:-convivo-pi}"
|
||||||
|
DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
ROOT="$(cd "$DIR/../../.." && pwd)"
|
||||||
|
SETUP="$DIR/setup.local.sh"
|
||||||
|
[[ -f $SETUP ]] || SETUP="$DIR/setup.sh"
|
||||||
|
PORTAL="$ROOT/apps/printer/portal/portal.py"
|
||||||
|
IMAGE="$DIR/convivo-printer-image.tar.gz"
|
||||||
|
# /tmp is a small RAM tmpfs on the Pi; the image tarball needs disk.
|
||||||
|
REMOTE=/var/tmp/convivo-setup
|
||||||
|
|
||||||
|
if [[ "${SKIP_BUILD:-0}" != 1 && "${SKIP_IMAGE:-0}" != 1 ]]; then
|
||||||
|
# SKIP_IMAGE reuses the Pi's image, so a local build would only be discarded.
|
||||||
|
# Cross-build the arm64 image from the repo root (default docker builder).
|
||||||
|
if ! docker buildx inspect default 2>/dev/null | grep -q linux/arm64; then
|
||||||
|
echo "linux/arm64 not in buildx default builder — installing QEMU binfmt" >&2
|
||||||
|
docker run --privileged --rm tonistiigi/binfmt --install arm64
|
||||||
|
fi
|
||||||
|
echo "Building convivo-printer image (arm64) → $IMAGE"
|
||||||
|
(
|
||||||
|
cd "$ROOT"
|
||||||
|
docker buildx build --platform linux/arm64 \
|
||||||
|
-f apps/printer/Dockerfile \
|
||||||
|
--build-arg "APP_VERSION=$(git rev-parse --short HEAD)-$(date +%Y%m%d%H%M)" \
|
||||||
|
-t convivo-printer:latest \
|
||||||
|
--output "type=docker,dest=-" . | gzip > "$IMAGE"
|
||||||
|
)
|
||||||
|
fi
|
||||||
|
|
||||||
|
ssh "$TARGET" "mkdir -p $REMOTE"
|
||||||
|
scp -q "$SETUP" "$TARGET:$REMOTE/setup.sh"
|
||||||
|
scp -q "$PORTAL" "$TARGET:$REMOTE/portal.py"
|
||||||
|
if [[ "${SKIP_IMAGE:-0}" == 1 ]]; then
|
||||||
|
# Reuse the image already loaded on the Pi; drop any stale tar so setup.sh does not load it.
|
||||||
|
ssh "$TARGET" "rm -f $REMOTE/convivo-printer-image.tar.gz"
|
||||||
|
else
|
||||||
|
[[ -f $IMAGE ]] && scp -q "$IMAGE" "$TARGET:$REMOTE/convivo-printer-image.tar.gz"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "${PI_SUDO_PASSWORD:-}" ]]; then
|
||||||
|
read -rsp "sudo password for $TARGET: " PI_SUDO_PASSWORD
|
||||||
|
echo
|
||||||
|
fi
|
||||||
|
|
||||||
|
STAGE_ENV=()
|
||||||
|
for v in STAGE_APP STAGE_WIFI_PORTAL REBOOT; do
|
||||||
|
[[ -n "${!v:-}" ]] && STAGE_ENV+=("$v=${!v}")
|
||||||
|
done
|
||||||
|
|
||||||
|
printf '%s\n' "$PI_SUDO_PASSWORD" | ssh "$TARGET" "sudo -S -p '' env ${STAGE_ENV[*]:-} bash $REMOTE/setup.sh"
|
||||||
Executable
+298
@@ -0,0 +1,298 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Convivo badge printer — Raspberry Pi 4 provisioning (Raspberry Pi OS / Debian trixie, arm64).
|
||||||
|
# Usage (on the Pi): sudo bash setup.sh
|
||||||
|
# Idempotent: safe to re-run for updates. Fill a copy as setup.local.sh (git-ignored); never commit the token.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# ---- Configuration -----------------------------------------------------------
|
||||||
|
# Empty CONVIVO_URL / CONVIVO_ANON_KEY / PRINTER_STATION_TOKEN keep the values already
|
||||||
|
# in $INSTALL_DIR/.env (e.g. configured through the portal), so re-runs never reset them.
|
||||||
|
: "${CONVIVO_URL:=}"
|
||||||
|
# Public anon key (same value baked into the web apps); not a secret.
|
||||||
|
: "${CONVIVO_ANON_KEY:=}"
|
||||||
|
# Station token from Admin → Printing → "Add station" (shown once). Required once, via this
|
||||||
|
# variable or the portal.
|
||||||
|
: "${PRINTER_STATION_TOKEN:=}"
|
||||||
|
: "${STATION_NAME:=Welcome desk}"
|
||||||
|
: "${BADGE_CHECKIN_ORIGIN:=https://admin.appe.at}"
|
||||||
|
: "${BROTHER_MODEL:=QL-1110NWB}"
|
||||||
|
: "${BROTHER_LABEL:=auto}"
|
||||||
|
: "${PRINTER_IDENTIFIER:=usb://0x04f9:0x20a8}"
|
||||||
|
# 1 = print "ready" / "no network" labels on the printer (costs media).
|
||||||
|
: "${STATUS_LABELS:=0}"
|
||||||
|
: "${PI_HOSTNAME:=convivo-printer}"
|
||||||
|
: "${TIMEZONE:=Europe/Vienna}"
|
||||||
|
# comitup replaces <nnnn> with a persistent per-device number.
|
||||||
|
: "${AP_NAME:=Convivo-Printer-<nnnn>}"
|
||||||
|
: "${IMAGE_TAR:=$(dirname "$(readlink -f "$0")")/convivo-printer-image.tar.gz}"
|
||||||
|
: "${INSTALL_DIR:=/opt/convivo-printer}"
|
||||||
|
# Stages: 1 = run, 0 = skip.
|
||||||
|
: "${STAGE_WIFI_PORTAL:=1}"
|
||||||
|
: "${STAGE_APP:=1}"
|
||||||
|
: "${REBOOT:=0}"
|
||||||
|
|
||||||
|
log() { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }
|
||||||
|
warn() { printf '\033[1;33m[warn] %s\033[0m\n' "$*" >&2; }
|
||||||
|
die() { printf '\033[1;31m[fail] %s\033[0m\n' "$*" >&2; exit 1; }
|
||||||
|
|
||||||
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
|
APT_OPTS=(-y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
|
||||||
|
|
||||||
|
preflight() {
|
||||||
|
log "Preflight"
|
||||||
|
[[ $EUID -eq 0 ]] || die "run as root: sudo bash $0"
|
||||||
|
[[ "$(uname -m)" == "aarch64" ]] || die "expected aarch64, got $(uname -m)"
|
||||||
|
. /etc/os-release
|
||||||
|
[[ "${ID:-}" == "debian" || "${ID_LIKE:-}" == *debian* ]] || die "unsupported OS: ${PRETTY_NAME:-unknown}"
|
||||||
|
echo "OS: $PRETTY_NAME · $(tr -d '\0' </proc/device-tree/model 2>/dev/null || true)"
|
||||||
|
curl -fsS --max-time 10 -o /dev/null https://deb.debian.org/ || die "no internet access (needed for apt/Docker)"
|
||||||
|
}
|
||||||
|
|
||||||
|
base_system() {
|
||||||
|
log "Base system"
|
||||||
|
if [[ "$(hostname)" != "$PI_HOSTNAME" ]]; then
|
||||||
|
hostnamectl set-hostname "$PI_HOSTNAME"
|
||||||
|
sed -i "s/^127\.0\.1\.1.*/127.0.1.1\t$PI_HOSTNAME/" /etc/hosts
|
||||||
|
grep -q "^127\.0\.1\.1" /etc/hosts || printf '127.0.1.1\t%s\n' "$PI_HOSTNAME" >>/etc/hosts
|
||||||
|
fi
|
||||||
|
timedatectl set-timezone "$TIMEZONE"
|
||||||
|
# No RTC on the Pi 4: TLS to Convivo fails until the clock is synced.
|
||||||
|
systemctl enable --now systemd-timesyncd
|
||||||
|
apt-get update
|
||||||
|
apt-get "${APT_OPTS[@]}" full-upgrade
|
||||||
|
apt-get "${APT_OPTS[@]}" install ca-certificates curl gnupg jq usbutils iw
|
||||||
|
}
|
||||||
|
|
||||||
|
reliability() {
|
||||||
|
log "Reliability (watchdog, Wi-Fi power save, logs, no auto-upgrades)"
|
||||||
|
install -d /etc/systemd/system.conf.d /etc/systemd/journald.conf.d /etc/NetworkManager/conf.d
|
||||||
|
local before
|
||||||
|
before=$(sha256sum /etc/systemd/system.conf.d/convivo-watchdog.conf 2>/dev/null || true)
|
||||||
|
cat >/etc/systemd/system.conf.d/convivo-watchdog.conf <<'EOF'
|
||||||
|
[Manager]
|
||||||
|
RuntimeWatchdogSec=15s
|
||||||
|
RebootWatchdogSec=2min
|
||||||
|
EOF
|
||||||
|
cat >/etc/systemd/journald.conf.d/convivo.conf <<'EOF'
|
||||||
|
[Journal]
|
||||||
|
SystemMaxUse=100M
|
||||||
|
EOF
|
||||||
|
cat >/etc/NetworkManager/conf.d/convivo-wifi-powersave.conf <<'EOF'
|
||||||
|
[connection]
|
||||||
|
wifi.powersave = 2
|
||||||
|
EOF
|
||||||
|
if [[ "$before" != "$(sha256sum /etc/systemd/system.conf.d/convivo-watchdog.conf)" ]]; then
|
||||||
|
systemctl daemon-reexec
|
||||||
|
# comitup keeps a D-Bus proxy to the old systemd; without a restart its hotspot never starts DHCP.
|
||||||
|
systemctl try-restart comitup.service
|
||||||
|
fi
|
||||||
|
systemctl restart systemd-journald
|
||||||
|
# Avoid surprise upgrades/reboots during an event; re-run this script to update.
|
||||||
|
systemctl disable --now apt-daily.timer apt-daily-upgrade.timer 2>/dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
|
install_docker() {
|
||||||
|
log "Docker Engine"
|
||||||
|
if ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then
|
||||||
|
install -m 0755 -d /etc/apt/keyrings
|
||||||
|
curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
|
||||||
|
chmod a+r /etc/apt/keyrings/docker.asc
|
||||||
|
. /etc/os-release
|
||||||
|
cat >/etc/apt/sources.list.d/docker.sources <<EOF
|
||||||
|
Types: deb
|
||||||
|
URIs: https://download.docker.com/linux/debian
|
||||||
|
Suites: ${VERSION_CODENAME}
|
||||||
|
Components: stable
|
||||||
|
Architectures: $(dpkg --print-architecture)
|
||||||
|
Signed-By: /etc/apt/keyrings/docker.asc
|
||||||
|
EOF
|
||||||
|
apt-get update
|
||||||
|
apt-get "${APT_OPTS[@]}" install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
|
||||||
|
fi
|
||||||
|
install -d /etc/docker
|
||||||
|
local before
|
||||||
|
before=$(sha256sum /etc/docker/daemon.json 2>/dev/null || true)
|
||||||
|
cat >/etc/docker/daemon.json <<'EOF'
|
||||||
|
{
|
||||||
|
"log-driver": "json-file",
|
||||||
|
"log-opts": { "max-size": "10m", "max-file": "3" }
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
systemctl enable docker
|
||||||
|
# A restart bounces the running worker on its old image, so only restart on config changes.
|
||||||
|
if [[ "$before" != "$(sha256sum /etc/docker/daemon.json)" ]]; then
|
||||||
|
systemctl restart docker
|
||||||
|
fi
|
||||||
|
if [[ -n "${SUDO_USER:-}" && "$SUDO_USER" != root ]]; then
|
||||||
|
usermod -aG docker "$SUDO_USER"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
usb_printer() {
|
||||||
|
log "USB printer access"
|
||||||
|
# brother_ql talks raw USB via libusb; the kernel printer driver would hold the device.
|
||||||
|
echo "blacklist usblp" >/etc/modprobe.d/convivo-no-usblp.conf
|
||||||
|
modprobe -r usblp 2>/dev/null || true
|
||||||
|
# ipp-usb claims the QL-1110NWB's IPP-over-USB interfaces (libusb then fails with "Resource busy").
|
||||||
|
if systemctl list-unit-files ipp-usb.service >/dev/null 2>&1; then
|
||||||
|
systemctl disable --now ipp-usb.service 2>/dev/null || true
|
||||||
|
systemctl mask ipp-usb.service
|
||||||
|
fi
|
||||||
|
if lsusb -d 04f9: >/dev/null; then
|
||||||
|
lsusb -d 04f9:
|
||||||
|
else
|
||||||
|
warn "no Brother printer detected on USB (connect it and power it on)"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
env_get() { # env_get KEY FILE -> value of the last KEY=... line (empty if absent)
|
||||||
|
awk -F= -v k="$1" '$1 == k { sub(/^[^=]*=/, ""); v=$0 } END { print v }' "$2" 2>/dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
|
install_app() {
|
||||||
|
log "Convivo printer worker"
|
||||||
|
if [[ $STAGE_APP != 1 ]]; then echo "skipped (STAGE_APP=0)"; return; fi
|
||||||
|
install -d -m 0755 "$INSTALL_DIR"
|
||||||
|
local envf="$INSTALL_DIR/.env" old=""
|
||||||
|
[[ -f $envf ]] && old=$(cat "$envf")
|
||||||
|
# Empty setup variables keep what the portal (or an earlier run) already stored.
|
||||||
|
if [[ -n $old ]]; then
|
||||||
|
[[ -n $CONVIVO_URL ]] || CONVIVO_URL=$(env_get CONVIVO_URL "$envf")
|
||||||
|
[[ -n $CONVIVO_ANON_KEY ]] || CONVIVO_ANON_KEY=$(env_get CONVIVO_ANON_KEY "$envf")
|
||||||
|
[[ -n $PRINTER_STATION_TOKEN ]] || PRINTER_STATION_TOKEN=$(env_get PRINTER_STATION_TOKEN "$envf")
|
||||||
|
fi
|
||||||
|
: "${CONVIVO_URL:=https://convivo.appe.at}"
|
||||||
|
if [[ -f $IMAGE_TAR && -z $PRINTER_STATION_TOKEN ]]; then
|
||||||
|
die "PRINTER_STATION_TOKEN is empty (create a station in Admin → Printing, or use the portal)"
|
||||||
|
fi
|
||||||
|
[[ -n $CONVIVO_ANON_KEY ]] || warn "CONVIVO_ANON_KEY is empty — set it in the portal or the worker cannot reach Convivo"
|
||||||
|
umask 077
|
||||||
|
cat >"$envf" <<EOF
|
||||||
|
CONVIVO_URL=$CONVIVO_URL
|
||||||
|
CONVIVO_ANON_KEY=$CONVIVO_ANON_KEY
|
||||||
|
PRINTER_STATION_TOKEN=$PRINTER_STATION_TOKEN
|
||||||
|
STATION_NAME=$STATION_NAME
|
||||||
|
BADGE_CHECKIN_ORIGIN=$BADGE_CHECKIN_ORIGIN
|
||||||
|
BROTHER_MODEL=$BROTHER_MODEL
|
||||||
|
BROTHER_LABEL=$BROTHER_LABEL
|
||||||
|
PRINTER_IDENTIFIER=$PRINTER_IDENTIFIER
|
||||||
|
STATUS_LABELS=$STATUS_LABELS
|
||||||
|
EOF
|
||||||
|
umask 022
|
||||||
|
cat >"$INSTALL_DIR/docker-compose.yml" <<'EOF'
|
||||||
|
services:
|
||||||
|
printer:
|
||||||
|
image: convivo-printer:latest
|
||||||
|
container_name: convivo-printer
|
||||||
|
restart: always
|
||||||
|
network_mode: host
|
||||||
|
env_file: .env
|
||||||
|
devices:
|
||||||
|
- /dev/bus/usb:/dev/bus/usb
|
||||||
|
# USB char devices (major 189) so a replugged printer is reachable without a restart.
|
||||||
|
device_cgroup_rules:
|
||||||
|
- "c 189:* rmw"
|
||||||
|
volumes:
|
||||||
|
- /run/convivo:/run/convivo:ro
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
shm_size: 256m
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options: { max-size: "10m", max-file: "3" }
|
||||||
|
EOF
|
||||||
|
local loaded
|
||||||
|
if [[ -f $IMAGE_TAR ]]; then
|
||||||
|
loaded=$(docker load -i "$IMAGE_TAR" | awk -F': ' '/Loaded image/ {print $2; exit}')
|
||||||
|
[[ -n $loaded ]] || die "docker load did not report an image"
|
||||||
|
[[ $loaded == convivo-printer:latest ]] || docker tag "$loaded" convivo-printer:latest
|
||||||
|
docker image prune -f >/dev/null
|
||||||
|
elif docker image inspect convivo-printer:latest >/dev/null 2>&1; then
|
||||||
|
warn "image tar not found — reusing convivo-printer:latest already on the Pi"
|
||||||
|
else
|
||||||
|
warn "no image tar and no convivo-printer:latest on the Pi — wrote .env/compose, worker not started"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
# Compose recreates the container only when the config or image actually changed.
|
||||||
|
docker compose -f "$INSTALL_DIR/docker-compose.yml" up -d --remove-orphans
|
||||||
|
}
|
||||||
|
|
||||||
|
wifi_portal() {
|
||||||
|
log "Wi-Fi provisioning portal (comitup)"
|
||||||
|
if [[ $STAGE_WIFI_PORTAL != 1 ]]; then echo "skipped (STAGE_WIFI_PORTAL=0)"; return; fi
|
||||||
|
apt-get "${APT_OPTS[@]}" install comitup
|
||||||
|
install -d /usr/local/lib/convivo
|
||||||
|
cat >/usr/local/lib/convivo/netstate.sh <<'EOF'
|
||||||
|
#!/bin/sh
|
||||||
|
# comitup external_callback ($1 = HOTSPOT|CONNECTING|CONNECTED): publish network state for the worker.
|
||||||
|
state="${1:-UNKNOWN}"
|
||||||
|
dir=/run/convivo
|
||||||
|
mkdir -p "$dir"
|
||||||
|
ssid=$(iw dev wlan0 info 2>/dev/null | awk '/ssid/ {sub(/^[ \t]*ssid /, ""); print; exit}')
|
||||||
|
ip=$(ip -4 -o addr show scope global 2>/dev/null | awk '{split($4, a, "/"); print a[1]; exit}')
|
||||||
|
jq -n --arg state "$state" --arg ssid "$ssid" --arg ip "$ip" --arg at "$(date -Is)" \
|
||||||
|
'{state: $state, ssid: $ssid, ip: $ip, updated_at: $at}' >"$dir/network.json.tmp"
|
||||||
|
mv "$dir/network.json.tmp" "$dir/network.json"
|
||||||
|
EOF
|
||||||
|
chmod 0755 /usr/local/lib/convivo/netstate.sh
|
||||||
|
echo "d /run/convivo 0755 root root -" >/etc/tmpfiles.d/convivo.conf
|
||||||
|
systemd-tmpfiles --create /etc/tmpfiles.d/convivo.conf
|
||||||
|
# The Convivo portal replaces comitup-web while in HOTSPOT. install.sh copies portal.py
|
||||||
|
# next to this script; fail clearly if it is missing rather than leave the stock portal.
|
||||||
|
local portal_src="$(dirname "$(readlink -f "$0")")/portal.py"
|
||||||
|
[[ -f $portal_src ]] || die "portal.py not found next to setup.sh ($portal_src) — copy it alongside (install.sh does this)"
|
||||||
|
install -m 0755 -o root -g root "$portal_src" /usr/local/lib/convivo/portal.py
|
||||||
|
local dropin_dir=/etc/systemd/system/comitup-web.service.d dropin="$dropin_dir/convivo.conf"
|
||||||
|
install -d -m 0755 "$dropin_dir"
|
||||||
|
local dropin_before
|
||||||
|
dropin_before=$(sha256sum "$dropin" 2>/dev/null || true)
|
||||||
|
cat >"$dropin" <<'EOF'
|
||||||
|
# Managed by Convivo setup.sh — serve the Convivo portal instead of comitup-web.
|
||||||
|
[Service]
|
||||||
|
ExecStart=
|
||||||
|
ExecStart=/usr/bin/python3 /usr/local/lib/convivo/portal.py
|
||||||
|
EOF
|
||||||
|
# A changed drop-in only needs a reload; comitup-web is started on demand in HOTSPOT.
|
||||||
|
[[ "$dropin_before" != "$(sha256sum "$dropin")" ]] && systemctl daemon-reload
|
||||||
|
local before
|
||||||
|
before=$(sha256sum /etc/comitup.conf 2>/dev/null || true)
|
||||||
|
cat >/etc/comitup.conf <<EOF
|
||||||
|
# Managed by Convivo setup.sh
|
||||||
|
ap_name: $AP_NAME
|
||||||
|
external_callback: /usr/local/lib/convivo/netstate.sh
|
||||||
|
enable_appliance_mode: false
|
||||||
|
verbose: 0
|
||||||
|
EOF
|
||||||
|
systemctl enable comitup
|
||||||
|
# A restart re-negotiates Wi-Fi, so only do it when something changed.
|
||||||
|
if [[ "$before" != "$(sha256sum /etc/comitup.conf)" ]] || ! systemctl is-active --quiet comitup; then
|
||||||
|
systemctl restart comitup
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
verify() {
|
||||||
|
log "Verification"
|
||||||
|
docker --version
|
||||||
|
docker compose version
|
||||||
|
systemctl is-active systemd-timesyncd docker >/dev/null && echo "timesyncd + docker active"
|
||||||
|
[[ -e /dev/watchdog ]] && echo "hardware watchdog present"
|
||||||
|
lsusb -d 04f9: || warn "Brother printer not detected"
|
||||||
|
[[ $STAGE_WIFI_PORTAL == 1 ]] && { systemctl is-active comitup || warn "comitup not active"; }
|
||||||
|
if docker ps --format '{{.Names}}' | grep -qx convivo-printer; then
|
||||||
|
docker ps --filter name=convivo-printer --format 'worker: {{.Status}}'
|
||||||
|
fi
|
||||||
|
if [[ -f /var/run/reboot-required ]]; then
|
||||||
|
warn "reboot required (kernel/firmware update)"
|
||||||
|
[[ $REBOOT == 1 ]] && { log "Rebooting"; systemctl reboot; }
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
preflight
|
||||||
|
base_system
|
||||||
|
reliability
|
||||||
|
install_docker
|
||||||
|
usb_printer
|
||||||
|
install_app
|
||||||
|
wifi_portal
|
||||||
|
verify
|
||||||
|
log "Done"
|
||||||
@@ -0,0 +1,585 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Convivo provisioning portal served in place of comitup-web while the Pi is in HOTSPOT.
|
||||||
|
|
||||||
|
Wi-Fi picker (comitup D-Bus) plus optional Convivo URL / anon key / station token,
|
||||||
|
which are written to /opt/convivo-printer/.env and applied with docker compose.
|
||||||
|
Only the standard library plus python3-dbus (already required by comitup) is used;
|
||||||
|
dbus is imported lazily so the pure helpers stay unit-testable.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
from http.cookies import SimpleCookie
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
|
||||||
|
ENV_FILE = os.environ.get("PORTAL_ENV_FILE", "/opt/convivo-printer/.env")
|
||||||
|
PORT = int(os.environ.get("PORTAL_PORT", "80"))
|
||||||
|
DRY_RUN = os.environ.get("PORTAL_DRY_RUN", "0") == "1"
|
||||||
|
|
||||||
|
COMPOSE_FILE = "/opt/convivo-printer/docker-compose.yml"
|
||||||
|
AP_ADDR = "10.41.0.1"
|
||||||
|
MAX_BODY_BYTES = 8192
|
||||||
|
TOKEN_PREFIX = "cvp_"
|
||||||
|
TOKEN_LENGTH = 68
|
||||||
|
|
||||||
|
# The only keys the portal may write; anything else is rejected.
|
||||||
|
ENV_KEY_WHITELIST = ("CONVIVO_URL", "CONVIVO_ANON_KEY", "PRINTER_STATION_TOKEN")
|
||||||
|
|
||||||
|
DBUS_NAME = "com.github.davesteele.comitup"
|
||||||
|
DBUS_PATH = "/com/github/davesteele/comitup"
|
||||||
|
|
||||||
|
FAKE_NETWORKS = [
|
||||||
|
{"ssid": "FakeOffice", "strength": "82", "security": "encrypted"},
|
||||||
|
{"ssid": "FakeOpen", "strength": "40", "security": "unencrypted"},
|
||||||
|
]
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Pure helpers (unit-tested, no dbus / no root)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def parse_env(text: str) -> dict[str, str]:
|
||||||
|
result: dict[str, str] = {}
|
||||||
|
for line in text.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
key, _, value = line.partition("=")
|
||||||
|
result[key.strip()] = value.strip()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def update_env(text: str, updates: dict[str, str]) -> str:
|
||||||
|
"""Rewrite env text with `updates`; unknown lines are preserved as-is."""
|
||||||
|
for key in updates:
|
||||||
|
if key not in ENV_KEY_WHITELIST:
|
||||||
|
raise ValueError(f"key not allowed: {key}")
|
||||||
|
value = updates[key]
|
||||||
|
if "=" in value or any(c in value for c in "\r\n"):
|
||||||
|
raise ValueError(f"value for {key} must not contain newlines or '='")
|
||||||
|
lines = text.splitlines()
|
||||||
|
seen: set[str] = set()
|
||||||
|
out: list[str] = []
|
||||||
|
for line in lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
if stripped and not stripped.startswith("#") and "=" in stripped:
|
||||||
|
key = stripped.partition("=")[0].strip()
|
||||||
|
if key in updates:
|
||||||
|
out.append(f"{key}={updates[key]}")
|
||||||
|
seen.add(key)
|
||||||
|
continue
|
||||||
|
out.append(line)
|
||||||
|
for key in updates:
|
||||||
|
if key not in seen:
|
||||||
|
out.append(f"{key}={updates[key]}")
|
||||||
|
return "\n".join(out) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def write_env(path: str, text: str) -> None:
|
||||||
|
"""Atomically replace `path` with owner-only mode 0600."""
|
||||||
|
tmp = f"{path}.tmp"
|
||||||
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(text)
|
||||||
|
os.chmod(tmp, 0o600)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
|
||||||
|
|
||||||
|
def mask_token(token: str) -> str:
|
||||||
|
if not token:
|
||||||
|
return ""
|
||||||
|
return f"{TOKEN_PREFIX}…{token[-4:]}" if len(token) > 8 else f"{TOKEN_PREFIX}…"
|
||||||
|
|
||||||
|
|
||||||
|
def _is_private_host(host: str) -> bool:
|
||||||
|
host = host.strip("[]").lower()
|
||||||
|
if host in ("localhost", "localhost.localdomain") or host.endswith(".local"):
|
||||||
|
return True
|
||||||
|
m = re.fullmatch(r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})", host)
|
||||||
|
if not m:
|
||||||
|
return False
|
||||||
|
a, b = int(m.group(1)), int(m.group(2))
|
||||||
|
return a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or a == 127
|
||||||
|
|
||||||
|
|
||||||
|
def validate_url(value: str) -> tuple[str | None, str | None]:
|
||||||
|
"""Return (error, warning) for a Convivo URL; warning set for plaintext http on a LAN host."""
|
||||||
|
try:
|
||||||
|
parsed = urllib.parse.urlsplit(value)
|
||||||
|
except ValueError as exc:
|
||||||
|
return f"URL is not valid: {exc}", None
|
||||||
|
host = (parsed.hostname or "").lower()
|
||||||
|
if parsed.scheme == "https" and host:
|
||||||
|
return None, None
|
||||||
|
if parsed.scheme == "http" and host and _is_private_host(host):
|
||||||
|
return None, ("http:// works only on the local network — it sends the station "
|
||||||
|
"token unencrypted; prefer https://.")
|
||||||
|
return "URL must start with https:// (http:// only for a local/LAN address).", None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_anon_key(value: str) -> str | None:
|
||||||
|
parts = value.split(".")
|
||||||
|
if len(parts) != 3 or not all(parts):
|
||||||
|
return "Anon key must look like a JWT: three base64url parts separated by dots."
|
||||||
|
if not all(re.fullmatch(r"[A-Za-z0-9_\-]+", p) for p in parts):
|
||||||
|
return "Anon key must look like a JWT: three base64url parts separated by dots."
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_token(value: str) -> str | None:
|
||||||
|
if not value.startswith(TOKEN_PREFIX):
|
||||||
|
return f"Station token must start with {TOKEN_PREFIX}."
|
||||||
|
if len(value) != TOKEN_LENGTH:
|
||||||
|
return f"Station token must be exactly {TOKEN_LENGTH} characters."
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def sort_aps(aps: list[dict]) -> list[dict]:
|
||||||
|
def strength(ap: dict) -> float:
|
||||||
|
try:
|
||||||
|
return float(ap.get("strength", 0))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
return sorted(aps, key=strength, reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_connect(form: dict) -> tuple[str, str, dict[str, str], list[str], list[str]]:
|
||||||
|
"""Validate portal form fields. Returns (ssid, password, env-updates, errors, warnings)."""
|
||||||
|
errors: list[str] = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
ssid = (form.get("hidden_ssid") if form.get("hidden") else form.get("ssid")) or ""
|
||||||
|
ssid = ssid.strip()
|
||||||
|
if len(ssid.encode("utf-8")) > 32 or any(c in ssid for c in "\r\n"):
|
||||||
|
errors.append("Network name is too long or contains invalid characters.")
|
||||||
|
ssid = ""
|
||||||
|
password = form.get("password") or ""
|
||||||
|
if not ssid and not errors:
|
||||||
|
errors.append("Please choose a Wi-Fi network (or enter a hidden network name).")
|
||||||
|
if any(c in password for c in "\r\n"):
|
||||||
|
errors.append("Password contains invalid characters.")
|
||||||
|
if len(password) > 128:
|
||||||
|
errors.append("Password is too long.")
|
||||||
|
|
||||||
|
updates: dict[str, str] = {}
|
||||||
|
url = (form.get("convivo_url") or "").strip()
|
||||||
|
if url:
|
||||||
|
err, warn = validate_url(url)
|
||||||
|
if err:
|
||||||
|
errors.append(err)
|
||||||
|
else:
|
||||||
|
if warn:
|
||||||
|
warnings.append(warn)
|
||||||
|
updates["CONVIVO_URL"] = url
|
||||||
|
anon = (form.get("anon_key") or "").strip()
|
||||||
|
if anon:
|
||||||
|
err = validate_anon_key(anon)
|
||||||
|
if err:
|
||||||
|
errors.append(err)
|
||||||
|
else:
|
||||||
|
updates["CONVIVO_ANON_KEY"] = anon
|
||||||
|
token = (form.get("station_token") or "").strip()
|
||||||
|
if token:
|
||||||
|
err = validate_token(token)
|
||||||
|
if err:
|
||||||
|
errors.append(err)
|
||||||
|
else:
|
||||||
|
updates["PRINTER_STATION_TOKEN"] = token
|
||||||
|
return ssid, password, updates, errors, warnings
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# comitup D-Bus client (verified against comitup/statemgr.py)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
_dbus_proxy = None
|
||||||
|
_dbus_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _comitup_proxy():
|
||||||
|
global _dbus_proxy
|
||||||
|
with _dbus_lock:
|
||||||
|
if _dbus_proxy is None:
|
||||||
|
import dbus # lazy: unit tests never need python3-dbus
|
||||||
|
|
||||||
|
bus = dbus.SystemBus()
|
||||||
|
_dbus_proxy = bus.get_object(DBUS_NAME, DBUS_PATH)
|
||||||
|
return _dbus_proxy
|
||||||
|
|
||||||
|
|
||||||
|
def comitup_access_points() -> list[dict]:
|
||||||
|
"""access_points() -> aa{ss}: dicts with ssid, strength (0-100 %), security."""
|
||||||
|
raw = _comitup_proxy().access_points(dbus_interface=DBUS_NAME)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"ssid": str(ap.get("ssid", "")),
|
||||||
|
"strength": str(ap.get("strength", "")),
|
||||||
|
"security": str(ap.get("security", "")),
|
||||||
|
}
|
||||||
|
for ap in raw
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def comitup_state() -> tuple[str, str]:
|
||||||
|
"""state() -> ss: (HOTSPOT|CONNECTING|CONNECTED, connection)."""
|
||||||
|
state, connection = _comitup_proxy().state(dbus_interface=DBUS_NAME)
|
||||||
|
return str(state), str(connection)
|
||||||
|
|
||||||
|
|
||||||
|
def comitup_connect(ssid: str, password: str) -> None:
|
||||||
|
"""connect(ss, ss): activate/create a NM profile for the SSID and drop the AP."""
|
||||||
|
_comitup_proxy().connect(ssid, password, dbus_interface=DBUS_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
def list_networks() -> list[dict]:
|
||||||
|
if DRY_RUN:
|
||||||
|
return sort_aps(list(FAKE_NETWORKS))
|
||||||
|
return sort_aps(comitup_access_points())
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# HTML rendering (inline CSS only — no internet in hotspot mode)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
BASE_CSS = """
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{margin:0;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;
|
||||||
|
background:#f2f4f7;color:#1c1e21}
|
||||||
|
.wrap{max-width:480px;margin:0 auto;padding:20px 16px 40px}
|
||||||
|
header{display:flex;align-items:center;gap:10px;margin-bottom:16px}
|
||||||
|
header .dot{width:12px;height:12px;border-radius:50%;background:#e8590c}
|
||||||
|
header h1{font-size:19px;margin:0;font-weight:700}
|
||||||
|
header p{margin:0;font-size:12.5px;color:#6b7280}
|
||||||
|
.card{background:#fff;border-radius:14px;padding:16px;margin-bottom:14px;
|
||||||
|
box-shadow:0 1px 3px rgba(0,0,0,.08)}
|
||||||
|
h2{font-size:13px;margin:0 0 12px;text-transform:uppercase;letter-spacing:.04em;color:#6b7280}
|
||||||
|
label{display:block;font-size:13.5px;font-weight:600;margin:12px 0 4px}
|
||||||
|
input,select{width:100%;padding:12px;font-size:16px;border:1px solid #d1d5db;
|
||||||
|
border-radius:10px;background:#fff}
|
||||||
|
input[type=checkbox]{width:auto}
|
||||||
|
.row{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:14px}
|
||||||
|
.row label{margin:0;font-weight:500}
|
||||||
|
button{width:100%;margin-top:18px;padding:14px;font-size:16px;font-weight:700;color:#fff;
|
||||||
|
background:#0b57d0;border:0;border-radius:12px}
|
||||||
|
button:active{transform:scale(.99)}
|
||||||
|
.note{font-size:12.5px;color:#6b7280;margin:6px 0 0}
|
||||||
|
.err{background:#fdecea;border:1px solid #f5c2c0;color:#8a1f11;border-radius:10px;
|
||||||
|
padding:10px 12px;font-size:14px;margin-bottom:12px}
|
||||||
|
.err ul{margin:0;padding-left:18px}
|
||||||
|
.warn{background:#fff8e1;border:1px solid #ffe08a;color:#7a5b00;border-radius:10px;
|
||||||
|
padding:10px 12px;font-size:13.5px;margin-bottom:12px}
|
||||||
|
.warn ul{margin:0;padding-left:18px}
|
||||||
|
.current{font-size:13.5px;color:#374151;margin:0 0 6px;word-break:break-all}
|
||||||
|
details summary{cursor:pointer;font-size:13px;text-transform:uppercase;
|
||||||
|
letter-spacing:.04em;color:#6b7280;font-weight:700}
|
||||||
|
details[open] summary{margin-bottom:10px}
|
||||||
|
.ok{background:#e6f4ea;border:1px solid #b7dfc0;color:#1e4620;border-radius:10px;
|
||||||
|
padding:10px 12px;font-size:14px;margin-bottom:12px}
|
||||||
|
.spin{width:34px;height:34px;margin:0 auto 14px;border:4px solid #d1d5db;
|
||||||
|
border-top-color:#0b57d0;border-radius:50%;animation:s 1s linear infinite}
|
||||||
|
@keyframes s{to{transform:rotate(360deg)}}
|
||||||
|
.center{text-align:center}
|
||||||
|
"""
|
||||||
|
|
||||||
|
HIDDEN_JS = """
|
||||||
|
var cb=document.getElementById('hidden-cb'),sel=document.getElementById('ssid'),
|
||||||
|
hid=document.getElementById('hidden-ssid');
|
||||||
|
function sync(){sel.disabled=cb.checked;hid.style.display=cb.checked?'block':'none';
|
||||||
|
if(cb.checked)hid.focus();}
|
||||||
|
cb.addEventListener('change',sync);sync();
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _e(value: object) -> str:
|
||||||
|
return html.escape(str(value), quote=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _network_options(aps: list[dict]) -> str:
|
||||||
|
options = ['<option value="" disabled selected>Choose a network…</option>']
|
||||||
|
for ap in aps:
|
||||||
|
enc = "encrypted" if ap.get("security") == "encrypted" else "open"
|
||||||
|
options.append(
|
||||||
|
f'<option value="{_e(ap["ssid"])}">{_e(ap["ssid"])} — {enc}, '
|
||||||
|
f'signal {_e(ap.get("strength", "?"))}%</option>'
|
||||||
|
)
|
||||||
|
return "\n".join(options)
|
||||||
|
|
||||||
|
|
||||||
|
def render_page(title: str, body: str) -> bytes:
|
||||||
|
doc = (
|
||||||
|
"<!doctype html><html lang=en><head>"
|
||||||
|
"<meta charset=utf-8>"
|
||||||
|
"<meta name=viewport content='width=device-width,initial-scale=1'>"
|
||||||
|
f"<title>{_e(title)}</title><style>{BASE_CSS}</style></head>"
|
||||||
|
f"<body><div class=wrap><header><span class=dot></span><div>"
|
||||||
|
"<h1>Convivo Printer</h1><p>Wi-Fi setup · 10.41.0.1</p></div></header>"
|
||||||
|
f"{body}</div></body></html>"
|
||||||
|
)
|
||||||
|
return doc.encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def render_form(aps: list[dict], current: dict, errors: list[str],
|
||||||
|
warnings: list[str], csrf: str) -> bytes:
|
||||||
|
parts: list[str] = []
|
||||||
|
if errors:
|
||||||
|
parts.append('<div class=err><ul>' + "".join(f"<li>{_e(e)}</li>" for e in errors) + "</ul></div>")
|
||||||
|
if warnings:
|
||||||
|
parts.append('<div class=warn><ul>' + "".join(f"<li>{_e(w)}</li>" for w in warnings) + "</ul></div>")
|
||||||
|
if not aps:
|
||||||
|
parts.append('<div class=warn>No networks found right now — use “hidden network”, '
|
||||||
|
"or press refresh after a moment.</div>")
|
||||||
|
|
||||||
|
url = current.get("CONVIVO_URL", "")
|
||||||
|
station = current.get("STATION_NAME", "")
|
||||||
|
token_mask = mask_token(current.get("PRINTER_STATION_TOKEN", ""))
|
||||||
|
_, url_warn = validate_url(url) if url else (None, None)
|
||||||
|
|
||||||
|
parts.append(
|
||||||
|
"<form method=POST action=/connect>"
|
||||||
|
f"<input type=hidden name=csrf value=\"{_e(csrf)}\">"
|
||||||
|
'<div class=card><h2>1 · Wi-Fi network</h2>'
|
||||||
|
f'<label for=ssid>Network</label><select id=ssid name=ssid>{_network_options(aps)}</select>'
|
||||||
|
'<div class=row><input type=checkbox id=hidden-cb name=hidden value=1>'
|
||||||
|
"<label for=hidden-cb>My network is hidden</label></div>"
|
||||||
|
'<input id=hidden-ssid name=hidden_ssid type=text maxlength=32 style=display:none '
|
||||||
|
'placeholder="Hidden network name (SSID)" autocomplete=off>'
|
||||||
|
'<label for=password>Password</label>'
|
||||||
|
'<input id=password name=password type=password maxlength=128 autocomplete=off '
|
||||||
|
'placeholder="Leave empty for an open network">'
|
||||||
|
'<p class=note>The printer keeps any network it already knows and always '
|
||||||
|
"prefers internet access.</p>"
|
||||||
|
"</div>"
|
||||||
|
'<div class=card><h2>2 · Convivo connection (optional)</h2>'
|
||||||
|
f'<p class=current>Current URL: <strong>{_e(url) or "—"}</strong></p>'
|
||||||
|
f'<p class=current>Station name: <strong>{_e(station) or "—"}</strong></p>'
|
||||||
|
f'<p class=current>Station token: <strong>{_e(token_mask) or "not set"}</strong></p>'
|
||||||
|
+ (f'<div class=warn><ul><li>{_e(url_warn)}</li></ul></div>' if url_warn else "")
|
||||||
|
+ '<label for=convivo_url>Convivo URL</label>'
|
||||||
|
'<input id=convivo_url name=convivo_url type=url inputmode=url autocomplete=off '
|
||||||
|
'placeholder="https://admin.appe.at — empty keeps current">'
|
||||||
|
'<label for=anon_key>Anon key</label>'
|
||||||
|
'<input id=anon_key name=anon_key type=text autocomplete=off '
|
||||||
|
'placeholder="eyJ… JWT — empty keeps current">'
|
||||||
|
'<label for=station_token>Station token</label>'
|
||||||
|
'<input id=station_token name=station_token type=password autocomplete=off '
|
||||||
|
'placeholder="cvp_… — empty keeps current">'
|
||||||
|
'<p class=note>Blank fields keep the current values; tokens are never shown in full.</p>'
|
||||||
|
"</div>"
|
||||||
|
"<button type=submit>Connect</button>"
|
||||||
|
"</form>"
|
||||||
|
"<p class=center><a href=/networks.json class=note>Refresh network list</a></p>"
|
||||||
|
f"<script>{HIDDEN_JS}</script>"
|
||||||
|
)
|
||||||
|
return render_page("Convivo Printer — Wi-Fi setup", "".join(parts))
|
||||||
|
|
||||||
|
|
||||||
|
def render_switching(ssid: str, applied: list[str]) -> bytes:
|
||||||
|
applied_text = (
|
||||||
|
" · ".join(_e(k) for k in applied) if applied else "no changes — current settings kept"
|
||||||
|
)
|
||||||
|
body = (
|
||||||
|
'<div class="card center">'
|
||||||
|
'<div class=spin id=spin></div>'
|
||||||
|
"<h2 style=text-transform:none>Switching networks…</h2>"
|
||||||
|
f"<p>The printer is leaving this hotspot and joining <strong>{_e(ssid)}</strong>.</p>"
|
||||||
|
f'<p class=note>Convivo settings: {applied_text}</p>'
|
||||||
|
'<p class=note>This page will update when the Pi leaves the hotspot.</p>'
|
||||||
|
"</div>"
|
||||||
|
'<div class=card id=done style=display:none><div class=ok><strong>Network applied.</strong></div>'
|
||||||
|
"<p class=note>The open <em>Convivo-Printer</em> hotspot is gone — reconnect your phone "
|
||||||
|
"to your own Wi-Fi.</p></div>"
|
||||||
|
'<div class=card><p class=note>In the Convivo admin console the printer pill turns '
|
||||||
|
"<strong>green</strong> as soon as the station is online. If it stays grey for more "
|
||||||
|
"than a minute, the Wi-Fi credentials or the Convivo URL/token may be wrong — power "
|
||||||
|
"the printer off and on again to get the hotspot back.</p></div>"
|
||||||
|
"<script>var done=false;function poll(){fetch('/status').then(function(r){return r.json()})"
|
||||||
|
".then(function(j){if(!done&&j.state!=='HOTSPOT'){done=true;"
|
||||||
|
"document.getElementById('spin').style.display='none';"
|
||||||
|
"document.getElementById('done').style.display='block';}}).catch(function(){});}"
|
||||||
|
"setInterval(poll,2000);poll();</script>"
|
||||||
|
'<meta http-equiv="refresh" content="6">'
|
||||||
|
)
|
||||||
|
return render_page("Switching networks…", body)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# HTTP server
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class PortalHandler(BaseHTTPRequestHandler):
|
||||||
|
server_version = "ConvivoPortal/1.0"
|
||||||
|
protocol_version = "HTTP/1.1"
|
||||||
|
|
||||||
|
def log_message(self, fmt, *args): # keep stdout quiet on the Pi
|
||||||
|
pass
|
||||||
|
|
||||||
|
# -- helpers ------------------------------------------------------------
|
||||||
|
|
||||||
|
def _cookies(self) -> SimpleCookie:
|
||||||
|
cookie = SimpleCookie()
|
||||||
|
raw = self.headers.get("Cookie")
|
||||||
|
if raw:
|
||||||
|
cookie.load(raw)
|
||||||
|
return cookie
|
||||||
|
|
||||||
|
def _respond(self, code: int, body: bytes, content_type: str,
|
||||||
|
extra_headers: list[tuple[str, str]] | None = None) -> None:
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", content_type)
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
|
for key, value in extra_headers or []:
|
||||||
|
self.send_header(key, value)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def _redirect_to_portal(self) -> None:
|
||||||
|
# Captive-portal probes (captive.apple.com, connectivity-check, …) land here.
|
||||||
|
self._respond(302, b"", "text/plain; charset=utf-8",
|
||||||
|
[("Location", f"http://{AP_ADDR}/")])
|
||||||
|
|
||||||
|
# -- routes -------------------------------------------------------------
|
||||||
|
|
||||||
|
def do_GET(self) -> None: # noqa: N802
|
||||||
|
path = urllib.parse.urlsplit(self.path).path
|
||||||
|
if path == "/":
|
||||||
|
try:
|
||||||
|
aps = list_networks()
|
||||||
|
except Exception:
|
||||||
|
aps = []
|
||||||
|
try:
|
||||||
|
with open(ENV_FILE, encoding="utf-8") as fh:
|
||||||
|
current = parse_env(fh.read())
|
||||||
|
except OSError:
|
||||||
|
current = {}
|
||||||
|
csrf = secrets.token_hex(16)
|
||||||
|
body = render_form(aps, current, [], [], csrf)
|
||||||
|
self._respond(200, body, "text/html; charset=utf-8",
|
||||||
|
[("Set-Cookie", f"portal_csrf={csrf}; Path=/; Max-Age=3600")])
|
||||||
|
elif path == "/networks.json":
|
||||||
|
try:
|
||||||
|
aps = list_networks()
|
||||||
|
except Exception as exc:
|
||||||
|
self._respond(503, json.dumps({"error": str(exc)}).encode(),
|
||||||
|
"application/json")
|
||||||
|
return
|
||||||
|
self._respond(200, json.dumps({"networks": aps}).encode(), "application/json")
|
||||||
|
elif path == "/status":
|
||||||
|
try:
|
||||||
|
state, connection = ("HOTSPOT", "") if DRY_RUN else comitup_state()
|
||||||
|
except Exception:
|
||||||
|
state, connection = "UNKNOWN", ""
|
||||||
|
self._respond(200, json.dumps({"state": state, "connection": connection}).encode(),
|
||||||
|
"application/json")
|
||||||
|
else:
|
||||||
|
self._redirect_to_portal()
|
||||||
|
|
||||||
|
def do_POST(self) -> None: # noqa: N802
|
||||||
|
path = urllib.parse.urlsplit(self.path).path
|
||||||
|
if path != "/connect":
|
||||||
|
self.close_connection = True # the body is not read
|
||||||
|
self._respond(405, b"", "text/plain; charset=utf-8")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
except ValueError:
|
||||||
|
length = -1
|
||||||
|
if length < 0 or length > MAX_BODY_BYTES:
|
||||||
|
# The unread body would corrupt a kept-alive connection.
|
||||||
|
self.close_connection = True
|
||||||
|
self._respond(431, b"", "text/plain; charset=utf-8")
|
||||||
|
return
|
||||||
|
body = self.rfile.read(length).decode("utf-8", "replace")
|
||||||
|
form = {k: v for k, v in urllib.parse.parse_qsl(body, keep_blank_values=True)}
|
||||||
|
|
||||||
|
cookie = self._cookies().get("portal_csrf")
|
||||||
|
expected = cookie.value if cookie else ""
|
||||||
|
|
||||||
|
def show_form(errors: list[str], warnings: list[str]) -> None:
|
||||||
|
try:
|
||||||
|
aps = list_networks()
|
||||||
|
except Exception:
|
||||||
|
aps = []
|
||||||
|
try:
|
||||||
|
with open(ENV_FILE, encoding="utf-8") as fh:
|
||||||
|
current = parse_env(fh.read())
|
||||||
|
except OSError:
|
||||||
|
current = {}
|
||||||
|
csrf = secrets.token_hex(16)
|
||||||
|
body_bytes = render_form(aps, current, errors, warnings, csrf)
|
||||||
|
self._respond(400, body_bytes, "text/html; charset=utf-8",
|
||||||
|
[("Set-Cookie", f"portal_csrf={csrf}; Path=/; Max-Age=3600")])
|
||||||
|
|
||||||
|
if not expected or not secrets.compare_digest(form.get("csrf", ""), expected):
|
||||||
|
show_form(["The form expired — please try again."], [])
|
||||||
|
return
|
||||||
|
|
||||||
|
ssid, password, updates, errors, warnings = parse_connect(form)
|
||||||
|
if errors:
|
||||||
|
show_form(errors, warnings)
|
||||||
|
return
|
||||||
|
|
||||||
|
if updates:
|
||||||
|
try:
|
||||||
|
with open(ENV_FILE, encoding="utf-8") as fh:
|
||||||
|
old = fh.read()
|
||||||
|
except OSError:
|
||||||
|
old = ""
|
||||||
|
try:
|
||||||
|
write_env(ENV_FILE, update_env(old, updates))
|
||||||
|
except ValueError as exc:
|
||||||
|
show_form([str(exc)], warnings)
|
||||||
|
return
|
||||||
|
|
||||||
|
if ssid:
|
||||||
|
if DRY_RUN:
|
||||||
|
sys.stderr.write(f"[dry-run] would comitup connect to {ssid!r}\n")
|
||||||
|
else:
|
||||||
|
worker = threading.Thread(
|
||||||
|
target=self._connect_worker, args=(ssid, password, bool(updates)),
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
worker.start()
|
||||||
|
body_bytes = render_switching(ssid or "(no network change)", sorted(updates))
|
||||||
|
self._respond(200, body_bytes, "text/html; charset=utf-8")
|
||||||
|
|
||||||
|
def _connect_worker(self, ssid: str, password: str, env_changed: bool) -> None:
|
||||||
|
# Let the HTTP response flush before the AP disappears / docker bounces.
|
||||||
|
time.sleep(1.0)
|
||||||
|
if env_changed:
|
||||||
|
try:
|
||||||
|
subprocess.run(
|
||||||
|
["docker", "compose", "-f", COMPOSE_FILE, "up", "-d", "--force-recreate"],
|
||||||
|
check=False, timeout=180,
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
sys.stderr.write(f"portal: docker compose failed: {exc}\n")
|
||||||
|
time.sleep(0.5)
|
||||||
|
try:
|
||||||
|
comitup_connect(ssid, password)
|
||||||
|
except Exception as exc:
|
||||||
|
sys.stderr.write(f"portal: comitup connect failed: {exc}\n")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
server = ThreadingHTTPServer(("0.0.0.0", PORT), PortalHandler)
|
||||||
|
sys.stderr.write(f"convivo portal listening on :{PORT} (env={ENV_FILE}, dry_run={DRY_RUN})\n")
|
||||||
|
try:
|
||||||
|
server.serve_forever()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
pytest==9.1.1
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
brother_ql_next==0.12.0
|
||||||
|
pillow==13.0.0
|
||||||
|
httpx==0.28.1
|
||||||
|
playwright==1.55.0
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
import pytest # noqa: E402
|
||||||
|
from PIL import Image # noqa: E402
|
||||||
|
|
||||||
|
from worker.config import Config # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cfg() -> Config:
|
||||||
|
return Config(
|
||||||
|
convivo_url="http://localhost:54321",
|
||||||
|
convivo_anon_key="anon-key",
|
||||||
|
station_token="cvp_test_token",
|
||||||
|
station_name="Test desk",
|
||||||
|
dry_run=True,
|
||||||
|
status_labels=True,
|
||||||
|
wait_seconds=0,
|
||||||
|
network_state_file="/nonexistent/network.json",
|
||||||
|
app_version="test",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FakePrinter:
|
||||||
|
def __init__(self, ready=True, label_id="103x164", errors=None):
|
||||||
|
self.ready = ready
|
||||||
|
self.label_id = label_id
|
||||||
|
self.errors = errors or []
|
||||||
|
self.printed: list[tuple[Image.Image, str]] = []
|
||||||
|
self.print_result = {"did_print": True, "outcome": "printed"}
|
||||||
|
|
||||||
|
def get_status(self):
|
||||||
|
return {
|
||||||
|
"connected": True,
|
||||||
|
"model": "QL-1100NWB",
|
||||||
|
"ready": self.ready and not self.errors,
|
||||||
|
"media_type": "die-cut",
|
||||||
|
"label_id": self.label_id,
|
||||||
|
"media_width_mm": 104,
|
||||||
|
"media_length_mm": 164,
|
||||||
|
"errors": list(self.errors),
|
||||||
|
}
|
||||||
|
|
||||||
|
def print_image(self, img, label_id):
|
||||||
|
self.printed.append((img, label_id))
|
||||||
|
return dict(self.print_result)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeRenderer:
|
||||||
|
def __init__(self, image=None, error=None):
|
||||||
|
self.image = image or Image.new("RGB", (1181, 827), "white")
|
||||||
|
self.error = error
|
||||||
|
self.calls: list[tuple[dict, str]] = []
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
def render(self, payload, checkin_origin):
|
||||||
|
self.calls.append((payload, checkin_origin))
|
||||||
|
if self.error:
|
||||||
|
raise self.error
|
||||||
|
return self.image
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
class FakeRpc:
|
||||||
|
def __init__(self, claim_rows=None, claim_error=None, complete_error=None, heartbeat_name="Test desk"):
|
||||||
|
self.claim_rows = list(claim_rows or [])
|
||||||
|
self.claim_error = claim_error
|
||||||
|
self.complete_error = complete_error
|
||||||
|
self.heartbeat_name = heartbeat_name
|
||||||
|
self.claims = 0
|
||||||
|
self.completed: list[int] = []
|
||||||
|
self.failed: list[tuple[int, str, bool]] = []
|
||||||
|
self.heartbeats: list[dict] = []
|
||||||
|
self.heartbeat_error = None
|
||||||
|
|
||||||
|
def claim(self, wait_seconds):
|
||||||
|
self.claims += 1
|
||||||
|
if self.claim_error:
|
||||||
|
err, self.claim_error = self.claim_error, None
|
||||||
|
raise err
|
||||||
|
return list(self.claim_rows)
|
||||||
|
|
||||||
|
def complete(self, msg_id):
|
||||||
|
if self.complete_error:
|
||||||
|
err, self.complete_error = self.complete_error, None
|
||||||
|
raise err
|
||||||
|
self.completed.append(msg_id)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def fail(self, msg_id, error, retryable=False):
|
||||||
|
self.failed.append((msg_id, error, retryable))
|
||||||
|
return "retry" if retryable else "dead_letter"
|
||||||
|
|
||||||
|
def heartbeat(self, status):
|
||||||
|
if self.heartbeat_error:
|
||||||
|
raise self.heartbeat_error
|
||||||
|
self.heartbeats.append(status)
|
||||||
|
return {"station_id": "x", "name": self.heartbeat_name}
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from worker.label import LayoutTooLarge, compose, find_label
|
||||||
|
|
||||||
|
DIE_CUT = find_label("103x164")
|
||||||
|
ENDLESS = find_label("103")
|
||||||
|
|
||||||
|
|
||||||
|
def mm(px: int) -> float:
|
||||||
|
return px * 25.4 / 300
|
||||||
|
|
||||||
|
|
||||||
|
def badge_mm(w_mm: float, h_mm: float) -> Image.Image:
|
||||||
|
return Image.new("RGB", (round(w_mm * 300 / 25.4), round(h_mm * 300 / 25.4)), "red")
|
||||||
|
|
||||||
|
|
||||||
|
def test_label_specs():
|
||||||
|
assert (DIE_CUT.width_px, DIE_CUT.height_px, DIE_CUT.die_cut) == (1200, 1822, True)
|
||||||
|
assert (ENDLESS.width_px, ENDLESS.height_px, ENDLESS.die_cut) == (1200, 0, False)
|
||||||
|
with pytest.raises(KeyError):
|
||||||
|
find_label("nope")
|
||||||
|
|
||||||
|
|
||||||
|
def test_die_cut_centers_badge():
|
||||||
|
badge = badge_mm(100, 70)
|
||||||
|
assert (badge.width, badge.height) == (1181, 827)
|
||||||
|
out = compose(badge, DIE_CUT)
|
||||||
|
assert out.size == (1200, 1822)
|
||||||
|
assert out.getpixel((9, 497)) == (255, 0, 0)
|
||||||
|
assert out.getpixel((0, 0)) == (255, 255, 255)
|
||||||
|
assert out.getpixel((1199, 1821)) == (255, 255, 255)
|
||||||
|
|
||||||
|
|
||||||
|
def test_endless_uses_badge_height():
|
||||||
|
out = compose(badge_mm(100, 70), ENDLESS)
|
||||||
|
assert out.size == (1200, 827)
|
||||||
|
assert out.getpixel((9, 0)) == (255, 0, 0)
|
||||||
|
assert out.getpixel((0, 0)) == (255, 255, 255)
|
||||||
|
|
||||||
|
|
||||||
|
def test_rotated_when_it_only_fits_rotated():
|
||||||
|
badge = badge_mm(150, 90)
|
||||||
|
assert badge.width > DIE_CUT.width_px
|
||||||
|
out = compose(badge, DIE_CUT)
|
||||||
|
assert out.size == (1200, 1822)
|
||||||
|
# Rotated 1063x1772 content is centered: margins 68/25 px.
|
||||||
|
assert out.getpixel((600, 25)) == (255, 0, 0)
|
||||||
|
assert out.getpixel((600, 0)) == (255, 255, 255)
|
||||||
|
|
||||||
|
|
||||||
|
def test_too_large_raises():
|
||||||
|
with pytest.raises(LayoutTooLarge) as err:
|
||||||
|
compose(badge_mm(120, 200), DIE_CUT)
|
||||||
|
message = str(err.value)
|
||||||
|
assert "120x200 mm" in message and "103x164" in message
|
||||||
|
|
||||||
|
|
||||||
|
def test_overshoot_is_cropped():
|
||||||
|
out = compose(Image.new("RGB", (1203, 1822), "red"), DIE_CUT)
|
||||||
|
assert out.size == (1200, 1822)
|
||||||
|
|
||||||
|
|
||||||
|
def test_grayscale_input_converted():
|
||||||
|
out = compose(Image.new("L", (1181, 827), 0), DIE_CUT)
|
||||||
|
assert out.mode == "RGB"
|
||||||
|
|
||||||
|
|
||||||
|
def test_compose_accepts_identifier_string():
|
||||||
|
out = compose(badge_mm(100, 70), "103")
|
||||||
|
assert mm(out.width) == pytest.approx(101.6, abs=0.1)
|
||||||
|
assert out.height == 827
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from conftest import FakePrinter, FakeRenderer, FakeRpc
|
||||||
|
from worker.label import LayoutTooLarge
|
||||||
|
from worker.main import Worker
|
||||||
|
from worker.render import RenderError
|
||||||
|
from worker.rpc import InvalidToken, RpcUnavailable
|
||||||
|
|
||||||
|
PAYLOAD = {"schema": "convivo.badge-print/v1", "kind": "checkin", "sample": {}, "layout": {}}
|
||||||
|
ROW = {"msg_id": 42, "read_ct": 1, "payload": PAYLOAD}
|
||||||
|
|
||||||
|
|
||||||
|
def make(cfg, rpc=None, printer=None, renderer=None, sleeps=None):
|
||||||
|
if sleeps is None:
|
||||||
|
sleeps = []
|
||||||
|
return Worker(
|
||||||
|
cfg,
|
||||||
|
rpc or FakeRpc(),
|
||||||
|
printer or FakePrinter(),
|
||||||
|
renderer or FakeRenderer(),
|
||||||
|
sleep=sleeps.append,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_completes(cfg):
|
||||||
|
rpc, printer, renderer = FakeRpc([ROW]), FakePrinter(), FakeRenderer()
|
||||||
|
make(cfg, rpc, printer, renderer).handle_job(ROW)
|
||||||
|
assert rpc.completed == [42] and not rpc.failed
|
||||||
|
assert len(printer.printed) == 1
|
||||||
|
assert printer.printed[0][0].size == (1200, 1822)
|
||||||
|
assert renderer.calls[0][1] == cfg.checkin_origin
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_printed_fails_non_retryable(cfg):
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter()
|
||||||
|
printer.print_result = {"did_print": False, "outcome": "error"}
|
||||||
|
make(cfg, rpc, printer, FakeRenderer()).handle_job(ROW)
|
||||||
|
assert rpc.failed == [(42, "printer: error", False)] and not rpc.completed
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_after_successful_print_still_completes(cfg):
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter()
|
||||||
|
printer.errors = ["Tape end"]
|
||||||
|
make(cfg, rpc, printer, FakeRenderer()).handle_job(ROW)
|
||||||
|
assert rpc.completed == [42] and not rpc.failed
|
||||||
|
|
||||||
|
|
||||||
|
def test_printer_state_errors_explain_failed_print(cfg):
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter()
|
||||||
|
printer.print_result = {"did_print": False, "outcome": "error", "printer_state": {"errors": ["Cover open while printing"]}}
|
||||||
|
make(cfg, rpc, printer, FakeRenderer()).handle_job(ROW)
|
||||||
|
assert rpc.failed == [(42, "printer: Cover open while printing", False)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_layout_too_large_fails_non_retryable(cfg):
|
||||||
|
rpc, renderer = FakeRpc(), FakeRenderer(image=Image.new("RGB", (1417, 2362), "red"))
|
||||||
|
make(cfg, rpc, FakePrinter(), renderer).handle_job(ROW)
|
||||||
|
assert rpc.failed and rpc.failed[0][0] == 42 and rpc.failed[0][2] is False
|
||||||
|
assert "does not fit label 103x164" in rpc.failed[0][1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_error_fails_non_retryable(cfg):
|
||||||
|
rpc = FakeRpc()
|
||||||
|
make(cfg, rpc, FakePrinter(), FakeRenderer(error=RenderError("image failed to load"))).handle_job(ROW)
|
||||||
|
assert rpc.failed == [(42, "render: image failed to load", False)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_schema_fails_without_rendering(cfg):
|
||||||
|
rpc, renderer = FakeRpc(), FakeRenderer()
|
||||||
|
row = {"msg_id": 7, "read_ct": 1, "payload": {"schema": "other/v2"}}
|
||||||
|
make(cfg, rpc, FakePrinter(), renderer).handle_job(row)
|
||||||
|
assert rpc.failed == [(7, "unsupported payload schema: other/v2", False)]
|
||||||
|
assert renderer.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_unexpected_error_fails_retryable(cfg):
|
||||||
|
class Boom(FakeRenderer):
|
||||||
|
def render(self, payload, checkin_origin):
|
||||||
|
raise RuntimeError("kaboom")
|
||||||
|
|
||||||
|
rpc = FakeRpc()
|
||||||
|
make(cfg, rpc, FakePrinter(), Boom()).handle_job(ROW)
|
||||||
|
assert rpc.failed == [(42, "worker: RuntimeError: kaboom", True)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_label_id_fails_retryable(cfg):
|
||||||
|
rpc = FakeRpc()
|
||||||
|
make(cfg, rpc, FakePrinter(label_id=None), FakeRenderer()).handle_job(ROW)
|
||||||
|
assert rpc.failed == [(42, "printer: no label detected", True)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_unavailable_retries_then_succeeds(cfg):
|
||||||
|
rpc = FakeRpc(complete_error=RpcUnavailable("claim: ConnectError"))
|
||||||
|
sleeps: list[float] = []
|
||||||
|
make(cfg, rpc, FakePrinter(), FakeRenderer(), sleeps).handle_job(ROW)
|
||||||
|
assert rpc.completed == [42]
|
||||||
|
assert sleeps and sleeps[0] == 2.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_gives_up_after_limit(cfg):
|
||||||
|
class AlwaysDown(FakeRpc):
|
||||||
|
def complete(self, msg_id):
|
||||||
|
raise RpcUnavailable("down")
|
||||||
|
|
||||||
|
sleeps: list[float] = []
|
||||||
|
make(cfg, AlwaysDown(), FakePrinter(), FakeRenderer(), sleeps).handle_job(ROW)
|
||||||
|
assert sum(sleeps) <= 60 + 32
|
||||||
|
assert not sleeps or sum(sleeps[:-1]) <= 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_skips_claim_when_not_ready(cfg):
|
||||||
|
rpc, printer = FakeRpc([ROW]), FakePrinter(ready=False, errors=["Tape end"])
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
worker.tick()
|
||||||
|
assert rpc.claims == 0
|
||||||
|
assert worker.worker == "paused"
|
||||||
|
assert worker.last_error == "Tape end"
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_claims_and_processes_when_ready(cfg):
|
||||||
|
rpc = FakeRpc([ROW])
|
||||||
|
worker = make(cfg, rpc, FakePrinter(), FakeRenderer(), [])
|
||||||
|
worker.tick()
|
||||||
|
assert rpc.claims == 1 and rpc.completed == [42]
|
||||||
|
assert worker.worker == "idle"
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_claim_invalid_token_keeps_running(cfg):
|
||||||
|
rpc = FakeRpc(claim_error=InvalidToken("bad"))
|
||||||
|
worker = make(cfg, rpc, FakePrinter(), FakeRenderer(), [])
|
||||||
|
worker.tick() # must not raise
|
||||||
|
assert worker.worker == "idle"
|
||||||
|
|
||||||
|
|
||||||
|
def test_heartbeat_body_shape(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
rpc = FakeRpc()
|
||||||
|
worker = make(cfg, rpc, FakePrinter(), FakeRenderer())
|
||||||
|
worker.beat()
|
||||||
|
body = rpc.heartbeats[0]
|
||||||
|
assert body["version"] == "test"
|
||||||
|
assert body["station_name"] == "Test desk"
|
||||||
|
assert body["worker"] == "starting"
|
||||||
|
assert body["job_msg_id"] is None
|
||||||
|
assert body["printer"]["ready"] is True
|
||||||
|
assert body["network"]["ssid"] == "office"
|
||||||
|
assert body["label"] == "103x164"
|
||||||
|
assert body["last_error"] is None
|
||||||
|
assert isinstance(body["uptime_s"], int)
|
||||||
|
assert (tmp_path / "heartbeat-ok").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_heartbeat_invalid_token_does_not_raise(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
rpc = FakeRpc()
|
||||||
|
rpc.heartbeat_error = InvalidToken("nope")
|
||||||
|
worker = make(cfg, rpc, FakePrinter(), FakeRenderer())
|
||||||
|
worker.beat() # must not raise
|
||||||
|
assert rpc.heartbeats == []
|
||||||
|
assert not (tmp_path / "heartbeat-ok").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_need_wifi_printed_once_per_hotspot_episode(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter()
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
|
||||||
|
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "Convivo-Printer-0042"}))
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 1 # once per episode, not per tick
|
||||||
|
assert rpc.claims == 2 # both ticks keep claiming after the info label
|
||||||
|
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.5"}))
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 2 # ready label on the new network, no second need-wifi
|
||||||
|
|
||||||
|
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "Convivo-Printer-0042"}))
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 3 # a new hotspot episode prints again
|
||||||
|
|
||||||
|
|
||||||
|
def test_need_wifi_skipped_when_printer_not_ready(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "ap"}))
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter(ready=False, errors=["Tape end"])
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert printer.printed == []
|
||||||
|
assert worker._need_wifi_pending # still queued for when the printer recovers
|
||||||
|
|
||||||
|
|
||||||
|
def test_ready_label_once_per_network_key(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter()
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 1 # ready label after first heartbeat
|
||||||
|
worker.tick()
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 1 # not repeated for the same (ssid, ip)
|
||||||
|
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "other", "ip": "10.0.1.2"}))
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 2 # new network key → new ready label
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_labels_off_print_nothing(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
cfg.status_labels = False
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter()
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "Convivo-Printer-1", "ip": "10.41.0.1"}))
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert printer.printed == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_failing_info_label_does_not_block_jobs(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
|
||||||
|
|
||||||
|
def broken_label(*_args):
|
||||||
|
raise TypeError("boom")
|
||||||
|
|
||||||
|
monkeypatch.setattr("worker.main.ready_label", broken_label)
|
||||||
|
rpc, printer = FakeRpc([ROW]), FakePrinter()
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert rpc.completed == [42]
|
||||||
|
|
||||||
|
|
||||||
|
def test_heartbeat_name_overrides_env_station_name(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
|
||||||
|
rpc, printer = FakeRpc(heartbeat_name="Front desk 2"), FakePrinter()
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
assert worker.station_name == "Test desk" # env fallback before any heartbeat
|
||||||
|
worker.beat()
|
||||||
|
assert worker.station_name == "Front desk 2"
|
||||||
|
worker.beat()
|
||||||
|
assert rpc.heartbeats[1]["station_name"] == "Front desk 2"
|
||||||
|
|
||||||
|
import worker.main as worker_main
|
||||||
|
|
||||||
|
real_ready_label = worker_main.ready_label
|
||||||
|
labels: list[str] = []
|
||||||
|
|
||||||
|
def spy_ready_label(spec, station, network, version, now):
|
||||||
|
labels.append(station)
|
||||||
|
return real_ready_label(spec, station, network, version, now)
|
||||||
|
|
||||||
|
monkeypatch.setattr(worker_main, "ready_label", spy_ready_label)
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 1 # ready label printed with the server name
|
||||||
|
assert labels == ["Front desk 2"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_blank_heartbeat_name_keeps_previous(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
rpc = FakeRpc(heartbeat_name=" ")
|
||||||
|
worker = make(cfg, rpc, FakePrinter(), FakeRenderer())
|
||||||
|
worker.beat()
|
||||||
|
assert worker.station_name == "Test desk"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ready_label_only_after_successful_heartbeat(cfg, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
|
||||||
|
net = tmp_path / "network.json"
|
||||||
|
cfg.network_state_file = str(net)
|
||||||
|
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
|
||||||
|
rpc, printer = FakeRpc(), FakePrinter()
|
||||||
|
rpc.heartbeat_error = RpcUnavailable("down")
|
||||||
|
worker = make(cfg, rpc, printer, FakeRenderer(), [])
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert printer.printed == [] # no heartbeat yet → no ready label
|
||||||
|
rpc.heartbeat_error = None
|
||||||
|
worker.beat()
|
||||||
|
worker.tick()
|
||||||
|
assert len(printer.printed) == 1
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from worker.network import read_network
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_file_falls_back(tmp_path):
|
||||||
|
result = read_network(str(tmp_path / "absent.json"))
|
||||||
|
assert result["state"] == "UNKNOWN"
|
||||||
|
assert result["ssid"] is None
|
||||||
|
assert "ip" in result
|
||||||
|
|
||||||
|
|
||||||
|
def test_reads_state(tmp_path):
|
||||||
|
path = tmp_path / "network.json"
|
||||||
|
path.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9", "updated_at": "x"}))
|
||||||
|
result = read_network(str(path))
|
||||||
|
assert result["state"] == "CONNECTED"
|
||||||
|
assert result["ssid"] == "office"
|
||||||
|
assert result["ip"] == "10.0.0.9"
|
||||||
|
|
||||||
|
|
||||||
|
def test_corrupt_file_falls_back(tmp_path):
|
||||||
|
path = tmp_path / "network.json"
|
||||||
|
path.write_text("{not json")
|
||||||
|
assert read_network(str(path))["state"] == "UNKNOWN"
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_strings_become_none(tmp_path):
|
||||||
|
path = tmp_path / "network.json"
|
||||||
|
path.write_text(json.dumps({"state": "HOTSPOT", "ssid": "", "ip": ""}))
|
||||||
|
result = read_network(str(path))
|
||||||
|
assert result["state"] == "HOTSPOT"
|
||||||
|
assert result["ssid"] is None
|
||||||
|
assert result["ip"] is None
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from http.server import ThreadingHTTPServer
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from portal import portal
|
||||||
|
|
||||||
|
JWT = "eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiYW5vbiJ9.sig-__"
|
||||||
|
TOKEN = "cvp_" + "a" * 64
|
||||||
|
|
||||||
|
|
||||||
|
# ---- pure helpers ----------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_env_basic():
|
||||||
|
parsed = portal.parse_env("# comment\n\nA=1\nB = two words \nBAD\n")
|
||||||
|
assert parsed == {"A": "1", "B": "two words"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_env_replaces_in_place_preserves_others_appends_missing():
|
||||||
|
old = (
|
||||||
|
"# header\n"
|
||||||
|
"CONVIVO_URL=https://old.example\n"
|
||||||
|
"STATION_NAME=Desk\n"
|
||||||
|
"PRINTER_IDENTIFIER=usb://0x04f9:0x20a8\n"
|
||||||
|
)
|
||||||
|
new = portal.update_env(old, {"CONVIVO_URL": "https://new.example", "CONVIVO_ANON_KEY": JWT})
|
||||||
|
lines = new.splitlines()
|
||||||
|
assert lines[0] == "# header"
|
||||||
|
assert lines[1] == "CONVIVO_URL=https://new.example"
|
||||||
|
assert "STATION_NAME=Desk" in lines
|
||||||
|
assert "PRINTER_IDENTIFIER=usb://0x04f9:0x20a8" in lines
|
||||||
|
assert lines[-1] == f"CONVIVO_ANON_KEY={JWT}"
|
||||||
|
assert new.endswith("\n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_env_rejects_non_whitelisted_key():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
portal.update_env("", {"PATH": "/evil"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_env_rejects_injection_in_values():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
portal.update_env("", {"CONVIVO_URL": "https://x\nEVIL=1"})
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
portal.update_env("", {"CONVIVO_ANON_KEY": "a=b"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_write_env_atomic_and_mode(tmp_path):
|
||||||
|
path = tmp_path / ".env"
|
||||||
|
portal.write_env(str(path), "CONVIVO_URL=https://x\n")
|
||||||
|
assert path.read_text() == "CONVIVO_URL=https://x\n"
|
||||||
|
assert path.stat().st_mode & 0o777 == 0o600
|
||||||
|
assert not (tmp_path / ".env.tmp").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_mask_token():
|
||||||
|
assert portal.mask_token(TOKEN) == "cvp_…" + TOKEN[-4:]
|
||||||
|
assert portal.mask_token("") == ""
|
||||||
|
assert portal.mask_token("cvp_sh") == "cvp_…"
|
||||||
|
assert "a" * 64 not in portal.mask_token(TOKEN)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_url():
|
||||||
|
assert portal.validate_url("https://admin.appe.at")[0] is None
|
||||||
|
assert portal.validate_url("https://x")[0] is None
|
||||||
|
assert portal.validate_url("http://192.168.178.4:54321")[1] is not None
|
||||||
|
assert portal.validate_url("http://192.168.178.4:54321")[0] is None
|
||||||
|
assert portal.validate_url("http://localhost:54321")[0] is None
|
||||||
|
assert portal.validate_url("http://127.0.0.1:8000")[0] is None
|
||||||
|
assert portal.validate_url("http://printer.local")[0] is None
|
||||||
|
assert portal.validate_url("http://10.0.0.5")[0] is None
|
||||||
|
assert portal.validate_url("http://172.20.0.1")[0] is None
|
||||||
|
assert portal.validate_url("http://evil.example")[0] is not None
|
||||||
|
assert portal.validate_url("http://8.8.8.8")[0] is not None
|
||||||
|
assert portal.validate_url("ftp://host")[0] is not None
|
||||||
|
assert portal.validate_url("https://")[0] is not None
|
||||||
|
assert portal.validate_url("not a url")[0] is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_anon_key():
|
||||||
|
assert portal.validate_anon_key(JWT) is None
|
||||||
|
assert portal.validate_anon_key("a.b") is not None
|
||||||
|
assert portal.validate_anon_key("a.b.c.d") is not None
|
||||||
|
assert portal.validate_anon_key("a.b.!bad") is not None
|
||||||
|
assert portal.validate_anon_key("a..c") is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_token():
|
||||||
|
assert portal.validate_token(TOKEN) is None
|
||||||
|
assert portal.validate_token("x" * 68) is not None
|
||||||
|
assert portal.validate_token("cvp_short") is not None
|
||||||
|
assert portal.validate_token(TOKEN[:-1]) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_sort_aps_by_strength_desc_and_bad_values():
|
||||||
|
aps = [
|
||||||
|
{"ssid": "a", "strength": "20"},
|
||||||
|
{"ssid": "b", "strength": "bad"},
|
||||||
|
{"ssid": "c", "strength": "90"},
|
||||||
|
]
|
||||||
|
assert [ap["ssid"] for ap in portal.sort_aps(aps)] == ["c", "a", "b"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_connect_ok_with_warning():
|
||||||
|
form = {
|
||||||
|
"ssid": "Office",
|
||||||
|
"password": "secret",
|
||||||
|
"convivo_url": "http://192.168.1.5:54321",
|
||||||
|
"anon_key": JWT,
|
||||||
|
"station_token": TOKEN,
|
||||||
|
}
|
||||||
|
ssid, password, updates, errors, warnings = portal.parse_connect(form)
|
||||||
|
assert (ssid, password) == ("Office", "secret")
|
||||||
|
assert updates == {
|
||||||
|
"CONVIVO_URL": "http://192.168.1.5:54321",
|
||||||
|
"CONVIVO_ANON_KEY": JWT,
|
||||||
|
"PRINTER_STATION_TOKEN": TOKEN,
|
||||||
|
}
|
||||||
|
assert errors == []
|
||||||
|
assert warnings
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_connect_hidden_network():
|
||||||
|
form = {"hidden": "1", "hidden_ssid": "SecretNet", "password": "pw"}
|
||||||
|
ssid, password, updates, errors, warnings = portal.parse_connect(form)
|
||||||
|
assert (ssid, password) == ("SecretNet", "pw")
|
||||||
|
assert updates == {} and errors == [] and warnings == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_connect_errors():
|
||||||
|
_, _, updates, errors, _ = portal.parse_connect({})
|
||||||
|
assert errors and not updates
|
||||||
|
_, _, updates, errors, _ = portal.parse_connect(
|
||||||
|
{"ssid": "x" * 40, "convivo_url": "http://evil.example", "station_token": "nope"}
|
||||||
|
)
|
||||||
|
assert len(errors) == 3 and not updates
|
||||||
|
|
||||||
|
|
||||||
|
# ---- HTTP server (dry-run, fake env file) ----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def portal_server(tmp_path, monkeypatch):
|
||||||
|
env = tmp_path / ".env"
|
||||||
|
env.write_text(
|
||||||
|
"CONVIVO_URL=https://old.example\n"
|
||||||
|
"CONVIVO_ANON_KEY=old.anon.key\n"
|
||||||
|
"PRINTER_STATION_TOKEN=cvp_" + "b" * 64 + "\n"
|
||||||
|
"STATION_NAME=Desk\n"
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(portal, "ENV_FILE", str(env))
|
||||||
|
monkeypatch.setattr(portal, "DRY_RUN", True)
|
||||||
|
server = ThreadingHTTPServer(("127.0.0.1", 0), portal.PortalHandler)
|
||||||
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
yield f"http://127.0.0.1:{server.server_address[1]}", env
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def _get(url: str):
|
||||||
|
with urllib.request.urlopen(url, timeout=5) as resp:
|
||||||
|
return resp.status, resp.read().decode()
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_root_lists_networks_and_masks_token(portal_server):
|
||||||
|
base, env = portal_server
|
||||||
|
status, page = _get(base + "/")
|
||||||
|
assert status == 200
|
||||||
|
assert "FakeOffice" in page and "FakeOpen" in page
|
||||||
|
assert "https://old.example" in page # current URL is shown
|
||||||
|
assert "cvp_" + "b" * 64 not in page # token only masked
|
||||||
|
assert "bbbb" in page # last four shown
|
||||||
|
|
||||||
|
|
||||||
|
def _get_with_cookie(url: str):
|
||||||
|
req = urllib.request.Request(url)
|
||||||
|
with urllib.request.urlopen(req, timeout=5) as resp:
|
||||||
|
page = resp.read().decode()
|
||||||
|
raw_cookie = resp.headers.get("Set-Cookie", "")
|
||||||
|
csrf_cookie = raw_cookie.split(";")[0] # portal_csrf=...
|
||||||
|
return page, csrf_cookie
|
||||||
|
|
||||||
|
|
||||||
|
def test_catchall_redirects_to_portal(portal_server):
|
||||||
|
base, _ = portal_server
|
||||||
|
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
opener = urllib.request.build_opener(NoRedirect)
|
||||||
|
for probe in ("/generate_204", "/hotspot-detect.html", "/ncsi.txt", "/connecttest.txt"):
|
||||||
|
try:
|
||||||
|
opener.open(base + probe, timeout=5)
|
||||||
|
pytest.fail(f"{probe} should not return 200")
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
assert exc.code == 302, probe
|
||||||
|
assert exc.headers.get("Location") == "http://10.41.0.1/", probe
|
||||||
|
|
||||||
|
|
||||||
|
def test_networks_json_and_status(portal_server):
|
||||||
|
base, _ = portal_server
|
||||||
|
status, payload = _get(base + "/networks.json")
|
||||||
|
assert status == 200
|
||||||
|
networks = json.loads(payload)["networks"]
|
||||||
|
assert [n["ssid"] for n in networks] == ["FakeOffice", "FakeOpen"]
|
||||||
|
status, payload = _get(base + "/status")
|
||||||
|
assert status == 200 and json.loads(payload)["state"] == "HOTSPOT"
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_connect_rewrites_env_without_echoing_secrets(portal_server):
|
||||||
|
base, env = portal_server
|
||||||
|
page, csrf_cookie = _get_with_cookie(base + "/")
|
||||||
|
csrf = page.split('name=csrf value="')[1].split('"')[0]
|
||||||
|
form = urllib.parse.urlencode(
|
||||||
|
{
|
||||||
|
"csrf": csrf,
|
||||||
|
"ssid": "FakeOffice",
|
||||||
|
"password": "hunter2",
|
||||||
|
"convivo_url": "https://admin.appe.at",
|
||||||
|
"anon_key": "",
|
||||||
|
"station_token": TOKEN,
|
||||||
|
}
|
||||||
|
).encode()
|
||||||
|
req = urllib.request.Request(base + "/connect", data=form,
|
||||||
|
headers={"Cookie": csrf_cookie})
|
||||||
|
with urllib.request.urlopen(req, timeout=5) as resp:
|
||||||
|
status, page = resp.status, resp.read().decode()
|
||||||
|
assert status == 200
|
||||||
|
assert "FakeOffice" in page
|
||||||
|
assert TOKEN not in page and JWT not in page
|
||||||
|
written = env.read_text()
|
||||||
|
assert "CONVIVO_URL=https://admin.appe.at" in written
|
||||||
|
assert f"PRINTER_STATION_TOKEN={TOKEN}" in written
|
||||||
|
assert "CONVIVO_ANON_KEY=old.anon.key" in written # blank field keeps current
|
||||||
|
assert "STATION_NAME=Desk" in written # untouched keys preserved
|
||||||
|
assert env.stat().st_mode & 0o777 == 0o600
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_connect_rejects_bad_csrf(portal_server):
|
||||||
|
base, env = portal_server
|
||||||
|
before = env.read_text()
|
||||||
|
form = urllib.parse.urlencode({"csrf": "nope", "ssid": "FakeOffice"}).encode()
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
urllib.request.urlopen(urllib.request.Request(base + "/connect", data=form), timeout=5)
|
||||||
|
assert exc.value.code == 400
|
||||||
|
assert env.read_text() == before
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_connect_rejects_oversized_body(portal_server):
|
||||||
|
base, _ = portal_server
|
||||||
|
form = b"csrf=x&ssid=" + b"A" * (portal.MAX_BODY_BYTES + 1)
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
urllib.request.urlopen(urllib.request.Request(base + "/connect", data=form), timeout=5)
|
||||||
|
assert exc.value.code == 431
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from worker.printer import Printer, map_status
|
||||||
|
from worker.config import Config
|
||||||
|
|
||||||
|
# Verbatim status dict reported by the real QL-1110NWB with DK-22246 loaded.
|
||||||
|
REAL_STATUS = {
|
||||||
|
"status_type": "Reply to status request",
|
||||||
|
"phase_type": "Waiting to receive",
|
||||||
|
"model_name": "QL-1100NWB",
|
||||||
|
"media_type": "Die-cut labels",
|
||||||
|
"media_width": 104,
|
||||||
|
"media_length": 164,
|
||||||
|
"identified_media": type(
|
||||||
|
"Label",
|
||||||
|
(),
|
||||||
|
{"identifier": "103x164", "dots_printable": (1200, 1822), "form_factor": 1},
|
||||||
|
)(),
|
||||||
|
"errors": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def cfg(label: str = "auto") -> Config:
|
||||||
|
return Config(
|
||||||
|
convivo_url="http://x",
|
||||||
|
convivo_anon_key="k",
|
||||||
|
station_token="t",
|
||||||
|
brother_label=label,
|
||||||
|
dry_run=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_maps_real_status():
|
||||||
|
st = map_status(REAL_STATUS, "auto")
|
||||||
|
assert st == {
|
||||||
|
"connected": True,
|
||||||
|
"model": "QL-1100NWB",
|
||||||
|
"ready": True,
|
||||||
|
"media_type": "die-cut",
|
||||||
|
"label_id": "103x164",
|
||||||
|
"media_width_mm": 104,
|
||||||
|
"media_length_mm": 164,
|
||||||
|
"errors": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_continuous_media_type():
|
||||||
|
raw = dict(REAL_STATUS, media_type="Continuous length tape")
|
||||||
|
st = map_status(raw, "auto")
|
||||||
|
assert st["media_type"] == "continuous" and st["ready"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_errors_block_ready():
|
||||||
|
raw = dict(REAL_STATUS, errors=["Tape end"])
|
||||||
|
st = map_status(raw, "auto")
|
||||||
|
assert st["errors"] == ["Tape end"] and not st["ready"] and st["connected"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_roll_mismatch():
|
||||||
|
st = map_status(REAL_STATUS, "103")
|
||||||
|
assert not st["ready"]
|
||||||
|
assert st["errors"] == ["wrong roll: loaded 103x164, expected 103"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_matching_expected_label_ok():
|
||||||
|
assert map_status(REAL_STATUS, "103x164")["ready"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_waiting_phase():
|
||||||
|
raw = dict(REAL_STATUS, phase_type="Printing data to receive buffer")
|
||||||
|
st = map_status(raw, "auto")
|
||||||
|
assert st["connected"] and not st["ready"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_media():
|
||||||
|
raw = dict(REAL_STATUS, media_type="No media", identified_media=None)
|
||||||
|
st = map_status(raw, "auto")
|
||||||
|
assert st["media_type"] is None and st["label_id"] is None
|
||||||
|
assert "no media loaded" in st["errors"] and not st["ready"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unidentified_media_not_ready():
|
||||||
|
raw = dict(REAL_STATUS, identified_media=None)
|
||||||
|
st = map_status(raw, "auto")
|
||||||
|
assert not st["ready"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_dry_run_status_and_print(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setattr("worker.printer.DRYRUN_DIR", tmp_path)
|
||||||
|
printer = Printer(cfg())
|
||||||
|
st = printer.get_status()
|
||||||
|
assert st["ready"] and st["label_id"] == "103x164"
|
||||||
|
result = printer.print_image(Image.new("RGB", (10, 10)), "103x164")
|
||||||
|
assert result["did_print"] is True
|
||||||
|
assert list(tmp_path.glob("dryrun-*.png"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_dry_run_honours_expected_label():
|
||||||
|
st = Printer(cfg("103")).get_status()
|
||||||
|
assert st["label_id"] == "103" and st["media_type"] == "continuous"
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from conftest import FakePrinter, FakeRenderer, FakeRpc # noqa: F401 (path setup)
|
||||||
|
from worker.config import Config
|
||||||
|
from worker.main import Worker
|
||||||
|
from worker.rpc import InvalidToken, Rpc, RpcError, RpcUnavailable
|
||||||
|
|
||||||
|
CFG = Config(convivo_url="http://x", convivo_anon_key="k", station_token="t")
|
||||||
|
|
||||||
|
|
||||||
|
def make_rpc(handler) -> Rpc:
|
||||||
|
client = httpx.Client(transport=httpx.MockTransport(handler), headers={"apikey": "k"})
|
||||||
|
return Rpc(CFG, client=client)
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_rows_and_timeout():
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
assert request.url.path == "/rest/v1/rpc/printer_claim_badge_job"
|
||||||
|
return httpx.Response(200, json=[{"msg_id": 1, "read_ct": 1, "payload": {}}])
|
||||||
|
|
||||||
|
rows = make_rpc(handler).claim(10)
|
||||||
|
assert rows[0]["msg_id"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_empty_returns_list():
|
||||||
|
rpc = make_rpc(lambda r: httpx.Response(200, json=[]))
|
||||||
|
assert rpc.claim(0) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_token_401():
|
||||||
|
rpc = make_rpc(lambda r: httpx.Response(401, json={"code": "28000"}))
|
||||||
|
with pytest.raises(InvalidToken):
|
||||||
|
rpc.complete(1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_token_via_body_code():
|
||||||
|
rpc = make_rpc(lambda r: httpx.Response(400, json={"code": "28000", "message": "invalid printer token"}))
|
||||||
|
with pytest.raises(InvalidToken):
|
||||||
|
rpc.heartbeat({})
|
||||||
|
|
||||||
|
|
||||||
|
def test_5xx_is_unavailable():
|
||||||
|
rpc = make_rpc(lambda r: httpx.Response(503, text="nope"))
|
||||||
|
with pytest.raises(RpcUnavailable):
|
||||||
|
rpc.complete(1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_connect_error_is_unavailable():
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
raise httpx.ConnectError("boom", request=request)
|
||||||
|
|
||||||
|
rpc = make_rpc(handler)
|
||||||
|
with pytest.raises(RpcUnavailable):
|
||||||
|
rpc.claim(0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_4xx_is_rpc_error():
|
||||||
|
rpc = make_rpc(lambda r: httpx.Response(400, json={"code": "P0001", "message": "job not found"}))
|
||||||
|
with pytest.raises(RpcError):
|
||||||
|
rpc.fail(1, "x")
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_never_in_repr():
|
||||||
|
cfg = Config(convivo_url="http://x", convivo_anon_key="k", station_token="cvp_secret123")
|
||||||
|
rpc = Rpc(cfg, client=httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json=[]))))
|
||||||
|
assert "cvp_secret123" not in repr(cfg)
|
||||||
|
assert "cvp_secret123" not in repr(rpc)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fail_returns_outcome_string():
|
||||||
|
rpc = make_rpc(lambda r: httpx.Response(200, json="dead_letter"))
|
||||||
|
assert rpc.fail(1, "err", retryable=False) == "dead_letter"
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from worker.label import find_label
|
||||||
|
from worker.status_labels import need_wifi_label, ready_label
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("label_id", ["103", "103x164", "62"])
|
||||||
|
def test_status_labels_render_for_any_roll(label_id):
|
||||||
|
spec = find_label(label_id)
|
||||||
|
network = {"state": "CONNECTED", "ssid": "Venue", "ip": "10.0.0.5"}
|
||||||
|
for img in (
|
||||||
|
ready_label(spec, "Welcome desk", network, "v1", datetime(2026, 10, 18, 9, 0)),
|
||||||
|
need_wifi_label(spec, "Convivo-Printer-6372"),
|
||||||
|
):
|
||||||
|
assert img.width == spec.width_px
|
||||||
|
assert img.height > 0 and isinstance(img.height, int)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Convivo badge-printer worker package."""
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from .main import main
|
||||||
|
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""Environment-driven configuration for the badge-printer worker."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
|
||||||
|
def _int(name: str, default: int) -> int:
|
||||||
|
raw = os.environ.get(name, "").strip()
|
||||||
|
try:
|
||||||
|
return int(raw) if raw else default
|
||||||
|
except ValueError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def _flag(name: str, default: str = "0") -> bool:
|
||||||
|
return os.environ.get(name, default).strip().lower() in ("1", "true", "yes", "on")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Config:
|
||||||
|
convivo_url: str
|
||||||
|
convivo_anon_key: str
|
||||||
|
station_name: str = "Welcome desk"
|
||||||
|
checkin_origin: str = "https://admin.appe.at"
|
||||||
|
brother_model: str = "QL-1110NWB"
|
||||||
|
brother_label: str = "auto"
|
||||||
|
printer_identifier: str = "usb://0x04f9:0x20a8"
|
||||||
|
dry_run: bool = False
|
||||||
|
# Ready / no-network labels cost media; the admin status pill is the default channel.
|
||||||
|
status_labels: bool = False
|
||||||
|
heartbeat_seconds: int = 10
|
||||||
|
vt_seconds: int = 120
|
||||||
|
wait_seconds: int = 2
|
||||||
|
network_state_file: str = "/run/convivo/network.json"
|
||||||
|
renderer_dir: str = "/app/renderer"
|
||||||
|
threshold: int = 70
|
||||||
|
dither: bool = False
|
||||||
|
app_version: str = "dev"
|
||||||
|
# Token kept out of repr so it can never reach a log line.
|
||||||
|
station_token: str = field(default="", repr=False)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_env(cls) -> "Config":
|
||||||
|
url = os.environ.get("CONVIVO_URL", "").strip().rstrip("/")
|
||||||
|
anon = os.environ.get("CONVIVO_ANON_KEY", "").strip()
|
||||||
|
token = os.environ.get("PRINTER_STATION_TOKEN", "").strip()
|
||||||
|
missing = [
|
||||||
|
name
|
||||||
|
for name, value in (
|
||||||
|
("CONVIVO_URL", url),
|
||||||
|
("CONVIVO_ANON_KEY", anon),
|
||||||
|
("PRINTER_STATION_TOKEN", token),
|
||||||
|
)
|
||||||
|
if not value
|
||||||
|
]
|
||||||
|
if missing:
|
||||||
|
raise RuntimeError(f"missing required env: {', '.join(missing)}")
|
||||||
|
return cls(
|
||||||
|
convivo_url=url,
|
||||||
|
convivo_anon_key=anon,
|
||||||
|
station_token=token,
|
||||||
|
station_name=os.environ.get("STATION_NAME", "Welcome desk").strip()
|
||||||
|
or "Welcome desk",
|
||||||
|
checkin_origin=os.environ.get("BADGE_CHECKIN_ORIGIN", "https://admin.appe.at")
|
||||||
|
.strip()
|
||||||
|
.rstrip("/"),
|
||||||
|
brother_model=os.environ.get("BROTHER_MODEL", "QL-1110NWB").strip(),
|
||||||
|
brother_label=os.environ.get("BROTHER_LABEL", "auto").strip() or "auto",
|
||||||
|
printer_identifier=os.environ.get("PRINTER_IDENTIFIER", "usb://0x04f9:0x20a8").strip(),
|
||||||
|
dry_run=_flag("DRY_RUN"),
|
||||||
|
status_labels=_flag("STATUS_LABELS"),
|
||||||
|
heartbeat_seconds=_int("HEARTBEAT_SECONDS", 10),
|
||||||
|
vt_seconds=_int("VT_SECONDS", 120),
|
||||||
|
wait_seconds=_int("WAIT_SECONDS", 2),
|
||||||
|
network_state_file=os.environ.get("NETWORK_STATE_FILE", "/run/convivo/network.json"),
|
||||||
|
renderer_dir=os.environ.get("RENDERER_DIR", "/app/renderer"),
|
||||||
|
threshold=_int("THRESHOLD", 70),
|
||||||
|
dither=_flag("DITHER"),
|
||||||
|
app_version=os.environ.get("APP_VERSION", "dev").strip() or "dev",
|
||||||
|
)
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
"""Fit a rendered badge image onto a printer label (pure Pillow, no hardware)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
from brother_ql.labels import ALL_LABELS, FormFactor, Label
|
||||||
|
|
||||||
|
PRINT_DPI = 300
|
||||||
|
# Small rounding differences between the renderer and the label spec are cropped.
|
||||||
|
OVERSHOOT_TOLERANCE_PX = 3
|
||||||
|
|
||||||
|
|
||||||
|
class LayoutTooLarge(Exception):
|
||||||
|
"""The badge cannot be printed on the loaded label, even rotated."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LabelSpec:
|
||||||
|
identifier: str
|
||||||
|
width_px: int
|
||||||
|
height_px: int # 0 for endless/continuous labels
|
||||||
|
die_cut: bool
|
||||||
|
|
||||||
|
|
||||||
|
def find_label(identifier: str) -> LabelSpec:
|
||||||
|
for label in ALL_LABELS:
|
||||||
|
if label.identifier == identifier:
|
||||||
|
width, height = label.dots_printable
|
||||||
|
return LabelSpec(
|
||||||
|
identifier=label.identifier,
|
||||||
|
width_px=int(width),
|
||||||
|
height_px=int(height),
|
||||||
|
die_cut=label.form_factor == FormFactor.DIE_CUT,
|
||||||
|
)
|
||||||
|
raise KeyError(f"unknown label identifier: {identifier}")
|
||||||
|
|
||||||
|
|
||||||
|
def _mm(px: int) -> int:
|
||||||
|
return round(px * 25.4 / PRINT_DPI)
|
||||||
|
|
||||||
|
|
||||||
|
def _too_large(badge: Image.Image, spec: LabelSpec) -> LayoutTooLarge:
|
||||||
|
return LayoutTooLarge(
|
||||||
|
f"layout {_mm(badge.width)}x{_mm(badge.height)} mm does not fit label {spec.identifier}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _fits(w: int, h: int, spec: LabelSpec) -> bool:
|
||||||
|
if w > spec.width_px + OVERSHOOT_TOLERANCE_PX:
|
||||||
|
return False
|
||||||
|
if spec.die_cut and h > spec.height_px + OVERSHOOT_TOLERANCE_PX:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _crop_to(w: int, h: int, spec: LabelSpec) -> tuple[int, int]:
|
||||||
|
return (
|
||||||
|
min(w, spec.width_px),
|
||||||
|
min(h, spec.height_px) if spec.die_cut else h,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def compose(badge: Image.Image, label: LabelSpec | str) -> Image.Image:
|
||||||
|
"""Return a bitmap sized for `label`, ready for brother_ql convert()."""
|
||||||
|
spec = find_label(label) if isinstance(label, str) else label
|
||||||
|
if badge.mode != "RGB":
|
||||||
|
badge = badge.convert("RGB")
|
||||||
|
|
||||||
|
if not _fits(badge.width, badge.height, spec):
|
||||||
|
rotated = badge.transpose(Image.Transpose.ROTATE_270)
|
||||||
|
if not _fits(rotated.width, rotated.height, spec):
|
||||||
|
raise _too_large(badge, spec)
|
||||||
|
badge = rotated
|
||||||
|
|
||||||
|
if spec.die_cut:
|
||||||
|
canvas = Image.new("RGB", (spec.width_px, spec.height_px), "white")
|
||||||
|
target = _crop_to(badge.width, badge.height, spec)
|
||||||
|
if (badge.width, badge.height) != target:
|
||||||
|
badge = badge.crop((0, 0, target[0], target[1]))
|
||||||
|
canvas.paste(badge, ((spec.width_px - badge.width) // 2, (spec.height_px - badge.height) // 2))
|
||||||
|
return canvas
|
||||||
|
|
||||||
|
# Endless: fixed width, length follows the badge.
|
||||||
|
target_w = min(badge.width, spec.width_px)
|
||||||
|
if badge.width != target_w:
|
||||||
|
badge = badge.crop((0, 0, target_w, badge.height))
|
||||||
|
canvas = Image.new("RGB", (spec.width_px, badge.height), "white")
|
||||||
|
canvas.paste(badge, ((spec.width_px - badge.width) // 2, 0))
|
||||||
|
return canvas
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
"""Worker loop: heartbeat beacon, informational labels and badge jobs."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from .config import Config
|
||||||
|
from .label import LayoutTooLarge, compose, find_label
|
||||||
|
from .network import read_network
|
||||||
|
from .render import RenderError, Renderer
|
||||||
|
from .rpc import InvalidToken, Rpc, RpcError, RpcUnavailable
|
||||||
|
from .status_labels import need_wifi_label, ready_label
|
||||||
|
|
||||||
|
log = logging.getLogger("worker")
|
||||||
|
|
||||||
|
SCHEMA = "convivo.badge-print/v1"
|
||||||
|
HEARTBEAT_TOUCH = "/tmp/heartbeat-ok"
|
||||||
|
COMPLETE_RETRY_LIMIT_SECONDS = 60
|
||||||
|
|
||||||
|
|
||||||
|
class Worker:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
cfg: Config,
|
||||||
|
rpc: Rpc,
|
||||||
|
printer: Any,
|
||||||
|
renderer: Any,
|
||||||
|
*,
|
||||||
|
sleep: Callable[[float], None] = time.sleep,
|
||||||
|
monotonic: Callable[[], float] = time.monotonic,
|
||||||
|
):
|
||||||
|
self.cfg = cfg
|
||||||
|
self._rpc = rpc
|
||||||
|
self._printer = printer
|
||||||
|
self._renderer = renderer
|
||||||
|
self._sleep = sleep
|
||||||
|
self._started = monotonic()
|
||||||
|
self._monotonic = monotonic
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._state_lock = threading.Lock()
|
||||||
|
self.worker = "starting"
|
||||||
|
self.job_msg_id: int | None = None
|
||||||
|
self.last_error: str | None = None
|
||||||
|
# Replaced by the server name once the first heartbeat succeeds.
|
||||||
|
self._station_name = cfg.station_name
|
||||||
|
self._printer_status: dict[str, Any] = printer.get_status()
|
||||||
|
self._network: dict[str, Any] = read_network(cfg.network_state_file)
|
||||||
|
self._heartbeat_thread: threading.Thread | None = None
|
||||||
|
self._last_invalid_token_log = 0.0
|
||||||
|
self._last_rpc_log = 0.0
|
||||||
|
# Informational-label bookkeeping.
|
||||||
|
self._was_hotspot = False
|
||||||
|
self._need_wifi_pending = False
|
||||||
|
self._ready_pending_key: tuple[str | None, str | None] | None = None
|
||||||
|
self._ready_printed_key: tuple[str | None, str | None] | None = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ helpers
|
||||||
|
@property
|
||||||
|
def printer_status(self) -> dict[str, Any]:
|
||||||
|
with self._state_lock:
|
||||||
|
return dict(self._printer_status)
|
||||||
|
|
||||||
|
def _set_printer_status(self, status: dict[str, Any]) -> None:
|
||||||
|
with self._state_lock:
|
||||||
|
self._printer_status = status
|
||||||
|
|
||||||
|
def _set_worker(self, value: str, msg_id: int | None = None, error: str | None = None) -> None:
|
||||||
|
with self._state_lock:
|
||||||
|
self.worker = value
|
||||||
|
self.job_msg_id = msg_id
|
||||||
|
self.last_error = error
|
||||||
|
|
||||||
|
@property
|
||||||
|
def station_name(self) -> str:
|
||||||
|
with self._state_lock:
|
||||||
|
return self._station_name
|
||||||
|
|
||||||
|
def _net_key(self) -> tuple[str | None, str | None]:
|
||||||
|
return (self._network.get("ssid"), self._network.get("ip"))
|
||||||
|
|
||||||
|
def _status_body(self) -> dict[str, Any]:
|
||||||
|
with self._state_lock:
|
||||||
|
printer = dict(self._printer_status)
|
||||||
|
body = {
|
||||||
|
"version": self.cfg.app_version,
|
||||||
|
"station_name": self._station_name,
|
||||||
|
"worker": self.worker,
|
||||||
|
"job_msg_id": self.job_msg_id,
|
||||||
|
"printer": printer,
|
||||||
|
"network": dict(self._network),
|
||||||
|
"label": printer.get("label_id"),
|
||||||
|
"last_error": self.last_error,
|
||||||
|
"uptime_s": int(self._monotonic() - self._started),
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
|
||||||
|
# -------------------------------------------------------------- heartbeat
|
||||||
|
def start_heartbeat(self) -> None:
|
||||||
|
self._heartbeat_thread = threading.Thread(target=self._heartbeat_loop, daemon=True)
|
||||||
|
self._heartbeat_thread.start()
|
||||||
|
|
||||||
|
def _heartbeat_loop(self) -> None:
|
||||||
|
interval = max(2, self.cfg.heartbeat_seconds)
|
||||||
|
while not self._stop.is_set():
|
||||||
|
self.beat()
|
||||||
|
self._stop.wait(interval)
|
||||||
|
|
||||||
|
def beat(self) -> None:
|
||||||
|
"""One heartbeat: read network state, then beacon it (never raises)."""
|
||||||
|
self._network = read_network(self.cfg.network_state_file)
|
||||||
|
if self._network.get("state") == "HOTSPOT":
|
||||||
|
if not self._was_hotspot:
|
||||||
|
self._need_wifi_pending = True
|
||||||
|
self._was_hotspot = True
|
||||||
|
else:
|
||||||
|
self._was_hotspot = False
|
||||||
|
try:
|
||||||
|
result = self._rpc.heartbeat(self._status_body())
|
||||||
|
self._apply_station_name(result)
|
||||||
|
except InvalidToken:
|
||||||
|
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
|
||||||
|
except RpcUnavailable as err:
|
||||||
|
self._log_rate_limited("_last_rpc_log", f"heartbeat unavailable: {err}")
|
||||||
|
except RpcError as err:
|
||||||
|
self._log_rate_limited("_last_rpc_log", f"heartbeat failed: {err}")
|
||||||
|
else:
|
||||||
|
self._touch_heartbeat()
|
||||||
|
# A ready label only makes sense on a real network, not in hotspot mode.
|
||||||
|
key = self._net_key()
|
||||||
|
if self._network.get("state") != "HOTSPOT" and key != self._ready_printed_key:
|
||||||
|
self._ready_pending_key = key
|
||||||
|
|
||||||
|
def _apply_station_name(self, result: Any) -> None:
|
||||||
|
"""Adopt the name the server reports for this station."""
|
||||||
|
if not isinstance(result, dict):
|
||||||
|
return
|
||||||
|
name = result.get("name")
|
||||||
|
if isinstance(name, str) and name.strip():
|
||||||
|
with self._state_lock:
|
||||||
|
self._station_name = name.strip()
|
||||||
|
|
||||||
|
def _touch_heartbeat(self) -> None:
|
||||||
|
try:
|
||||||
|
Path(HEARTBEAT_TOUCH).touch()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _log_rate_limited(self, attr: str, message: str, interval: float = 60.0) -> None:
|
||||||
|
now = self._monotonic()
|
||||||
|
if now - getattr(self, attr) >= interval:
|
||||||
|
setattr(self, attr, now)
|
||||||
|
log.warning(message)
|
||||||
|
|
||||||
|
# ------------------------------------------------- informational labels
|
||||||
|
def _print_local(self, img: Image.Image) -> bool:
|
||||||
|
label_id = self.printer_status.get("label_id") or "103x164"
|
||||||
|
try:
|
||||||
|
result = self._printer.print_image(img, label_id)
|
||||||
|
except Exception as err: # noqa: BLE001
|
||||||
|
log.warning("info label failed: %s", err)
|
||||||
|
return False
|
||||||
|
if not result.get("did_print"):
|
||||||
|
log.warning("info label not printed: %s", result.get("outcome"))
|
||||||
|
return False
|
||||||
|
log.info("printed info label on %s", label_id)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _maybe_print_info_labels(self) -> bool:
|
||||||
|
"""Print a pending ready/need-Wi-Fi label. True if the loop should continue."""
|
||||||
|
if not self.cfg.status_labels:
|
||||||
|
return False
|
||||||
|
if not (self._need_wifi_pending or self._ready_pending_key):
|
||||||
|
return False
|
||||||
|
status = self.printer_status
|
||||||
|
if not status.get("ready"):
|
||||||
|
return False
|
||||||
|
spec_id = status.get("label_id")
|
||||||
|
if not spec_id:
|
||||||
|
return False
|
||||||
|
spec = find_label(spec_id)
|
||||||
|
try:
|
||||||
|
if self._need_wifi_pending:
|
||||||
|
if self._print_local(need_wifi_label(spec, self._network.get("ssid") or "Convivo-Printer")):
|
||||||
|
self._need_wifi_pending = False
|
||||||
|
return True
|
||||||
|
key = self._ready_pending_key
|
||||||
|
assert key is not None
|
||||||
|
if self._print_local(ready_label(spec, self.station_name, self._network, self.cfg.app_version, datetime.now())):
|
||||||
|
self._ready_printed_key = key
|
||||||
|
self._ready_pending_key = None
|
||||||
|
except Exception: # noqa: BLE001 — a status label must never block badge jobs
|
||||||
|
log.exception("info label failed; dropping it")
|
||||||
|
self._need_wifi_pending = False
|
||||||
|
self._ready_printed_key, self._ready_pending_key = self._ready_pending_key, None
|
||||||
|
return True
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------- jobs
|
||||||
|
def _fail(self, msg_id: int, error: str, retryable: bool) -> None:
|
||||||
|
log.warning("job %s failed (%s): %s", msg_id, "retry" if retryable else "dead-letter", error)
|
||||||
|
try:
|
||||||
|
outcome = self._rpc.fail(msg_id, error, retryable)
|
||||||
|
log.info("job %s → %s", msg_id, outcome)
|
||||||
|
except InvalidToken:
|
||||||
|
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
|
||||||
|
except (RpcUnavailable, RpcError) as err:
|
||||||
|
log.warning("could not report failure for job %s: %s", msg_id, err)
|
||||||
|
|
||||||
|
def _complete(self, msg_id: int) -> None:
|
||||||
|
delay = 2.0
|
||||||
|
waited = 0.0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
self._rpc.complete(msg_id)
|
||||||
|
log.info("job %s completed", msg_id)
|
||||||
|
return
|
||||||
|
except InvalidToken:
|
||||||
|
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
|
||||||
|
return
|
||||||
|
except RpcUnavailable as err:
|
||||||
|
if waited + delay > COMPLETE_RETRY_LIMIT_SECONDS:
|
||||||
|
# The job stays in flight; redelivery may print a duplicate.
|
||||||
|
log.error("complete for job %s still failing after %ds: %s", msg_id, int(waited), err)
|
||||||
|
return
|
||||||
|
log.warning("complete for job %s unavailable, retrying in %.0fs", msg_id, delay)
|
||||||
|
self._sleep(delay)
|
||||||
|
waited += delay
|
||||||
|
delay = min(delay * 2, 32.0)
|
||||||
|
except RpcError as err:
|
||||||
|
log.error("complete for job %s rejected: %s", msg_id, err)
|
||||||
|
return
|
||||||
|
|
||||||
|
def handle_job(self, row: dict[str, Any]) -> None:
|
||||||
|
msg_id = int(row.get("msg_id", 0))
|
||||||
|
payload = row.get("payload")
|
||||||
|
self._set_worker("printing", msg_id)
|
||||||
|
try:
|
||||||
|
if not isinstance(payload, dict) or payload.get("schema") != SCHEMA:
|
||||||
|
got = payload.get("schema") if isinstance(payload, dict) else type(payload).__name__
|
||||||
|
self._fail(msg_id, f"unsupported payload schema: {got}", retryable=False)
|
||||||
|
return
|
||||||
|
label_id = self.printer_status.get("label_id")
|
||||||
|
if not label_id:
|
||||||
|
self._fail(msg_id, "printer: no label detected", retryable=True)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
badge = self._renderer.render(payload, self.cfg.checkin_origin)
|
||||||
|
composed = compose_or_raise(badge, label_id)
|
||||||
|
except LayoutTooLarge as err:
|
||||||
|
self._fail(msg_id, str(err), retryable=False)
|
||||||
|
return
|
||||||
|
except RenderError as err:
|
||||||
|
self._fail(msg_id, f"render: {err}", retryable=False)
|
||||||
|
return
|
||||||
|
result = self._printer.print_image(composed, label_id)
|
||||||
|
status = self._printer.get_status()
|
||||||
|
self._set_printer_status(status)
|
||||||
|
# A post-print error (e.g. roll just ran out) must not dead-letter a badge that did print.
|
||||||
|
if result.get("did_print"):
|
||||||
|
self._complete(msg_id)
|
||||||
|
return
|
||||||
|
errors = (result.get("printer_state") or {}).get("errors") or status.get("errors") or []
|
||||||
|
detail = "; ".join(str(e) for e in errors) or result.get("outcome", "unknown")
|
||||||
|
self._fail(msg_id, f"printer: {detail}", retryable=False)
|
||||||
|
except Exception as err: # noqa: BLE001 — never lose a job silently
|
||||||
|
log.exception("unexpected error on job %s", msg_id)
|
||||||
|
self._fail(msg_id, f"worker: {type(err).__name__}: {err}", retryable=True)
|
||||||
|
finally:
|
||||||
|
self._set_worker("idle")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------- loop
|
||||||
|
def tick(self) -> None:
|
||||||
|
status = self._printer.get_status()
|
||||||
|
self._set_printer_status(status)
|
||||||
|
if self._maybe_print_info_labels():
|
||||||
|
status = self._printer.get_status()
|
||||||
|
self._set_printer_status(status)
|
||||||
|
if not status.get("ready"):
|
||||||
|
self._set_worker("paused", error="; ".join(status.get("errors") or []) or "printer not ready")
|
||||||
|
self._sleep(3)
|
||||||
|
return
|
||||||
|
self._set_worker("idle")
|
||||||
|
try:
|
||||||
|
rows = self._rpc.claim(self.cfg.wait_seconds)
|
||||||
|
except InvalidToken:
|
||||||
|
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
|
||||||
|
self._sleep(5)
|
||||||
|
return
|
||||||
|
except RpcUnavailable as err:
|
||||||
|
self._log_rate_limited("_last_rpc_log", f"claim unavailable: {err}")
|
||||||
|
self._sleep(5)
|
||||||
|
return
|
||||||
|
except RpcError as err:
|
||||||
|
log.warning("claim failed: %s", err)
|
||||||
|
self._sleep(5)
|
||||||
|
return
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
self.handle_job(rows[0])
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
self.start_heartbeat()
|
||||||
|
while not self._stop.is_set():
|
||||||
|
try:
|
||||||
|
self.tick()
|
||||||
|
except Exception: # noqa: BLE001 — the loop must survive anything
|
||||||
|
log.exception("loop iteration failed")
|
||||||
|
self._sleep(3)
|
||||||
|
log.info("worker stopping")
|
||||||
|
self._renderer.close()
|
||||||
|
self._rpc.close()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
|
||||||
|
|
||||||
|
def compose_or_raise(badge: Image.Image, label_id: str) -> Image.Image:
|
||||||
|
return compose(badge, find_label(label_id))
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
|
try:
|
||||||
|
cfg = Config.from_env()
|
||||||
|
except RuntimeError as err:
|
||||||
|
log.error("%s", err)
|
||||||
|
return 2
|
||||||
|
log.info("convivo printer worker %s starting (station=%s, dry_run=%s)", cfg.app_version, cfg.station_name, cfg.dry_run)
|
||||||
|
rpc = Rpc(cfg)
|
||||||
|
from .printer import Printer
|
||||||
|
|
||||||
|
printer = Printer(cfg)
|
||||||
|
renderer = Renderer(cfg.renderer_dir)
|
||||||
|
worker = Worker(cfg, rpc, printer, renderer)
|
||||||
|
|
||||||
|
def _handle_signal(_sig: int, _frame: Any) -> None:
|
||||||
|
log.info("signal received, finishing current job")
|
||||||
|
worker.stop()
|
||||||
|
|
||||||
|
signal.signal(signal.SIGTERM, _handle_signal)
|
||||||
|
signal.signal(signal.SIGINT, _handle_signal)
|
||||||
|
worker.run()
|
||||||
|
return 0
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""Read the comitup network state file written by the host."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
UNKNOWN = {"state": "UNKNOWN", "ssid": None, "ip": None}
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_ip() -> str | None:
|
||||||
|
# UDP connect trick: picks the source address of the default route, no traffic sent.
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
try:
|
||||||
|
sock.connect(("8.8.8.8", 53))
|
||||||
|
return str(sock.getsockname()[0])
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
sock.close()
|
||||||
|
|
||||||
|
|
||||||
|
def read_network(path: str) -> dict:
|
||||||
|
try:
|
||||||
|
raw = json.loads(Path(path).read_text())
|
||||||
|
except (OSError, ValueError):
|
||||||
|
result = dict(UNKNOWN)
|
||||||
|
result["ip"] = _detect_ip()
|
||||||
|
return result
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
result = dict(UNKNOWN)
|
||||||
|
result["ip"] = _detect_ip()
|
||||||
|
return result
|
||||||
|
return {
|
||||||
|
"state": str(raw.get("state") or "UNKNOWN"),
|
||||||
|
"ssid": raw.get("ssid") or None,
|
||||||
|
"ip": raw.get("ip") or None,
|
||||||
|
"updated_at": raw.get("updated_at"),
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""Brother QL printer access through brother_ql (pyusb backend), serialized by a lock."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from brother_ql.backends.helpers import send as bq_send
|
||||||
|
from brother_ql.backends.helpers import status as bq_status
|
||||||
|
from brother_ql.conversion import convert
|
||||||
|
from brother_ql.raster import BrotherQLRaster
|
||||||
|
|
||||||
|
from .config import Config
|
||||||
|
from .label import find_label
|
||||||
|
|
||||||
|
log = logging.getLogger("worker.printer")
|
||||||
|
|
||||||
|
DIE_CUT_MEDIA = "Die-cut labels"
|
||||||
|
CONTINUOUS_MEDIA = "Continuous length tape"
|
||||||
|
DRYRUN_DIR = Path("/tmp/dryrun")
|
||||||
|
|
||||||
|
|
||||||
|
def map_status(raw: dict[str, Any], expected_label: str) -> dict[str, Any]:
|
||||||
|
"""Translate a brother_ql status dict into the heartbeat printer block."""
|
||||||
|
errors = [str(e) for e in (raw.get("errors") or [])]
|
||||||
|
identified = raw.get("identified_media")
|
||||||
|
label_id = getattr(identified, "identifier", None)
|
||||||
|
media_type = raw.get("media_type")
|
||||||
|
media = {"Die-cut labels": "die-cut", "Continuous length tape": "continuous"}.get(
|
||||||
|
str(media_type)
|
||||||
|
)
|
||||||
|
if media is None and str(media_type) == "No media":
|
||||||
|
errors.append("no media loaded")
|
||||||
|
|
||||||
|
if expected_label not in ("auto", "") and label_id and label_id != expected_label:
|
||||||
|
errors.append(f"wrong roll: loaded {label_id}, expected {expected_label}")
|
||||||
|
|
||||||
|
connected = str(raw.get("status_type", "")) == "Reply to status request"
|
||||||
|
phase_ok = str(raw.get("phase_type", "")) == "Waiting to receive"
|
||||||
|
ready = connected and phase_ok and not errors and label_id is not None
|
||||||
|
|
||||||
|
return {
|
||||||
|
"connected": connected,
|
||||||
|
"model": raw.get("model_name"),
|
||||||
|
"ready": ready,
|
||||||
|
"media_type": media,
|
||||||
|
"label_id": label_id,
|
||||||
|
"media_width_mm": raw.get("media_width"),
|
||||||
|
"media_length_mm": raw.get("media_length"),
|
||||||
|
"errors": errors,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Printer:
|
||||||
|
def __init__(self, cfg: Config):
|
||||||
|
self._model = cfg.brother_model
|
||||||
|
self._identifier = cfg.printer_identifier
|
||||||
|
self._expected_label = cfg.brother_label
|
||||||
|
self._threshold = cfg.threshold
|
||||||
|
self._dither = cfg.dither
|
||||||
|
self._dry_run = cfg.dry_run
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
if self._dry_run:
|
||||||
|
log.warning("DRY_RUN active: nothing is sent to the printer")
|
||||||
|
|
||||||
|
def get_status(self) -> dict[str, Any]:
|
||||||
|
if self._dry_run:
|
||||||
|
label_id = None if self._expected_label == "auto" else self._expected_label
|
||||||
|
label_id = label_id or "103x164"
|
||||||
|
spec = find_label(label_id)
|
||||||
|
return {
|
||||||
|
"connected": True,
|
||||||
|
"model": f"{self._model} (dry-run)",
|
||||||
|
"ready": True,
|
||||||
|
"media_type": "die-cut" if spec.die_cut else "continuous",
|
||||||
|
"label_id": label_id,
|
||||||
|
"media_width_mm": int(spec.width_px * 25.4 // 300),
|
||||||
|
"media_length_mm": int(spec.height_px * 25.4 // 300) if spec.die_cut else 0,
|
||||||
|
"errors": [],
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
with self._lock:
|
||||||
|
st, _raw = bq_status(
|
||||||
|
printer_model=self._model,
|
||||||
|
printer_identifier=self._identifier,
|
||||||
|
backend_identifier="pyusb",
|
||||||
|
)
|
||||||
|
except Exception as err: # noqa: BLE001 — USB stack raises many types
|
||||||
|
log.debug("status failed: %r", err)
|
||||||
|
return {
|
||||||
|
"connected": False,
|
||||||
|
"model": None,
|
||||||
|
"ready": False,
|
||||||
|
"media_type": None,
|
||||||
|
"label_id": None,
|
||||||
|
"media_width_mm": None,
|
||||||
|
"media_length_mm": None,
|
||||||
|
"errors": [f"printer unreachable: {type(err).__name__}"],
|
||||||
|
}
|
||||||
|
return map_status(st if isinstance(st, dict) else {}, self._expected_label)
|
||||||
|
|
||||||
|
def print_image(self, img: Image.Image, label_id: str) -> dict[str, Any]:
|
||||||
|
if self._dry_run:
|
||||||
|
out = DRYRUN_DIR
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
path = out / f"dryrun-{threading.get_ident()}.png"
|
||||||
|
img.save(path)
|
||||||
|
log.info("dry-run: saved %s (%dx%d)", path, img.width, img.height)
|
||||||
|
return {
|
||||||
|
"instructions_sent": True,
|
||||||
|
"outcome": "printed",
|
||||||
|
"did_print": True,
|
||||||
|
"ready_for_next_job": True,
|
||||||
|
}
|
||||||
|
qlr = BrotherQLRaster(self._model)
|
||||||
|
qlr.exception_on_warning = True
|
||||||
|
instructions = convert(
|
||||||
|
qlr,
|
||||||
|
[img],
|
||||||
|
label_id,
|
||||||
|
rotate="0",
|
||||||
|
threshold=self._threshold,
|
||||||
|
dither=self._dither,
|
||||||
|
cut=True,
|
||||||
|
)
|
||||||
|
with self._lock:
|
||||||
|
result = bq_send(
|
||||||
|
instructions,
|
||||||
|
self._identifier,
|
||||||
|
backend_identifier="pyusb",
|
||||||
|
blocking=True,
|
||||||
|
)
|
||||||
|
return result if isinstance(result, dict) else {"outcome": "unknown"}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
"""Headless-Chromium badge renderer: serves dist-print and screenshots the badge page."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import functools
|
||||||
|
import http.server
|
||||||
|
import io
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
log = logging.getLogger("worker.render")
|
||||||
|
|
||||||
|
PRINT_DPI = 300
|
||||||
|
CSS_DPI = 96
|
||||||
|
RENDER_TIMEOUT_MS = 30_000
|
||||||
|
|
||||||
|
|
||||||
|
class RenderError(Exception):
|
||||||
|
"""The badge could not be rendered."""
|
||||||
|
|
||||||
|
|
||||||
|
class _QuietHandler(http.server.SimpleHTTPRequestHandler):
|
||||||
|
def log_message(self, *_args: Any) -> None: # keep worker stdout clean
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Renderer:
|
||||||
|
"""One Chromium instance reused for every badge; relaunches itself after a crash."""
|
||||||
|
|
||||||
|
def __init__(self, renderer_dir: str):
|
||||||
|
self._dir = renderer_dir
|
||||||
|
self._server: http.server.ThreadingHTTPServer | None = None
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
self._browser = None
|
||||||
|
self._page = None
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def _ensure_http(self) -> str:
|
||||||
|
if self._server is not None:
|
||||||
|
return f"http://127.0.0.1:{self._server.server_address[1]}/print.html"
|
||||||
|
handler = functools.partial(_QuietHandler, directory=self._dir)
|
||||||
|
self._server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||||
|
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
port = self._server.server_address[1]
|
||||||
|
log.info("renderer http server on 127.0.0.1:%s", port)
|
||||||
|
return f"http://127.0.0.1:{port}/print.html"
|
||||||
|
|
||||||
|
def _ensure_browser(self) -> None:
|
||||||
|
if self._page is not None:
|
||||||
|
return
|
||||||
|
# Lazy import so the pure modules stay testable without playwright installed.
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
self._pw = sync_playwright().start()
|
||||||
|
self._browser = self._pw.chromium.launch(args=["--no-sandbox"])
|
||||||
|
context = self._browser.new_context(
|
||||||
|
device_scale_factor=PRINT_DPI / CSS_DPI, viewport={"width": 1800, "height": 1800}
|
||||||
|
)
|
||||||
|
self._page = context.new_page()
|
||||||
|
self._page.set_default_timeout(RENDER_TIMEOUT_MS)
|
||||||
|
url = self._ensure_http()
|
||||||
|
self._page.goto(url, wait_until="load", timeout=RENDER_TIMEOUT_MS)
|
||||||
|
# The module defines renderBadge on load; the ready/error flags only
|
||||||
|
# change once renderBadge is actually called.
|
||||||
|
self._page.wait_for_function("typeof window.renderBadge === 'function'", timeout=RENDER_TIMEOUT_MS)
|
||||||
|
log.info("renderer chromium ready (%s)", url)
|
||||||
|
|
||||||
|
def _shutdown_browser(self) -> None:
|
||||||
|
for closer in ("_page", "_browser", "_pw"):
|
||||||
|
obj = getattr(self, closer, None)
|
||||||
|
if obj is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
(obj.stop if closer == "_pw" else obj.close)()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
setattr(self, closer, None)
|
||||||
|
|
||||||
|
def render(self, payload: dict[str, Any], checkin_origin: str) -> Image.Image:
|
||||||
|
with self._lock:
|
||||||
|
try:
|
||||||
|
self._ensure_browser()
|
||||||
|
return self._render_locked(payload, checkin_origin)
|
||||||
|
except RenderError:
|
||||||
|
raise
|
||||||
|
except Exception as err: # noqa: BLE001 — browser crash: relaunch once
|
||||||
|
log.warning("renderer error (%s), relaunching chromium", type(err).__name__)
|
||||||
|
self._shutdown_browser()
|
||||||
|
try:
|
||||||
|
self._ensure_browser()
|
||||||
|
return self._render_locked(payload, checkin_origin)
|
||||||
|
except RenderError:
|
||||||
|
raise
|
||||||
|
except Exception as err2: # noqa: BLE001
|
||||||
|
raise RenderError(f"render failed: {err2}") from err2
|
||||||
|
|
||||||
|
def _render_locked(self, payload: dict[str, Any], checkin_origin: str) -> Image.Image:
|
||||||
|
page = self._page
|
||||||
|
assert page is not None
|
||||||
|
try:
|
||||||
|
page.evaluate(
|
||||||
|
"([p, o]) => window.renderBadge(p, o)",
|
||||||
|
[payload, {"checkinOrigin": checkin_origin}],
|
||||||
|
)
|
||||||
|
except Exception as err: # noqa: BLE001 — renderBadge rejects on bad payload
|
||||||
|
raise RenderError(str(err).splitlines()[0][:300]) from err
|
||||||
|
png = page.locator("#badge-root .badge-page").screenshot(timeout=RENDER_TIMEOUT_MS)
|
||||||
|
return Image.open(io.BytesIO(png))
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
with self._lock:
|
||||||
|
self._shutdown_browser()
|
||||||
|
if self._server is not None:
|
||||||
|
self._server.shutdown()
|
||||||
|
self._server.server_close()
|
||||||
|
self._server = None
|
||||||
|
if self._thread is not None:
|
||||||
|
self._thread.join(timeout=5)
|
||||||
|
self._thread = None
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""PostgREST RPC client for the token-gated printer functions."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from .config import Config
|
||||||
|
|
||||||
|
log = logging.getLogger("worker.rpc")
|
||||||
|
|
||||||
|
# SQLSTATE raised by _print_station_from_token for invalid/revoked tokens.
|
||||||
|
INVALID_TOKEN_CODE = "28000"
|
||||||
|
|
||||||
|
|
||||||
|
class RpcError(Exception):
|
||||||
|
"""RPC returned an unexpected response."""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidToken(RpcError):
|
||||||
|
"""The station token is invalid or revoked (HTTP 401/403 or SQLSTATE 28000)."""
|
||||||
|
|
||||||
|
|
||||||
|
class RpcUnavailable(RpcError):
|
||||||
|
"""Network failure, timeout or 5xx — the backend may come back."""
|
||||||
|
|
||||||
|
|
||||||
|
class Rpc:
|
||||||
|
def __init__(self, cfg: Config, client: httpx.Client | None = None):
|
||||||
|
self._token = cfg.station_token
|
||||||
|
self._base = f"{cfg.convivo_url}/rest/v1/rpc"
|
||||||
|
self._vt = cfg.vt_seconds
|
||||||
|
self._client = client or httpx.Client(
|
||||||
|
headers={
|
||||||
|
"apikey": cfg.convivo_anon_key,
|
||||||
|
"Authorization": f"Bearer {cfg.convivo_anon_key}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
timeout=httpx.Timeout(30.0),
|
||||||
|
)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._client.close()
|
||||||
|
|
||||||
|
def _call(self, fn: str, params: dict[str, Any], timeout: float) -> Any:
|
||||||
|
try:
|
||||||
|
resp = self._client.post(f"{self._base}/{fn}", json=params, timeout=timeout)
|
||||||
|
except httpx.HTTPError as err:
|
||||||
|
raise RpcUnavailable(f"{fn}: {type(err).__name__}") from err
|
||||||
|
if resp.status_code in (401, 403):
|
||||||
|
raise InvalidToken(f"{fn}: rejected ({resp.status_code})")
|
||||||
|
if resp.status_code >= 500:
|
||||||
|
raise RpcUnavailable(f"{fn}: HTTP {resp.status_code}")
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
try:
|
||||||
|
body = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
body = {}
|
||||||
|
if str(body.get("code", "")) == INVALID_TOKEN_CODE:
|
||||||
|
raise InvalidToken(f"{fn}: invalid station token")
|
||||||
|
detail = str(body.get("message", ""))[:200]
|
||||||
|
raise RpcError(f"{fn}: HTTP {resp.status_code} {detail}".strip())
|
||||||
|
try:
|
||||||
|
return resp.json()
|
||||||
|
except ValueError as err:
|
||||||
|
raise RpcError(f"{fn}: non-JSON response") from err
|
||||||
|
|
||||||
|
def claim(self, wait_seconds: int) -> list[dict[str, Any]]:
|
||||||
|
# Long-poll: the server waits up to wait_seconds before answering.
|
||||||
|
rows = self._call(
|
||||||
|
"printer_claim_badge_job",
|
||||||
|
{"p_token": self._token, "p_vt": self._vt, "p_wait_seconds": wait_seconds},
|
||||||
|
timeout=wait_seconds + 15,
|
||||||
|
)
|
||||||
|
return rows if isinstance(rows, list) else []
|
||||||
|
|
||||||
|
def complete(self, msg_id: int) -> bool:
|
||||||
|
return bool(self._call("printer_complete_badge_job", {"p_token": self._token, "p_msg_id": msg_id}, 20))
|
||||||
|
|
||||||
|
def fail(self, msg_id: int, error: str, retryable: bool = False) -> str:
|
||||||
|
result = self._call(
|
||||||
|
"printer_fail_badge_job",
|
||||||
|
{"p_token": self._token, "p_msg_id": msg_id, "p_error": error, "p_retryable": retryable},
|
||||||
|
20,
|
||||||
|
)
|
||||||
|
return str(result)
|
||||||
|
|
||||||
|
def heartbeat(self, status: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
result = self._call("printer_heartbeat", {"p_token": self._token, "p_status": status}, 15)
|
||||||
|
return result if isinstance(result, dict) else {}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""Locally-printed informational labels (ready / need Wi-Fi), drawn with Pillow."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
from .label import LabelSpec
|
||||||
|
|
||||||
|
FONT_DIRS = (
|
||||||
|
"/usr/share/fonts/truetype/dejavu",
|
||||||
|
"/usr/share/fonts/dejavu",
|
||||||
|
"/System/Library/Fonts",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _font(size: int, bold: bool = False) -> ImageFont.ImageFont:
|
||||||
|
name = "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf"
|
||||||
|
for base in FONT_DIRS:
|
||||||
|
try:
|
||||||
|
return ImageFont.truetype(f"{base}/{name}", size)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
return ImageFont.load_default(size)
|
||||||
|
|
||||||
|
|
||||||
|
def _size(font: ImageFont.ImageFont) -> int:
|
||||||
|
return int(getattr(font, "size", 16) or 16)
|
||||||
|
|
||||||
|
|
||||||
|
def _fit(text: str, max_width: int, size: int, bold: bool) -> ImageFont.ImageFont:
|
||||||
|
font = _font(size, bold)
|
||||||
|
while size > 14 and font.getlength(text) > max_width:
|
||||||
|
size -= 4
|
||||||
|
font = _font(size, bold)
|
||||||
|
return font
|
||||||
|
|
||||||
|
|
||||||
|
def _render_lines(spec: LabelSpec, headline: str, lines: list[str]) -> Image.Image:
|
||||||
|
if spec.die_cut:
|
||||||
|
width, height = spec.width_px, spec.height_px
|
||||||
|
else:
|
||||||
|
width = spec.width_px
|
||||||
|
# ~60 mm of endless tape, but never shorter than half the label width.
|
||||||
|
height = max(int(60 * 300 / 25.4), width // 2)
|
||||||
|
|
||||||
|
img = Image.new("RGB", (width, height), "white")
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
margin = width // 20
|
||||||
|
text_width = width - 2 * margin
|
||||||
|
|
||||||
|
y = margin
|
||||||
|
font = _fit(headline, text_width, width // 9, True)
|
||||||
|
draw.text((margin, y), headline, fill="black", font=font)
|
||||||
|
y += int(_size(font) * 1.6)
|
||||||
|
for line in lines:
|
||||||
|
font = _fit(line, text_width, width // 16, False)
|
||||||
|
draw.text((margin, y), line, fill="black", font=font)
|
||||||
|
y += int(_size(font) * 1.6)
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def ready_label(spec: LabelSpec, station: str, network: dict, version: str, now: datetime) -> Image.Image:
|
||||||
|
lines = [f"Station: {station}"]
|
||||||
|
if network.get("ssid"):
|
||||||
|
lines.append(f"Wi-Fi: {network['ssid']}")
|
||||||
|
if network.get("ip"):
|
||||||
|
lines.append(f"IP: {network['ip']}")
|
||||||
|
lines.append(now.strftime("%Y-%m-%d %H:%M"))
|
||||||
|
lines.append(f"v{version}")
|
||||||
|
return _render_lines(spec, "Convivo printer ready", lines)
|
||||||
|
|
||||||
|
|
||||||
|
def need_wifi_label(spec: LabelSpec, ap_ssid: str) -> Image.Image:
|
||||||
|
return _render_lines(
|
||||||
|
spec,
|
||||||
|
"No network",
|
||||||
|
["Connect a phone to the open Wi-Fi", ap_ssid, "then open http://10.41.0.1"],
|
||||||
|
)
|
||||||
@@ -28,6 +28,7 @@ system works*; the root [`README.md`](../README.md) is the quick-start.
|
|||||||
| API client (how the app talks to Supabase) | [frontend/api-client.md](./frontend/api-client.md) |
|
| API client (how the app talks to Supabase) | [frontend/api-client.md](./frontend/api-client.md) |
|
||||||
| **Admin console** (views, auth guard, QR reset, points, schedule) | [frontend/admin-app.md](./frontend/admin-app.md) |
|
| **Admin console** (views, auth guard, QR reset, points, schedule) | [frontend/admin-app.md](./frontend/admin-app.md) |
|
||||||
| Manual event/session feedback summaries and LLM configuration | [backend/feedback-ai.md](./backend/feedback-ai.md) |
|
| Manual event/session feedback summaries and LLM configuration | [backend/feedback-ai.md](./backend/feedback-ai.md) |
|
||||||
|
| **Badge printing** — pgmq queue, Raspberry Pi stations, tokens, troubleshooting | [backend/printing.md](./backend/printing.md) |
|
||||||
| **Deployment — VM access (remote host for `appe.at`)** | [deployment.md](./deployment.md) |
|
| **Deployment — VM access (remote host for `appe.at`)** | [deployment.md](./deployment.md) |
|
||||||
| **2026-10-10 changes, deployment and verification** | [releases/2026-10-10.md](./releases/2026-10-10.md) |
|
| **2026-10-10 changes, deployment and verification** | [releases/2026-10-10.md](./releases/2026-10-10.md) |
|
||||||
| **What's next (Redesign Phases 3–6 + later + open items)** | [next-steps.md](./next-steps.md) |
|
| **What's next (Redesign Phases 3–6 + later + open items)** | [next-steps.md](./next-steps.md) |
|
||||||
|
|||||||
+23
-5
@@ -49,12 +49,24 @@ flowchart LR
|
|||||||
N -->|"proxy (supabase_kong_Convivo:8000)"| K
|
N -->|"proxy (supabase_kong_Convivo:8000)"| K
|
||||||
NA -->|"proxy (supabase_kong_Convivo:8000)"| K
|
NA -->|"proxy (supabase_kong_Convivo:8000)"| K
|
||||||
SC -->|"service-role key"| K
|
SC -->|"service-role key"| K
|
||||||
|
|
||||||
|
subgraph Edge["Event venue"]
|
||||||
|
PI["Raspberry Pi print station<br/>Docker: Python worker +<br/>headless Chromium + Brother QL"]
|
||||||
|
end
|
||||||
|
PI -->|"token-gated printer RPCs<br/>(anon key + station token)"| K
|
||||||
|
P -->|"badge_print pgmq queue<br/>(enqueue on check-in)"| PI
|
||||||
```
|
```
|
||||||
|
|
||||||
The **sidecar** (`:3002`) is the one server-side component that holds the
|
The **sidecar** (`:3002`) is the one server-side component that holds the
|
||||||
service-role key. It is driven by the admin's **Interfaces** menu and runs on
|
service-role key. It is driven by the admin's **Interfaces** menu and runs on
|
||||||
demand only — see [backend/sidecar.md](./backend/sidecar.md).
|
demand only — see [backend/sidecar.md](./backend/sidecar.md).
|
||||||
|
|
||||||
|
The **Raspberry Pi print station** is the one piece of on-premise hardware:
|
||||||
|
when staff welcome-check-in an attendee, the badge is pushed onto a `pgmq`
|
||||||
|
queue in Postgres and the Pi long-polls token-gated RPCs to render and print
|
||||||
|
it. No custom backend service sits in between — see
|
||||||
|
[backend/printing.md](./backend/printing.md).
|
||||||
|
|
||||||
**Key idea:** there is **no custom backend**. Supabase provides auth, data,
|
**Key idea:** there is **no custom backend**. Supabase provides auth, data,
|
||||||
business logic (as Postgres RPCs), and realtime. The app is a thin client that
|
business logic (as Postgres RPCs), and realtime. The app is a thin client that
|
||||||
talks to Supabase through **same-origin paths**, so there is no CORS to manage.
|
talks to Supabase through **same-origin paths**, so there is no CORS to manage.
|
||||||
@@ -96,15 +108,16 @@ with **`is_admin`** or an **`@appe.at`** email. See [frontend/admin-app.md](./fr
|
|||||||
- **Views** — Dashboard (active event + aggregates), Contacts, Registrations,
|
- **Views** — Dashboard (active event + aggregates), Contacts, Registrations,
|
||||||
Sponsors, Schedule (slots/sessions/speakers/material), Activity (manual event
|
Sponsors, Schedule (slots/sessions/speakers/material), Activity (manual event
|
||||||
and session AI summaries), Raffle (attendee prize draws), Badges (per-event
|
and session AI summaries), Raffle (attendee prize draws), Badges (per-event
|
||||||
WYSIWYG badge layout editor), Events, Interfaces,
|
WYSIWYG badge layout editor), Printing (badge-print stations + queue), Events,
|
||||||
Reports and Settings.
|
Interfaces, Reports and Settings.
|
||||||
- **Auth guard** — email-only magic links; non-admin sessions are rejected.
|
- **Auth guard** — email-only magic links; non-admin sessions are rejected.
|
||||||
- **Key RPCs** — `reset_registration_qr_token` (regenerate a registration's
|
- **Key RPCs** — `reset_registration_qr_token` (regenerate a registration's
|
||||||
lanyard token + sync the Auth password), `adjust_points`, `upsert_contact`,
|
lanyard token + sync the Auth password), `adjust_points`, `upsert_contact`,
|
||||||
`create_registration`, `set_registration_type`, `set_session_material`, and the
|
`create_registration`, `set_registration_type`, `set_session_material`, and the
|
||||||
raffle functions `get_raffle_pool` / `draw_raffle_winner` / `reset_raffle`
|
raffle functions `get_raffle_pool` / `draw_raffle_winner` / `reset_raffle`,
|
||||||
and the badge-layout functions `save_badge_layout` / `set_default_badge_layout`
|
the badge-layout functions `save_badge_layout` / `set_default_badge_layout`
|
||||||
/ `delete_badge_layout`
|
/ `delete_badge_layout`, and the badge-print functions
|
||||||
|
`get_print_overview` / `enqueue_badge_print` / `create_print_station`
|
||||||
(see [backend/rpcs.md](./backend/rpcs.md)). The deprecated AI stub is no longer
|
(see [backend/rpcs.md](./backend/rpcs.md)). The deprecated AI stub is no longer
|
||||||
client-callable; generation uses authenticated [sidecar routes](./backend/feedback-ai.md).
|
client-callable; generation uses authenticated [sidecar routes](./backend/feedback-ai.md).
|
||||||
|
|
||||||
@@ -209,6 +222,11 @@ Convivo/
|
|||||||
├─ apps/sidecar/ # Sessionize sync sidecar (Node, on demand)
|
├─ apps/sidecar/ # Sessionize sync sidecar (Node, on demand)
|
||||||
│ ├─ Dockerfile # node:20-alpine + xlsx (parses the Excel export)
|
│ ├─ Dockerfile # node:20-alpine + xlsx (parses the Excel export)
|
||||||
│ └─ src/server.js # /health, /status, /run, /import-excel (blocking)
|
│ └─ src/server.js # /health, /status, /run, /import-excel (blocking)
|
||||||
|
├─ apps/printer/ # Raspberry Pi badge-print worker (Python + Docker)
|
||||||
|
│ ├─ Dockerfile # repo-root context: node print-renderer stage + Playwright Chromium runtime
|
||||||
|
│ ├─ worker/ # claim → render (headless Chromium) → compose → print (Brother QL) → report
|
||||||
|
│ └─ pi/ # setup.sh / install.sh: Pi provisioning (Docker, comitup Wi-Fi portal)
|
||||||
|
│ # → backend/printing.md
|
||||||
├─ supabase/
|
├─ supabase/
|
||||||
│ ├─ config.toml # Local stack config (ports, auth, RLS defaults)
|
│ ├─ config.toml # Local stack config (ports, auth, RLS defaults)
|
||||||
│ ├─ migrations/
|
│ ├─ migrations/
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ summaries. This folder documents both the database core and those integrations.
|
|||||||
| [docker.md](./docker.md) | Docker: the app image + root compose (how the core + app run together) |
|
| [docker.md](./docker.md) | Docker: the app image + root compose (how the core + app run together) |
|
||||||
| [sidecar.md](./sidecar.md) | The Sessionize sync sidecar (on-demand, service-role) |
|
| [sidecar.md](./sidecar.md) | The Sessionize sync sidecar (on-demand, service-role) |
|
||||||
| [feedback-ai.md](./feedback-ai.md) | Admin-configured LLM endpoint and manual event/session feedback summaries |
|
| [feedback-ai.md](./feedback-ai.md) | Admin-configured LLM endpoint and manual event/session feedback summaries |
|
||||||
|
| [printing.md](./printing.md) | Badge printing: the pgmq queue, token-gated printer RPCs and the Raspberry Pi print stations |
|
||||||
| [tests.md](./tests.md) | The RPC test suite (`npm run test:rpc`) |
|
| [tests.md](./tests.md) | The RPC test suite (`npm run test:rpc`) |
|
||||||
|
|
||||||
## The big picture
|
## The big picture
|
||||||
|
|||||||
@@ -0,0 +1,286 @@
|
|||||||
|
# Badge Printing (queue + Raspberry Pi stations)
|
||||||
|
|
||||||
|
Staff scan an attendee's lanyard at the welcome desk; the badge is rendered,
|
||||||
|
queued in Postgres, and printed a few metres away by a headless **Raspberry Pi +
|
||||||
|
Brother QL** station. Failures retry, then land in a dead-letter queue an admin
|
||||||
|
can requeue or discard. The whole path is database-driven — there is no print
|
||||||
|
server.
|
||||||
|
|
||||||
|
Source of truth:
|
||||||
|
[`supabase/migrations/20261018170000_badge_print_queue.sql`](../../supabase/migrations/20261018170000_badge_print_queue.sql)
|
||||||
|
(queue, stations, RPCs),
|
||||||
|
[`apps/printer/`](../../apps/printer/) (Pi worker + provisioning),
|
||||||
|
[`apps/admin/`](../../apps/admin/) (print renderer + Printing view).
|
||||||
|
Operational detail for the Pi lives in
|
||||||
|
[`apps/printer/AGENT.md`](../../apps/printer/AGENT.md).
|
||||||
|
|
||||||
|
> **Status (2026-10-18):** built, verified locally and on a real Pi; **not yet
|
||||||
|
> deployed to production**. See [release record](../releases/2026-10-18.md).
|
||||||
|
|
||||||
|
## 1. Architecture
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
S["Staff scan<br/>(Convivo app)"]
|
||||||
|
A["Admin → Printing /<br/>Registrations Print"]
|
||||||
|
subgraph DB["Postgres (Supabase)"]
|
||||||
|
Q[("pgmq queue<br/>badge_print")]
|
||||||
|
DLQ[("pgmq queue<br/>badge_print_dlq")]
|
||||||
|
ST[("print_stations")]
|
||||||
|
ARCH[("archive<br/>a_badge_print")]
|
||||||
|
end
|
||||||
|
subgraph PI["Raspberry Pi (Docker)"]
|
||||||
|
W["Python worker"]
|
||||||
|
R["Playwright Chromium<br/>print.html renderer"]
|
||||||
|
P["Brother QL-1110NWB<br/>(USB, brother_ql)"]
|
||||||
|
end
|
||||||
|
AD["APPE Admin<br/>Printing view + pill"]
|
||||||
|
|
||||||
|
S -->|"welcome_checkin(qr)<br/>enqueue in same tx"| Q
|
||||||
|
A -->|"enqueue_badge_print"| Q
|
||||||
|
W -->|"printer_claim_badge_job<br/>(token, long-poll 2 s)"| Q
|
||||||
|
W -->|"printer_complete_badge_job"| ARCH
|
||||||
|
W -->|"printer_fail_badge_job<br/>(retry / DLQ after 3)"| DLQ
|
||||||
|
W -->|"printer_heartbeat (10 s)"| ST
|
||||||
|
W --> R
|
||||||
|
W --> P
|
||||||
|
AD -->|"get_print_overview (5 s)"| DB
|
||||||
|
AD -->|"requeue / discard"| DLQ
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Enqueue** happens in the same transaction as the check-in (or the admin
|
||||||
|
reprint), so a badge job is never lost or duplicated by the scan itself.
|
||||||
|
- The Pi **long-polls** for jobs and reports every outcome back through
|
||||||
|
token-gated RPCs. It never reads tables directly.
|
||||||
|
- The admin console polls one aggregate RPC (`get_print_overview`) for stations,
|
||||||
|
queue counters, recent jobs and dead letters.
|
||||||
|
|
||||||
|
## 2. Queues and the stations table
|
||||||
|
|
||||||
|
Two [pgmq](https://github.com/pgmq/pgmq) queues, `badge_print` (live) and
|
||||||
|
`badge_print_dlq` (dead letters), plus the `print_stations` table — column-level
|
||||||
|
detail in [schema.md](./schema.md#print_stations--badge-printer-stations).
|
||||||
|
|
||||||
|
**pgmq is unreachable from the API.** The migration revokes the schema, its
|
||||||
|
tables, sequences and functions from `public` / `anon` / `authenticated`; every
|
||||||
|
queue access goes through the RPCs below. Completed jobs stay queryable in the
|
||||||
|
pgmq archive (`a_badge_print`), which `get_print_overview` exposes as the
|
||||||
|
"recent" list.
|
||||||
|
|
||||||
|
## 3. Payload contract — `convivo.badge-print/v1`
|
||||||
|
|
||||||
|
Built by `_badge_print_payload` (see the migration) and mirrored by
|
||||||
|
`BadgePrintPayload` in
|
||||||
|
[`apps/admin/src/lib/types.ts`](../../apps/admin/src/lib/types.ts). The message
|
||||||
|
is a **self-contained badge document** — the station needs no further reads to
|
||||||
|
print:
|
||||||
|
|
||||||
|
| Field | Contents |
|
||||||
|
|---|---|
|
||||||
|
| `schema` | `"convivo.badge-print/v1"` (the worker rejects anything else) |
|
||||||
|
| `kind` | `checkin` \| `reprint` |
|
||||||
|
| `requested_at` / `requested_by` | enqueue time / staff email (null for scans by staff without an email match) |
|
||||||
|
| `event` | `{ id, name, company }` |
|
||||||
|
| `registration` | `{ id, email, type }` |
|
||||||
|
| `sample` | the badge fields the layout binds to: `full_name`, `email`, `ticket_type`, `qr_token`, `event_name`, `company` |
|
||||||
|
| `layout` | the resolved `badge_layouts` row: `{ id, name, page_width_mm, page_height_mm, elements }` |
|
||||||
|
|
||||||
|
Layout resolution: the event's **default layout that has elements**, else the
|
||||||
|
first (by `created_at`, `name`) that has elements. **No usable layout → no
|
||||||
|
payload → no job** (`welcome_checkin` silently skips; `enqueue_badge_print`
|
||||||
|
raises `no badge layout configured for this event`).
|
||||||
|
|
||||||
|
## 4. RPCs
|
||||||
|
|
||||||
|
Full behaviour lives here; [rpcs.md](./rpcs.md#badge-printing) carries the
|
||||||
|
cross-reference list.
|
||||||
|
|
||||||
|
### Admin RPCs (`security definer`, `is_admin()` inside, SQLSTATE `42501`)
|
||||||
|
|
||||||
|
| Function | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `enqueue_badge_print(p_registration_id)` | Manual reprint: queue the badge of one registration (`kind = reprint`); returns the queue msg id |
|
||||||
|
| `create_print_station(p_name)` | Register a station. Generates `cvp_<64 hex>` (32 random bytes), stores only its **SHA-256 hex digest**, returns the plaintext token **once** |
|
||||||
|
| `rename_print_station(p_id, p_name)` | Rename (trimmed, required, ≤ 80 chars). Revoked stations stay renamable so history remains readable |
|
||||||
|
| `revoke_print_station(p_id)` | Sets `revoked_at`; the token stops working immediately |
|
||||||
|
| `get_print_overview()` | Admin dashboard snapshot: stations with a derived `state`, queue counters, last 20 completed jobs, dead letters. Never exposes `qr_token` or full payloads |
|
||||||
|
| `requeue_dead_badge_print(p_msg_id)` | Push a dead letter's original payload back onto the live queue unchanged |
|
||||||
|
| `discard_dead_badge_print(p_msg_id)` | Drop a dead letter without retrying |
|
||||||
|
|
||||||
|
### Printer RPCs (token-gated, no user session)
|
||||||
|
|
||||||
|
Granted to `anon` (the Pi has no login) — the **station token is the
|
||||||
|
credential**. Each resolves the token via `_print_station_from_token`
|
||||||
|
(SHA-256 lookup, revoked/unknown → SQLSTATE `28000` → HTTP 401/403 for the
|
||||||
|
worker) and stamps `last_seen_at`.
|
||||||
|
|
||||||
|
| Function | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `printer_claim_badge_job(p_token, p_vt=120, p_wait_seconds=2)` | Long-poll for one job. `p_vt` clamped to 30–600 s; **`p_wait_seconds` clamped to 2 s** because PostgREST runs this as `anon`, whose `statement_timeout` is 3 s. A message already read > 3 times is dead-lettered instead of returned |
|
||||||
|
| `printer_complete_badge_job(p_token, p_msg_id)` | Report success → `pgmq.archive` (job leaves the queue for good) |
|
||||||
|
| `printer_fail_badge_job(p_token, p_msg_id, p_error, p_retryable)` | Retryable **and** `read_ct < 3` → `set_vt` backoff (`min(300, 15·read_ct)` s), returns `retry`; otherwise dead-letter (error capped at 2000 chars) and return `dead_letter` |
|
||||||
|
| `printer_heartbeat(p_token, p_status)` | Liveness + status beacon (blob capped at 16 KB). Returns `{ station_id, name }` — **the worker adopts its display name from this response**, so renames apply without re-provisioning |
|
||||||
|
|
||||||
|
`welcome_checkin` was re-created in the same migration: identical signature and
|
||||||
|
behaviour, plus the `badge_print` enqueue for a **genuine first check-in** only,
|
||||||
|
inside the same transaction (see [rpcs.md](./rpcs.md#welcome_checkinp_attendee_qr--attendee_email-attendee_name-already)).
|
||||||
|
|
||||||
|
## 5. Station tokens & security model
|
||||||
|
|
||||||
|
- Token format `cvp_…` (256 bits of entropy), generated server-side, shown
|
||||||
|
**once** at creation, stored only as a SHA-256 digest. A leaked database dump
|
||||||
|
does not leak usable tokens.
|
||||||
|
- The worker sends the token in the **JSON body** of each RPC call, together
|
||||||
|
with the **anon key** — which is public by design (same value baked into both
|
||||||
|
web apps), not a secret.
|
||||||
|
- `print_stations` has RLS enabled with **no policies** and no grants to
|
||||||
|
`anon` / `authenticated`: even the admin UI can only see stations through
|
||||||
|
`get_print_overview`.
|
||||||
|
- **Open-AP risk:** the Pi's comitup provisioning AP (`Convivo-Printer-<nnnn>`)
|
||||||
|
is open by design so staff can join it from a phone. While a station is in
|
||||||
|
hotspot mode it is not printing, and the token never travels over that AP —
|
||||||
|
it only talks to Convivo on a configured network.
|
||||||
|
- Revoking a station in Admin → Printing takes effect on the token's next call,
|
||||||
|
no Pi-side change needed.
|
||||||
|
|
||||||
|
## 6. Station state derivation
|
||||||
|
|
||||||
|
`get_print_overview` derives each station's `state` server-side (worst applicable
|
||||||
|
rule wins, in order):
|
||||||
|
|
||||||
|
| State | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `revoked` | `revoked_at` is set |
|
||||||
|
| `offline` | never seen, or `last_seen_at` older than **45 s** (heartbeat interval is 10 s) |
|
||||||
|
| `error` | last heartbeat's printer block: not `connected`, not `ready`, or a non-empty `errors` array |
|
||||||
|
| `printing` | heartbeat `worker = "printing"` |
|
||||||
|
| `ready` | everything else |
|
||||||
|
|
||||||
|
Queue counters: `pending` (`vt <= now()`, visible for claim), `in_flight`
|
||||||
|
(`vt > now()`, claimed but not reported), `dead_letter` (DLQ size), `completed`
|
||||||
|
(archive size). The admin UI maps these to the pill and per-station hints —
|
||||||
|
see [../frontend/admin-app.md#printing](../frontend/admin-app.md#printing).
|
||||||
|
|
||||||
|
## 7. The Pi worker (`apps/printer/worker/`)
|
||||||
|
|
||||||
|
A small Python loop in Docker; every module is hardware-free and unit-tested
|
||||||
|
except the thin `printer.py` wrapper.
|
||||||
|
|
||||||
|
| Module | Role |
|
||||||
|
|---|---|
|
||||||
|
| `main.py` | `Worker` loop: heartbeat thread, informational labels, claim → render → compose → print → complete/fail |
|
||||||
|
| `rpc.py` | PostgREST client; maps 401/403/`28000` → `InvalidToken`, 5xx/network → `RpcUnavailable` (retry-safe), 4xx → `RpcError` |
|
||||||
|
| `render.py` | One reused headless **Chromium** (Playwright) serving `dist-print` on loopback; `window.renderBadge(payload, {checkinOrigin})`, then screenshots `#badge-root .badge-page` at **300 dpi** (`device_scale_factor = 300/96`). Relaunches itself once after a browser crash |
|
||||||
|
| `label.py` | Pure Pillow composition onto the **detected** roll (see §8) |
|
||||||
|
| `printer.py` | `brother_ql_next` over **pyusb** to the Brother QL-1110NWB (`usb://0x04f9:0x20a8`); status read-back mapped to the heartbeat `printer` block; `DRY_RUN=1` writes PNGs instead |
|
||||||
|
| `network.py` | Reads `/run/convivo/network.json` (written by the comitup callback); falls back to a UDP-route IP guess |
|
||||||
|
| `status_labels.py` | Optional locally-drawn "ready" / "needs Wi-Fi" labels |
|
||||||
|
| `config.py` | All settings from env (`CONVIVO_URL`, `CONVIVO_ANON_KEY`, `PRINTER_STATION_TOKEN`, `BROTHER_LABEL=auto`, `HEARTBEAT_SECONDS=10`, `WAIT_SECONDS=2`, `STATUS_LABELS=0`, …). The token is excluded from `repr` so it can never reach a log line |
|
||||||
|
|
||||||
|
Loop behaviour worth knowing:
|
||||||
|
|
||||||
|
- **Heartbeat** every 10 s on its own thread (worker state, printer status,
|
||||||
|
network, version, uptime) — this is what drives the admin pill. A successful
|
||||||
|
beat touches `/tmp/heartbeat-ok`, which the image's `HEALTHCHECK` watches.
|
||||||
|
- **Not ready** (no roll, cover open, USB gone): the worker pauses, reports
|
||||||
|
`paused` + the error in its heartbeat, and retries in 3 s — it does **not**
|
||||||
|
claim jobs, so nothing fails while the printer is broken.
|
||||||
|
- **Job outcome rules:** unsupported schema / `LayoutTooLarge` / render errors →
|
||||||
|
dead-letter immediately (retrying can't help). No roll, transport errors →
|
||||||
|
retryable. A print that reports `did_print` is **completed even if a
|
||||||
|
post-print error appeared** (e.g. the roll ran out right after) — a badge that
|
||||||
|
printed must not be reprinted.
|
||||||
|
- **Complete is sticky:** if the backend is briefly unreachable after printing,
|
||||||
|
the worker retries `complete` with backoff for up to 60 s; past that the job
|
||||||
|
stays in flight and may be redelivered (a possible duplicate beats a lost
|
||||||
|
badge).
|
||||||
|
- **Station name** comes from the heartbeat response, so Admin → Printing
|
||||||
|
renames show on the next beat without touching the Pi.
|
||||||
|
|
||||||
|
### Image & rendering
|
||||||
|
|
||||||
|
[`apps/printer/Dockerfile`](../../apps/printer/Dockerfile) builds from the
|
||||||
|
**repo root** context: a Node stage runs `npm run build:print` in `apps/admin`
|
||||||
|
(`vite.print.config.ts` → `dist-print`), and the runtime stage is
|
||||||
|
`mcr.microsoft.com/playwright/python` (Chromium preinstalled) +
|
||||||
|
`brother_ql_next` + the worker. The renderer bundle is the **same React code**
|
||||||
|
as the admin previews — see §9 — so what the admin previews is what prints.
|
||||||
|
|
||||||
|
## 8. Label / roll handling
|
||||||
|
|
||||||
|
The worker prints on whatever roll is detected (`BROTHER_LABEL=auto`);
|
||||||
|
`label.compose` fits the 300 dpi badge image to it:
|
||||||
|
|
||||||
|
- **Die-cut** (e.g. `103x164`): the badge is centred on the exact label canvas;
|
||||||
|
a few px of rounding overshoot are cropped.
|
||||||
|
- **Endless / continuous** (e.g. `103` = DK-22246): fixed width, the tape length
|
||||||
|
follows the badge.
|
||||||
|
- If the badge doesn't fit, it is **auto-rotated** 90°; if it still doesn't
|
||||||
|
fit, `LayoutTooLarge` → dead-letter with the mm dimensions in the error.
|
||||||
|
|
||||||
|
Practical consequence (see §11): a ~101×30 mm badge **cannot** be printed on a
|
||||||
|
die-cut 103×164 roll — the cutter cannot cut inside a die. Load continuous
|
||||||
|
DK-22246 for short badges; no code change is needed.
|
||||||
|
|
||||||
|
## 9. Admin surface (summary)
|
||||||
|
|
||||||
|
The **Printing** view (stations, queue counters, recent jobs with **Reprint**,
|
||||||
|
dead letters with **Requeue** / **Discard**, add/rename/revoke station), the
|
||||||
|
always-visible **printer status pill** in the sidebar, the **Print** button on
|
||||||
|
Registrations rows, and the standalone print renderer entry (`print.html` →
|
||||||
|
`window.renderBadge`) are documented in
|
||||||
|
[../frontend/admin-app.md#printing](../frontend/admin-app.md#printing).
|
||||||
|
|
||||||
|
## 10. Pi provisioning & the Wi-Fi portal
|
||||||
|
|
||||||
|
[`apps/printer/pi/install.sh`](../../apps/printer/pi/install.sh) (from a dev
|
||||||
|
machine) cross-builds the arm64 image, uploads setup + image tarball to
|
||||||
|
`/var/tmp/convivo-setup` (the Pi's `/tmp` is a tiny tmpfs) and runs
|
||||||
|
[`setup.sh`](../../apps/printer/pi/setup.sh) as root. The setup is idempotent
|
||||||
|
and staged (`STAGE_APP` / `STAGE_WIFI_PORTAL` / `REBOOT`):
|
||||||
|
|
||||||
|
- base system (hostname, timezone, timesyncd — no RTC on the Pi, TLS fails
|
||||||
|
until the clock syncs), hardware watchdog, journald cap, Wi-Fi power-save off;
|
||||||
|
- Docker Engine + log caps;
|
||||||
|
- USB printer access: blacklist `usblp`, **mask `ipp-usb`** (it claims the
|
||||||
|
QL-1110NWB's IPP-over-USB interfaces and libusb then fails "Resource busy");
|
||||||
|
- the worker container (`/opt/convivo-printer`, host network, USB device
|
||||||
|
cgroup rules so a replugged printer works without a restart);
|
||||||
|
- **Wi-Fi provisioning portal (comitup):** installs comitup, which exposes the
|
||||||
|
open AP **`Convivo-Printer-<nnnn>`** with a captive portal at
|
||||||
|
**http://10.41.0.1**. A comitup callback writes `/run/convivo/network.json`
|
||||||
|
(`HOTSPOT` / `CONNECTING` / `CONNECTED` + SSID + IP) for the worker. A Convivo
|
||||||
|
captive portal (`apps/printer/portal/portal.py`) extends that flow so staff
|
||||||
|
can **pick any Wi-Fi network and optionally set the Convivo URL / anon key /
|
||||||
|
station token** from their phone — operational detail in
|
||||||
|
[`apps/printer/AGENT.md`](../../apps/printer/AGENT.md).
|
||||||
|
|
||||||
|
## 11. Troubleshooting (lessons learned)
|
||||||
|
|
||||||
|
| Symptom | Cause → fix |
|
||||||
|
|---|---|
|
||||||
|
| Badge won't print on a die-cut roll / cut lands mid-badge | Die-cut 103×164 labels **cannot be cut shorter** than the die. Use continuous DK-22246 (`103`) for short badges |
|
||||||
|
| `Resource busy` opening the printer | `ipp-usb` grabbed the USB interfaces → `systemctl mask ipp-usb` (setup.sh does this) |
|
||||||
|
| Install fails writing the image tarball | The Pi's `/tmp` is a small tmpfs → install uploads to `/var/tmp/convivo-setup` |
|
||||||
|
| Hotspot AP appears but hands out no DHCP after a setup run | `systemctl daemon-reexec` breaks running comitup's D-Bus proxy → setup only re-execs when its config actually changed **and restarts comitup** afterwards |
|
||||||
|
| Worker suddenly runs an old image | A Docker restart bounces the container on whatever image is loaded → setup restarts Docker only on `daemon.json` changes; re-run setup to update the image |
|
||||||
|
| Claim RPC returns HTTP 500 `57014` (query canceled) | Supabase `anon` has a **3 s statement_timeout** → the claim long-poll is clamped to 2 s server-side and `WAIT_SECONDS` defaults to 2 |
|
||||||
|
| Pill says offline right after plugging in the Pi | Clock skew: no RTC → wait for `systemd-timesyncd`, heartbeat older than 45 s reads offline |
|
||||||
|
|
||||||
|
## 12. Tests
|
||||||
|
|
||||||
|
- **SQL:** [`supabase/tests/badge_print_tests.sql`](../../supabase/tests/badge_print_tests.sql)
|
||||||
|
— rollback-only, **101 assertions**; run it **combined with the migration**
|
||||||
|
(idempotent, works before and after apply):
|
||||||
|
```sh
|
||||||
|
(echo 'begin;'; \
|
||||||
|
cat supabase/migrations/20261018170000_badge_print_queue.sql; \
|
||||||
|
sed '/^begin;$/d' supabase/tests/badge_print_tests.sql) \
|
||||||
|
| docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -v ON_ERROR_STOP=1
|
||||||
|
```
|
||||||
|
- **Worker unit tests:** `pytest apps/printer/tests` — **77 passing**
|
||||||
|
(56 test functions, 77 with parametrization; no hardware or browser needed).
|
||||||
|
- **Browser:** [`e2e/tests/printing.spec.ts`](../../e2e/tests/printing.spec.ts)
|
||||||
|
— 15 API-mocked Playwright tests for the pill, Printing view, station
|
||||||
|
lifecycle and the Print button.
|
||||||
|
Run commands in [tests.md](./tests.md#badge-print-queue-regression).
|
||||||
@@ -450,6 +450,48 @@ default per event. All three functions are `security definer` with an empty
|
|||||||
`search_path`, revoke execution from `PUBLIC` / `anon`, and grant it back only to
|
`search_path`, revoke execution from `PUBLIC` / `anon`, and grant it back only to
|
||||||
`authenticated` (the admin check is enforced inside each function).
|
`authenticated` (the admin check is enforced inside each function).
|
||||||
|
|
||||||
|
## Badge printing
|
||||||
|
|
||||||
|
Source: [20261018170000_badge_print_queue.sql](../../supabase/migrations/20261018170000_badge_print_queue.sql).
|
||||||
|
The full contract — payload, state derivation, token security model, retry /
|
||||||
|
dead-letter semantics — lives in
|
||||||
|
[printing.md](./printing.md#4-rpcs); this is the function inventory.
|
||||||
|
|
||||||
|
**Admin RPCs** (`security definer`, empty `search_path`, `is_admin()` inside,
|
||||||
|
granted to `authenticated` only):
|
||||||
|
|
||||||
|
- `enqueue_badge_print(p_registration_id)` → `bigint` — queue one attendee's
|
||||||
|
badge for printing (`kind = reprint`); raises when the event has no usable
|
||||||
|
layout.
|
||||||
|
- `create_print_station(p_name)` → `(id, token)` — register a printer station;
|
||||||
|
the `cvp_…` token is returned **once**, only its SHA-256 digest is stored.
|
||||||
|
- `rename_print_station(p_id, p_name)` → `void` — rename a station (also
|
||||||
|
revoked ones).
|
||||||
|
- `revoke_print_station(p_id)` → `void` — retire a station; its token fails
|
||||||
|
immediately.
|
||||||
|
- `get_print_overview()` → `jsonb` — stations with a derived state, queue
|
||||||
|
counters, the last 20 completed jobs and the dead letters.
|
||||||
|
- `requeue_dead_badge_print(p_msg_id)` → `bigint` / `discard_dead_badge_print(p_msg_id)` → `void`
|
||||||
|
— dead-letter triage.
|
||||||
|
|
||||||
|
**Printer RPCs** (granted to `anon` — the Pi has no user session; gated by the
|
||||||
|
station token, invalid/revoked raises SQLSTATE `28000`):
|
||||||
|
|
||||||
|
- `printer_claim_badge_job(p_token, p_vt, p_wait_seconds)` →
|
||||||
|
`(msg_id, read_ct, payload)` — long-poll claim; the wait is clamped to **2 s**
|
||||||
|
because the `anon` role has a 3 s `statement_timeout`; a message read more
|
||||||
|
than 3 times is dead-lettered instead of returned.
|
||||||
|
- `printer_complete_badge_job(p_token, p_msg_id)` → `boolean` — archive the job.
|
||||||
|
- `printer_fail_badge_job(p_token, p_msg_id, p_error, p_retryable)` → `text` —
|
||||||
|
`retry` (backoff via `set_vt`) while attempts remain, else `dead_letter`.
|
||||||
|
- `printer_heartbeat(p_token, p_status)` → `jsonb` — liveness + status beacon;
|
||||||
|
returns the station's current `name` (the worker adopts renames from it).
|
||||||
|
|
||||||
|
**Changed existing RPC:** `welcome_checkin` re-creates with one addition — on a
|
||||||
|
genuine **first** check-in it enqueues the badge job in the same transaction
|
||||||
|
when the event has a layout with elements (see
|
||||||
|
[welcome_checkin](#welcome_checkinp_attendee_qr--attendee_email-attendee_name-already).
|
||||||
|
|
||||||
## Error handling
|
## Error handling
|
||||||
|
|
||||||
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
|
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
|
||||||
|
|||||||
@@ -303,6 +303,37 @@ Interfaces view's "recent runs").
|
|||||||
(`sync_runs_select_admin`). Written only by the `sync_sessionize_event` /
|
(`sync_runs_select_admin`). Written only by the `sync_sessionize_event` /
|
||||||
`sync_sessionize_excel` RPCs.
|
`sync_sessionize_excel` RPCs.
|
||||||
|
|
||||||
|
## `print_stations` — badge printer stations
|
||||||
|
|
||||||
|
One row per Raspberry Pi print station. Added by
|
||||||
|
[`20261018170000_badge_print_queue.sql`](../../supabase/migrations/20261018170000_badge_print_queue.sql)
|
||||||
|
together with the badge-print queues — the full model (tokens, states, RPCs)
|
||||||
|
is in [printing.md](./printing.md).
|
||||||
|
|
||||||
|
| Column | Type | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `id` | `uuid` PK | `gen_random_uuid()` |
|
||||||
|
| `name` | `text` | non-blank; renamed via `rename_print_station`, shown to the worker through the heartbeat response |
|
||||||
|
| `token_hash` | `text` **unique** | the **SHA-256 hex digest** of the station's `cvp_…` bearer token — the plaintext is shown once at creation and never stored |
|
||||||
|
| `created_at` | `timestamptz` | |
|
||||||
|
| `revoked_at` | `timestamptz` | nullable — set by `revoke_print_station`; the token stops working immediately |
|
||||||
|
| `last_seen_at` | `timestamptz` | stamped by every printer RPC; > 45 s old ⇒ state `offline` |
|
||||||
|
| `last_status` | `jsonb` | the latest heartbeat blob (printer / network / worker), capped at 16 KB |
|
||||||
|
|
||||||
|
**RLS enabled with no policies** and no grants to `anon` / `authenticated` —
|
||||||
|
every access goes through the `security definer` RPCs (admin:
|
||||||
|
`get_print_overview` & friends; printer: the token-gated `printer_*` functions).
|
||||||
|
|
||||||
|
### pgmq queues (`badge_print`, `badge_print_dlq`)
|
||||||
|
|
||||||
|
The `pgmq` extension holds the badge-print job queue and its dead-letter queue.
|
||||||
|
Queue rows live in the **`pgmq` schema** (`pgmq.q_badge_print`,
|
||||||
|
`pgmq.a_badge_print` for completed/archived jobs, `pgmq.q_badge_print_dlq`),
|
||||||
|
not in `public`. The schema, tables, sequences and functions are revoked from
|
||||||
|
`public` / `anon` / `authenticated`: the API never exposes queue contents —
|
||||||
|
enqueuing, claiming, completing and dead-lettering all go through the RPCs in
|
||||||
|
[printing.md](./printing.md#4-rpcs).
|
||||||
|
|
||||||
## Other indexes
|
## Other indexes
|
||||||
|
|
||||||
- `slots_event_id_idx (event_id)`, `registrations_event_id_idx (event_id)`,
|
- `slots_event_id_idx (event_id)`, `registrations_event_id_idx (event_id)`,
|
||||||
|
|||||||
@@ -1,3 +1,39 @@
|
|||||||
|
# Badge Print Queue Regression
|
||||||
|
|
||||||
|
After applying `20261018170000_badge_print_queue`, run the SQL suite **combined
|
||||||
|
with the migration** in one transaction (the migration is idempotent, so the
|
||||||
|
same stream also re-verifies an already-applied database):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
(echo 'begin;'; \
|
||||||
|
cat supabase/migrations/20261018170000_badge_print_queue.sql; \
|
||||||
|
sed '/^begin;$/d' supabase/tests/badge_print_tests.sql) \
|
||||||
|
| docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -v ON_ERROR_STOP=1
|
||||||
|
CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- printing.spec.ts --project=chromium
|
||||||
|
pytest apps/printer/tests # worker unit tests (no hardware, no browser)
|
||||||
|
```
|
||||||
|
|
||||||
|
The SQL fixture is rollback-only: **101 assertions** cover queue creation and
|
||||||
|
migration idempotency, pgmq/API isolation, the self-contained payload shape and
|
||||||
|
layout resolution (default-with-elements, fallback, none → no job), first-scan
|
||||||
|
enqueue inside `welcome_checkin` (re-scan enqueues nothing), station token
|
||||||
|
lifecycle (create shows the token once, only the SHA-256 digest is stored,
|
||||||
|
rename, revoke → `28000`), claim/complete/fail semantics (visibility timeout,
|
||||||
|
retry backoff, dead-letter after 3 reads, requeue/discard), the heartbeat
|
||||||
|
(status cap, name echo) and admin/non-admin/anon authorization.
|
||||||
|
The browser suite is API-mocked and covers the always-visible printer pill
|
||||||
|
(ready / error / offline / mobile, click navigates), the offline Wi-Fi setup
|
||||||
|
hint, add-station token-shown-once, inline rename, dead-letter Requeue/Discard,
|
||||||
|
completed-job Reprint, the Registrations **Print** button (queue + toast,
|
||||||
|
offline still queues, no-layout disabled state) and the 5 s overview polling.
|
||||||
|
The pytest suite covers label composition (die-cut, endless, auto-rotate,
|
||||||
|
`LayoutTooLarge`), the worker loop (job outcomes, sticky complete, paused
|
||||||
|
printer), the RPC client error mapping, status mapping and the network-state
|
||||||
|
reader. No real printer, Pi or attendee data is involved.
|
||||||
|
|
||||||
|
See [printing.md](./printing.md) for the feature reference and the
|
||||||
|
[release record](../releases/2026-10-18.md) for results.
|
||||||
|
|
||||||
# Badge Editor Regression
|
# Badge Editor Regression
|
||||||
|
|
||||||
After applying `20261015194531_badge_editor`, run:
|
After applying `20261015194531_badge_editor`, run:
|
||||||
|
|||||||
@@ -16,12 +16,13 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
|
|||||||
|---|---|
|
|---|---|
|
||||||
| **Dashboard** | Active event card (name, dates, location, aggregates: avg feedback, #sessions, #speakers, #registrations, #checked-in) + top points + recent activity. |
|
| **Dashboard** | Active event card (name, dates, location, aggregates: avg feedback, #sessions, #speakers, #registrations, #checked-in) + top points + recent activity. |
|
||||||
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) A general search matches **first name, last name or email address**; the **LinkedIn**, **Visibility** and **Admin** columns each have an Excel-style **multi-select filter** with live counts. |
|
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) A general search matches **first name, last name or email address**; the **LinkedIn**, **Visibility** and **Admin** columns each have an Excel-style **multi-select filter** with live counts. |
|
||||||
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. |
|
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company), plus a **Print** button that queues the badge on the print station ([../backend/printing.md](../backend/printing.md)). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. |
|
||||||
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). |
|
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). |
|
||||||
| **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. |
|
| **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. |
|
||||||
| **Activity** | Tables of check-ins, connections, and feedback (per active event), with manual **Generate AI Summary** controls for the event and individual sessions. |
|
| **Activity** | Tables of check-ins, connections, and feedback (per active event), with manual **Generate AI Summary** controls for the event and individual sessions. |
|
||||||
| **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). |
|
| **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). |
|
||||||
| **Badges** | A **per-event WYSIWYG badge / PDF layout editor** (modelled on pretix's PDF Editor). Pick the event, then design one or more named **layouts** (a **Default** per event, switchable / creatable / deletable). Add **text boxes**, **QR codes** and **images** to a millimetre canvas; drag to move, use the 8 resize handles + rotation handle, **Shift-click to multi-select**, and **press `Del`** to remove. While dragging, **PowerPoint-style smart guides** appear — dashed alignment lines (edges / centres, page and neighbouring items) plus equal-spacing lines — and the element **snaps** to them. A **Word-style align** toolbar (left / center / right, top / middle / bottom) plus **PowerPoint-style** object alignment — align to the **page** or to the **selection**, and **distribute** horizontally / vertically — with the same controls in the properties panel. Text binds to attendee fields (name, email, ticket type, QR token, event name, **company / organizer**, or static) with font, size, line-height, colour, bold/italic, a labelled **Align text in box** section (horizontal left / center / right and vertical top / middle / bottom, inside the element's own frame) and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo** (`Ctrl`+`Z` / `Ctrl`+`Y`, also `Ctrl`+`Shift`+`Z`), a **Preview** mode (no handles), a **JSON** view of the layout, and **Save**. Previewed against a real sample registration. See [../backend/rpcs.md#badge-editor](../backend/rpcs.md#badge-editor). |
|
| **Badges** | A **per-event WYSIWYG badge / PDF layout editor** (modelled on pretix's PDF Editor). Pick the event, then design one or more named **layouts** (a **Default** per event, switchable / creatable / deletable). Add **text boxes**, **QR codes** and **images** to a millimetre canvas; drag to move, use the 8 resize handles + rotation handle, **Shift-click to multi-select**, and **press `Del`** to remove. While dragging, **PowerPoint-style smart guides** appear — dashed alignment lines (edges / centres, page and neighbouring items) plus equal-spacing lines — and the element **snaps** to them. A **Word-style align** toolbar (left / center / right, top / middle / bottom) plus **PowerPoint-style** object alignment — align to the **page** or to the **selection**, and **distribute** horizontally / vertically — with the same controls in the properties panel. Text binds to attendee fields (name, email, ticket type, QR token, event name, **company / organizer**, or static) with font, size, line-height, colour, bold/italic, a labelled **Align text in box** section (horizontal left / center / right and vertical top / middle / bottom, inside the element's own frame) and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo** (`Ctrl`+`Z` / `Ctrl`+`Y`, also `Ctrl`+`Shift`+`Z`), a **Preview** mode (no handles), a **JSON** view of the layout, and **Save**. Previewed against a real sample registration. See [../backend/rpcs.md#badge-editor](../backend/rpcs.md#badge-editor). |
|
||||||
|
| **Printing** | Badge-print control center: printer stations (add / inline **rename** / **revoke**, the `cvp_…` token shown **once** on creation), live station cards with state + staff hints, queue counters (pending / in flight / dead letters / completed), the last completed jobs with **Reprint**, and dead letters with **Requeue** / **Discard**. Backed by `get_print_overview` (polled every 5 s) — see [../backend/printing.md](../backend/printing.md). |
|
||||||
| **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. |
|
| **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. |
|
||||||
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
|
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
|
||||||
| **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). |
|
| **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). |
|
||||||
@@ -109,11 +110,16 @@ apps/admin/src/
|
|||||||
│ └─ ToastContext.tsx # transient toasts
|
│ └─ ToastContext.tsx # transient toasts
|
||||||
├─ lib/
|
├─ lib/
|
||||||
│ ├─ supabase.ts # createClient (same-origin)
|
│ ├─ supabase.ts # createClient (same-origin)
|
||||||
│ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points)
|
│ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points, printing)
|
||||||
│ └─ types.ts # TS types mirroring the DB
|
│ ├─ printStatus.tsx # PrintStatusProvider (5 s get_print_overview poll) + pill/hint helpers
|
||||||
|
│ └─ types.ts # TS types mirroring the DB (incl. BadgePrintPayload, PrintOverview)
|
||||||
├─ components/
|
├─ components/
|
||||||
│ ├─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, TypeBadge, Toggle, Tooltip, ColumnFilter
|
│ ├─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, TypeBadge, Toggle, Tooltip, ColumnFilter
|
||||||
│ └─ BadgeRender.tsx # shared badge renderer: resolveText/resolveQr, BadgeElementBody, BadgePagePreview, fitScale
|
│ ├─ BadgeRender.tsx # shared badge renderer: resolveText/resolveQr, BadgeElementBody, BadgePagePreview, fitScale
|
||||||
|
│ ├─ badge-render.css # badge rules + bundled @fontsource fonts aliased to the editor family names
|
||||||
|
│ └─ PrinterStatusPill.tsx # always-visible sidebar pill (aggregated station state)
|
||||||
|
├─ print/
|
||||||
|
│ └─ main.tsx # standalone print renderer entry: window.renderBadge(payload, opts)
|
||||||
├─ screens/
|
├─ screens/
|
||||||
│ └─ Login.tsx # email-only magic-link login (admin-only)
|
│ └─ Login.tsx # email-only magic-link login (admin-only)
|
||||||
└─ views/
|
└─ views/
|
||||||
@@ -143,8 +149,11 @@ key. Everything it can do is allowed by RLS:
|
|||||||
(admin-only policies).
|
(admin-only policies).
|
||||||
- **RPCs** — `adjust_points` (manual, audited as `admin`), `upsert_contact`,
|
- **RPCs** — `adjust_points` (manual, audited as `admin`), `upsert_contact`,
|
||||||
`create_registration`, `set_registration_type`,
|
`create_registration`, `set_registration_type`,
|
||||||
`set_session_material` (attach uploaded material), and
|
`set_session_material` (attach uploaded material),
|
||||||
`delete_event_schedule` (clear the active event's slots/sessions). The
|
`delete_event_schedule` (clear the active event's slots/sessions), and the
|
||||||
|
badge-print admin RPCs (`get_print_overview`, `enqueue_badge_print`,
|
||||||
|
`create_print_station`, `rename_print_station`, `revoke_print_station`,
|
||||||
|
`requeue_dead_badge_print`, `discard_dead_badge_print`). The
|
||||||
`reset_registration_qr_token` RPC still exists but the admin UI no longer
|
`reset_registration_qr_token` RPC still exists but the admin UI no longer
|
||||||
exposes a token reset. See
|
exposes a token reset. See
|
||||||
[../backend/rpcs.md](../backend/rpcs.md).
|
[../backend/rpcs.md](../backend/rpcs.md).
|
||||||
@@ -180,6 +189,62 @@ portal so it is never clipped by the table's `overflow: hidden`. The shared badg
|
|||||||
renderer lives in `components/BadgeRender.tsx`, used by both the editor and this
|
renderer lives in `components/BadgeRender.tsx`, used by both the editor and this
|
||||||
preview.
|
preview.
|
||||||
|
|
||||||
|
### Printing
|
||||||
|
|
||||||
|
The **Printing** view is the badge-print control center; the queue, stations and
|
||||||
|
RPCs behind it are documented in [../backend/printing.md](../backend/printing.md).
|
||||||
|
|
||||||
|
- **Status pill** — `PrinterStatusPill` sits in the sidebar on **every** view
|
||||||
|
(desktop and mobile): the Pi has no screen, so staff must see the printer
|
||||||
|
state from anywhere. It aggregates the active stations by worst state
|
||||||
|
(error > offline > printing > ready), shows a shortened error / "offline · 2
|
||||||
|
min" text, and a tooltip lists every station (roll, network, last seen, hint).
|
||||||
|
Clicking it navigates to the Printing view.
|
||||||
|
- **Shared poller** — `PrintStatusProvider` (`lib/printStatus.tsx`) calls
|
||||||
|
`get_print_overview` once every **5 s** while the tab is visible (immediate
|
||||||
|
refresh on `visibilitychange`, one request in flight at a time, last data kept
|
||||||
|
on failure). The pill, the Printing view and the Registrations Print button
|
||||||
|
all read from it.
|
||||||
|
- **Stations** — **Add station** opens a modal that shows the generated
|
||||||
|
`cvp_…` token **once** (copy button; it is gone after Done — only its digest
|
||||||
|
is stored). Each card shows the derived state, roll, network, uptime and a
|
||||||
|
plain-language **hint** for staff (e.g. the offline hint points to the open
|
||||||
|
`Convivo-Printer-XXXX` Wi-Fi and http://10.41.0.1). Inline **rename** (Save
|
||||||
|
disabled while blank, Escape cancels) and **Revoke** (confirm; the token stops
|
||||||
|
working immediately).
|
||||||
|
- **Queue** — counters for pending / in flight / dead letters / completed, the
|
||||||
|
last 20 completed jobs each with **Reprint** (calls `enqueue_badge_print` for
|
||||||
|
that registration), and dead letters with **Requeue** / **Discard**.
|
||||||
|
- **Registrations Print** — every row has a **Print** button that queues the
|
||||||
|
badge and toasts the result (when every station is offline the toast says the
|
||||||
|
job is queued and will print when the station returns). With **no badge
|
||||||
|
layout** configured, the button is disabled with the same configure-first
|
||||||
|
tooltip as the Badge preview.
|
||||||
|
|
||||||
|
### Print renderer entry (`print.html`)
|
||||||
|
|
||||||
|
The badge image the Pi prints is produced by the **same React renderer** as the
|
||||||
|
previews, in a standalone bundle: `apps/admin/print.html` +
|
||||||
|
`src/print/main.tsx`, built by `npm run build:print`
|
||||||
|
([`vite.print.config.ts`](../../apps/admin/vite.print.config.ts) →
|
||||||
|
`dist-print/`). The bundle exposes `window.renderBadge(payload, {checkinOrigin})`,
|
||||||
|
which validates the `convivo.badge-print/v1` payload, renders the layout through
|
||||||
|
the shared `BadgePagePreview` at exact millimetre scale, waits for fonts and
|
||||||
|
images, and resolves with the badge's CSS-pixel size. The worker serves the
|
||||||
|
static files in a headless Chromium and screenshots the page — see
|
||||||
|
[../backend/printing.md](../backend/printing.md#7-the-pi-worker-appsprinterworker).
|
||||||
|
Fonts are **bundled** via `@fontsource` in `components/badge-render.css`,
|
||||||
|
aliased to the editor's family names, so rendering never depends on fonts
|
||||||
|
installed on the viewer's OS (admin laptop vs. the Pi).
|
||||||
|
|
||||||
|
Browser coverage (API-mocked, no real printer):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- printing.spec.ts --project=chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
See [Badge Print Queue Regression](../backend/tests.md#badge-print-queue-regression).
|
||||||
|
|
||||||
### Sponsor lookup (in-place)
|
### Sponsor lookup (in-place)
|
||||||
|
|
||||||
Setting a registration's type to **Sponsor** requires a sponsor lookup. If none
|
Setting a registration's type to **Sponsor** requires a sponsor lookup. If none
|
||||||
|
|||||||
@@ -97,3 +97,106 @@ touched.
|
|||||||
absent from the served JS, `give-feedback` still present (non-service path).
|
absent from the served JS, `give-feedback` still present (non-service path).
|
||||||
- **45/45** mocked Playwright checks against `https://convivo.appe.at`.
|
- **45/45** mocked Playwright checks against `https://convivo.appe.at`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Badge Printing End-to-End (2026-10-18)
|
||||||
|
|
||||||
|
Welcome-desk badge printing on a Raspberry Pi: scan a lanyard QR, the badge
|
||||||
|
prints seconds later. Full reference: [backend/printing.md](../backend/printing.md).
|
||||||
|
**Status: local only — production deployment pending at the time of writing.**
|
||||||
|
|
||||||
|
## What shipped
|
||||||
|
|
||||||
|
- **Database** — migration
|
||||||
|
[`20261018170000_badge_print_queue.sql`](../../supabase/migrations/20261018170000_badge_print_queue.sql):
|
||||||
|
`pgmq` queues `badge_print` / `badge_print_dlq`, the `print_stations` table
|
||||||
|
(SHA-256 token digests, RLS with no policies), the self-contained
|
||||||
|
`convivo.badge-print/v1` payload, `welcome_checkin` re-created to enqueue the
|
||||||
|
badge on a **first** check-in in the same transaction, seven admin RPCs
|
||||||
|
(reprint, station create/rename/revoke, overview, DLQ requeue/discard) and
|
||||||
|
four token-gated printer RPCs (claim / complete / fail / heartbeat).
|
||||||
|
- **Admin** — the **Printing** view (stations, queue counters, recent jobs with
|
||||||
|
Reprint, dead letters with Requeue/Discard), the always-visible sidebar
|
||||||
|
**printer status pill** with staff-facing hints, the **Print** button on
|
||||||
|
Registrations rows, and the standalone print renderer entry (`print.html` →
|
||||||
|
`window.renderBadge`, built by `npm run build:print`) sharing the editor's
|
||||||
|
`BadgeRender` code and **bundled @fontsource fonts**, so preview = print on
|
||||||
|
any machine.
|
||||||
|
- **Worker** — `apps/printer/`: Python in Docker (repo-root build; a Node stage
|
||||||
|
builds the renderer into the Playwright Chromium runtime image). Long-polls
|
||||||
|
the queue with the station token, screenshots the badge at 300 dpi, composes
|
||||||
|
it onto the **detected** roll (die-cut exact canvas / endless cut-to-length /
|
||||||
|
auto-rotate / `LayoutTooLarge` → DLQ), prints on a Brother QL-1110NWB over
|
||||||
|
USB with status read-back, and heartbeats every 10 s (the station name comes
|
||||||
|
from the heartbeat response, so renames apply without re-provisioning).
|
||||||
|
- **Station rename** — `rename_print_station` RPC + inline rename in the
|
||||||
|
Printing view.
|
||||||
|
- **Pi provisioning + Wi-Fi portal** — `apps/printer/pi/setup.sh` +
|
||||||
|
`install.sh` (idempotent, staged): Docker, watchdog, `usblp`/`ipp-usb`
|
||||||
|
handling, the worker container, and **comitup** providing the open AP
|
||||||
|
`Convivo-Printer-<nnnn>` with a captive portal at **http://10.41.0.1**:
|
||||||
|
**pick any Wi-Fi + optional Convivo settings** (URL / anon key / station
|
||||||
|
token) from a phone. A comitup callback writes `/run/convivo/network.json`
|
||||||
|
for the worker. Operational detail:
|
||||||
|
[`apps/printer/AGENT.md`](../../apps/printer/AGENT.md).
|
||||||
|
- **Status labels (opt-in)** — `STATUS_LABELS=1` (default off) prints
|
||||||
|
locally-drawn "ready" / "needs Wi-Fi" labels on the printer itself, since
|
||||||
|
the Pi has no screen.
|
||||||
|
- **Fixes found on real hardware** — claim long-poll clamped to **2 s**
|
||||||
|
(Supabase `anon` has a 3 s `statement_timeout`; 10 s caused HTTP 500
|
||||||
|
`57014`); setup re-execs systemd only on config change and restarts comitup
|
||||||
|
after (a bare `daemon-reexec` broke the hotspot's DHCP); Docker restarted
|
||||||
|
only on `daemon.json` change (a bounce re-ran the worker on the old image);
|
||||||
|
install uploads to `/var/tmp` (the Pi's `/tmp` is a ~1 GB tmpfs); `ipp-usb`
|
||||||
|
masked (it grabbed the printer's USB interfaces — "Resource busy").
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
- **SQL:** `supabase/tests/badge_print_tests.sql` — rollback-only, run combined
|
||||||
|
with the migration: **101/101 assertions** (payload shape, layout resolution,
|
||||||
|
first-scan enqueue, token lifecycle, retry/backoff/DLQ, heartbeat, role
|
||||||
|
guards, idempotent re-apply).
|
||||||
|
- **Worker:** pytest `apps/printer/tests` — **77 passing** (56 test
|
||||||
|
functions, 77 with parametrized label cases; no hardware or browser required).
|
||||||
|
- **Browser:** `e2e/tests/printing.spec.ts` — **15/15** API-mocked Playwright
|
||||||
|
tests (pill states + mobile, token-shown-once, rename, requeue/discard,
|
||||||
|
reprint, Print button, 5 s polling).
|
||||||
|
- **Real Pi end-to-end:** a provisioned Pi 4 with a QL-1110NWB printed live
|
||||||
|
badges against the local Supabase stack — welcome check-in → queue → print →
|
||||||
|
archive, plus reprint, revoke (token rejected immediately), rename visible on
|
||||||
|
the next heartbeat, and the DLQ path.
|
||||||
|
- **Portal:** joined the open `Convivo-Printer-<nnnn>` AP from a phone, picked
|
||||||
|
a Wi-Fi network at http://10.41.0.1, and the worker reconnected and resumed
|
||||||
|
claiming on the new network.
|
||||||
|
- Neighbour regression green: `badge_layout_tests.sql` (15 assertions — the
|
||||||
|
print payload reuses badge layouts).
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
**Deployed to production 2026-10-18** (commit `a2fe724`, admin-only + DB migration).
|
||||||
|
|
||||||
|
- **Migration** `20261018170000_badge_print_queue.sql` applied to prod in a
|
||||||
|
single transaction with `ON_ERROR_STOP=1` and recorded in the ledger
|
||||||
|
(ledger 38 → 39). `pgmq 1.5.1` was already available on the prod image (no
|
||||||
|
`shared_preload_libraries` change needed); the queues `badge_print` /
|
||||||
|
`badge_print_dlq`, `print_stations`, and all admin/printer RPCs are present.
|
||||||
|
Backup `/home/APPE/convivo-backups/printqueue-20261018T201701Z` (pg_dump,
|
||||||
|
counts, runtime admin source, rollback tag `convivo-admin:rollback-printqueue-…`).
|
||||||
|
- **SQL regression** `badge_print_tests.sql` run rollback-only against prod in
|
||||||
|
the same transaction as the migration: **101/101 assertions**, then rolled
|
||||||
|
back — `print_stations`/queues/events/counts unchanged afterwards.
|
||||||
|
- **Admin** rebuilt from HEAD with a baseline drift guard (all 9 changed prod
|
||||||
|
files byte-identical to `HEAD~1` → whole-file copy safe). Only
|
||||||
|
`convivo-admin` recreated; every unrelated container ID preserved. Live
|
||||||
|
bundle `index-pPo7RVlo.js` is byte-identical to the local HEAD build.
|
||||||
|
- **Station** `Welcome desk` provisioned in prod (token shown once, only its
|
||||||
|
SHA-256 stored). `printer_heartbeat` returns 200 over PostgREST with the
|
||||||
|
anon key + bearer token.
|
||||||
|
- **Pi** reconfigured from the local dev stack to `https://convivo.appe.at`
|
||||||
|
(`BADGE_CHECKIN_ORIGIN=https://admin.appe.at`); the running worker image
|
||||||
|
already matched HEAD, so no rebuild was needed — only `.env` swap +
|
||||||
|
`docker compose up -d --force-recreate`. The station now heartbeats to prod
|
||||||
|
(`last_seen_at` fresh, `last_status` reporting printer ready).
|
||||||
|
|
||||||
|
Troubleshooting lessons are collected in [printing.md §11](../backend/printing.md#11-troubleshooting-lessons-learned).
|
||||||
|
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
import { test, expect, type Page } from '@playwright/test';
|
||||||
|
|
||||||
|
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
|
||||||
|
const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||||
|
const user = { id: '99999999-9999-4999-8999-999999999999', email: '[email protected]', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
|
||||||
|
|
||||||
|
const jane = { id: '11111111-1111-4111-8111-111111111111', event_id: eventId, contact_email: '[email protected]', type: 'attendee', qr_token: 'CV-JANE-01', external_id: null, import_source: null, checked_in: true, points: 3 };
|
||||||
|
const sam = { id: '22222222-2222-4222-8222-222222222222', event_id: eventId, contact_email: '[email protected]', type: 'speaker', qr_token: 'CV-SAM-02', external_id: null, import_source: null, checked_in: false, points: 12 };
|
||||||
|
|
||||||
|
const layout = {
|
||||||
|
id: 'l-default', event_id: eventId, name: 'Default', is_default: true,
|
||||||
|
page_width_mm: 103, page_height_mm: 194, created_at: '2026-10-18T10:00:00Z', updated_at: '2026-10-18T10:00:00Z',
|
||||||
|
elements: [{ id: 't1', type: 'text', x: 8, y: 8, width: 60, height: 12, rotation: 0, content: 'attendee_name', text: 'fallback', font: 'Open Sans', font_size: 14, line_height: 1.2, color: '#000000', bold: false, italic: false, align_h: 'left', align_v: 'middle', transform: 'none' }],
|
||||||
|
};
|
||||||
|
|
||||||
|
const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString();
|
||||||
|
|
||||||
|
function station(overrides: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
id: 'st-0001', name: 'Entrance printer', created_at: '2026-10-18T09:00:00Z', revoked_at: null,
|
||||||
|
last_seen_at: minutesAgo(0.05),
|
||||||
|
last_status: {
|
||||||
|
version: '1.2.0', station_name: 'Entrance printer', worker: 'idle', job_msg_id: null,
|
||||||
|
printer: { connected: true, model: 'Brother QL-1110NWBc', ready: true, media_type: 'continuous', label_id: '103', media_width_mm: 103, media_length_mm: null, errors: [] },
|
||||||
|
network: { state: 'CONNECTED', ssid: 'OfficeWi-Fi', ip: '192.168.178.55' },
|
||||||
|
label: null, last_error: null, uptime_s: 7325,
|
||||||
|
},
|
||||||
|
state: 'ready',
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const errorStation = station({
|
||||||
|
id: 'st-err', name: 'Error printer',
|
||||||
|
last_status: {
|
||||||
|
version: '1.2.0', station_name: 'Error printer', worker: 'idle', job_msg_id: null,
|
||||||
|
printer: { connected: true, model: 'Brother QL-1110NWBc', ready: false, media_type: 'die-cut', label_id: 'DK11209G', media_width_mm: 62, media_length_mm: 104, errors: ['No media when printing'] },
|
||||||
|
network: { state: 'CONNECTED', ssid: 'OfficeWi-Fi', ip: '192.168.178.56' },
|
||||||
|
label: null, last_error: 'print failed: no media', uptime_s: 600,
|
||||||
|
},
|
||||||
|
state: 'error',
|
||||||
|
});
|
||||||
|
|
||||||
|
const offlineStation = station({
|
||||||
|
id: 'st-off', name: 'Offline printer', last_seen_at: minutesAgo(2),
|
||||||
|
last_status: {
|
||||||
|
version: '1.2.0', station_name: 'Offline printer', worker: 'idle', job_msg_id: null,
|
||||||
|
printer: { connected: true, model: 'Brother QL-1110NWBc', ready: true, media_type: 'continuous', label_id: '103', media_width_mm: 103, media_length_mm: null, errors: [] },
|
||||||
|
network: { state: 'CONNECTED', ssid: 'OldCafeGuest', ip: '10.0.0.9' },
|
||||||
|
label: null, last_error: null, uptime_s: 120,
|
||||||
|
},
|
||||||
|
state: 'offline',
|
||||||
|
});
|
||||||
|
|
||||||
|
const deadLetter = {
|
||||||
|
msg_id: 77, enqueued_at: '2026-10-18T11:00:00Z', failed_at: '2026-10-18T11:05:00Z',
|
||||||
|
error: 'Printer reported: End of media (die-cut size only)', attempts: 3, kind: 'checkin',
|
||||||
|
full_name: 'Bob Broken', email: '[email protected]', event_name: 'Badge Conference', registration_id: '33333333-3333-4333-8333-333333333333',
|
||||||
|
};
|
||||||
|
|
||||||
|
const recentJob = {
|
||||||
|
msg_id: 42, archived_at: '2026-10-18T11:30:00Z', kind: 'checkin',
|
||||||
|
full_name: 'Jane Attendee', email: '[email protected]', event_name: 'Badge Conference', registration_id: jane.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
function overview(stations: Record<string, unknown>[], overrides: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
stations,
|
||||||
|
queue: { pending: 1, in_flight: 0, dead_letter: stations.length ? 1 : 0, completed: 5 },
|
||||||
|
recent: [recentJob],
|
||||||
|
dead_letters: stations.length ? [deadLetter] : [],
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Options {
|
||||||
|
stations?: Record<string, unknown>[];
|
||||||
|
layouts?: Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RpcState {
|
||||||
|
calls: { fn: string; body: Record<string, unknown> }[];
|
||||||
|
overviewRequests: () => number;
|
||||||
|
callsTo: (fn: string) => Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openAdmin(page: Page, options: Options = {}): Promise<RpcState> {
|
||||||
|
const ov = overview(options.stations ?? [station()]);
|
||||||
|
const layouts = options.layouts ?? [layout];
|
||||||
|
const calls: { fn: string; body: Record<string, unknown> }[] = [];
|
||||||
|
let overviewRequests = 0;
|
||||||
|
|
||||||
|
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
|
||||||
|
const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'mock-refresh-token', expires_in: 3600, token_type: 'bearer' };
|
||||||
|
const event = { id: eventId, name: 'Badge Conference', company: 'Austrian Power Platform Enthusiasts', is_active: true, start_date: '2026-10-18', end_date: '2026-10-18', num_registrations: 2, num_checked_in_registrations: 1, num_sessions: 0, num_speakers: 1 };
|
||||||
|
const contacts = [
|
||||||
|
{ email: user.email, full_name: 'Admin', is_admin: true },
|
||||||
|
{ email: '[email protected]', full_name: 'Jane Attendee', is_admin: false },
|
||||||
|
{ email: '[email protected]', full_name: 'Sam Speaker', is_admin: false },
|
||||||
|
];
|
||||||
|
|
||||||
|
await page.route('**/auth/v1/**', (route) => route.fulfill({ json: new URL(route.request().url()).pathname.endsWith('/user') ? user : session }));
|
||||||
|
await page.route('**/rest/v1/**', (route) => {
|
||||||
|
const url = new URL(route.request().url());
|
||||||
|
const rpcMatch = url.pathname.match(/\/rpc\/([a-z_]+)$/);
|
||||||
|
if (rpcMatch) {
|
||||||
|
const fn = rpcMatch[1];
|
||||||
|
const body = (route.request().postDataJSON() ?? {}) as Record<string, unknown>;
|
||||||
|
calls.push({ fn, body });
|
||||||
|
if (fn === 'get_print_overview') {
|
||||||
|
overviewRequests += 1;
|
||||||
|
return route.fulfill({ json: ov });
|
||||||
|
}
|
||||||
|
if (fn === 'enqueue_badge_print') return route.fulfill({ json: 101 });
|
||||||
|
if (fn === 'create_print_station') return route.fulfill({ json: [{ id: 'st-new', token: 'cvp_supersecrettoken1234567890abcdef' }] });
|
||||||
|
if (fn === 'rename_print_station') {
|
||||||
|
// Apply the rename to the mocked overview so the UI reflects it.
|
||||||
|
const target = ov.stations.find((s) => s.id === body.p_id);
|
||||||
|
if (target) target.name = String(body.p_name);
|
||||||
|
return route.fulfill({ json: {} });
|
||||||
|
}
|
||||||
|
if (fn === 'requeue_dead_badge_print') return route.fulfill({ json: 102 });
|
||||||
|
if (fn === 'discard_dead_badge_print') return route.fulfill({ json: {} });
|
||||||
|
return route.fulfill({ json: [] });
|
||||||
|
}
|
||||||
|
const table = url.pathname.split('/').pop();
|
||||||
|
if (table === 'registrations') return route.fulfill({ json: [jane, sam] });
|
||||||
|
if (table === 'badge_layouts') return route.fulfill({ json: layouts });
|
||||||
|
if (table === 'contacts') return route.fulfill({ json: url.searchParams.has('email') ? contacts[0] : contacts });
|
||||||
|
if (table === 'events') return route.fulfill({ json: url.searchParams.has('is_active') ? event : [event] });
|
||||||
|
return route.fulfill({ json: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
|
||||||
|
// Nav labels include emoji, so scope to .nav and match by regex.
|
||||||
|
await expect(page.locator('.nav').getByRole('button', { name: /Printing/ })).toBeVisible();
|
||||||
|
return {
|
||||||
|
calls,
|
||||||
|
overviewRequests: () => overviewRequests,
|
||||||
|
callsTo: (fn: string) => calls.filter((c) => c.fn === fn).map((c) => c.body),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const pill = (page: Page) => page.getByTestId('printer-pill');
|
||||||
|
const navTo = async (page: Page, name: RegExp) => {
|
||||||
|
await page.locator('.nav').getByRole('button', { name }).click();
|
||||||
|
};
|
||||||
|
|
||||||
|
test('the printer pill is visible on Dashboard and Registrations and reflects ready/error/offline', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
await openAdmin(page);
|
||||||
|
// Dashboard (initial view): ready station.
|
||||||
|
await expect(pill(page)).toBeVisible();
|
||||||
|
await expect(pill(page)).toHaveAttribute('data-state', 'ready');
|
||||||
|
await expect(pill(page)).toContainText('Printer ready');
|
||||||
|
|
||||||
|
await navTo(page, /Registrations/);
|
||||||
|
await expect(page.getByRole('row').filter({ hasText: '[email protected]' })).toBeVisible();
|
||||||
|
await expect(pill(page)).toBeVisible();
|
||||||
|
await expect(pill(page)).toHaveAttribute('data-state', 'ready');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the pill shows the first printer error, shortened', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
await openAdmin(page, { stations: [errorStation] });
|
||||||
|
await expect(pill(page)).toHaveAttribute('data-state', 'error');
|
||||||
|
await expect(pill(page)).toContainText('Printer: No media');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the pill shows offline with the time since the last heartbeat', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
await openAdmin(page, { stations: [offlineStation] });
|
||||||
|
await expect(pill(page)).toHaveAttribute('data-state', 'offline');
|
||||||
|
await expect(pill(page)).toContainText('Printer offline · 2 min');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the pill is visible at a 390px mobile viewport', async ({ page }, testInfo) => {
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await openAdmin(page, { stations: [errorStation] });
|
||||||
|
await expect(pill(page)).toBeVisible();
|
||||||
|
await expect(pill(page)).toHaveAttribute('data-state', 'error');
|
||||||
|
await page.screenshot({ path: testInfo.outputPath('pill-mobile-390.png') });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking the pill opens the Printing view', async ({ page }, testInfo) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
await openAdmin(page);
|
||||||
|
await pill(page).click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Printing', exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByTestId('station-st-0001')).toContainText('Entrance printer');
|
||||||
|
await page.screenshot({ path: testInfo.outputPath('printing-view.png'), fullPage: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an offline station shows the Wi-Fi setup hint with 10.41.0.1', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
await openAdmin(page, { stations: [offlineStation] });
|
||||||
|
await pill(page).click();
|
||||||
|
const hint = page.getByRole('note');
|
||||||
|
await expect(hint).toContainText('10.41.0.1');
|
||||||
|
await expect(hint).toContainText('OldCafeGuest');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('adding a station shows the token once and it is gone after Done', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
await openAdmin(page);
|
||||||
|
await pill(page).click();
|
||||||
|
await page.getByRole('button', { name: '+ Add station' }).click();
|
||||||
|
await page.getByPlaceholder('Station name…').fill('Back desk');
|
||||||
|
await page.getByRole('button', { name: 'Create' }).click();
|
||||||
|
const dialog = page.getByRole('dialog', { name: /Station token/ });
|
||||||
|
await expect(dialog).toBeVisible();
|
||||||
|
await expect(dialog.getByText('cannot be shown again')).toBeVisible();
|
||||||
|
const tokenField = dialog.getByLabel('Station token');
|
||||||
|
await expect(tokenField).toHaveValue('cvp_supersecrettoken1234567890abcdef');
|
||||||
|
expect((await tokenField.evaluate((el) => (el as HTMLInputElement).readOnly)).toString()).toBe('true');
|
||||||
|
await dialog.getByRole('button', { name: 'Done' }).click();
|
||||||
|
await expect(dialog).toHaveCount(0);
|
||||||
|
// The token is no longer rendered anywhere on the page.
|
||||||
|
await expect(page.getByText('cvp_supersecrettoken1234567890abcdef')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renaming a station calls the RPC with the trimmed name and updates the card', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
const state = await openAdmin(page);
|
||||||
|
await pill(page).click();
|
||||||
|
const card = page.getByTestId('station-st-0001');
|
||||||
|
await expect(card).toContainText('Entrance printer');
|
||||||
|
|
||||||
|
await card.getByRole('button', { name: 'Rename', exact: true }).click();
|
||||||
|
const field = card.getByLabel('Station name');
|
||||||
|
await expect(field).toHaveValue('Entrance printer');
|
||||||
|
await field.fill(' Main hall ');
|
||||||
|
await field.press('Enter');
|
||||||
|
|
||||||
|
await expect.poll(() => state.callsTo('rename_print_station').length).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(state.callsTo('rename_print_station')[0]).toMatchObject({ p_id: 'st-0001', p_name: 'Main hall' });
|
||||||
|
await expect(card).toContainText('Main hall');
|
||||||
|
await expect(page.locator('.toast-success')).toContainText('Main hall');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rename keeps Save disabled for a blank name and Escape cancels', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
const state = await openAdmin(page);
|
||||||
|
await pill(page).click();
|
||||||
|
const card = page.getByTestId('station-st-0001');
|
||||||
|
|
||||||
|
await card.getByRole('button', { name: 'Rename', exact: true }).click();
|
||||||
|
const field = card.getByLabel('Station name');
|
||||||
|
await field.fill(' ');
|
||||||
|
await expect(card.getByRole('button', { name: 'Save' })).toBeDisabled();
|
||||||
|
await field.press('Escape');
|
||||||
|
await expect(card.getByRole('button', { name: 'Save' })).toHaveCount(0);
|
||||||
|
await expect(card).toContainText('Entrance printer');
|
||||||
|
expect(state.callsTo('rename_print_station')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Requeue and Discard call their RPCs with the dead letter id', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
const state = await openAdmin(page);
|
||||||
|
await pill(page).click();
|
||||||
|
const row = page.getByRole('row').filter({ hasText: 'Bob Broken' });
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
|
||||||
|
await row.getByRole('button', { name: 'Requeue', exact: true }).click();
|
||||||
|
await expect.poll(() => state.callsTo('requeue_dead_badge_print').length).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(state.callsTo('requeue_dead_badge_print')[0]).toMatchObject({ p_msg_id: 77 });
|
||||||
|
|
||||||
|
page.once('dialog', (dialog) => dialog.accept());
|
||||||
|
await row.getByRole('button', { name: 'Discard', exact: true }).click();
|
||||||
|
await expect.poll(() => state.callsTo('discard_dead_badge_print').length).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(state.callsTo('discard_dead_badge_print')[0]).toMatchObject({ p_msg_id: 77 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Reprint on a completed job enqueues that registration', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
const state = await openAdmin(page);
|
||||||
|
await pill(page).click();
|
||||||
|
const row = page.getByRole('row').filter({ hasText: 'Jane Attendee' }).filter({ hasText: 'check-in' });
|
||||||
|
await row.getByRole('button', { name: 'Reprint' }).click();
|
||||||
|
await expect.poll(() => state.callsTo('enqueue_badge_print').length).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(state.callsTo('enqueue_badge_print')[0]).toMatchObject({ p_registration_id: jane.id });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the Registrations Print button enqueues the row and toasts', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
const state = await openAdmin(page);
|
||||||
|
await navTo(page, /Registrations/);
|
||||||
|
const row = page.getByRole('row').filter({ hasText: '[email protected]' });
|
||||||
|
await row.getByRole('button', { name: 'Print', exact: true }).click();
|
||||||
|
await expect.poll(() => state.callsTo('enqueue_badge_print').length).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(state.callsTo('enqueue_badge_print')[0]).toMatchObject({ p_registration_id: jane.id });
|
||||||
|
await expect(page.locator('.toast-success')).toContainText('Sent to printer');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('with the printer offline, Print still queues and the toast says so', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
const state = await openAdmin(page, { stations: [offlineStation] });
|
||||||
|
await navTo(page, /Registrations/);
|
||||||
|
await page.getByRole('row').filter({ hasText: '[email protected]' }).getByRole('button', { name: 'Print', exact: true }).click();
|
||||||
|
await expect.poll(() => state.callsTo('enqueue_badge_print').length).toBeGreaterThanOrEqual(1);
|
||||||
|
await expect(page.locator('.toast-success')).toContainText('Queued — printer is offline');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Print is disabled with the configure-first tooltip when no layout exists', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
await openAdmin(page, { layouts: [] });
|
||||||
|
await navTo(page, /Registrations/);
|
||||||
|
const print = page.getByRole('row').filter({ hasText: '[email protected]' }).getByRole('button', { name: 'Print', exact: true });
|
||||||
|
await expect(print).toBeVisible();
|
||||||
|
await expect(print).toBeDisabled();
|
||||||
|
await print.locator('xpath=ancestor::span[contains(@class,"tip-anchor")]').hover();
|
||||||
|
const tip = page.getByRole('tooltip');
|
||||||
|
await expect(tip).toContainText('No badge yet');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the overview polls repeatedly while the app is open', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
|
const state = await openAdmin(page);
|
||||||
|
// StrictMode double effects + the 5 s interval: at least one initial poll.
|
||||||
|
await expect.poll(state.overviewRequests).toBeGreaterThanOrEqual(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,644 @@
|
|||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- Badge print queue (pgmq) + printer stations.
|
||||||
|
--
|
||||||
|
-- When staff check an attendee in with a welcome scan, the badge for that
|
||||||
|
-- attendee is pushed onto a `badge_print` queue. A headless printer station
|
||||||
|
-- (Raspberry Pi + Brother QL) long-polls the queue through token-gated RPCs,
|
||||||
|
-- renders the badge layout and reports success/failure. Jobs that keep failing
|
||||||
|
-- move to `badge_print_dlq` where an admin can requeue or discard them.
|
||||||
|
--
|
||||||
|
-- Design notes:
|
||||||
|
-- * pgmq is reachable ONLY through the RPCs below. The schema, its tables and
|
||||||
|
-- its functions are revoked from anon/authenticated/public, so the API never
|
||||||
|
-- exposes queue contents.
|
||||||
|
-- * Printer stations authenticate with a bearer token (`cvp_...`). Only the
|
||||||
|
-- SHA-256 hex digest is stored; the token itself is shown once at creation.
|
||||||
|
-- * `print_stations` has RLS enabled with no policies: every access goes
|
||||||
|
-- through a security definer function.
|
||||||
|
-- * The queue payload is a self-contained badge document
|
||||||
|
-- (`convivo.badge-print/v1`): event, registration, sample data and the
|
||||||
|
-- resolved layout. The station needs no further reads to print a badge.
|
||||||
|
--
|
||||||
|
-- This migration is written to be re-runnable (idempotent) so it can be
|
||||||
|
-- replayed inside the rollback test stream.
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 1. QUEUE EXTENSION AND QUEUES
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
create extension if not exists pgmq;
|
||||||
|
|
||||||
|
-- Idempotent queue creation: pgmq.create() inserts into pgmq.meta, so guard on
|
||||||
|
-- the catalogue instead of relying on the "already exists, skipping" notices.
|
||||||
|
do $$
|
||||||
|
begin
|
||||||
|
if not exists (select 1 from pgmq.meta where queue_name = 'badge_print') then
|
||||||
|
perform pgmq.create('badge_print');
|
||||||
|
end if;
|
||||||
|
if not exists (select 1 from pgmq.meta where queue_name = 'badge_print_dlq') then
|
||||||
|
perform pgmq.create('badge_print_dlq');
|
||||||
|
end if;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- No direct queue access from the API roles: everything goes through the RPCs.
|
||||||
|
revoke all on schema pgmq from public, anon, authenticated;
|
||||||
|
revoke all on all tables in schema pgmq from public, anon, authenticated;
|
||||||
|
revoke all on all sequences in schema pgmq from public, anon, authenticated;
|
||||||
|
revoke execute on all functions in schema pgmq from public, anon, authenticated;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 2. PRINTER STATIONS
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
create table if not exists public.print_stations (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
name text not null check (btrim(name) <> ''),
|
||||||
|
token_hash text not null unique,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
revoked_at timestamptz,
|
||||||
|
last_seen_at timestamptz,
|
||||||
|
last_status jsonb
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.print_stations enable row level security;
|
||||||
|
revoke all on public.print_stations from public, anon, authenticated;
|
||||||
|
grant all on public.print_stations to service_role;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 3. INTERNAL HELPERS
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- Build the badge document for one registration, or NULL when the registration
|
||||||
|
-- (or its event) has no layout with at least one element. Layout choice: the
|
||||||
|
-- default layout that has elements, else the first (created_at, name) that has.
|
||||||
|
create or replace function public._badge_print_payload(
|
||||||
|
p_registration_id uuid,
|
||||||
|
p_kind text,
|
||||||
|
p_requested_by text
|
||||||
|
) returns jsonb
|
||||||
|
language plpgsql stable security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_reg public.registrations;
|
||||||
|
v_event public.events;
|
||||||
|
v_name text;
|
||||||
|
v_layout public.badge_layouts;
|
||||||
|
begin
|
||||||
|
select r.* into v_reg
|
||||||
|
from public.registrations r
|
||||||
|
where r.id = p_registration_id;
|
||||||
|
if not found then
|
||||||
|
return null;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select e.* into v_event
|
||||||
|
from public.events e
|
||||||
|
where e.id = v_reg.event_id;
|
||||||
|
if not found then
|
||||||
|
return null;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select l.* into v_layout
|
||||||
|
from public.badge_layouts l
|
||||||
|
where l.event_id = v_event.id
|
||||||
|
and jsonb_typeof(l.elements) = 'array'
|
||||||
|
and jsonb_array_length(l.elements) > 0
|
||||||
|
order by l.is_default desc, l.created_at, l.name
|
||||||
|
limit 1;
|
||||||
|
if not found then
|
||||||
|
return null;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select c.full_name into v_name
|
||||||
|
from public.contacts c
|
||||||
|
where c.email = v_reg.contact_email;
|
||||||
|
|
||||||
|
return jsonb_build_object(
|
||||||
|
'schema', 'convivo.badge-print/v1',
|
||||||
|
'kind', p_kind,
|
||||||
|
'requested_at', now(),
|
||||||
|
'requested_by', p_requested_by,
|
||||||
|
'event', jsonb_build_object(
|
||||||
|
'id', v_event.id,
|
||||||
|
'name', v_event.name,
|
||||||
|
'company', v_event.company
|
||||||
|
),
|
||||||
|
'registration', jsonb_build_object(
|
||||||
|
'id', v_reg.id,
|
||||||
|
'email', v_reg.contact_email,
|
||||||
|
'type', v_reg."type"
|
||||||
|
),
|
||||||
|
'sample', jsonb_build_object(
|
||||||
|
'full_name', coalesce(v_name, v_reg.contact_email),
|
||||||
|
'email', v_reg.contact_email,
|
||||||
|
'ticket_type', v_reg."type"::text,
|
||||||
|
'qr_token', coalesce(v_reg.qr_token, ''),
|
||||||
|
'event_name', v_event.name,
|
||||||
|
'company', coalesce(v_event.company, '')
|
||||||
|
),
|
||||||
|
'layout', jsonb_build_object(
|
||||||
|
'id', v_layout.id,
|
||||||
|
'name', v_layout.name,
|
||||||
|
'page_width_mm', v_layout.page_width_mm,
|
||||||
|
'page_height_mm', v_layout.page_height_mm,
|
||||||
|
'elements', v_layout.elements
|
||||||
|
)
|
||||||
|
);
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Resolve a bearer token to its (non-revoked) station id.
|
||||||
|
create or replace function public._print_station_from_token(p_token text)
|
||||||
|
returns uuid
|
||||||
|
language plpgsql stable security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_id uuid;
|
||||||
|
begin
|
||||||
|
if p_token is null or btrim(p_token) = '' then
|
||||||
|
raise exception 'invalid printer token' using errcode = '28000';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select s.id into v_id
|
||||||
|
from public.print_stations s
|
||||||
|
where s.token_hash = encode(extensions.digest(p_token, 'sha256'), 'hex')
|
||||||
|
and s.revoked_at is null;
|
||||||
|
if v_id is null then
|
||||||
|
raise exception 'invalid printer token' using errcode = '28000';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
return v_id;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
revoke execute on function public._badge_print_payload(uuid, text, text)
|
||||||
|
from public, anon, authenticated;
|
||||||
|
revoke execute on function public._print_station_from_token(text)
|
||||||
|
from public, anon, authenticated;
|
||||||
|
grant execute on function public._badge_print_payload(uuid, text, text) to service_role;
|
||||||
|
grant execute on function public._print_station_from_token(text) to service_role;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 4. WELCOME CHECK-IN: enqueue a badge job on the first check-in
|
||||||
|
--
|
||||||
|
-- Re-created verbatim from 20260829000000 (same signature, return type,
|
||||||
|
-- security definer / search_path and behaviour). The only addition is the
|
||||||
|
-- `badge_print` enqueue for an attendee that was not checked in yet, inside the
|
||||||
|
-- same transaction as the checked_in update.
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
create or replace function public.welcome_checkin(p_attendee_qr text)
|
||||||
|
returns table (attendee_email text, attendee_name text, already boolean)
|
||||||
|
language plpgsql security definer set search_path = public as $$
|
||||||
|
declare
|
||||||
|
v_staff text := public.current_email();
|
||||||
|
v_attendee text;
|
||||||
|
v_name text;
|
||||||
|
v_event_id uuid;
|
||||||
|
v_checked boolean;
|
||||||
|
v_reg_id uuid;
|
||||||
|
v_payload jsonb;
|
||||||
|
begin
|
||||||
|
if v_staff is null then raise exception 'not authenticated'; end if;
|
||||||
|
if not public.is_staff_or_admin() then raise exception 'staff or admin only'; end if;
|
||||||
|
select id into v_event_id from public.events where is_active limit 1;
|
||||||
|
if v_event_id is null then raise exception 'no active event'; end if;
|
||||||
|
select r.contact_email, c.full_name, r.id into v_attendee, v_name, v_reg_id
|
||||||
|
from public.registrations r
|
||||||
|
join public.contacts c on c.email = r.contact_email
|
||||||
|
where r.qr_token = p_attendee_qr
|
||||||
|
and r.event_id = v_event_id;
|
||||||
|
if v_attendee is null then raise exception 'no attendee found for that QR code'; end if;
|
||||||
|
select checked_in into v_checked
|
||||||
|
from public.registrations
|
||||||
|
where event_id = v_event_id and contact_email = v_attendee;
|
||||||
|
update public.registrations set checked_in = true
|
||||||
|
where event_id = v_event_id and contact_email = v_attendee;
|
||||||
|
|
||||||
|
-- Badge printing: only for a genuine first check-in, and only when the event
|
||||||
|
-- actually has a badge layout. No payload -> no job.
|
||||||
|
if v_checked is not true then
|
||||||
|
v_payload := public._badge_print_payload(v_reg_id, 'checkin', v_staff);
|
||||||
|
if v_payload is not null then
|
||||||
|
perform pgmq.send('badge_print', v_payload);
|
||||||
|
end if;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
return query select v_attendee, v_name, coalesce(v_checked, false);
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
grant execute on function public.welcome_checkin(text) to authenticated;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 5. ADMIN RPCs
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- Manual reprint: queue the badge of one registration again.
|
||||||
|
create or replace function public.enqueue_badge_print(p_registration_id uuid)
|
||||||
|
returns bigint
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_found boolean;
|
||||||
|
v_payload jsonb;
|
||||||
|
v_msg_id bigint;
|
||||||
|
begin
|
||||||
|
if not public.is_admin() then
|
||||||
|
raise exception 'admin only' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select exists (
|
||||||
|
select 1 from public.registrations r where r.id = p_registration_id
|
||||||
|
) into v_found;
|
||||||
|
if not v_found then
|
||||||
|
raise exception 'registration not found';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
v_payload := public._badge_print_payload(
|
||||||
|
p_registration_id, 'reprint', public.current_email());
|
||||||
|
if v_payload is null then
|
||||||
|
raise exception 'no badge layout configured for this event';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select pgmq.send('badge_print', v_payload) into v_msg_id;
|
||||||
|
return v_msg_id;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Register a printer station. The plaintext token is returned once; only its
|
||||||
|
-- SHA-256 digest is stored.
|
||||||
|
create or replace function public.create_print_station(p_name text)
|
||||||
|
returns table (id uuid, token text)
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_id uuid;
|
||||||
|
v_token text;
|
||||||
|
begin
|
||||||
|
if not public.is_admin() then
|
||||||
|
raise exception 'admin only' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
if p_name is null or btrim(p_name) = '' then
|
||||||
|
raise exception 'station name is required';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
v_token := 'cvp_' || encode(extensions.gen_random_bytes(32), 'hex');
|
||||||
|
|
||||||
|
insert into public.print_stations (name, token_hash)
|
||||||
|
values (btrim(p_name), encode(extensions.digest(v_token, 'sha256'), 'hex'))
|
||||||
|
returning print_stations.id into v_id;
|
||||||
|
|
||||||
|
return query select v_id, v_token;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Retire a station: its token stops working immediately.
|
||||||
|
create or replace function public.revoke_print_station(p_id uuid)
|
||||||
|
returns void
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
begin
|
||||||
|
if not public.is_admin() then
|
||||||
|
raise exception 'admin only' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
update public.print_stations
|
||||||
|
set revoked_at = coalesce(revoked_at, now())
|
||||||
|
where id = p_id;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Rename a station. Revoked stations may be renamed too, so their history
|
||||||
|
-- stays readable in the overview.
|
||||||
|
create or replace function public.rename_print_station(p_id uuid, p_name text)
|
||||||
|
returns void
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_name text := btrim(coalesce(p_name, ''));
|
||||||
|
begin
|
||||||
|
if not public.is_admin() then
|
||||||
|
raise exception 'admin only' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
if v_name = '' then
|
||||||
|
raise exception 'station name is required';
|
||||||
|
end if;
|
||||||
|
if length(v_name) > 80 then
|
||||||
|
raise exception 'station name is too long';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
update public.print_stations set name = v_name where id = p_id;
|
||||||
|
if not found then
|
||||||
|
raise exception 'station not found';
|
||||||
|
end if;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Admin dashboard snapshot: stations (with a derived state), queue counters,
|
||||||
|
-- the last completed jobs and the dead letters. Never exposes qr_token or the
|
||||||
|
-- full job payloads.
|
||||||
|
create or replace function public.get_print_overview()
|
||||||
|
returns jsonb
|
||||||
|
language plpgsql stable security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_stations jsonb;
|
||||||
|
v_queue jsonb;
|
||||||
|
v_recent jsonb;
|
||||||
|
v_dead jsonb;
|
||||||
|
begin
|
||||||
|
if not public.is_admin() then
|
||||||
|
raise exception 'admin only' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select coalesce(jsonb_agg(jsonb_build_object(
|
||||||
|
'id', s.id,
|
||||||
|
'name', s.name,
|
||||||
|
'created_at', s.created_at,
|
||||||
|
'revoked_at', s.revoked_at,
|
||||||
|
'last_seen_at', s.last_seen_at,
|
||||||
|
'last_status', s.last_status,
|
||||||
|
'state', case
|
||||||
|
when s.revoked_at is not null then 'revoked'
|
||||||
|
when s.last_seen_at is null
|
||||||
|
or s.last_seen_at < now() - interval '45 seconds' then 'offline'
|
||||||
|
when coalesce(s.last_status -> 'printer' ->> 'connected', '') <> 'true'
|
||||||
|
or coalesce(s.last_status -> 'printer' ->> 'ready', '') <> 'true'
|
||||||
|
or (jsonb_typeof(s.last_status -> 'printer' -> 'errors') = 'array'
|
||||||
|
and jsonb_array_length(s.last_status -> 'printer' -> 'errors') > 0) then 'error'
|
||||||
|
when s.last_status ->> 'worker' = 'printing' then 'printing'
|
||||||
|
else 'ready'
|
||||||
|
end
|
||||||
|
) order by s.created_at, s.name), '[]'::jsonb)
|
||||||
|
into v_stations
|
||||||
|
from public.print_stations s;
|
||||||
|
|
||||||
|
select jsonb_build_object(
|
||||||
|
'pending', (select count(*) from pgmq.q_badge_print where vt <= now()),
|
||||||
|
'in_flight', (select count(*) from pgmq.q_badge_print where vt > now()),
|
||||||
|
'dead_letter', (select count(*) from pgmq.q_badge_print_dlq),
|
||||||
|
'completed', (select count(*) from pgmq.a_badge_print)
|
||||||
|
)
|
||||||
|
into v_queue;
|
||||||
|
|
||||||
|
select coalesce(jsonb_agg(x.row_data order by x.archived_at desc), '[]'::jsonb)
|
||||||
|
into v_recent
|
||||||
|
from (
|
||||||
|
select
|
||||||
|
m.archived_at,
|
||||||
|
jsonb_build_object(
|
||||||
|
'msg_id', m.msg_id,
|
||||||
|
'archived_at', m.archived_at,
|
||||||
|
'kind', m.message ->> 'kind',
|
||||||
|
'full_name', m.message -> 'sample' ->> 'full_name',
|
||||||
|
'email', m.message -> 'sample' ->> 'email',
|
||||||
|
'event_name', m.message -> 'event' ->> 'name',
|
||||||
|
'registration_id', m.message -> 'registration' ->> 'id'
|
||||||
|
) as row_data
|
||||||
|
from pgmq.a_badge_print m
|
||||||
|
order by m.archived_at desc
|
||||||
|
limit 20
|
||||||
|
) x;
|
||||||
|
|
||||||
|
select coalesce(jsonb_agg(y.row_data order by y.enqueued_at desc), '[]'::jsonb)
|
||||||
|
into v_dead
|
||||||
|
from (
|
||||||
|
select
|
||||||
|
d.enqueued_at,
|
||||||
|
jsonb_build_object(
|
||||||
|
'msg_id', d.msg_id,
|
||||||
|
'enqueued_at', d.enqueued_at,
|
||||||
|
'failed_at', d.message ->> 'failed_at',
|
||||||
|
'error', d.message ->> 'error',
|
||||||
|
'attempts', d.message ->> 'attempts',
|
||||||
|
'kind', d.message -> 'original' ->> 'kind',
|
||||||
|
'full_name', d.message -> 'original' -> 'sample' ->> 'full_name',
|
||||||
|
'email', d.message -> 'original' -> 'sample' ->> 'email',
|
||||||
|
'event_name', d.message -> 'original' -> 'event' ->> 'name',
|
||||||
|
'registration_id', d.message -> 'original' -> 'registration' ->> 'id'
|
||||||
|
) as row_data
|
||||||
|
from pgmq.q_badge_print_dlq d
|
||||||
|
) y;
|
||||||
|
|
||||||
|
return jsonb_build_object(
|
||||||
|
'stations', v_stations,
|
||||||
|
'queue', v_queue,
|
||||||
|
'recent', v_recent,
|
||||||
|
'dead_letters', v_dead
|
||||||
|
);
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Push a dead letter's original payload back onto the live queue unchanged.
|
||||||
|
create or replace function public.requeue_dead_badge_print(p_msg_id bigint)
|
||||||
|
returns bigint
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_original jsonb;
|
||||||
|
v_msg_id bigint;
|
||||||
|
begin
|
||||||
|
if not public.is_admin() then
|
||||||
|
raise exception 'admin only' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select d.message -> 'original' into v_original
|
||||||
|
from pgmq.q_badge_print_dlq d
|
||||||
|
where d.msg_id = p_msg_id;
|
||||||
|
if not found or v_original is null then
|
||||||
|
raise exception 'dead letter not found';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select pgmq.send('badge_print', v_original) into v_msg_id;
|
||||||
|
perform pgmq.delete('badge_print_dlq', p_msg_id);
|
||||||
|
return v_msg_id;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Drop a dead letter without retrying it.
|
||||||
|
create or replace function public.discard_dead_badge_print(p_msg_id bigint)
|
||||||
|
returns void
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_found boolean;
|
||||||
|
begin
|
||||||
|
if not public.is_admin() then
|
||||||
|
raise exception 'admin only' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
select pgmq.delete('badge_print_dlq', p_msg_id) into v_found;
|
||||||
|
if not v_found then
|
||||||
|
raise exception 'dead letter not found';
|
||||||
|
end if;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
revoke execute on function public.enqueue_badge_print(uuid) from public, anon, authenticated;
|
||||||
|
revoke execute on function public.create_print_station(text) from public, anon, authenticated;
|
||||||
|
revoke execute on function public.revoke_print_station(uuid) from public, anon, authenticated;
|
||||||
|
revoke execute on function public.rename_print_station(uuid, text) from public, anon, authenticated;
|
||||||
|
revoke execute on function public.get_print_overview() from public, anon, authenticated;
|
||||||
|
revoke execute on function public.requeue_dead_badge_print(bigint) from public, anon, authenticated;
|
||||||
|
revoke execute on function public.discard_dead_badge_print(bigint) from public, anon, authenticated;
|
||||||
|
|
||||||
|
grant execute on function public.enqueue_badge_print(uuid) to authenticated, service_role;
|
||||||
|
grant execute on function public.create_print_station(text) to authenticated, service_role;
|
||||||
|
grant execute on function public.rename_print_station(uuid, text) to authenticated, service_role;
|
||||||
|
grant execute on function public.revoke_print_station(uuid) to authenticated, service_role;
|
||||||
|
grant execute on function public.get_print_overview() to authenticated, service_role;
|
||||||
|
grant execute on function public.requeue_dead_badge_print(bigint) to authenticated, service_role;
|
||||||
|
grant execute on function public.discard_dead_badge_print(bigint) to authenticated, service_role;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 6. PRINTER STATION RPCs (token gated, no user session required)
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- Long-poll for the next badge job. A job that has been handed out more than
|
||||||
|
-- three times is moved to the dead letter queue instead of looping forever.
|
||||||
|
create or replace function public.printer_claim_badge_job(
|
||||||
|
p_token text,
|
||||||
|
p_vt integer default 120,
|
||||||
|
p_wait_seconds integer default 2
|
||||||
|
) returns table (msg_id bigint, read_ct integer, payload jsonb)
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_station uuid;
|
||||||
|
v_vt integer;
|
||||||
|
v_wait integer;
|
||||||
|
v_rec pgmq.message_record;
|
||||||
|
begin
|
||||||
|
v_station := public._print_station_from_token(p_token);
|
||||||
|
v_vt := least(600, greatest(30, coalesce(p_vt, 120)));
|
||||||
|
-- PostgREST runs this as anon, whose statement_timeout is 3 s.
|
||||||
|
v_wait := least(2, greatest(0, coalesce(p_wait_seconds, 2)));
|
||||||
|
|
||||||
|
update public.print_stations
|
||||||
|
set last_seen_at = now()
|
||||||
|
where id = v_station;
|
||||||
|
|
||||||
|
if v_wait > 0 then
|
||||||
|
select * into v_rec from pgmq.read_with_poll('badge_print', v_vt, 1, v_wait);
|
||||||
|
else
|
||||||
|
select * into v_rec from pgmq.read('badge_print', v_vt, 1);
|
||||||
|
end if;
|
||||||
|
if not found then
|
||||||
|
return;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
if v_rec.read_ct > 3 then
|
||||||
|
perform pgmq.send('badge_print_dlq', jsonb_build_object(
|
||||||
|
'original', v_rec.message,
|
||||||
|
'error', 'max attempts exceeded',
|
||||||
|
'attempts', v_rec.read_ct,
|
||||||
|
'failed_at', now(),
|
||||||
|
'station_id', v_station,
|
||||||
|
'source_msg_id', v_rec.msg_id
|
||||||
|
));
|
||||||
|
perform pgmq.delete('badge_print', v_rec.msg_id);
|
||||||
|
return;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
return query select v_rec.msg_id, v_rec.read_ct, v_rec.message;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Report success: the job leaves the queue for good (pgmq archive).
|
||||||
|
create or replace function public.printer_complete_badge_job(
|
||||||
|
p_token text,
|
||||||
|
p_msg_id bigint
|
||||||
|
) returns boolean
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_station uuid;
|
||||||
|
v_done boolean;
|
||||||
|
begin
|
||||||
|
v_station := public._print_station_from_token(p_token);
|
||||||
|
update public.print_stations set last_seen_at = now() where id = v_station;
|
||||||
|
select pgmq.archive('badge_print', p_msg_id) into v_done;
|
||||||
|
return v_done;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Report a failure: retry with backoff while the job still has attempts left,
|
||||||
|
-- otherwise dead-letter it.
|
||||||
|
create or replace function public.printer_fail_badge_job(
|
||||||
|
p_token text,
|
||||||
|
p_msg_id bigint,
|
||||||
|
p_error text,
|
||||||
|
p_retryable boolean default false
|
||||||
|
) returns text
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_station uuid;
|
||||||
|
v_rec pgmq.message_record;
|
||||||
|
begin
|
||||||
|
v_station := public._print_station_from_token(p_token);
|
||||||
|
update public.print_stations set last_seen_at = now() where id = v_station;
|
||||||
|
|
||||||
|
select * into v_rec from pgmq.q_badge_print m where m.msg_id = p_msg_id;
|
||||||
|
if not found then
|
||||||
|
raise exception 'job not found';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
if coalesce(p_retryable, false) and v_rec.read_ct < 3 then
|
||||||
|
perform pgmq.set_vt('badge_print', p_msg_id, least(300, 15 * v_rec.read_ct));
|
||||||
|
return 'retry';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
perform pgmq.send('badge_print_dlq', jsonb_build_object(
|
||||||
|
'original', v_rec.message,
|
||||||
|
'error', left(coalesce(p_error, ''), 2000),
|
||||||
|
'attempts', v_rec.read_ct,
|
||||||
|
'failed_at', now(),
|
||||||
|
'station_id', v_station,
|
||||||
|
'source_msg_id', p_msg_id
|
||||||
|
));
|
||||||
|
perform pgmq.delete('badge_print', p_msg_id);
|
||||||
|
return 'dead_letter';
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Liveness + status beacon. The status blob is size-capped so a chatty station
|
||||||
|
-- cannot bloat the row.
|
||||||
|
create or replace function public.printer_heartbeat(
|
||||||
|
p_token text,
|
||||||
|
p_status jsonb
|
||||||
|
) returns jsonb
|
||||||
|
language plpgsql security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_station uuid;
|
||||||
|
v_name text;
|
||||||
|
begin
|
||||||
|
v_station := public._print_station_from_token(p_token);
|
||||||
|
if p_status is not null and pg_column_size(p_status) > 16384 then
|
||||||
|
raise exception 'printer status payload too large';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
update public.print_stations
|
||||||
|
set last_status = coalesce(p_status, '{}'::jsonb),
|
||||||
|
last_seen_at = now()
|
||||||
|
where id = v_station
|
||||||
|
returning print_stations.name into v_name;
|
||||||
|
|
||||||
|
return jsonb_build_object('station_id', v_station, 'name', v_name);
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
revoke execute on function public.printer_claim_badge_job(text, integer, integer)
|
||||||
|
from public, anon, authenticated;
|
||||||
|
revoke execute on function public.printer_complete_badge_job(text, bigint)
|
||||||
|
from public, anon, authenticated;
|
||||||
|
revoke execute on function public.printer_fail_badge_job(text, bigint, text, boolean)
|
||||||
|
from public, anon, authenticated;
|
||||||
|
revoke execute on function public.printer_heartbeat(text, jsonb)
|
||||||
|
from public, anon, authenticated;
|
||||||
|
|
||||||
|
grant execute on function public.printer_claim_badge_job(text, integer, integer)
|
||||||
|
to anon, authenticated, service_role;
|
||||||
|
grant execute on function public.printer_complete_badge_job(text, bigint)
|
||||||
|
to anon, authenticated, service_role;
|
||||||
|
grant execute on function public.printer_fail_badge_job(text, bigint, text, boolean)
|
||||||
|
to anon, authenticated, service_role;
|
||||||
|
grant execute on function public.printer_heartbeat(text, jsonb)
|
||||||
|
to anon, authenticated, service_role;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 7. API RELOAD
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
notify pgrst, 'reload schema';
|
||||||
@@ -0,0 +1,918 @@
|
|||||||
|
\set ON_ERROR_STOP on
|
||||||
|
begin;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- Badge print queue regression suite (rollback only).
|
||||||
|
--
|
||||||
|
-- Run it TOGETHER with the migration in one transaction so nothing is persisted:
|
||||||
|
--
|
||||||
|
-- (echo 'begin;'; \
|
||||||
|
-- cat supabase/migrations/20261018170000_badge_print_queue.sql; \
|
||||||
|
-- sed '/^begin;$/d' supabase/tests/badge_print_tests.sql) \
|
||||||
|
-- | docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres \
|
||||||
|
-- -v ON_ERROR_STOP=1
|
||||||
|
--
|
||||||
|
-- The migration is re-runnable, so the same stream also works after the
|
||||||
|
-- migration has been applied for real (idempotency check).
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- Start from empty stations/queues so real local data can't skew counts (rolled back).
|
||||||
|
delete from public.print_stations;
|
||||||
|
delete from pgmq.q_badge_print;
|
||||||
|
delete from pgmq.q_badge_print_dlq;
|
||||||
|
delete from pgmq.a_badge_print;
|
||||||
|
delete from pgmq.a_badge_print_dlq;
|
||||||
|
|
||||||
|
create temporary table bp_results (name text);
|
||||||
|
grant insert, select on bp_results to authenticated, anon;
|
||||||
|
|
||||||
|
create function pg_temp.assert_bp(p_condition boolean, p_name text) returns void
|
||||||
|
language plpgsql as $$
|
||||||
|
begin
|
||||||
|
if p_condition is distinct from true then raise exception 'FAIL: %', p_name; end if;
|
||||||
|
insert into bp_results values (p_name);
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Scratch tables (owned by postgres, writable/readable by the API roles so the
|
||||||
|
-- anon blocks can store and read RPC results).
|
||||||
|
create temporary table bp_station (id uuid, token text);
|
||||||
|
create temporary table bp_station2 (id uuid, token text);
|
||||||
|
create temporary table bp_hb (hb jsonb);
|
||||||
|
create temporary table bp_claim (msg_id bigint, read_ct integer, payload jsonb);
|
||||||
|
create temporary table bp_enq (msg_id bigint);
|
||||||
|
create temporary table bp_res (res text);
|
||||||
|
create temporary table bp_done (ok boolean);
|
||||||
|
create temporary table bp_ov (ov jsonb);
|
||||||
|
grant insert, select, delete on bp_station, bp_station2, bp_hb, bp_claim, bp_enq, bp_res, bp_done, bp_ov
|
||||||
|
to authenticated, anon;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 1. FIXTURES
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- One active event with a badge layout, one inactive event without a layout.
|
||||||
|
update public.events set is_active = false where is_active;
|
||||||
|
insert into public.events (id, name, start_date, end_date, is_active, company) values
|
||||||
|
('b9d00001-0000-0000-0000-00000000000a', 'Print event A', current_date, current_date, true, 'Convivo GmbH'),
|
||||||
|
('b9d00002-0000-0000-0000-00000000000b', 'Print event B', current_date, current_date, false, null);
|
||||||
|
|
||||||
|
insert into public.contacts (email, full_name, is_admin) values
|
||||||
|
('[email protected]', 'Print Admin', true),
|
||||||
|
('[email protected]', 'Print Staff', false),
|
||||||
|
('[email protected]','Plain Viewer', false),
|
||||||
|
('[email protected]', 'Ada Attendee', false),
|
||||||
|
('[email protected]', 'Checked Ina', false),
|
||||||
|
('[email protected]', 'Session Sam', false),
|
||||||
|
('[email protected]', 'Direct Dana', false),
|
||||||
|
('[email protected]', 'Savepoint Sol', false),
|
||||||
|
('[email protected]', 'No-layout Nia', false);
|
||||||
|
|
||||||
|
insert into public.registrations (event_id, contact_email, type, checked_in, qr_token) values
|
||||||
|
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'staff', false, null),
|
||||||
|
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-1'),
|
||||||
|
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', true, 'BPQR-ATT-2'),
|
||||||
|
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-3'),
|
||||||
|
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-4'),
|
||||||
|
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-5'),
|
||||||
|
('b9d00002-0000-0000-0000-00000000000b', '[email protected]', 'attendee', false, 'BPQR-ATT-B');
|
||||||
|
|
||||||
|
-- Event A: an empty layout that sorts first (created_at) plus the default one
|
||||||
|
-- that actually has elements. The payload must pick the default with elements.
|
||||||
|
insert into public.badge_layouts (id, event_id, name, is_default, page_width_mm, page_height_mm, elements, created_at) values
|
||||||
|
('b9d00004-0000-0000-0000-00000000000a', 'b9d00001-0000-0000-0000-00000000000a', 'AAA Empty', false, 100, 70, '[]'::jsonb, now() - interval '3 hours'),
|
||||||
|
('b9d00005-0000-0000-0000-00000000000a', 'b9d00001-0000-0000-0000-00000000000a', 'Default', true, 100, 70,
|
||||||
|
'[{"id":"t1","type":"text","x":5,"y":5,"width":90,"height":12,"rotation":0,"content":"attendee_name","text":"","font":"Open Sans","font_size":14,"line_height":1,"color":"#000000","bold":true,"italic":false,"align_h":"center","align_v":"middle","transform":"none"}]'::jsonb,
|
||||||
|
now() - interval '2 hours');
|
||||||
|
|
||||||
|
-- A session so the regular session check-in path can be exercised.
|
||||||
|
insert into public.slots (id, event_id, type, name, slot_date, start_time, end_time)
|
||||||
|
values (900001, 'b9d00001-0000-0000-0000-00000000000a', 'session', 'Print slot', current_date, '10:00', '11:00');
|
||||||
|
insert into public.sessions (id, event_id, slot_id, title)
|
||||||
|
values ('b9d00003-0000-0000-0000-00000000000a', 'b9d00001-0000-0000-0000-00000000000a', 900001, 'Print session');
|
||||||
|
|
||||||
|
-- Deterministic, empty queues for this run (rolled back with everything else).
|
||||||
|
delete from pgmq.q_badge_print;
|
||||||
|
delete from pgmq.q_badge_print_dlq;
|
||||||
|
delete from pgmq.a_badge_print;
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print), 'queues start empty for the run');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from public.events where is_active)
|
||||||
|
and (select is_active from public.events where id = 'b9d00001-0000-0000-0000-00000000000a'),
|
||||||
|
'exactly one active event, and it is the print event');
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 2. WELCOME CHECK-IN ENQUEUES A BADGE JOB
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
create temporary table bp_scan1 as select * from public.welcome_checkin('BPQR-ATT-1');
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print),
|
||||||
|
'first welcome check-in enqueues exactly one job');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select already = false from bp_scan1),
|
||||||
|
'first check-in reports already = false');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select attendee_email = '[email protected]' and attendee_name = 'Ada Attendee' from bp_scan1),
|
||||||
|
'check-in still returns the attendee');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select checked_in from public.registrations where contact_email = '[email protected]'),
|
||||||
|
'check-in marks the attendee checked in');
|
||||||
|
|
||||||
|
-- Payload shape: exactly the seven documented keys plus requested_at.
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select array_agg(k order by k) from
|
||||||
|
(select jsonb_object_keys(q.message) as k
|
||||||
|
from (select message from pgmq.q_badge_print limit 1) q) x)
|
||||||
|
= array['event','kind','layout','registration','requested_at','requested_by','sample','schema'],
|
||||||
|
'payload top level keys are exact');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select array_agg(k order by k) from
|
||||||
|
(select jsonb_object_keys(q.message -> 'sample') as k
|
||||||
|
from (select message from pgmq.q_badge_print limit 1) q) x)
|
||||||
|
= array['company','email','event_name','full_name','qr_token','ticket_type'],
|
||||||
|
'payload sample keys are exact');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select array_agg(k order by k) from
|
||||||
|
(select jsonb_object_keys(q.message -> 'event') as k
|
||||||
|
from (select message from pgmq.q_badge_print limit 1) q) x)
|
||||||
|
= array['company','id','name'],
|
||||||
|
'payload event keys are exact');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select array_agg(k order by k) from
|
||||||
|
(select jsonb_object_keys(q.message -> 'registration') as k
|
||||||
|
from (select message from pgmq.q_badge_print limit 1) q) x)
|
||||||
|
= array['email','id','type'],
|
||||||
|
'payload registration keys are exact');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select array_agg(k order by k) from
|
||||||
|
(select jsonb_object_keys(q.message -> 'layout') as k
|
||||||
|
from (select message from pgmq.q_badge_print limit 1) q) x)
|
||||||
|
= array['elements','id','name','page_height_mm','page_width_mm'],
|
||||||
|
'payload layout keys are exact');
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select message ->> 'schema' = 'convivo.badge-print/v1'
|
||||||
|
and message ->> 'kind' = 'checkin'
|
||||||
|
and message ->> 'requested_by' = '[email protected]'
|
||||||
|
from pgmq.q_badge_print limit 1),
|
||||||
|
'payload schema/kind/requested_by are correct');
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select message -> 'sample' ->> 'full_name' = 'Ada Attendee'
|
||||||
|
and message -> 'sample' ->> 'email' = '[email protected]'
|
||||||
|
and message -> 'sample' ->> 'ticket_type' = 'attendee'
|
||||||
|
and message -> 'sample' ->> 'qr_token' = 'BPQR-ATT-1'
|
||||||
|
and message -> 'sample' ->> 'event_name' = 'Print event A'
|
||||||
|
and message -> 'sample' ->> 'company' = 'Convivo GmbH'
|
||||||
|
from pgmq.q_badge_print limit 1),
|
||||||
|
'payload sample values are correct');
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select jsonb_typeof(message -> 'layout' -> 'page_width_mm') = 'number'
|
||||||
|
and jsonb_typeof(message -> 'layout' -> 'page_height_mm') = 'number'
|
||||||
|
and (message -> 'layout' ->> 'page_width_mm')::numeric = 100
|
||||||
|
and (message -> 'layout' ->> 'page_height_mm')::numeric = 70
|
||||||
|
and jsonb_array_length(message -> 'layout' -> 'elements') = 1
|
||||||
|
from pgmq.q_badge_print limit 1),
|
||||||
|
'layout page sizes are JSON numbers with the right elements');
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select message -> 'layout' ->> 'name' = 'Default'
|
||||||
|
from pgmq.q_badge_print limit 1),
|
||||||
|
'layout choice prefers the default layout that has elements');
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select (message ->> 'requested_at')::timestamptz between now() - interval '5 minutes' and now() + interval '5 minutes'
|
||||||
|
from pgmq.q_badge_print limit 1),
|
||||||
|
'requested_at is a usable timestamp');
|
||||||
|
|
||||||
|
-- Full document equality (requested_at excluded: it is generated per call).
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select m.message - 'requested_at' = jsonb_build_object(
|
||||||
|
'schema', 'convivo.badge-print/v1',
|
||||||
|
'kind', 'checkin',
|
||||||
|
'requested_by', '[email protected]',
|
||||||
|
'event', jsonb_build_object('id', e.id, 'name', e.name, 'company', e.company),
|
||||||
|
'registration', jsonb_build_object('id', r.id, 'email', r.contact_email, 'type', r."type"),
|
||||||
|
'sample', jsonb_build_object(
|
||||||
|
'full_name', c.full_name, 'email', r.contact_email,
|
||||||
|
'ticket_type', r."type"::text, 'qr_token', r.qr_token,
|
||||||
|
'event_name', e.name, 'company', coalesce(e.company, '')),
|
||||||
|
'layout', jsonb_build_object(
|
||||||
|
'id', l.id, 'name', l.name,
|
||||||
|
'page_width_mm', l.page_width_mm, 'page_height_mm', l.page_height_mm,
|
||||||
|
'elements', l.elements)) - 'requested_at'
|
||||||
|
from pgmq.q_badge_print m
|
||||||
|
join public.registrations r on r.id = (m.message -> 'registration' ->> 'id')::uuid
|
||||||
|
join public.events e on e.id = r.event_id
|
||||||
|
join public.contacts c on c.email = r.contact_email
|
||||||
|
join public.badge_layouts l on l.id = (m.message -> 'layout' ->> 'id')::uuid
|
||||||
|
limit 1),
|
||||||
|
'check-in payload equals the expected badge document');
|
||||||
|
|
||||||
|
-- A second scan of the same lanyard is a no-op for the queue.
|
||||||
|
create temporary table bp_scan2 as select * from public.welcome_checkin('BPQR-ATT-1');
|
||||||
|
select pg_temp.assert_bp((select already = true from bp_scan2), 'second scan reports already = true');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print), 'second check-in enqueues nothing');
|
||||||
|
|
||||||
|
-- An attendee that was already checked in before the scan produces no job.
|
||||||
|
create temporary table bp_scan3 as select * from public.welcome_checkin('BPQR-ATT-2');
|
||||||
|
select pg_temp.assert_bp((select already = true from bp_scan3), 'pre-checked-in attendee reports already = true');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print), 'already checked-in attendee enqueues nothing');
|
||||||
|
|
||||||
|
-- An event without a badge layout: check-in works, nothing is queued.
|
||||||
|
update public.events set is_active = true where id = 'b9d00002-0000-0000-0000-00000000000b';
|
||||||
|
create temporary table bp_scan4 as select * from public.welcome_checkin('BPQR-ATT-B');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select attendee_email = '[email protected]' from bp_scan4),
|
||||||
|
'check-in succeeds for an event without a layout');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print), 'event without a layout enqueues nothing');
|
||||||
|
update public.events set is_active = true where id = 'b9d00001-0000-0000-0000-00000000000a';
|
||||||
|
|
||||||
|
-- The regular session check-in must not print badges.
|
||||||
|
select public.checkin_attendee('b9d00003-0000-0000-0000-00000000000a', 'BPQR-ATT-3');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from public.checkins where session_id = 'b9d00003-0000-0000-0000-00000000000a'),
|
||||||
|
'session check-in recorded');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print), 'session check-in enqueues nothing');
|
||||||
|
|
||||||
|
-- A direct write of checked_in (admin edit) must not print badges either.
|
||||||
|
update public.registrations set checked_in = true where contact_email = '[email protected]';
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print), 'direct checked_in update enqueues nothing');
|
||||||
|
|
||||||
|
-- The enqueue is transactional with the check-in itself.
|
||||||
|
savepoint bp_sp;
|
||||||
|
select public.welcome_checkin('BPQR-ATT-5');
|
||||||
|
rollback to savepoint bp_sp;
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print),
|
||||||
|
'rolled back check-in leaves no queue message');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select not checked_in from public.registrations where contact_email = '[email protected]'),
|
||||||
|
'rolled back check-in leaves the attendee unchecked');
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 3. PRINT STATION PROVISIONING AND PERMISSIONS
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
insert into bp_station select * from public.create_print_station('Front desk');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from bp_station), 'admin can create a print station');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select token like 'cvp_%' and length(token) = 68 from bp_station),
|
||||||
|
'station token is cvp_ plus 64 hex chars');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select p.token_hash = encode(extensions.digest(s.token, 'sha256'), 'hex')
|
||||||
|
and p.token_hash !~ 'cvp_'
|
||||||
|
from public.print_stations p, bp_station s where p.id = s.id),
|
||||||
|
'only the sha256 of the token is stored');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select name = 'Front desk' and revoked_at is null and last_seen_at is null
|
||||||
|
from public.print_stations p join bp_station s on s.id = p.id),
|
||||||
|
'new station starts unseen and active');
|
||||||
|
|
||||||
|
-- Blank names are rejected.
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform * from public.create_print_station(' ');
|
||||||
|
raise exception 'blank station name allowed';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'station name is required' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'blank station name rejected');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- Non-admins get a hard permission error.
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.create_print_station('Sneaky');
|
||||||
|
raise exception 'non-admin create allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform public.get_print_overview();
|
||||||
|
raise exception 'non-admin overview allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'non-admin cannot create stations or read the overview');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- The API roles have no direct access to the queues or the station table.
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform count(*) from pgmq.q_badge_print;
|
||||||
|
raise exception 'anon read the queue';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
null;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform count(*) from pgmq.q_badge_print_dlq;
|
||||||
|
raise exception 'anon read the dead letter queue';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
null;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform count(*) from public.print_stations;
|
||||||
|
raise exception 'anon read print_stations';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
null;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform count(*) from pgmq.send('badge_print', '{}'::jsonb);
|
||||||
|
raise exception 'anon called pgmq.send';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
null;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'anon cannot touch pgmq or print_stations directly');
|
||||||
|
end; $$;
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 4. PRINTER PROTOCOL (token gated, called as anon)
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
|
||||||
|
delete from bp_hb;
|
||||||
|
insert into bp_hb
|
||||||
|
select public.printer_heartbeat(s.token,
|
||||||
|
'{"printer": {"connected": true, "ready": true, "errors": []}, "worker": "idle"}'::jsonb)
|
||||||
|
from bp_station s;
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select hb ? 'station_id' and hb ->> 'name' = 'Front desk' from bp_hb),
|
||||||
|
'heartbeat returns the station identity');
|
||||||
|
|
||||||
|
-- Oversized status blobs are refused.
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.printer_heartbeat(s.token, jsonb_build_object('blob', repeat('x', 20000))::jsonb)
|
||||||
|
from bp_station s;
|
||||||
|
raise exception 'oversized heartbeat accepted';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'printer status payload too large' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'oversized heartbeat rejected');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- Claim the queued job (no polling in tests).
|
||||||
|
insert into bp_claim
|
||||||
|
select * from public.printer_claim_badge_job((select token from bp_station), 120, 0);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from bp_claim), 'anon with a valid token claims the job');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select read_ct = 1 and payload ->> 'kind' = 'checkin' from bp_claim),
|
||||||
|
'claimed row carries read_ct and the payload');
|
||||||
|
|
||||||
|
-- Nothing else to claim.
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from public.printer_claim_badge_job((select token from bp_station), 120, 0)),
|
||||||
|
'second claim returns no row');
|
||||||
|
|
||||||
|
-- Bad tokens are rejected with 28000.
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.printer_heartbeat('cvp_deadbeef', '{}'::jsonb);
|
||||||
|
raise exception 'bad token accepted';
|
||||||
|
exception when others then
|
||||||
|
if sqlstate <> '28000' then raise; end if;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform * from public.printer_claim_badge_job(null, 120, 0);
|
||||||
|
raise exception 'null token accepted';
|
||||||
|
exception when others then
|
||||||
|
if sqlstate <> '28000' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'invalid token rejected with 28000');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- Completing archives it.
|
||||||
|
reset role;
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print where vt > now()),
|
||||||
|
'claim hides the job behind a visibility timeout');
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_done;
|
||||||
|
insert into bp_done
|
||||||
|
select public.printer_complete_badge_job(s.token, c.msg_id) from bp_station s, bp_claim c;
|
||||||
|
select pg_temp.assert_bp((select ok = true from bp_done), 'complete archives the job');
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select last_seen_at is not null and last_status -> 'printer' ->> 'ready' = 'true'
|
||||||
|
from public.print_stations p join bp_station s on s.id = p.id),
|
||||||
|
'heartbeat stores status and last_seen_at');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.a_badge_print), 'archive table holds the completed job');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print), 'queue is empty after completion');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
insert into bp_station2 select * from public.create_print_station('Back office');
|
||||||
|
select public.revoke_print_station((select id from bp_station2));
|
||||||
|
-- Both stations are created inside the same statement, so make the creation
|
||||||
|
-- order (and therefore the overview order) unambiguous.
|
||||||
|
update public.print_stations set created_at = created_at + interval '1 minute'
|
||||||
|
where id = (select id from bp_station2);
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform * from public.printer_claim_badge_job((select token from bp_station2), 120, 0);
|
||||||
|
raise exception 'revoked token accepted';
|
||||||
|
exception when others then
|
||||||
|
if sqlstate <> '28000' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'revoked token rejected with 28000');
|
||||||
|
end; $$;
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 5. RETRY, DEAD LETTERS, REQUEUE, DISCARD
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
insert into bp_enq
|
||||||
|
select public.enqueue_badge_print(
|
||||||
|
(select id from public.registrations where contact_email = '[email protected]'));
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq)),
|
||||||
|
'admin enqueue_badge_print queues a job');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select message ->> 'kind' = 'reprint'
|
||||||
|
and message ->> 'requested_by' = '[email protected]'
|
||||||
|
from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq)),
|
||||||
|
'manual job is a reprint requested by the admin');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
|
||||||
|
-- Retryable failure keeps the job and pushes the visibility timeout out.
|
||||||
|
delete from bp_claim;
|
||||||
|
insert into bp_claim
|
||||||
|
select * from public.printer_claim_badge_job((select token from bp_station), 120, 0);
|
||||||
|
delete from bp_res;
|
||||||
|
insert into bp_res
|
||||||
|
select public.printer_fail_badge_job(s.token, c.msg_id, 'printer offline', true)
|
||||||
|
from bp_station s, bp_claim c where c.read_ct = 1;
|
||||||
|
select pg_temp.assert_bp((select res = 'retry' from bp_res), 'retryable failure returns retry');
|
||||||
|
|
||||||
|
-- Unknown jobs cannot be failed.
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.printer_fail_badge_job((select token from bp_station), 999999, 'nope', false);
|
||||||
|
raise exception 'missing job accepted';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'job not found' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'failing an unknown job raises job not found');
|
||||||
|
end; $$;
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq) and vt > now()),
|
||||||
|
'retry keeps the job with a future visibility timeout');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print_dlq), 'retry leaves the dead letter queue empty');
|
||||||
|
|
||||||
|
-- Simulate the backoff elapsing, claim again, then fail permanently.
|
||||||
|
update pgmq.q_badge_print set vt = now() - interval '1 second'
|
||||||
|
where msg_id = (select msg_id from bp_enq);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_claim;
|
||||||
|
insert into bp_claim
|
||||||
|
select * from public.printer_claim_badge_job((select token from bp_station), 120, 0);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 and bool_and(read_ct = 2) from bp_claim),
|
||||||
|
'job becomes claimable again after the backoff');
|
||||||
|
delete from bp_res;
|
||||||
|
insert into bp_res
|
||||||
|
select public.printer_fail_badge_job(s.token, c.msg_id, 'paper jam', false)
|
||||||
|
from bp_station s, bp_claim c;
|
||||||
|
select pg_temp.assert_bp((select res = 'dead_letter' from bp_res), 'fatal failure returns dead_letter');
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print_dlq), 'fatal failure lands in the dead letter queue');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print), 'dead-lettered job leaves the queue');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select d.message -> 'original' = c.payload
|
||||||
|
and d.message ->> 'error' = 'paper jam'
|
||||||
|
and (d.message ->> 'attempts')::int = 2
|
||||||
|
and d.message ->> 'station_id' = (select id::text from bp_station)
|
||||||
|
and (d.message ->> 'source_msg_id')::bigint = (select msg_id from bp_enq)
|
||||||
|
and (d.message ->> 'failed_at')::timestamptz is not null
|
||||||
|
from pgmq.q_badge_print_dlq d, bp_claim c),
|
||||||
|
'dead letter envelope carries the original payload and context');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.requeue_dead_badge_print(999999);
|
||||||
|
raise exception 'unknown dead letter requeued';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'dead letter not found' then raise; end if;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform public.discard_dead_badge_print(999999);
|
||||||
|
raise exception 'unknown dead letter discarded';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'dead letter not found' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'requeue/discard reject unknown dead letters');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- Requeue puts the byte-identical payload back on the live queue.
|
||||||
|
delete from bp_enq;
|
||||||
|
insert into bp_enq select public.requeue_dead_badge_print(
|
||||||
|
(select msg_id from pgmq.q_badge_print_dlq));
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq)),
|
||||||
|
'requeue puts the job back on badge_print');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print_dlq), 'requeue removes the dead letter');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select q.message = c.payload
|
||||||
|
from pgmq.q_badge_print q, bp_claim c
|
||||||
|
where q.msg_id = (select msg_id from bp_enq)),
|
||||||
|
'requeued payload is identical to the original');
|
||||||
|
|
||||||
|
-- And it prints again: fail it once more, then discard it for good.
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_claim;
|
||||||
|
insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0);
|
||||||
|
delete from bp_res;
|
||||||
|
insert into bp_res
|
||||||
|
select public.printer_fail_badge_job(s.token, c.msg_id, 'still jammed', false)
|
||||||
|
from bp_station s, bp_claim c;
|
||||||
|
select pg_temp.assert_bp((select res = 'dead_letter' from bp_res), 'requeued job can dead-letter again');
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 from pgmq.q_badge_print_dlq), 'the re-run job dead-lettered once more');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
select public.discard_dead_badge_print((select msg_id from pgmq.q_badge_print_dlq));
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print_dlq), 'discard removes the dead letter');
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 6. MAX ATTEMPTS AUTO DEAD-LETTER ON CLAIM
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
delete from bp_enq;
|
||||||
|
insert into bp_enq select public.enqueue_badge_print(
|
||||||
|
(select id from public.registrations where contact_email = '[email protected]'));
|
||||||
|
|
||||||
|
-- Pretend the job was handed out three times already (the claim below makes it
|
||||||
|
-- the fourth read, which is past the max-attempts limit).
|
||||||
|
update pgmq.q_badge_print set read_ct = 3, vt = now() - interval '1 second'
|
||||||
|
where msg_id = (select msg_id from bp_enq);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_claim;
|
||||||
|
insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from bp_claim), 'claim refuses a job that exceeded max attempts');
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print), 'exhausted job leaves the queue');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 1 and bool_and(message ->> 'error' = 'max attempts exceeded')
|
||||||
|
and bool_and((message ->> 'attempts')::int = 4)
|
||||||
|
from pgmq.q_badge_print_dlq),
|
||||||
|
'exhausted job is dead-lettered as max attempts exceeded');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
select public.discard_dead_badge_print((select msg_id from pgmq.q_badge_print_dlq));
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 0 from pgmq.q_badge_print_dlq), 'admin can discard the exhausted job');
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 7. ADMIN OVERVIEW
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_hb;
|
||||||
|
insert into bp_hb
|
||||||
|
select public.printer_heartbeat(s.token,
|
||||||
|
'{"printer": {"connected": true, "ready": true, "errors": []}, "worker": "idle"}'::jsonb)
|
||||||
|
from bp_station s;
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
delete from bp_ov;
|
||||||
|
insert into bp_ov select public.get_print_overview();
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select array_agg(k order by k) from
|
||||||
|
(select jsonb_object_keys(o.ov) as k from (select ov from bp_ov limit 1) o) x)
|
||||||
|
= array['dead_letters','queue','recent','stations'],
|
||||||
|
'overview top level keys are exact');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select ov #> '{stations,0,state}' = '"ready"'::jsonb from bp_ov),
|
||||||
|
'station state is ready after a healthy heartbeat');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select jsonb_array_length(ov -> 'stations') = 2 from bp_ov),
|
||||||
|
'overview lists both stations');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select (ov -> 'stations' -> 0 ->> 'name') = 'Front desk' from bp_ov),
|
||||||
|
'stations are ordered by creation');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select ov #> '{stations,1,state}' = '"revoked"'::jsonb from bp_ov),
|
||||||
|
'revoked station reports state revoked');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select ov -> 'queue' ->> 'completed' = '1'
|
||||||
|
and ov -> 'queue' ->> 'pending' = '0'
|
||||||
|
and ov -> 'queue' ->> 'in_flight' = '0'
|
||||||
|
and ov -> 'queue' ->> 'dead_letter' = '0' from bp_ov),
|
||||||
|
'queue counters match the queue state');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select jsonb_array_length(ov -> 'recent') = 1
|
||||||
|
and (ov -> 'recent' -> 0 ->> 'full_name') = 'Ada Attendee'
|
||||||
|
and (ov -> 'recent' -> 0 ->> 'kind') = 'checkin' from bp_ov),
|
||||||
|
'recent lists the completed job summary');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select array_agg(k order by k) from
|
||||||
|
(select jsonb_object_keys(o.ov -> 'recent' -> 0) as k from (select ov from bp_ov limit 1) o) x)
|
||||||
|
= array['archived_at','email','event_name','full_name','kind','msg_id','registration_id'],
|
||||||
|
'recent rows expose only summary fields');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select position('BPQR-ATT-1' in ov::text) = 0
|
||||||
|
and position('qr_token' in ov::text) = 0 from bp_ov),
|
||||||
|
'overview never leaks the qr token or raw payloads');
|
||||||
|
|
||||||
|
-- Printer reports an error -> state error.
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_hb;
|
||||||
|
insert into bp_hb
|
||||||
|
select public.printer_heartbeat(s.token,
|
||||||
|
'{"printer": {"connected": true, "ready": true, "errors": ["paper jam"]}, "worker": "printing"}'::jsonb)
|
||||||
|
from bp_station s;
|
||||||
|
reset role;
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select get_print_overview() #> '{stations,0,state}' = '"error"'::jsonb),
|
||||||
|
'station state is error when the printer reports errors');
|
||||||
|
|
||||||
|
-- A disconnected printer is also an error, even without an error list.
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_hb;
|
||||||
|
insert into bp_hb
|
||||||
|
select public.printer_heartbeat(s.token,
|
||||||
|
'{"printer": {"connected": false, "ready": false, "errors": []}, "worker": "idle"}'::jsonb)
|
||||||
|
from bp_station s;
|
||||||
|
reset role;
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select get_print_overview() #> '{stations,0,state}' = '"error"'::jsonb),
|
||||||
|
'station state is error when the printer is disconnected');
|
||||||
|
|
||||||
|
-- A stale heartbeat makes it offline.
|
||||||
|
update public.print_stations set last_seen_at = now() - interval '60 seconds'
|
||||||
|
where id = (select id from bp_station);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select get_print_overview() #> '{stations,0,state}' = '"offline"'::jsonb),
|
||||||
|
'station state is offline when the heartbeat is stale');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select get_print_overview() #> '{stations,1,state}' = '"revoked"'::jsonb),
|
||||||
|
'revoked wins over a missing heartbeat');
|
||||||
|
|
||||||
|
-- Dead letters surface in the overview too.
|
||||||
|
delete from bp_enq;
|
||||||
|
insert into bp_enq select public.enqueue_badge_print(
|
||||||
|
(select id from public.registrations where contact_email = '[email protected]'));
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_claim;
|
||||||
|
insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0);
|
||||||
|
select public.printer_fail_badge_job((select token from bp_station), (select msg_id from bp_claim), 'usb error', false);
|
||||||
|
reset role;
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select jsonb_array_length(get_print_overview() -> 'dead_letters') = 1
|
||||||
|
and (get_print_overview() -> 'dead_letters' -> 0 ->> 'error') = 'usb error'
|
||||||
|
and (get_print_overview() -> 'dead_letters' -> 0 ->> 'full_name') = 'Ada Attendee'
|
||||||
|
and position('BPQR-ATT-1' in get_print_overview()::text) = 0),
|
||||||
|
'dead letters are summarised without leaking payloads');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select get_print_overview() -> 'queue' ->> 'dead_letter' = '1'),
|
||||||
|
'dead letter counter reflects the queue');
|
||||||
|
|
||||||
|
-- Non-admins cannot read the overview.
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.get_print_overview();
|
||||||
|
raise exception 'non-admin overview allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'overview is admin only');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 7b. STATION RENAME
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
select public.rename_print_station((select id from bp_station), ' Front desk 2 ');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select name = 'Front desk 2' from public.print_stations p join bp_station s on s.id = p.id),
|
||||||
|
'admin rename updates and trims the name');
|
||||||
|
|
||||||
|
-- Revoked stations stay renamable so their history remains readable.
|
||||||
|
select public.rename_print_station((select id from bp_station2), 'Back office (old)');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select name = 'Back office (old)' and revoked_at is not null
|
||||||
|
from public.print_stations p join bp_station2 s on s.id = p.id),
|
||||||
|
'a revoked station can still be renamed');
|
||||||
|
|
||||||
|
-- The heartbeat echoes the new name (the station treats it as authoritative).
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
delete from bp_hb;
|
||||||
|
insert into bp_hb
|
||||||
|
select public.printer_heartbeat(s.token,
|
||||||
|
'{"printer": {"connected": true, "ready": true, "errors": []}, "worker": "idle"}'::jsonb)
|
||||||
|
from bp_station s;
|
||||||
|
reset role;
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select hb ->> 'name' = 'Front desk 2' from bp_hb),
|
||||||
|
'heartbeat after a rename returns the new name');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select get_print_overview() -> 'stations' -> 0 ->> 'name' = 'Front desk 2'),
|
||||||
|
'overview shows the renamed station');
|
||||||
|
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.rename_print_station((select id from bp_station), ' ');
|
||||||
|
raise exception 'blank station name accepted by rename';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'station name is required' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'blank rename rejected');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.rename_print_station((select id from bp_station), repeat('x', 81));
|
||||||
|
raise exception 'over-long station name accepted by rename';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'station name is too long' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'over-long rename rejected');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- Exactly 80 chars is still allowed.
|
||||||
|
select public.rename_print_station((select id from bp_station), repeat('y', 80));
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select name = repeat('y', 80) from public.print_stations p join bp_station s on s.id = p.id),
|
||||||
|
'rename accepts a name of exactly 80 chars');
|
||||||
|
select public.rename_print_station((select id from bp_station), 'Front desk 2');
|
||||||
|
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.rename_print_station('b9d00009-0000-0000-0000-000000000009', 'Ghost');
|
||||||
|
raise exception 'unknown station rename accepted';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'station not found' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'rename of an unknown station raises station not found');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select name = 'Front desk 2' from public.print_stations p join bp_station s on s.id = p.id),
|
||||||
|
'rejected rename attempts leave the name unchanged');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform public.rename_print_station((select id from bp_station), 'Sneaky');
|
||||||
|
raise exception 'non-admin rename allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'non-admin cannot rename stations');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 8. ENQUEUE GUARDS
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
-- Event B has no layout at all.
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform * from public.enqueue_badge_print(
|
||||||
|
(select id from public.registrations where contact_email = '[email protected]'));
|
||||||
|
raise exception 'enqueue without a layout allowed';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'no badge layout configured for this event' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'enqueue raises when the event has no layout');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform * from public.enqueue_badge_print('b9d00009-0000-0000-0000-000000000009');
|
||||||
|
raise exception 'enqueue of a missing registration allowed';
|
||||||
|
exception when raise_exception then
|
||||||
|
if sqlerrm <> 'registration not found' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'enqueue raises for an unknown registration');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","role":"authenticated"}', true);
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform * from public.enqueue_badge_print(
|
||||||
|
(select id from public.registrations where contact_email = '[email protected]'));
|
||||||
|
raise exception 'non-admin enqueue allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform public.revoke_print_station((select id from bp_station));
|
||||||
|
raise exception 'non-admin revoke allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform public.requeue_dead_badge_print(1);
|
||||||
|
raise exception 'non-admin requeue allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
begin
|
||||||
|
perform public.discard_dead_badge_print(1);
|
||||||
|
raise exception 'non-admin discard allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
if sqlerrm <> 'admin only' then raise; end if;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'admin print RPCs are admin only');
|
||||||
|
end; $$;
|
||||||
|
|
||||||
|
-- The anonymous role cannot call the admin RPCs either.
|
||||||
|
select set_config('request.jwt.claims', '{"role":"anon"}', true);
|
||||||
|
set local role anon;
|
||||||
|
do $$ begin
|
||||||
|
begin
|
||||||
|
perform * from public.enqueue_badge_print(
|
||||||
|
(select id from public.registrations where contact_email = '[email protected]'));
|
||||||
|
raise exception 'anon enqueue allowed';
|
||||||
|
exception when insufficient_privilege then
|
||||||
|
null;
|
||||||
|
end;
|
||||||
|
perform pg_temp.assert_bp(true, 'anon cannot enqueue badge jobs');
|
||||||
|
end; $$;
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 9. MIGRATION IDEMPOTENCY (the stream re-runs the migration on an applied DB)
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 2 from pgmq.meta
|
||||||
|
where queue_name in ('badge_print', 'badge_print_dlq')),
|
||||||
|
'both queues exist exactly once');
|
||||||
|
select pg_temp.assert_bp(
|
||||||
|
(select count(*) = 2 from pgmq.list_queues() l
|
||||||
|
where (l).queue_name in ('badge_print', 'badge_print_dlq')),
|
||||||
|
'list_queues reports both queues');
|
||||||
|
|
||||||
|
select count(*) as passed_assertions from bp_results;
|
||||||
|
rollback;
|
||||||
Reference in new issue
Block a user