feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view

- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations,
  token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs,
  welcome_checkin enqueue; badge_print_tests.sql (101 assertions)
- apps/printer: Python worker (Playwright render -> brother_ql via pyusb),
  comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token),
  arm64 image build + idempotent Pi setup/install scripts, 77 pytest
- apps/admin: Printing view, station management/DLQ, global printer status
  pill, Print button on Registrations, standalone print renderer entry
  (print.html -> dist-print) with bundled fonts
- docs: printing.md + architecture/schema/rpcs/tests/admin-app updates,
  apps/printer/AGENT.md operating manual
- e2e: printing.spec.ts
This commit is contained in:
Lago committed 2026-10-18 22:25:38 +02:00
1 parent 04f3f55b78
commit c980effddc
55 files changed
+7406 -29

No files matched your search

+1
View File
@@ -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) |
| **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) |
| **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) |
| **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) |
+23 -5
View File
@@ -49,12 +49,24 @@ flowchart LR
N -->|"proxy (supabase_kong_Convivo:8000)"| K
NA -->|"proxy (supabase_kong_Convivo:8000)"| 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
service-role key. It is driven by the admin's **Interfaces** menu and runs on
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,
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.
@@ -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,
Sponsors, Schedule (slots/sessions/speakers/material), Activity (manual event
and session AI summaries), Raffle (attendee prize draws), Badges (per-event
WYSIWYG badge layout editor), Events, Interfaces,
Reports and Settings.
WYSIWYG badge layout editor), Printing (badge-print stations + queue), Events,
Interfaces, Reports and Settings.
- **Auth guard** — email-only magic links; non-admin sessions are rejected.
- **Key RPCs** — `reset_registration_qr_token` (regenerate a registration's
lanyard token + sync the Auth password), `adjust_points`, `upsert_contact`,
`create_registration`, `set_registration_type`, `set_session_material`, and the
raffle functions `get_raffle_pool` / `draw_raffle_winner` / `reset_raffle`
and the badge-layout functions `save_badge_layout` / `set_default_badge_layout`
/ `delete_badge_layout`
raffle functions `get_raffle_pool` / `draw_raffle_winner` / `reset_raffle`,
the badge-layout functions `save_badge_layout` / `set_default_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
client-callable; generation uses authenticated [sidecar routes](./backend/feedback-ai.md).
@@ -209,6 +222,11 @@ Convivo/
├─ apps/sidecar/ # Sessionize sync sidecar (Node, on demand)
│ ├─ Dockerfile # node:20-alpine + xlsx (parses the Excel export)
│ └─ 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/
│ ├─ config.toml # Local stack config (ports, auth, RLS defaults)
│ ├─ migrations/
+1
View File
@@ -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) |
| [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 |
| [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`) |
## The big picture
+286
View File
@@ -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).
+42
View File
@@ -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
`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
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
+31
View File
@@ -303,6 +303,37 @@ Interfaces view's "recent runs").
(`sync_runs_select_admin`). Written only by the `sync_sessionize_event` /
`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
- `slots_event_id_idx (event_id)`, `registrations_event_id_idx (event_id)`,
+36
View File
@@ -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
After applying `20261015194531_badge_editor`, run:
+71 -6
View File
@@ -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. |
| **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**). |
| **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. |
| **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). |
| **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. |
| **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). |
@@ -109,11 +110,16 @@ apps/admin/src/
│ └─ ToastContext.tsx # transient toasts
├─ lib/
│ ├─ supabase.ts # createClient (same-origin)
│ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points)
│ └─ types.ts # TS types mirroring the DB
│ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points, printing)
│ ├─ printStatus.tsx # PrintStatusProvider (5 s get_print_overview poll) + pill/hint helpers
│ └─ types.ts # TS types mirroring the DB (incl. BadgePrintPayload, PrintOverview)
├─ components/
│ ├─ 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/
│ └─ Login.tsx # email-only magic-link login (admin-only)
└─ views/
@@ -143,8 +149,11 @@ key. Everything it can do is allowed by RLS:
(admin-only policies).
- **RPCs** — `adjust_points` (manual, audited as `admin`), `upsert_contact`,
`create_registration`, `set_registration_type`,
`set_session_material` (attach uploaded material), and
`delete_event_schedule` (clear the active event's slots/sessions). The
`set_session_material` (attach uploaded material),
`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
exposes a token reset. See
[../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
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)
Setting a registration's type to **Sponsor** requires a sponsor lookup. If none
+103
View File
@@ -97,3 +97,106 @@ touched.
absent from the served JS, `give-feedback` still present (non-service path).
- **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).