Compare commits

..
63 Commits
Author SHA1 Message Date
f0f88c2b15 docs: remove credentials from deployment.md + document co-authors
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-29 22:11:27 +01:00
e86e6cb327 docs(release): Follow-up 5 — Sessions-view material column + inline manager deploy record
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-21 21:33:23 +02:00
45ab567355 feat(admin): material column + inline material manager in the Sessions view
- Sessions table gains a Material column (uploaded pill with the clean
  filename in its tooltip, dash when none)
- Expanded session row: shared MaterialPanel (open / download / delete
  with confirm) plus immediate upload/replace via MaterialUploadRow
- Schedule session modal refactored onto the same MaterialPanel; its
  upload keeps the uploads-on-Save behavior
- sessions-view e2e: new test pins the pill, panel buttons, clean
  filename, unlock hint and replace control

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-21 21:30:31 +02:00
22d2418125 docs(release): Follow-up 4 — admin session material management deploy record
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-21 21:19:43 +02:00
5619b94c97 feat(admin): full session material management in the session editor
See the attached file (clean name), Open (signed-URL preview), Download
(authenticated blob under the original filename), Delete (confirm, storage
object + path, errors surface), and Upload/Replace with previous-object
cleanup and upload rollback on DB failure. Admins already passed every
storage RLS gate for material writes, so no migration; this also documents
and smoke-verifies insert/read/update/delete as an impersonated admin.
Also fixes the stale e2e expectation that the speaker-portal download is an
<a href> (it became an authenticated blob button with the private bucket).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-21 21:17:02 +02:00
ea1ed87fc9 docs(release): material time-lock deploy record + private-bucket docs
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-21 19:01:40 +02:00
a8f3f5b8e1 feat(sessions): material downloads unlock when the session ends
Private materials bucket + RLS read gate (admins/own speakers anytime, all
attendees after the scheduled slot end, event-local Amsterdam time); always
visible uploaded-state, locked download panel, authenticated client downloads,
admin signed URLs. 12 new assertions in material_time_lock_tests.sql.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-21 18:57:15 +02:00
7776145a77 docs(release): record service-sessions-English deploy + prod feed language discovery + stale-suite audit
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-21 00:03:14 +02:00
68de851b28 test(leaderboard): catch fixtures up to event-feedback +5 and auto-connect
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-20 23:43:23 +02:00
bb55020350 feat(sessions): service sessions are always English
Both sync functions now force language='English' for sessions flagged
is_service_session (covers Sessionize, GridSmart and Excel paths); existing
service rows are backfilled by the migration. Regular sessions keep the
Language-category behavior unchanged. Seed mirrors the rule; test suite
extended (11 cases, all green).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-20 23:25:35 +02:00
9c916b2f0e docs(release): record the session-language production deploy (2026-10-21)
Migration 20261021090000 + sidecar + both frontends live on the VM.
Baseline-guarded, backed up (szlang-20261020T211211Z), rollback-tagged.
Prod function defs verified byte-identical to local post-migrate; live
gridsmart sync through the new transform: 30 updates, 0 errors, level/area
untouched. language null until the organizer defines the category.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-20 23:15:28 +02:00
ec23da9bb9 feat(sessions): import language tag from Sessionize Language category
Sabrina's backlog: show a per-session delivery language in the sessions
overview. Sessionize has no native language field (verified live), so the
sidecar now resolves each session's categoryItems against a session
category titled "Language" (Sessionize's own demo-endpoint pattern) and
ships it as a plain string; a native session.language wins if it ever
appears.

- migration 20261021090000: sessions.language + re-created
  get_agenda / sync_sessionize_event / sync_sessionize_excel. Language
  upserts with the same coalesce(excluded, existing) rule as level/area,
  so a source without language never erases it. get_agenda is dropped +
  re-created (OUT shape change) and re-granted to anon/authenticated.
- sidecar: transform extracted to sessionize-transform.js (unit-tested);
  Excel import gains Language / Sprache / "Sprache / Language" headers.
- attendee app: third agenda filter dropdown ("All languages", only
  rendered when values exist) + language pill in SessionDetail.
- admin app: Sessions search + subtitle include language.
- seed: English for all talks, German for the two German-titled sessions.
- tests: session_language_tests.sql (8 assertions, all pass),
  sessionize-transform.test.js (7), transform-excel Language case; 43/43
  sidecar tests, date-guard/gridsmart/session-persistence suites green.
- docs: schema.md sessions columns + next-steps.md completion entry.

Organizer precondition (Sabrina): define the "Language" category AND
enable session custom fields on the event's API/Embed page, otherwise
live syncs keep language null (Excel import is the fallback).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-20 22:55:24 +02:00
07ee05e1cd docs(release): record the staff-auto-connect + event-feedback-points production deploy
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-20 22:20:04 +02:00
3ee91b5ad6 feat(points): staff auto-connect never scores; event feedback pays +5
- Migration 20261020120000: staff (type staff / Admin / @appe.at) are
  auto-connected to every participant of the event via connections.auto
  rows inserted directly as accepted - never through accept_connection,
  so zero points by construction; backfill + idempotent helper + trigger.
- Migration 20261020130000: submit_event_feedback awards +5 on the first
  submission per participant x event (edits earn 0), gated by
  _points_eligible; response gains earned column; ACL restored.
- Admin: points move from Contacts to Registrations (active-event rows
  only, in-place save); Dashboard Top points drops emails; Dashboard and
  Activity hide auto connections.
- Attendee: leaderboard masks surnames (Max M.); EventFeedback toast
  shows +5 pts on paid submissions.
- Tests: staff_auto_connections_tests.sql (14 assertions), rpc_tests
  section 11 (4 assertions). Docs + release record 2026-10-20.
- README: document the git-ignored .env provisioning step (missing key
  = white screen).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-20 22:15:29 +02:00
e243b83a56 docs: seed drift, pretix skip observability, new-suite run books, current-state refresh
tests.md: new 'Full E2E Suite Status' opener -- suite is NOT green (213/42,
2026-10-19, exit 1); the pipe-through-tail trap that produced two false '0
failed' records; seed-drift mechanism (config.ts identities gone, reset.ts
UPDATE-only no-ops, logins hang); 11 failing families; admin-schedule
exonerated by the reverted-Schedule.tsx check; fix direction (upsert demo
identities, self-provision new specs). Four new run sections: llm-connection
(three-state verdict), tooltip containment (mutation-validated provenance),
CONV-MATERIAL-005 (self-contained fixture pattern), corrected counts
(sidecar 35, checkin-points 4).

pretix.md: 'Positions that never become registrations' -- the email+name
guard, the 118->115 grouping on production numbers, and the anonymous-Skipped
gap (QRJZN case study, sync_runs.skipped never sees client-side drops).

next-steps.md: new 'Known work (open as of 2026-10-19)' section (seed drift,
skip observability, QRJZN operator action); stale cross-cutting items marked
done (subdomains live, printing shipped after the 'skipped by decision'
note, testing exists); Open decisions cleared; current-state blockquote
extended through the 2026-10-19 round.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 22:39:23 +02:00
bd157ac4f5 docs: close round-2 doc gaps — sidecar route table, printing points note, deployment markers, releases index
- sidecar.md HTTP API table now lists the LLM routes (/llm-settings GET/PUT,
  /llm-test, /feedback-summary) it had silently omitted; points at
  feedback-ai.md for contracts
- printing.md: welcome_checkin gained points/points_awarded (+10 on the first
  check-in, same branch as the badge loop; popup promises the award only when
  points_awarded)
- deployment.md: the 2026-10-07 status table is now labelled as that day's
  snapshot with a pointer to releases/ and the current 2026-10-19 bundles,
  migration, backup and rollback tags (old index-Gv3o7AW6/CocPCSGt markers were
  misleading readers about live state)
- new docs/releases/README.md index (7 files existed, docs/README linked only
  one); docs/README.md links it

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 22:23:06 +02:00
6f13d47020 docs(release): correct the false '0 failed' claims and record the pipe mistake
Both 202/211-passed-0-failed claims came from piping the suite through tail:
the pipe reports tail's exit code and tail's window makes Playwright's
failed-test list (indented spec paths) look like progress. Real measurement,
exit code captured: 213 passed, 42 failed -- all pre-existing seed drift
(pretix reseed removed the demo identities reset.ts only UPDATEs), with
admin-schedule proven unrelated by rerunning it against the reverted
pre-silent-refresh Schedule.tsx. Everything added this round passed.
Also records the QRJZN diagnosis: skipped since Sept 9 for missing name,
never importable -- the defect is that skip reasons are anonymous.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 22:17:09 +02:00
9cd2f0b957 feat(convivo): pending-material chip opens the session detail directly
Tapping a session in the red-clip popup only did go('agenda'), leaving the
speaker to hunt for the talk the popup had just named. It now opens the same
SessionDetail sheet "My picks today" uses -- the upload form is inside it, so
one tap reaches the action.

CONV-MATERIAL-005 provisions its own speaker fixture (the old demo speaker died
with the pretix-import reseed), drives the real QR login, and asserts the
upload notice is visible with the home tab still active; mutation-checked by
restoring go('agenda') -- the test fails on the old behavior.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 21:40:56 +02:00
23af4f3930 fix(admin): clamp tooltips into the viewport
The portal kept cards out of table overflow but nothing kept them on screen:
centred on a fixed-width card, any trigger near an edge lost text -- reported
on Sessions' right-aligned Generate button. The shared Tooltip now measures the
card, clamps it to the viewport, flips below when there is no room above, and
keeps the arrow aimed at the trigger. No more CSS centreing transform, JS owns
the coordinates.

New tooltip-containment.spec.ts (4 tests) asserts the measured rectangle, no
document widening and arrow alignment at wide/narrow/short viewports; verified
it catches the bug by reverting the fix (3 of 4 fail). Full serial e2e: 211
passed, 0 failed.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 21:19:30 +02:00
8be6680a67 docs(release): record the points/sessions/sidecar deployment
Backup 20261019T181646Z with the four pre-migration function definitions (the
migration drops them, so the dump alone was not a rollback path); 113/24/57
assertions run rollback-only against prod data before applying; welcome +10 ->
session +10 -> total 20 and the staff zero-award path both proven on real prod
rows inside rolled-back transactions; three container IDs changed, seventeen
preserved; the llm-test verdict fix redeployed without recreating convivo-app.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 20:41:51 +02:00
b715e414dc fix(llm-test): an unreported reasoning-token counter is not a warning
Measured against the gateway this deployment actually uses (ai.lago.dev), a
"Reply with OK" request comes back with usage.completion_tokens_details: {} --
the provider does not report a reasoning counter at all. Thinking is
verifiably off there (2 completion tokens, 424 ms, versus ~235 tokens and
~3.5x latency when on), but reasoning_tokens is undefined, not 0.

The verdict had two states, so a healthy production connection rendered amber
with "the model is still thinking" -- the button would have reported a working
configuration as broken. The reasoning verdict is now three-state:

- reported 0        -> reasoning_disabled: true, green
- not reported      -> reasoning_tokens: null, no warning, neutral card that
                       says it cannot be confirmed from the usage block
- reported and > 0  -> amber + the existing warning

Only a reported 0 asserts reasoning_disabled, so the UI still never claims
thinking is off without evidence.

Sidecar 34 -> 35 tests (all three unreported shapes assert no warning); new
e2e/tests/llm-connection-test.spec.ts, 6 tests, covering the three verdict
tones, the failure case, the dirty-form lock and the in-flight state.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 20:35:13 +02:00
d3083b7940 fix(points): welcome check-in awards +10; add Sessions view, AI connection test, silent reload
The front-desk check-in set checked_in and printed badges but awarded nothing,
so the +10 depended on which check-in a person happened to get. Every award
path was reviewed:

- welcome_checkin awards +10 (category checkin) on a genuine first check-in and
  returns points + points_awarded; checkin_attendee and preview_welcome_checkin
  return points_awarded too.
- set_registration_checked_in(false) deleted all checkin points while keeping
  the checkins rows, and switching back on awarded nothing -- one mistaken
  toggle destroyed those points permanently. ON now recomputes from the rows
  that still exist and awards only the shortfall: reversible, still unfarmable.
- The staff/Admin/@appe.at exclusion stays (product decision) but is no longer
  silent: three-way points sheets in the scanner, "no points" with a tooltip in
  Registrations, and the Contacts points modal refuses to apply rather than
  letting adjust_points (void) no-op quietly.

Also in this change:
- admin silent refresh (5s poll + 500ms after writes) across all data views;
  Registrations patches in place so rows never slide under the cursor
- Settings "Validate AI connection" via a new sidecar POST /llm-test verdict
  endpoint (never leaks the key, distinguishes "no usage block" from "off")
- new Sessions view between Schedule and Activity: speakers, attendance,
  ratings, attendee filter, and one button that summarises every session with
  feedback (one request each, concurrency 3, UI blocked until all settle)
- provider requests disable thinking through one shared body builder sending
  both reasoning_effort:"none" and chat_template_kwargs.enable_thinking

SQL: 113 / 57 / 24 assertions (set_registration_checked_in section 3 was
rewritten, it asserted the bug). Sidecar 34 unit tests. Full e2e 202 passed,
0 failed. Migration applied locally only -- not deployed.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 20:14:03 +02:00
cdb4793273 docs(release): record the 2026-10-19 production deployment
Deployed to prod: migration 20261019110000 (ledger 41 -> 42) applied with the
badge_print suite run rollback-only in the same transaction (113/113), both
images rebuilt and recreated, live bundles now index-DSNhW0mZ.js (admin) and
index-CXd2kxEv.js (attendee) md5-identical to the HEAD build.

Gate and copies verified against real prod data inside rolled-back transactions:
a session scan of an un-welcomed attendee raised the front-desk message, the same
call returned a checkin_id after welcome_checkin, and refused again once the flag
was cleared; with badge_copies = 3 one welcome enqueued exactly 3 pgmq jobs and
preview reported copies = 3. Counts match the backup afterwards (119 contacts,
115 registrations, 2 checkins, queue 0, 173 auth users).

Backup /home/APPE/convivo-backups/gatecopies-20261019T131204Z with rollback tags
convivo-{app,admin}:rollback-gatecopies-20261019T131204Z. No data backfill:
[email protected] keeps checked_in = false, so the front desk re-welcomes him or an
admin flips the toggle. No printer change - the Pi renders from its own bundled
dist-print, and multiplicity is N queue jobs. .design-audit/ is ignored now.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 15:20:26 +02:00
17473916a6 fix(admin): per-row check-in toggle; feat(db): front-desk gate + badge copies
Registrations table felt buggy because both row actions did
setBusy(true) -> write -> reloadRegistrations() -> setBusy(false):
the list is sorted by points, so a reload made the row you just
touched jump (or vanish under a Checked-in filter), and the single
`busy` flag disabled every control in the table for the whole
request. The fix is per-row in-flight state (busyIds + withRowBusy)
and no reload at all: the toggle patches its own row's checked_in
plus the points delta the RPC returns, the type change patches
`type`; a rejected write rolls both back. Only the touched row is
disabled, shows a "Saving…" pulse, and two rows can save at once.
Toggle hit area is now 40x41 px with a focus-visible ring.

Front-desk gate: checkin_attendee reads registrations.checked_in
and raises "This attendee needs to be checked in at the front desk
first." when it is not true, and no longer sets checked_in as a
side effect. checkins has no INSERT policy, so the RPC is the only
write path and the gate cannot be bypassed. The scanner shows a
dedicated "Not checked in yet" sheet instead of a toast.

Badge copies: events.badge_copies (1..4, default 1). welcome_checkin
sends that many pgmq jobs in one transaction (the Pi prints one
label per job, so N jobs = N labels; no worker change) and clamps
the value again itself. preview_welcome_checkin gained a `copies`
column (drop + recreate) so the popup states the real count. Manual
reprint still prints exactly one. Set from Settings -> Badge
printing (active event) and the Events form, always as a
single-column update; the Settings badge section now renders even
when the LLM settings call fails.

Tests: badge_print 113 (+6), leaderboard 47 (+1), new
registration-checkin-toggle (6), front-desk-gate (3),
welcome-badge-copies (3); the stale registrations-PATCH mock in
registration-ticket-merge now targets set_registration_checked_in,
the ambiguous Save button is "Save copies", and the print-copy
assertion tolerates the typographic apostrophe. Docs updated
(rpcs, schema, printing, tests, admin-app, screens) with a release
record; NOT deployed - see docs/releases/2026-10-19.md.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 15:10:20 +02:00
d3531e1fac fix(scanner): camera restarts automatically after a scan (paused-driven lifecycle)
The camera stopped after decoding one code (by design, one scan at a time)
but was only ever started on mount, so it stayed dead until staff navigated
away and back. The parent now owns the lifecycle via a paused prop: Scan
pauses while busy or any sheet is open (camera re-arms when the sheet
closes), Login pauses while busy (re-arms after a failed scan). scannedRef
guards duplicate callbacks between decode and stop.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 11:03:08 +02:00
383a80f5ec fix(scanner): camera scans used stale first-render handler (welcome mode ignored); feat(admin): un-check-in removes check-in points
- Scanner: invoke onResult through a ref refreshed each render; the camera
  callback captured the mount-time closure, so scans kept running session
  check-in even with the Welcome toggle on (manual entry was unaffected)
- new RPC set_registration_checked_in(id, bool): admin-only; on un-check,
  deletes the event's 'checkin' points_log rows and applies the negative
  delta via _award_points('admin') so leaderboard + audit stay consistent;
  re-check awards nothing; returns points_removed
- admin Registrations toggle now calls the RPC, refreshes rows and toasts
  the removed points
- supabase/tests/set_registration_checked_in_tests.sql: 15 assertions

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 10:35:10 +02:00
65dcf64c4e feat(scan): confirm before welcome check-in, with print warning
The staff scanner checked attendees in silently, and the default session
mode never prints — so a welcome-desk scan could check someone in with no
badge and no confirmation.

- new read-only RPC preview_welcome_checkin(qr): resolves the attendee and
  reports already + will_print (mirrors the exact welcome_checkin enqueue
  condition: first check-in AND a layout exists). Staff/admin only; checks
  nobody in, enqueues nothing.
- attendee Scan screen previews first and shows a Yes/No sheet: "You are
  checking in [Name]. By confirming, you will print this person's label."
  Only Yes runs welcome_checkin. Session check-in unchanged (never prints).
- badge_print_tests.sql +8 assertions (109 total); ScanPage + welcome specs
  drive the confirm step; new CONV-CHECKIN-003 (No cancels, Yes checks in).
- docs: rpcs.md, printing.md, releases/2026-10-19.md.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 09:45:20 +02:00
00c89c1b48 feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view
- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations,
  token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs,
  welcome_checkin enqueue; badge_print_tests.sql (101 assertions)
- apps/printer: Python worker (Playwright render -> brother_ql via pyusb),
  comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token),
  arm64 image build + idempotent Pi setup/install scripts, 77 pytest
- apps/admin: Printing view, station management/DLQ, global printer status
  pill, Print button on Registrations, standalone print renderer entry
  (print.html -> dist-print) with bundled fonts
- docs: printing.md + architecture/schema/rpcs/tests/admin-app updates,
  apps/printer/AGENT.md operating manual
- e2e: printing.spec.ts

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-18 22:25:38 +02:00
0f3720d48a docs: record attendee feedback-polish deployment (a81ec4b, attendee-only)
Live bundle index-DRSsD1hj.js / index-4X1LaDjo.css byte-identical to a clean
local build of a81ec4b; previous index-CRttiV1E.js now 404. Drift guard passed
against the 6d375d0 baseline, backup + rollback tag
convivo-app:rollback-fbpolish-a81ec4b-20261018T162520Z, only convivo-app
recreated, unrelated containers unchanged, 45/45 mocked checks vs production.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-18 18:27:49 +02:00
4547bb0f49 docs(pretix): document organizer-detail endpoint feeding events.company
Catch-up note for the organizer display-name fetch added with 5cb67af:
GET /organizers/<slug>/ returns the organisation name (multi-lingual object
or string), which the sidecar resolves via pickPretixName and stores on
events.company during each Pretix sync so badges can bind a Company field.
There is no separate company field on the organizer resource.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-18 18:20:24 +02:00
a81ec4b787 fix(convivo): readable descriptions, no feedback UI on service sessions, no demo-clock badge
Three attendee-app polish items from hands-on testing (Sabrina). All
presentation-layer: no migration, no RPC, no admin/sidecar change.

- Session detail collapsed multi-paragraph descriptions into one block. The
  feed carries real newlines (the sidecar passes Sessionize description through
  untouched), so this was pure CSS: new .sd-desc uses white-space: pre-line.
  The AI feedback summary gets the same via .feedback-review .fr-text.
- Staff saw "Your session feedback" on Break/Lunch cards, because
  _assign_service_session_speakers makes every staff member a speaker of every
  service slot. showFeedback = !isService now gates all three feedback surfaces
  (review block, Give-feedback button, "not checked in" note). The sheet itself
  stays openable for service sessions.
- Removed the "Demo clock" badge from the Home header. The simulated clock is an
  internal demo aid; attendees were never meant to see it. useEvent() still
  exposes clockMode and the admin toggle is unchanged.

Tests: three new API-mocked cases in convivo-admin-entry.spec.ts (service
feedback suppression, multi-line description via pre-line CSS + exact textContent
+ rendered-height comparison, no demo-clock badge per clock mode). 45/45 green
against the local dev server; attendee build clean.

Docs synced: screens.md, app-structure.md, backend/tests.md, next-steps.md, plus
a release record at docs/releases/2026-10-18.md noting that items 1/3/7 of the
report were already shipped (84d3922, 2aa2b89) and that this change is not yet
deployed.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-18 18:20:16 +02:00
6d375d0413 docs: record Home pick-nudge fix deployment (2aa2b89, attendee-only)
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-17 10:39:09 +02:00
2aa2b894e4 fix(home): hide the 'No pick yet' nudge once the user has any pick
The Now/Next cards fall back to a concurrent-session list when the user
has no pick for that specific slot, and always appended a 'No pick yet —
tap a session in the Agenda to choose.' hint. With picks on other slots
this contradicted the 'My picks today' list right below (screenshot).
ConcurrentList now takes hasPicks and renders the hint only while the
user has no picks at all.

e2e: two new 'Home session picks' cases (hint hidden with a pick on the
other slot; still shown with none, asserted per card). 43/43 local.
Docs: screens.md nudge rule, tests.md regression note.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-17 10:36:58 +02:00
25df5b3abc chore(assets): move Manfred originals to assets/manfred, rename by pose
Relocate the four full-resolution mascot source PNGs out of the root
Manfred/ folder into assets/manfred/ (a non-build-context source dir,
like mockup/), renamed from their ChatGPT export names to pose names:
manfred-{waving,confident,coffee,celebrating}.png. git mv preserves
history (all four recorded as renames).

These originals are never shipped (Vite serves only apps/convivo/public/),
so the served 224px WebP poses are untouched and the attendee bundle is
byte-identical. Add assets/manfred/README.md with the pose table and a
regeneration command, and note a pre-existing cosmetic mismatch: the
deployed WebP filenames are rotated relative to their content (harmless —
Profile picks a pose at random and e2e asserts the filename).

Docs: fix the stale Manfred/ pointer in releases/2026-10-10.md and
cross-reference the source dir from frontend/screens.md.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 23:32:57 +02:00
940bc5b160 chore(parity): record prod⇄dev⇄repo parity execution + fix stale schedule test
- docs/prod-parity-plan.md: audit + phased plan, now marked EXECUTED with the
  autonomous decisions (target=HEAD, data preserved, bonus shipped at 0,
  whole-tree deploy).
- docs/releases/2026-10-16.md: append the parity release record (schema +
  ledger + whole-tree code deploy, backups/rollback tags, 151/151 e2e, 46-assert
  live rollback smoke, autosync preserved, dev==prod==repo).
- e2e/admin-schedule.spec.ts: drop the stale 'Evaluate' disabled assertion
  (button removed from the codebase in 821907b).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 17:56:09 +02:00
2d4be583ce build(sidecar): use npm ci with lockfile for reproducible installs
Fold prod's genuinely-better Dockerfile into the repo so a whole-tree
prod deploy loses nothing: copy package-lock.json and run npm ci
instead of npm install. The repo lockfile already contains pdfkit, so
this resolves cleanly.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 17:43:58 +02:00
ad915dda1a docs: record attendee agenda polish deployment (scoped overlay, 84d3922)
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 16:22:59 +02:00
84d39224ba fix(convivo): consistent service cards, in-place pick details, no duplicated slot time
- groupAgenda drops orphan service slots (no session row), so every Service Session card consistently shows header + session row; list, slot count and Home Now/Next agree
- Extract the session detail bottom sheet into shared components/SessionDetail.tsx; Home's My-picks chips now open it in place instead of routing to the Agenda (App passes openFeedback so Give-feedback works there too)
- Sheet subtitle shows the slot name only when it adds information: auto-named 'Slot 10:15-11:00' no longer repeats the time range, and service names equal to the session title are skipped
- e2e: orphan-slot test + Home session picks test (exact subtitle assertion) in convivo-admin-entry.spec.ts, 41/41 green; speaker-portal 19/19; docs + release record 2026-10-16.md

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 16:11:12 +02:00
8e38052f4c feat(admin): per-row badge preview with unconfigured tooltip, Excel-style column filters and search in Contacts/Registrations
- New shared BadgeRender module (resolveText/resolveQr/BadgeElementBody/BadgePagePreview/fitScale) reused by the badge editor and the new read-only preview modal
- Registrations: Badge button on every row opens a live preview of that attendee's badge; grayed out with a Uiverse-style APPE-red tooltip when the event has no badge configured
- Contacts + Registrations: per-column multi-select filters (LinkedIn/Visibility/Admin; Type/Ticket/Checked in) with Excel-style live counts, plus general search (contacts: first/last/email; registrations: +type)
- New Tooltip and ColumnFilter primitives in ui.tsx (portal-based, escape/outside-click close)
- e2e: registration-badge-preview.spec.ts (13) + table-filters.spec.ts (13), all green; docs synced

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 08:53:46 +02:00
30ed4388c0 feat(badges): labeled align-text-in-box section and Ctrl+Z/Ctrl+Y shortcuts
Replace the cryptic single-letter text alignment buttons with a labeled 'Align text in box' section (horizontal + vertical icon groups); make wrapped text honor textAlign via full-width span; add undo/redo keyboard shortcuts (Ctrl/Cmd+Z, Ctrl+Y, Ctrl/Cmd+Shift+Z) gated behind the typing guard; 7 new e2e tests (20 total).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 07:57:50 +02:00
5cb67afb5e feat: add per-event badge editor, pretix company import, smart guides
Badge Designer (admin): per-event WYSIWYG badge/PDF layout editor with mm canvas, text/QR/image elements, multi-select, Word+PowerPoint alignment, PowerPoint-style smart guides with snapping, Delete-key, preview and JSON views. Migration 20261015194531_badge_editor (badge_layouts + admin-only save/set-default/delete RPCs).

Company import: migration 20261015200719_events_company adds events.company; the sidecar pretix sync now fetches the organizer display name and stores it (best-effort). Bindable on badges as Company/organizer.

Tests: 15 SQL rollback assertions + 13 mocked browser tests. Docs synced.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-15 22:25:15 +02:00
4ec03410ff feat: add admin raffle with confetti and top-3/staff exclusion
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-15 21:39:57 +02:00
4cf09cd739 docs: record verified feedback and leaderboard deployment
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-15 19:15:03 +02:00
821907b164 feat: add manual feedback AI summaries and secure leaderboard scoring
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-15 19:06:10 +02:00
407b878e23 docs: record October 11 delivery and seed formatting
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-11 09:03:38 +02:00
84691de6ee feat: sync GridSmart agendas and use event-relative demo time
Support script and URL sources, automatic Sessionize polling, staff-linked service sessions, chronological agenda blocks, and inline Placeholders. Fix demo mode to use the active event date and document deployed behavior with regression coverage.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-11 08:39:15 +02:00
f32289f583 fix: preserve week-long sessions and add profile mascot
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-10 20:40:42 +02:00
fbc827c2b8 feat: finalize ticket merging and speaker-aware imports
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-10 13:28:18 +02:00
7f340b4c08 fix: import localized topics and flattened Sessionize speakers
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-10 01:50:08 +02:00
22de4a8645 feat: add event-scoped schedule deletion and import date guard
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-10 01:44:40 +02:00
15789ab04d feat: polish speaker material upload control
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-07 19:58:00 +02:00
68fecc2ad1 feat: add magic-link admin login and speaker materials portal
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-07 18:27:56 +02:00
0b6d1f2b6f Post-event reporting + talk networking incentives
- Talk networking: per-event talk_networking_bonus awarded when two people
  who shared a checked-in talk accept a connection (accept_connection
  re-created, shared_talk flag, get_talk_cohort RPC, points_log category
  check widened); Convivo Networking sub-tab inside the Connect screen
  (Home quick action deep-links in; Connect button reflects existing
  connection state and is disabled for sent/connected/declined); admin
  Events view bonus input (0-10).
- Reports: sidecar POST /export (CSV / multi-sheet XLSX / PDF report via
  new pdfkit dep); APPE Admin Reports view (any event: on-screen summary,
  session feedback summary, top-5, CSV/Excel/PDF downloads); Activity
  session-feedback per-session aggregate header.
- Also carried: @appe.at admin trigger + default password, bulk contact
  delete, session level/area + event-level feedback, agenda level/area
  filters, admin password self-service, schedule level/area fields.
- 18/18 RPC tests; both apps build; exports verified end-to-end.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-21 22:34:25 +02:00
f74db9dc26 pretix: per-event API key + live organizer/event picker
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 18:03:18 +02:00
0ad02970a0 admin: group Sessionize + Pretix into labeled sections in event modal
Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 17:37:29 +02:00
567d7e5d40 Force admin registrations to staff type (no exception)
Adds a BEFORE INSERT OR UPDATE trigger on public.registrations: if the
registrant is an admin (is_admin flag OR @appe.at domain — same rule as
is_admin()), the registration type is forced to 'staff' (staff is merged
into admin in this app). No exception.

Enforced at the DB transaction level, so it covers every write path — the
Pretix sync RPC, Sessionize sync, manual admin edits, direct Postgres.
Backfilled the 2 existing admin registrations ([email protected], [email protected]
were 'attendee' -> now 'staff'). Verified: setting an admin reg to 'attendee'
is immediately forced back to 'staff'.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 13:09:04 +02:00
265e38aade Auto-set is_admin for @appe.at contacts via trigger
The one-time backfill (20260909010000) missed contacts created later (e.g. by
the Pretix sync), so their is_admin flag stayed false and the admin UI badge
showed them as non-admin even though is_admin() treated them as admins.

Adds a BEFORE INSERT OR UPDATE trigger that auto-sets is_admin=true for any
@appe.at email, keeping the flag, the UI badge, and is_admin() in sync for
every current + future contact. Re-applied the rule to the 2 rows created
since the last backfill.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 13:05:26 +02:00
ee839db75f Make @appe.at contacts admins automatically
- is_admin() now returns true when the caller's email is on the @appe.at
  domain (in addition to the is_admin flag) — covers all admin RLS policies
  + admin-only RPCs at once.
- Backfill contacts.is_admin=true for existing @appe.at rows.
- Admin app login gate (AuthContext) mirrors the same rule so a freshly
  created @appe.at contact can sign in immediately.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 12:58:52 +02:00
996db14a98 Fix: 'delete all contacts for event' no longer deletes the logged-in admin
The bulk delete now excludes the currently-logged-in contact (me.email) so
you can't delete your own account out from under yourself.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 12:54:36 +02:00
a1fd108e4c Admin: per-event registrations view, contact deletion, collapsible interface logs
- Registrations: event selector dropdown (default = active event), event name
  shown prominently in header with active badge, 'Delete all contacts for this
  event' action (deletes the contacts registered for the selected event)
- Contacts: per-row Delete button (with confirm; cascades to registrations)
- Interfaces: Sessionize + Pretix 'Recent runs' tables now in per-interface
  collapsibles, collapsed by default
- api: deleteContact + deleteContacts helpers

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 12:49:07 +02:00
509e342204 Add Pretix ticketing integration (every-minute sidecar sync)
- docs/backend/pretix.md: Pretix REST API reference (auth, orders/items
  endpoints, pagination, rate limiting, worked example)
- migration 20260909000000_pretix_sync.sql: events.pretix_organizer +
  pretix_event_slug; _map_ticket_type, _ensure_auth_user (QR token =
  password), sync_pretix_attendees (service-role-only, idempotent)
- sidecar: pretixFetch/fetchPretixOrders/fetchPretixItems/transformPretix,
  runPretixSync + every-minute runPretixLoop, POST /run-pretix, /status
  extended with pretix state
- admin: Pretix panel + recent runs in Interfaces, per-event Pretix config
  + Sync button in Events, api/types for Pretix
- docker-compose: PRETIX_API_KEY / PRETIX_BASE / PRETIX_SYNC_INTERVAL_MS

Verified on VM: 25 paid orders -> 25 attendees, auto-sync every minute,
login via QR token works, idempotent (no duplicate registrations).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 11:40:56 +02:00
d5ec009cb5 Add Playwright E2E suite (46 tests) + app testids + test_cases.md
- e2e/: full Playwright suite covering every spec case (staff auth/UI,
  welcome + session check-in, attendee access/gating, connections,
  profile visibility, speaker material, sponsor, feedback, E2E journeys,
  role security matrix). 46/46 passing.
- apps/convivo: add data-testid attributes (gate, tabs, scanner, toggles)
  to support the E2E suite.
- test_cases.md: spec-case-to-test coverage map (all cases fully covered).
- .gitignore: ignore e2e node_modules/reports/test-results.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-09 10:13:26 +02:00
b08a439949 Check-in gate + fixes, RPC test suite, docs
- Convivo: not-checked-in gate for non-staff (see-a-staff screen with QR
  code + logout); lifts automatically once staff checks them in
- Convivo: fix check-in 'pick a session first' race (synchronous default
  session fallback)
- Add RPC test suite (npm run test:rpc): points idempotency, role guards,
  service-session guard, speaker auto-promote, leaderboard staff exclusion
- Fix db:types script (create packages/shared/src); gitignore generated types
- Docs: README/roadmap drift fixes, tests.md, backend README link

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-09-08 21:05:34 +02:00
264 changed files with 39344 additions and 1230 deletions

No files matched your search

+23
View File
@@ -5,11 +5,20 @@ node_modules/
dist/
build/
*.tsbuildinfo
apps/admin/dist-print/
# Generated types (regenerate with `npm run db:types`)
packages/shared/src/database.types.ts
# Environment (keep the example)
.env
.env.*
!.env.example
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/.temp/
@@ -27,3 +36,17 @@ Thumbs.db
# Browser test artifacts
.playwright-mcp/
# Playwright E2E artifacts
e2e/node_modules/
e2e/reports/
e2e/test-results/
test-results/
# Python bytecode
__pycache__/
*.pyc
.scratch/
# Design-audit capture artifacts (screenshots + measurements)
.design-audit/
+36 -29
View File
@@ -15,8 +15,9 @@
> - **Phase 5** — Convivo App: 24h login, 5s polling, QR type badge, red dot, speaker material.
> - **Phase 6** — Branding: APPE favicon + icons for both apps.
>
> **Next:** cross-cutting work (real event clock, deployment, automated testing).
> See [`roadmap.md`](./roadmap.md).
> **Next:** cross-cutting work (deployment, automated testing, push
> notifications). The real event clock is implemented as a per-event
> `use_realtime_clock` toggle (see §4.7). See [`roadmap.md`](./roadmap.md).
---
@@ -30,22 +31,15 @@ Conferences are full of people who want to meet each other but don't know how to
## 2. Event format
| | |
|---|---|
| **Date** | Wednesday, 23 October |
| **Hours** | 09:00 – 17:00 |
| **Structure** | 6 slots × 45 minutes, **3 parallel sessions per slot** |
| **Breaks** | 09:45–10:00 · coffee 10:45–11:30 · lunch 12:15–13:15 · 14:45–15:00 · closing 15:45–17:00 |
The schedule is **data-driven** (stored in Postgres), so times and sessions can
be changed without an app update. The seed uses the real **Global Power
Platform Bootcamp (Austria)** agenda — 2026-02-20, Vienna — with 10 slots
(7 `session` + 3 `service_session`) and 22 sessions.
| Slot | Time | Slot | Time |
|---|---|---|---|
| 1 | 09:00–09:45 | 4 | 13:15–14:00 |
| 2 | 10:00–10:45 | 5 | 14:00–14:45 |
| 3 | 11:30–12:15 | 6 | 15:00–15:45 |
The schedule is **data-driven** (stored in Postgres), so times and sessions can be changed without an app update.
> **Demo clock:** the app uses a simulated "now" of `2026-10-23 10:20` so Slot 1 is *done* and Slot 2 is *live* — matching the mockup. See `apps/convivo/src/lib/time.ts`.
> **Demo clock:** by default the app uses a simulated "now" of
> `2026-02-20 10:20` so a slot is *live* — matching the mockup. A per-event
> `use_realtime_clock` flag (toggled in the admin Events view) switches the
> app to the real system clock. See `apps/convivo/src/lib/time.ts`.
## 3. Roles
@@ -69,7 +63,7 @@ Check-in tab.
**How it works:** the QR token is stored as the Supabase Auth **password** and the email as the **identifier**. Login is a standard `signInWithPassword({ email, password: qrToken })` — no custom JWT, no separate backend, and **no email is ever sent** (`enable_confirmations = false`).
### 4.2 Agenda & preferences
- The agenda shows all 6 slots and their 3 parallel sessions (title, room, speaker, description).
- The agenda shows every slot and its parallel sessions (title, room, speaker, description).
- Attendees mark **one preferred session per slot** (they can change their pick until the slot starts).
- Home shows "Now / Next" based on the current time and the user's picks.
@@ -93,12 +87,18 @@ Check-in tab.
- Your own row is highlighted.
- **Live:** the leaderboard table is a Realtime source, so it updates in every open app the moment points change.
### 4.7 Real-time clock toggle
- A per-event `use_realtime_clock` flag (default `false`), toggled in the admin Events view.
- When `false`, the app drives slot status (Live/Next/Done) from a **simulated mid-event clock** so the demo always looks live. When `true`, it uses the **real system clock**.
- The Home header shows a "🎬 Demo clock" badge only in simulated mode.
## 5. Points system
| Action | Points |
|---|---|
| Checked into a session (by staff) | **+10** |
| Connection accepted | **+5 each** (both people) |
| Connection accepted **with a shared talk** | **+`talk_networking_bonus` each** (per event, default 2, `0` = off) |
| Feedback — rating only | **+5** |
| Feedback — rating + free text | **+10 total** |
@@ -153,8 +153,8 @@ The model is **multi-event**: people (`contacts`) register for `events` via
| `events` | id, name, start_date, end_date, location, is_active, + aggregates | Partial unique index → at most one active event |
| `registrations` | id, event_id, contact_email, type (attendee/speaker/staff/sponsor), checked_in, points, external_id | Unique (event_id, contact_email); points live here |
| `sponsors` | id, event_id, type, name, email, phone, paid, amount_eur, contact_email | `paid` gates visibility to non-admins |
| `slots` | id, event_id, type (session/lunch_break/coffee_break/keynote/close_up), name, slot_date, start_time, end_time | 6 rows for 23 Oct |
| `sessions` | id, event_id, slot_id, title, description, room, capacity, average_feedback, ai_generated_feedback, material_path, external_id | 18 rows (3 per session slot); `external_id` reserved for an external system |
| `slots` | id, event_id, type (`session`/`service_session` enum), name, slot_date, start_time, end_time | 10 rows in the seed (7 session + 3 service) |
| `sessions` | id, event_id, slot_id, title, description, room, capacity, average_feedback, ai_generated_feedback, material_path, external_id | 22 rows in the seed; `external_id` reserved for an external system |
| `session_speakers` | session_id, contact_email | Join; a session must have ≥1 speaker |
| `preferences` | event_id, contact_email, session_id, slot_id | Unique per (event, contact, slot) — one pick per slot |
| `connections` | event_id, from_email, to_email, status, created_at, resolved_at | Unique per unordered pair (via `least`/`greatest` index) |
@@ -195,9 +195,10 @@ Convivo/
│ └─ src/ # screens, components, lib, context
├─ supabase/
│ ├─ config.toml # Local stack config (ports, auth, RLS defaults)
│ ├─ migrations/ # 20260824000000_redesign.sql + follow-up migrations
│ ├─ migrations/ # 13 migrations (init → real-time clock toggle)
│ └─ seed.sql # 1 real event (Power Platform Bootcamp AT), 10 slots, 22 sessions, 54 contacts
├─ apps/admin/ # APPE Admin console (React + Vite + TS)
├─ apps/sidecar/ # Sessionize sync sidecar (Node, one dep: xlsx)
├─ docker-compose.yml # Runs the app sidecars on the Supabase network
└─ mockup/index.html # Original interactive mockup (design reference)
```
@@ -217,13 +218,19 @@ npm run db:start
# 2. (Re)apply migrations + seed, then restart the stack
npm run db:reset
# 3. Run the apps (Vite dev servers, proxy to the core)
# 3. One-time: provision each app's dev env (git-ignored, never committed)
cp apps/convivo/.env.example apps/convivo/.env
cp apps/admin/.env.example apps/admin/.env
# 4. Run the apps (Vite dev servers, proxy to the core)
npm run app:dev # attendee app on :3000
npm run admin:dev # admin console on :3001
npm run sidecar:dev # Sessionize sync sidecar on :3002
```
Open **http://localhost:3000** (attendee) and **http://localhost:3001** (admin). Studio is at **http://localhost:54323** (user `postgres`, password `postgres`).
> **Blank white page?** You skipped step 3. Without `VITE_SUPABASE_ANON_KEY` the Supabase client throws at load and React renders nothing (the server still answers HTTP 200 — the failure is in the browser console). The `.env` files are git-ignored, so a fresh clone or worktree never has them; the values in `.env.example` are the standard local-stack demo keys and are not secrets. After creating them, restart Vite (env is read only at startup) and hard-refresh the browser (Ctrl+Shift+R).
### Option B — Docker (apps as sidecars)
```bash
# 1. Start the Supabase core (creates the supabase_network_Convivo network)
@@ -297,13 +304,6 @@ Full detail in [`roadmap.md`](./roadmap.md).
- Push notifications (connection requests are seen when the app is opened)
- Multi-day events
- Session capacity enforcement
- i18n / offline mode
## 15. Open questions
1. **Schedule times** — the 6 slot times above are an assumption; confirm against the real agenda.
2. **Connection acceptance** — in-app only for v1? (Push notifications would be a later add-on.)
## 16. Authors & co-authors
@@ -329,3 +329,10 @@ Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
```
- Session capacity enforcement
- i18n / offline mode
## 15. Open questions
1. **Schedule times** — the 6 slot times above are an assumption; confirm against the real agenda.
2. **Connection acceptance** — in-app only for v1? (Push notifications would be a later add-on.)
+6
View File
@@ -25,6 +25,12 @@ server {
try_files $uri $uri/ /index.html;
}
location = /auth/callback {
add_header Cache-Control "no-store";
add_header Referrer-Policy "no-referrer";
try_files /index.html =404;
}
# Long-cache immutable build assets.
location /assets/ {
expires 30d;
+84
View File
@@ -9,11 +9,19 @@
"version": "0.1.0",
"dependencies": {
"@supabase/supabase-js": "^2.45.4",
"canvas-confetti": "1.9.3",
"lucide-react": "0.468.0",
"qrcode.react": "^4.0.1",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"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/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
@@ -694,6 +702,56 @@
"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": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -1297,6 +1355,13 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/canvas-confetti": {
"version": "1.6.4",
"resolved": "https://registry.npmjs.org/@types/canvas-confetti/-/canvas-confetti-1.6.4.tgz",
"integrity": "sha512-fNyZ/Fdw/Y92X0vv7B+BD6ysHL4xVU5dJcgzgxLdGbn8O3PezZNIJpml44lKM0nsGur+o/6+NZbZeNTt00U1uA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -1421,6 +1486,16 @@
],
"license": "CC-BY-4.0"
},
"node_modules/canvas-confetti": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/canvas-confetti/-/canvas-confetti-1.9.3.tgz",
"integrity": "sha512-rFfTURMvmVEX1gyXFgn5QMn81bYk70qa0HLzcIOSVEyl57n6o9ItHeBtUSWdvKAPY0xlvBHno4/v3QPrT83q9g==",
"license": "ISC",
"funding": {
"type": "donate",
"url": "https://www.paypal.me/kirilvatev"
}
},
"node_modules/convert-source-map": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
@@ -1597,6 +1672,15 @@
"yallist": "^3.0.2"
}
},
"node_modules/lucide-react": {
"version": "0.468.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.468.0.tgz",
"integrity": "sha512-6koYRhnM2N0GGZIdXzSeiNwguv1gt/FAjZOiPl76roBi3xKEXa4WmfpxgQwTTL4KipXjefrnf3oV4IsYhi4JFA==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+9
View File
@@ -6,15 +6,24 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"build:print": "vite build --config vite.print.config.ts",
"preview": "vite preview"
},
"dependencies": {
"@supabase/supabase-js": "^2.45.4",
"canvas-confetti": "1.9.3",
"lucide-react": "0.468.0",
"qrcode.react": "^4.0.1",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"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/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
+18
View File
@@ -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>
+33 -2
View File
@@ -7,10 +7,19 @@ import { Contacts } from './views/Contacts';
import { Registrations } from './views/Registrations';
import { Sponsors } from './views/Sponsors';
import { Schedule } from './views/Schedule';
import { Sessions } from './views/Sessions';
import { Activity } from './views/Activity';
import { Raffle } from './views/Raffle';
import { BadgeEditor } from './views/BadgeEditor';
import { Printing } from './views/Printing';
import { Events } from './views/Events';
import { Interfaces } from './views/Interfaces';
import { Reports } from './views/Reports';
import { Settings } from './views/Settings';
import { Settings as SettingsIcon } from 'lucide-react';
import { Spinner } from './components/ui';
import { PrinterStatusPill } from './components/PrinterStatusPill';
import { PrintStatusProvider } from './lib/printStatus';
export type View =
| 'dashboard'
@@ -18,9 +27,15 @@ export type View =
| 'registrations'
| 'sponsors'
| 'schedule'
| 'sessions'
| 'activity'
| 'raffle'
| 'badges'
| 'printing'
| 'events'
| 'interfaces';
| 'interfaces'
| 'reports'
| 'settings';
const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'dashboard', label: 'Dashboard', ico: '📊' },
@@ -28,9 +43,15 @@ const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'registrations', label: 'Registrations', ico: '🎟️' },
{ id: 'sponsors', label: 'Sponsors', ico: '🤝' },
{ id: 'schedule', label: 'Schedule', ico: '🗓️' },
{ id: 'sessions', label: 'Sessions', ico: '🎤' },
{ id: 'activity', label: 'Activity', ico: '⚡' },
{ id: 'raffle', label: 'Raffle', ico: '🎯' },
{ id: 'badges', label: 'Badges', ico: '🎫' },
{ id: 'printing', label: 'Printing', ico: '🖨️' },
{ id: 'events', label: 'Events', ico: '📅' },
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
{ id: 'reports', label: 'Reports', ico: '📤' },
{ id: 'settings', label: 'Settings', ico: '' },
];
function Shell() {
@@ -48,6 +69,7 @@ function Shell() {
if (!contact) return <Login />;
return (
<PrintStatusProvider>
<div className="app">
<aside className="sidebar">
<div className="brand">
@@ -64,11 +86,13 @@ function Shell() {
className={`nav-item ${view === n.id ? 'active' : ''}`}
onClick={() => setView(n.id)}
>
<span className="ico">{n.ico}</span>
<span className="ico">{n.id === 'settings' ? <SettingsIcon size={19} aria-hidden="true" /> : n.ico}</span>
{n.label}
</button>
))}
</nav>
{/* Outside .sidebar-foot so it also shows on mobile (the Pi has no screen). */}
<PrinterStatusPill onNavigate={setView} />
<div className="sidebar-foot">
<div className="admin-card">
<span className="avatar" style={{ width: 36, height: 36, fontSize: 13, background: '#d50000' }}>
@@ -96,11 +120,18 @@ function Shell() {
{view === 'registrations' && <Registrations />}
{view === 'sponsors' && <Sponsors />}
{view === 'schedule' && <Schedule />}
{view === 'sessions' && <Sessions />}
{view === 'activity' && <Activity />}
{view === 'raffle' && <Raffle />}
{view === 'badges' && <BadgeEditor />}
{view === 'printing' && <Printing />}
{view === 'events' && <Events />}
{view === 'interfaces' && <Interfaces />}
{view === 'reports' && <Reports />}
{view === 'settings' && <Settings />}
</main>
</div>
</PrintStatusProvider>
);
}
@@ -0,0 +1,108 @@
import { useEffect, useState } from 'react';
import { setBadgeCopies } from '../lib/api';
/** Number of labels a welcome check-in can print, per the DB check constraint. */
export const BADGE_COPIES_MIN = 1;
export const BADGE_COPIES_MAX = 4;
export function clampBadgeCopies(n: number): number {
return Number.isFinite(n) ? Math.max(BADGE_COPIES_MIN, Math.min(BADGE_COPIES_MAX, Math.round(n))) : BADGE_COPIES_MIN;
}
/**
* Presentational 1..4 picker. Two consumers on purpose:
* - the Events form holds this in its own state, so Cancel still cancels;
* - `BadgeCopiesSetting` wraps it for the Settings view, which saves at once.
*/
export function BadgeCopiesPicker({ value, onChange, disabled = false, labelId }: {
value: number;
onChange: (v: number) => void;
disabled?: boolean;
labelId?: string;
}) {
return (
<div className="seg seg-num" role="group" aria-labelledby={labelId} data-testid="badge-copies">
{[1, 2, 3, 4].map((n) => (
<button
key={n}
type="button"
className={value === n ? 'active' : ''}
aria-pressed={value === n}
disabled={disabled}
onClick={() => onChange(n)}
>
{n}
</button>
))}
</div>
);
}
const HELP = 'How many labels print when an attendee is welcomed in at the front desk';
/**
* Badge copies on welcome check-in (1..4, default 1) for one event.
* `events.badge_copies` drives `welcome_checkin`, which enqueues that many
* labels; a manual reprint from Registrations always prints one.
*
* Saves immediately through `setBadgeCopies` — a scoped single-column update,
* so it can never overwrite another event field the rest of the UI holds stale.
*/
export function BadgeCopiesSetting({ eventId, initialCopies, eventName }: {
eventId: string;
initialCopies: number;
eventName?: string;
}) {
const [copies, setCopies] = useState(clampBadgeCopies(initialCopies));
const [saved, setSaved] = useState<number | null>(clampBadgeCopies(initialCopies));
const [committed, setCommitted] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Follow the event when the caller switches to a different one.
useEffect(() => {
const next = clampBadgeCopies(initialCopies);
setCopies(next);
setSaved(next);
setCommitted(false);
setError(null);
}, [eventId, initialCopies]);
const dirty = copies !== saved;
async function save() {
if (busy || !dirty) return;
setBusy(true);
setError(null);
try {
await setBadgeCopies(eventId, copies);
setSaved(copies);
setCommitted(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Could not save');
} finally {
setBusy(false);
}
}
return (
<div className="field">
<div className="row between" style={{ alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
<div>
<label id="badge-copies-label">Badge copies on welcome check-in</label>
<div className="muted small" style={{ marginTop: 2, maxWidth: 460 }}>
{HELP}{eventName ? <> for <b>{eventName}</b></> : null}. Manual reprints from the
Registrations view always print one.
</div>
</div>
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
<BadgeCopiesPicker value={copies} onChange={setCopies} disabled={busy} labelId="badge-copies-label" />
<button className="btn" type="button" disabled={busy || !dirty} onClick={save} data-testid="badge-copies-save">
{busy ? 'Saving…' : dirty ? 'Save copies' : committed ? 'Copies saved' : 'Save copies'}
</button>
</div>
</div>
{error && <p className="feedback-error" role="alert" style={{ marginTop: 8 }}>{error}</p>}
</div>
);
}
+133
View File
@@ -0,0 +1,133 @@
import { QRCodeSVG } from 'qrcode.react';
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.
export const MM = 3.7795275591;
export const CONTENT_LABEL: Record<BadgeTextElement['content'], string> = {
attendee_name: 'Attendee name',
full_name: 'Full name',
email: 'Email address',
ticket_type: 'Ticket type',
event_name: 'Event name',
company: 'Company / organizer',
qr_token: 'QR / badge token',
static: 'Static text',
};
export const QR_LABEL: Record<BadgeQrElement['value'], string> = {
qr_token: 'QR / badge token',
checkin_url: 'Check-in URL',
email: 'Email address',
attendee_name: 'Attendee name',
static: 'Static value',
};
/** Resolve the bound content of a text element against a sample attendee. */
export function resolveText(el: BadgeTextElement, sample: BadgeSample): string {
let v: string;
switch (el.content) {
case 'attendee_name':
case 'full_name': v = sample.full_name; break;
case 'email': v = sample.email; break;
case 'ticket_type': v = sample.ticket_type; break;
case 'event_name': v = sample.event_name; break;
case 'company': v = sample.company; break;
case 'qr_token': v = sample.qr_token; break;
default: v = el.text;
}
if (el.transform === 'uppercase') return v.toUpperCase();
if (el.transform === 'lowercase') return v.toLowerCase();
if (el.transform === 'capitalize') return v.replace(/\b\w/g, (m) => m.toUpperCase());
return v;
}
/** Resolve the encoded value of a QR element against a sample attendee. */
export function resolveQr(el: BadgeQrElement, sample: BadgeSample): string {
switch (el.value) {
case 'qr_token': return sample.qr_token || 'CONVIVO-QR';
case 'checkin_url': return `${sample.checkin_origin ?? window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`;
case 'email': return sample.email || '[email protected]';
case 'attendee_name': return sample.full_name || 'Attendee';
default: return el.static_value || 'https://example.com';
}
}
/** The visual body of one badge element (text / QR / image), no editing chrome. */
export function BadgeElementBody({ el, sample, pxPerMm }: { el: BadgeElement; sample: BadgeSample; pxPerMm: number }) {
if (el.type === 'text') {
const text = resolveText(el, sample);
return (
<div
className="badge-text-body"
style={{
fontFamily: `"${el.font}", sans-serif`,
fontSize: el.font_size * (pxPerMm / MM), // pt→mm→px so print scale matches
lineHeight: el.line_height,
color: el.color,
fontWeight: el.bold ? 700 : 400,
fontStyle: el.italic ? 'italic' : 'normal',
justifyContent: el.align_h === 'left' ? 'flex-start' : el.align_h === 'right' ? 'flex-end' : 'center',
alignItems: el.align_v === 'top' ? 'flex-start' : el.align_v === 'bottom' ? 'flex-end' : 'center',
textAlign: el.align_h,
}}
>
<span>{text || <span className="badge-el-placeholder">{CONTENT_LABEL[el.content]}</span>}</span>
</div>
);
}
if (el.type === 'qr') {
const size = Math.round(Math.min(el.width, el.height) * pxPerMm);
return (
<div className="badge-qr-body">
<QRCodeSVG value={resolveQr(el, sample)} size={Math.max(16, size)} level="M" marginSize={0} />
</div>
);
}
// image
if (!el.src) {
return <div className="badge-image-body badge-image-empty">Image</div>;
}
return <img className="badge-image-body" src={el.src} alt="" style={{ objectFit: el.fit }} />;
}
export interface BadgePageData {
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
}
/**
* Read-only rendering of a badge layout for a specific attendee — the exact
* same markup the editor canvas produces, minus the editing chrome.
*/
export function BadgePagePreview({ layout, sample, pxPerMm, className = '' }: {
layout: BadgePageData; sample: BadgeSample; pxPerMm: number; className?: string;
}) {
return (
<div
className={`badge-page badge-page-static ${className}`}
style={{ width: layout.page_width_mm * pxPerMm, height: layout.page_height_mm * pxPerMm }}
>
{layout.elements.map((el) => (
<div
key={el.id}
className={`badge-el badge-el-${el.type}`}
style={{
left: el.x * pxPerMm, top: el.y * pxPerMm,
width: el.width * pxPerMm, height: el.height * pxPerMm,
transform: `rotate(${el.rotation}deg)`,
cursor: 'default',
}}
>
<BadgeElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
</div>
))}
</div>
);
}
/** Fit a layout inside a box of `maxW` × `maxH` px, returning the px-per-mm scale. */
export function fitScale(layout: BadgePageData, maxW: number, maxH: number): number {
return Math.min(maxW / layout.page_width_mm, maxH / layout.page_height_mm);
}
@@ -0,0 +1,48 @@
import { useRef, useState } from 'react';
import { Sparkles } from 'lucide-react';
import { generateFeedbackSummary } from '../lib/api';
import type { FeedbackSummary } from '../lib/types';
export function FeedbackSummaryPanel({ eventId, sessionId, title, count, configured, summary, onGenerated }: {
eventId: string;
sessionId?: string;
title: string;
count: number;
configured: boolean;
summary?: FeedbackSummary;
onGenerated: (summary: FeedbackSummary) => void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const running = useRef(false);
async function generate() {
if (running.current) return;
running.current = true;
setBusy(true);
setError(null);
try { onGenerated(await generateFeedbackSummary(eventId, sessionId)); }
catch (cause) { setError(cause instanceof Error ? cause.message : 'Summary generation failed'); }
finally { running.current = false; setBusy(false); }
}
return (
<section className="feedback-summary" aria-label={`AI summary: ${title}`} aria-busy={busy}>
<div className="feedback-summary-head">
<div><h2 className="h2">{title}</h2><span className="muted small">{count} responses</span></div>
<button className="btn small" disabled={busy || count === 0 || !configured} onClick={generate}
title={!configured ? 'LLM endpoint not configured' : count === 0 ? 'No feedback available' : undefined}>
<Sparkles size={16} aria-hidden="true" />{busy ? 'Generating...' : 'Generate AI Summary'}
</button>
</div>
{!configured && <p className="muted small">LLM endpoint not configured</p>}
{error && <p className="feedback-error" role="alert">{error}</p>}
{busy && <p className="muted small" role="status">Generating summary...</p>}
{summary && <>
<div className="feedback-summary-text">{summary.summary}</div>
<p className="muted small">AI-generated · {summary.response_count} responses · {summary.model} · {new Date(summary.generated_at).toLocaleString()}</p>
{summary.response_count !== count && <p className="muted small">Response count has changed since this summary.</p>}
</>}
</section>
);
}
+145
View File
@@ -0,0 +1,145 @@
import { useState } from 'react';
import {
downloadSessionMaterial,
openSessionMaterial,
removeSessionMaterial,
sessionMaterialName,
uploadSessionMaterial,
} from '../lib/api';
/**
* See / open / download / delete a session's material file. Admins bypass the
* attendee time-lock in storage RLS (`can_read_session_material` /
* `can_write_session_material` allow `is_admin()`), so every action works at
* any time — the `unlocksAt` hint is only about when *attendees* get access.
* Shared by the Schedule session modal and the Sessions view's expanded row.
*/
export function MaterialPanel(props: {
session: { id: string; material_path: string | null };
/** Human-readable unlock moment, e.g. "Thu, Oct 22, 16:30" — null falls back to a generic hint. */
unlocksAt?: string | null;
/** Notified after a successful delete (reload / close). */
onChanged: () => void;
}) {
const [busy, setBusy] = useState<'open' | 'download' | 'delete' | null>(null);
const [error, setError] = useState<string | null>(null);
const path = props.session.material_path;
if (!path) return <p className="muted small">No material uploaded yet.</p>;
const name = sessionMaterialName(path);
async function run(action: 'open' | 'download' | 'delete', fn: () => Promise<void>) {
setBusy(action);
setError(null);
try {
await fn();
} catch (cause) {
setError(cause instanceof Error ? cause.message : 'Material action failed');
} finally {
setBusy(null);
}
}
return (
<div className="material-panel" data-testid={`material-panel-${props.session.id}`}>
<div className="material-file" title={path}>
📎 {name}
</div>
<div className="material-actions">
<button
className="btn small"
onClick={() => void run('open', () => openSessionMaterial(path))}
disabled={busy !== null}
>
{busy === 'open' ? 'Opening…' : 'Open'}
</button>
<button
className="btn small"
onClick={() => void run('download', () => downloadSessionMaterial(path))}
disabled={busy !== null}
>
{busy === 'download' ? 'Downloading…' : '⬇ Download'}
</button>
<button
className="btn small danger"
onClick={() => {
if (!window.confirm(`Delete "${name}"? Attendees and the speaker will no longer be able to download it.`)) return;
void run('delete', async () => {
await removeSessionMaterial(props.session.id);
props.onChanged();
});
}}
disabled={busy !== null}
>
{busy === 'delete' ? 'Deleting…' : 'Delete'}
</button>
</div>
<p className="muted small">
{props.unlocksAt
? `Attendees can download it once the session ends (${props.unlocksAt}).`
: 'Attendees can download it once the session ends.'}
</p>
{error && (
<p className="feedback-error" role="alert">
{error}
</p>
)}
</div>
);
}
/**
* Immediate (not on-save) upload/replace of a session material — uploads the
* picked file and points the session at it in one go, removing the previous
* object. Used in the Sessions view's expanded row; the Schedule modal keeps
* its upload-on-save behavior instead.
*/
export function MaterialUploadRow(props: {
session: { id: string; material_path: string | null };
onUploaded: (path: string) => void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [uploadedName, setUploadedName] = useState<string | null>(null);
const previousPath = props.session.material_path;
async function upload(file: File) {
setBusy(true);
setError(null);
setUploadedName(null);
try {
const path = await uploadSessionMaterial(props.session.id, file, previousPath);
setUploadedName(file.name);
props.onUploaded(path);
} catch (cause) {
setError(cause instanceof Error ? cause.message : 'Upload failed');
} finally {
setBusy(false);
}
}
return (
<div className="material-upload">
<label className="btn small" style={{ cursor: 'pointer' }}>
<input
type="file"
style={{ display: 'none' }}
disabled={busy}
onChange={(e) => {
const file = e.target.files?.[0];
e.target.value = '';
if (file) void upload(file);
}}
/>
{busy ? 'Uploading…' : previousPath ? 'Replace file…' : 'Upload file…'}
</label>
{uploadedName && !busy && <span className="muted small">Uploaded “{uploadedName}”</span>}
{error && (
<span className="feedback-error small" role="alert">
{error}
</span>
)}
</div>
);
}
@@ -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>
);
}
+586
View File
@@ -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;
}
+194 -2
View File
@@ -1,4 +1,6 @@
import { type ReactNode } from 'react';
import { cloneElement, isValidElement, useEffect, useRef, useState, useId, type ReactElement, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { Filter } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777'];
@@ -91,14 +93,16 @@ export function Toggle({
checked,
onChange,
label,
disabled = false,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label?: string;
disabled?: boolean;
}) {
return (
<label className="toggle" title={label}>
<input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
<input type="checkbox" checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
<span className="track">
<span className="knob" />
</span>
@@ -106,3 +110,191 @@ export function Toggle({
</label>
);
}
/**
* Hover/focus tooltip rendered through a portal, so it is never clipped by
* scrollable or `overflow: hidden` ancestors (e.g. data tables). The card
* visual follows the Uiverse dark-glass tooltip already used in Interfaces,
* re-themed to the APPE red accent. Wrap any element — including a disabled
* button, whose own mouse events browsers suppress.
*/
export function Tooltip({ content, title, children }: {
content: ReactNode;
title?: string;
children: ReactNode;
}) {
const anchor = useRef<HTMLSpanElement>(null);
const cardRef = useRef<HTMLDivElement>(null);
const id = useId();
// left/top are the card's real viewport coordinates (the card carries no CSS
// transform), so the clamping below and the rendered position cannot disagree.
const [pos, setPos] = useState<{ left: number; top: number; arrow: number; below: boolean } | null>(null);
const hide = () => setPos(null);
/**
* Compute the card's viewport position so it stays entirely on screen.
*
* It is portal-rendered so no table's `overflow` can clip it, but nothing used
* to keep it inside the *screen*: centred on its trigger, the tooltip on a
* right-aligned button (Sessions' "Generate AI Feedback Summary") ran past the
* right edge and lost half its text. A trigger near the top also has nowhere to
* put the card, so it flips below.
*
* `below` is derived from the card's height rather than passed in, so the
* caller does not have to guess it — which matters because the height is only
* knowable once the card is in the DOM.
*/
const compute = (
w: number, h: number,
trigger: { x: number; top: number; bottom: number },
) => {
const gap = 10;
// Keep this in sync with the `inset` in @keyframes tip-in: the card starts
// 6px lower and slides up, so reserving 6px more keeps a flipped card from
// briefly overlapping the control it describes.
const slide = 6;
const vw = window.innerWidth;
const edge = Math.min(8, Math.max(0, (vw - w) / 2));
let left = trigger.x - w / 2;
if (left + w > vw - edge) left = vw - edge - w;
if (left < edge) left = edge;
// Flip below when there is not enough room above, including the arrow gap.
const below = trigger.top - h - gap - slide < edge;
const top = below ? trigger.bottom + gap : trigger.top - h - gap;
// The arrow tracks the trigger even after the card slides sideways, but
// stays inside the card so the two never look disconnected.
const arrow = Math.max(18, Math.min(trigger.x - left, w - 18));
return { left, top, arrow, below };
};
const show = () => {
const r = anchor.current?.getBoundingClientRect();
if (!r) return;
const trigger = { x: r.left + r.width / 2, top: r.top, bottom: r.bottom };
// The card is unmounted between hovers, so its size is unknown until it is
// in the DOM. Mount it at a provisional spot, then measure and correct: two
// passes total, no recursion, nothing that can loop.
setPos(compute(cardRef.current?.offsetWidth || 250, cardRef.current?.offsetHeight || 96, trigger));
requestAnimationFrame(() => {
const card = cardRef.current;
if (card) setPos(compute(card.offsetWidth, card.offsetHeight, trigger));
});
};
// Point the control at the card so screen readers announce the explanation
// when it is focused (focus also reveals it visually).
const child = isValidElement(children)
? cloneElement(children as ReactElement<{ 'aria-describedby'?: string }>, { 'aria-describedby': id })
: children;
return (
<span className="tip-anchor" ref={anchor} onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}>
{child}
{pos && createPortal(
<div
className={`tip-card${pos.below ? ' tip-below' : ''}`} role="tooltip" id={id} ref={cardRef}
style={{ left: pos.left, top: pos.top, ['--tip-arrow' as string]: `${pos.arrow}px` }}
>
{title && (
<div className="tip-head">
<span className="tip-ico" aria-hidden="true">
<svg viewBox="0 0 20 20" fill="currentColor" width="15" height="15">
<path clipRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" fillRule="evenodd" />
</svg>
</span>
<strong>{title}</strong>
</div>
)}
<p>{content}</p>
<span className="tip-arrow" style={{ left: pos.arrow }} aria-hidden="true" />
</div>,
document.body,
)}
</span>
);
}
/** One selectable value inside a `ColumnFilter`, with a live result count. */
export interface ColumnFilterOption {
value: string;
label: string;
count: number;
}
/**
* Excel-style multi-select filter for a table column. Rendered through a portal
* so the dropdown is never clipped by the table's `overflow: hidden`. An empty
* selection means "no filter" (everything matches).
*/
export function ColumnFilter({ label, options, selected, onChange }: {
label: string;
options: ColumnFilterOption[];
selected: string[];
onChange: (next: string[]) => void;
}) {
const btnRef = useRef<HTMLButtonElement>(null);
const popRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
const active = selected.length > 0;
const toggleOpen = () => {
if (!open) {
const r = btnRef.current?.getBoundingClientRect();
if (r) setPos({ left: Math.min(Math.max(8, r.left), window.innerWidth - 240), top: r.bottom + 6 });
}
setOpen((o) => !o);
};
const toggleValue = (value: string) =>
onChange(selected.includes(value) ? selected.filter((v) => v !== value) : [...selected, value]);
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => {
const t = e.target as Node;
if (popRef.current?.contains(t) || btnRef.current?.contains(t)) return;
setOpen(false);
};
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
const onScroll = () => setOpen(false);
window.addEventListener('mousedown', onDown);
window.addEventListener('keydown', onKey);
window.addEventListener('scroll', onScroll, true);
return () => {
window.removeEventListener('mousedown', onDown);
window.removeEventListener('keydown', onKey);
window.removeEventListener('scroll', onScroll, true);
};
}, [open]);
return (
<span className="colfilter">
<button
ref={btnRef}
type="button"
className={`colfilter-btn ${active ? 'on' : ''}`}
onClick={toggleOpen}
aria-label={`Filter ${label}`}
aria-expanded={open}
title={`Filter ${label}`}
>
<Filter size={13} aria-hidden="true" />
{active && <span className="colfilter-count">{selected.length}</span>}
</button>
{open && pos && createPortal(
<div className="colfilter-pop" ref={popRef} role="group" aria-label={`Filter ${label}`} style={{ left: pos.left, top: pos.top }}>
<div className="colfilter-head">
<strong>{label}</strong>
{active && <button type="button" className="colfilter-clear" onClick={() => onChange([])}>Clear</button>}
</div>
{options.map((o) => (
<label key={o.value} className="colfilter-opt">
<input type="checkbox" checked={selected.includes(o.value)} onChange={() => toggleValue(o.value)} />
<span className="lbl">{o.label}</span>
<span className="cnt">{o.count}</span>
</label>
))}
</div>,
document.body,
)}
</span>
);
}
+69 -23
View File
@@ -5,13 +5,18 @@ import type { Contact } from '../lib/types';
interface AuthState {
contact: Contact | null;
loading: boolean;
/** Sign in with the admin's email + password (event-independent). */
signIn: (email: string, password: string) => Promise<void>;
authError: string | null;
signOut: () => Promise<void>;
}
const AuthContext = createContext<AuthState | null>(null);
// A contact is an admin if their `is_admin` flag is set OR their email is on
// the @appe.at domain (mirrors the DB `is_admin()` rule).
function isAdminContact(c: Contact | null): boolean {
return !!c && (c.is_admin || c.email.endsWith('@appe.at'));
}
// Load the current user's contact row. Returns null if it doesn't exist or the
// contact is not an admin (this is an admin-only app).
async function loadAdminContact(email: string): Promise<Contact | null> {
@@ -21,27 +26,74 @@ async function loadAdminContact(email: string): Promise<Contact | null> {
.eq('email', email)
.maybeSingle();
const c = data as Contact | null;
return c && c.is_admin ? c : null;
return isAdminContact(c) ? c : null;
}
const callbackUrl = window.location.pathname === '/auth/callback' ? new URL(window.location.href) : null;
if (callbackUrl) window.history.replaceState(null, '', '/');
let callbackPending = !!callbackUrl;
let callbackResult: Promise<{ contact: Contact | null; error: string | null }> | null = null;
function consumeCallback() {
if (!callbackResult) callbackResult = (async () => {
const invalidLink = 'This sign-in link is invalid or expired. Please request a new link.';
try {
const hash = new URLSearchParams(callbackUrl!.hash.slice(1));
const query = callbackUrl!.searchParams;
if (hash.has('error') || hash.has('error_code') || query.has('error') || query.has('error_code')) {
throw new Error(invalidLink);
}
const accessToken = hash.get('access_token');
const refreshToken = hash.get('refresh_token');
const code = query.get('code');
const result = accessToken && refreshToken
? await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken })
: code ? await supabase.auth.exchangeCodeForSession(code) : null;
if (!result || result.error || !result.data.session?.user.email) throw new Error(invalidLink);
const admin = await loadAdminContact(result.data.session.user.email);
if (!admin) throw new Error('This account is not an admin.');
return { contact: admin, error: null };
} catch (error) {
await supabase.auth.signOut({ scope: 'local' });
return { contact: null, error: error instanceof Error && error.message === 'This account is not an admin.' ? error.message : invalidLink };
} finally {
callbackPending = false;
}
})();
return callbackResult;
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [contact, setContact] = useState<Contact | null>(null);
const [loading, setLoading] = useState(true);
const [authError, setAuthError] = useState<string | null>(null);
// On mount: restore any existing session and load the contact. If the
// session belongs to a non-admin, sign out immediately (admin-only app).
useEffect(() => {
let cancelled = false;
let revision = 0;
async function init() {
if (callbackUrl) {
const result = await consumeCallback();
if (!cancelled) {
setContact(result.contact);
setAuthError(result.error);
setLoading(false);
}
return;
}
const currentRevision = revision;
const { data } = await supabase.auth.getSession();
if (cancelled || currentRevision !== revision) return;
const session = data.session;
if (!session) {
if (!cancelled) setLoading(false);
return;
}
const c = session.user.email ? await loadAdminContact(session.user.email) : null;
if (cancelled) return;
if (cancelled || currentRevision !== revision) return;
if (c) {
setContact(c);
} else {
@@ -53,18 +105,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
init();
const { data: sub } = supabase.auth.onAuthStateChange(async (_event, session) => {
const { data: sub } = supabase.auth.onAuthStateChange((event, session) => {
if (cancelled || callbackPending || event === 'INITIAL_SESSION') return;
const currentRevision = ++revision;
if (!session) {
setContact(null);
setLoading(false);
return;
}
window.setTimeout(() => {
void (async () => {
if (cancelled || currentRevision !== revision) return;
const c = session.user.email ? await loadAdminContact(session.user.email) : null;
if (cancelled || currentRevision !== revision) return;
if (c) {
setContact(c);
} else {
await supabase.auth.signOut();
setContact(null);
await supabase.auth.signOut();
}
if (!cancelled) setLoading(false);
})();
}, 0);
});
return () => {
@@ -73,29 +135,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
};
}, []);
async function signIn(email: string, password: string) {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) throw new Error(error.message);
const c = data.user.email ? await loadAdminContact(data.user.email) : null;
if (!c) {
// Signed in, but not an admin — reject and sign out.
await supabase.auth.signOut();
throw new Error('This account is not an admin.');
}
setContact(c);
}
async function signOut() {
await supabase.auth.signOut();
setContact(null);
}
return (
<AuthContext.Provider value={{ contact, loading, signIn, signOut }}>
<AuthContext.Provider value={{ contact, loading, authError, signOut }}>
{children}
</AuthContext.Provider>
);
+377 -14
View File
@@ -1,13 +1,25 @@
import { supabase } from './supabase';
import type {
BadgeElement,
BadgeLayout,
Checkin,
Connection,
Contact,
DeleteEventScheduleResult,
Event,
EventFeedback,
ExcelSyncResult,
Feedback,
FeedbackSummary,
LlmSettings,
LlmTestResult,
LeaderboardRow,
PointsLogRow,
PretixOptions,
PretixSyncResult,
PrintOverview,
RafflePoolEntry,
RaffleWinner,
Registration,
ResetQrResult,
Session,
@@ -21,6 +33,9 @@ import type {
export class ApiError extends Error {}
/** The default admin password for @appe.at contacts (set by the DB trigger). */
export const DEFAULT_ADMIN_PASSWORD = 'appe-admin-2026';
async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
const { data, error } = await supabase.rpc(fn, args);
if (error) throw new ApiError(error.message);
@@ -35,6 +50,25 @@ async function all<T>(table: string, order?: { col: string; asc?: boolean }): Pr
return data as T[];
}
/**
* Paged read of one event's rows. PostgREST is configured with
* `max_rows = 1000` (supabase/config.toml) and `all()` above has no paging, so a
* single unsorted select silently truncates at 1000 — fine for contacts at this
* event's size, not fine for check-ins once every attendee has scanned a few
* sessions. `id` is the tiebreaker so rows cannot shift between pages.
*/
async function pagedForEvent<T>(table: string, eventId: string, order: { col: string; asc?: boolean }): Promise<T[]> {
const rows: T[] = [];
for (let offset = 0; ; offset += 500) {
let q = supabase.from(table).select('*').eq('event_id', eventId);
q = q.order(order.col, { ascending: order.asc ?? true }).order('id', { ascending: true });
const { data, error } = await q.range(offset, offset + 499);
if (error) throw new ApiError(error.message);
rows.push(...(data as T[]));
if (data.length < 500) return rows;
}
}
// ---- Reads (admin can read all rows via RLS) --------------------------------
export const getAllContacts = () => all<Contact>('contacts', { col: 'full_name' });
@@ -59,6 +93,48 @@ export const getAllSessionSpeakers = () => all<SessionSpeaker>('session_speakers
export const getAllConnections = () => all<Connection>('connections', { col: 'created_at', asc: false });
export const getAllCheckins = () => all<Checkin>('checkins', { col: 'created_at', asc: false });
export const getAllFeedback = () => all<Feedback>('feedback', { col: 'created_at', asc: false });
/** Check-ins for one event, paged past the 1000-row PostgREST cap. */
export const getEventCheckins = (eventId: string) =>
pagedForEvent<Checkin>('checkins', eventId, { col: 'created_at', asc: false });
/** Session feedback for one event, paged past the 1000-row cap. */
export const getEventFeedbackRows = (eventId: string) =>
pagedForEvent<Feedback>('feedback', eventId, { col: 'created_at', asc: false });
/**
* Speaker links for one event. `session_speakers` has no event_id column, so
* this filters through the session FK with an inner join — a plain `all()`
* would return every event's links and truncate at 1000 rows.
*/
export async function getEventSessionSpeakers(eventId: string): Promise<SessionSpeaker[]> {
const rows: SessionSpeaker[] = [];
for (let offset = 0; ; offset += 500) {
const { data, error } = await supabase
.from('session_speakers')
.select('session_id, contact_email, sessions!inner(event_id)')
.eq('sessions.event_id', eventId)
.order('session_id', { ascending: true })
.order('contact_email', { ascending: true })
.range(offset, offset + 499);
if (error) throw new ApiError(error.message);
for (const r of data as (SessionSpeaker & { sessions?: unknown })[]) {
delete r.sessions;
rows.push(r);
}
if (data.length < 500) return rows;
}
}
export const getAllEventFeedback = () => all<EventFeedback>('event_feedback', { col: 'created_at', asc: false });
async function eventFeedbackRows<T>(table: 'feedback' | 'event_feedback', eventId: string): Promise<T[]> {
const rows: T[] = [];
for (let offset = 0; ; offset += 500) {
const { data, error } = await supabase.from(table).select('*').eq('event_id', eventId)
.order('created_at', { ascending: false }).order('id', { ascending: false }).range(offset, offset + 499);
if (error) throw new ApiError(error.message);
rows.push(...data as T[]);
if (data.length < 500) return rows;
}
}
export const getEventSessionFeedback = (eventId: string) => eventFeedbackRows<Feedback>('feedback', eventId);
export const getEventFeedback = (eventId: string) => eventFeedbackRows<EventFeedback>('event_feedback', eventId);
export const getAllPointsLog = () => all<PointsLogRow>('points_log', { col: 'created_at', asc: false });
export const getLeaderboard = () => all<LeaderboardRow>('leaderboard', { col: 'points', asc: false });
@@ -88,6 +164,42 @@ export async function updateContact(
if (error) throw new ApiError(error.message);
}
/** Delete a single contact (admin-only RLS). Cascades to their registrations. */
export async function deleteContact(email: string): Promise<void> {
const { error } = await supabase.from('contacts').delete().eq('email', email);
if (error) throw new ApiError(error.message);
}
/**
* Delete many contacts at once (admin-only). Uses the `bulk_delete_contacts`
* RPC, which bypasses the "a session must have at least one speaker" guard —
* a direct PostgREST delete would fail (P0001) if the batch includes a contact
* who is the sole speaker of a session.
*/
export async function deleteContacts(emails: string[]): Promise<void> {
if (emails.length === 0) return;
await rpc<number>('bulk_delete_contacts', { p_emails: emails });
}
/**
* Change the current admin's own login password. Sets `contacts.password`
* (the `trg_contact_password_sync` trigger re-hashes it into
* `auth.users.encrypted_password`), then re-authenticates with the new
* password so the session reflects the change.
*/
export async function changeMyPassword(email: string, newPassword: string): Promise<void> {
const { error: updateError } = await supabase
.from('contacts')
.update({ password: newPassword })
.eq('email', email);
if (updateError) throw new ApiError(updateError.message);
const { error: signInError } = await supabase.auth.signInWithPassword({
email,
password: newPassword,
});
if (signInError) throw new ApiError(signInError.message);
}
/**
* Regenerate the QR token of a contact's registration for the active event
* (syncs the auth password, forces re-login). The token lives on the
@@ -108,11 +220,29 @@ export async function setRegistrationType(contactEmail: string, type: Registrati
await rpc('set_registration_type', { p_contact_email: contactEmail, p_type: type });
}
export async function setCheckedIn(registrationId: string, checkedIn: boolean): Promise<void> {
const { error } = await supabase.from('registrations').update({ checked_in: checkedIn }).eq('id', registrationId);
if (error) throw new ApiError(error.message);
/**
* Flip an attendee's event check-in state. Turning it OFF removes every point
* this person earned from check-ins in the event; turning it back ON restores the
* points their surviving session check-ins justify (see
* set_registration_checked_in). Only one of the two is ever non-zero.
*/
export async function setCheckedIn(
registrationId: string,
checkedIn: boolean,
): Promise<{ removed: number; added: number }> {
const rows = await rpc<{
registration_id: string;
checked_in: boolean;
points_removed: number;
points_added?: number;
}[]>('set_registration_checked_in', { p_registration_id: registrationId, p_checked_in: checkedIn });
if (!rows?.length) throw new ApiError('Registration no longer exists');
return { removed: rows[0].points_removed ?? 0, added: rows[0].points_added ?? 0 };
}
export const mergeTickets = (sourceId: string, targetId: string) =>
rpc<import('./types').TicketMergeResult>('merge_tickets', { p_source_id: sourceId, p_target_id: targetId });
// ---- Sponsors ----------------------------------------------------------------
export async function upsertSponsor(
@@ -151,8 +281,14 @@ export async function upsertEvent(
start_date: string;
end_date: string;
location?: string | null;
company?: string | null;
sessionize_endpoint?: string | null;
pretix_organizer?: string | null;
pretix_event_slug?: string | null;
pretix_api_key?: string | null;
use_realtime_clock?: boolean;
talk_networking_bonus?: number;
badge_copies?: number;
},
): Promise<void> {
if (id) {
@@ -164,6 +300,18 @@ export async function upsertEvent(
}
}
/**
* Set how many badge labels a welcome (front-desk) check-in prints for one
* event. Scoped update on purpose: it touches only this column, so it can never
* overwrite another field the Events form happens to hold stale values for.
* Clamped to 1..4 in the database (events.badge_copies check constraint).
*/
export async function setBadgeCopies(eventId: string, copies: number): Promise<void> {
const value = Math.max(1, Math.min(4, Math.round(copies) || 1));
const { error } = await supabase.from('events').update({ badge_copies: value }).eq('id', eventId);
if (error) throw new ApiError(error.message);
}
// ---- Sessionize sync (sidecar) ---------------------------------------------
// The sidecar is a separate Docker service (not Supabase), so these use raw
// fetch against the same-origin /sidecar proxy (see nginx.conf.template).
@@ -189,6 +337,18 @@ export const getSidecarStatus = () => sidecarFetch<SidecarStatus>('/status');
export const runSessionizeSync = (eventId: string) =>
sidecarFetch<SyncResult>('/run', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
/** Trigger a (blocking) Pretix sync for an event. Resolves with the result. */
export const runPretixSync = (eventId: string) =>
sidecarFetch<PretixSyncResult>('/run-pretix', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
/**
* Ask the sidecar to list the given Pretix API key's organizers + their active
* events. Used by the event-settings "paste the API key" flow to populate the
* organizer + event-slug dropdowns from real data.
*/
export const fetchPretixOptions = (apiKey: string) =>
sidecarFetch<PretixOptions>('/pretix-options', { method: 'POST', body: JSON.stringify({ api_key: apiKey }) });
/**
* Upload the Sessionize "Sessions and speakers (advanced)" .xlsx for an event.
* The sidecar parses it and imports speakers/sessions/agenda + speaker
@@ -210,12 +370,44 @@ export async function importSessionizeExcel(eventId: string, file: File): Promis
});
}
/**
* Request an event report from the sidecar (`POST /export`). Returns the
* filename, mime type, and base64 content; the caller decodes and downloads.
*/
export const exportEventReport = (
eventId: string,
format: 'csv' | 'xlsx' | 'pdf',
tables?: string[],
) =>
sidecarFetch<{ filename: string; mime: string; content_base64: string }>('/export', {
method: 'POST',
body: JSON.stringify({ event_id: eventId, format, tables }),
});
/** Decode a base64 report body and trigger a browser download. */
export function downloadReport(res: { filename: string; mime: string; content_base64: string }): void {
const bytes = Uint8Array.from(atob(res.content_base64), (c) => c.charCodeAt(0));
const blob = new Blob([bytes], { type: res.mime });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = res.filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/** Recent sync_runs rows for an event (newest first). */
export const getSyncRuns = (eventId: string) =>
all<SyncRun>('sync_runs', { col: 'started_at', asc: false }).then((rows) =>
rows.filter((r) => r.event_id === eventId),
);
/** Recent Pretix sync_runs rows for an event (newest first). */
export const getPretixRuns = (eventId: string) =>
getSyncRuns(eventId).then((rows) => rows.filter((r) => r.source === 'pretix'));
/** Set an event active (deactivates all others via trigger). */
export async function activateEvent(id: string): Promise<void> {
const { error } = await supabase.from('events').update({ is_active: true }).eq('id', id);
@@ -228,6 +420,10 @@ export async function deactivateEvent(id: string): Promise<void> {
if (error) throw new ApiError(error.message);
}
export async function deleteEventSchedule(eventId: string): Promise<DeleteEventScheduleResult> {
return await rpc<DeleteEventScheduleResult>('delete_event_schedule', { p_event_id: eventId });
}
// ---- Points ------------------------------------------------------------------
/** Admin manual points adjustment for the active event (audited as 'admin'). */
@@ -235,6 +431,70 @@ export async function adjustPoints(contactEmail: string, delta: number, reason:
await rpc('adjust_points', { p_contact_email: contactEmail, p_delta: delta, p_reason: reason });
}
// ---- Raffle ------------------------------------------------------------------
/** Eligible attendees for the active event: excludes staff/Admin, the
* leaderboard top 3, and everyone already drawn in the current run. */
export async function getRafflePool(): Promise<RafflePoolEntry[]> {
return rpc<RafflePoolEntry[]>('get_raffle_pool', {});
}
/** Winners already drawn in the current run (oldest first). */
export async function getRaffleWinners(): Promise<RaffleWinner[]> {
return all<RaffleWinner>('raffle_draws', { col: 'draw_number' });
}
/** Draw one random eligible attendee and record them as the next winner. */
export async function drawRaffleWinner(): Promise<RaffleWinner> {
const rows = await rpc<Omit<RaffleWinner, 'drawn_at'>[]>('draw_raffle_winner', {});
if (!rows[0]) throw new ApiError('No eligible attendees left to draw');
return { ...rows[0], drawn_at: new Date().toISOString() };
}
/** Clear the current run's winners so a new run can begin. */
export async function resetRaffle(): Promise<void> {
await rpc('reset_raffle', {});
}
// ---- Badge editor (per-event WYSIWYG badge layout) --------------------------
/** All badge layouts for an event (default first, then by name). */
export async function getBadgeLayouts(eventId: string): Promise<BadgeLayout[]> {
const rows = await all<BadgeLayout>('badge_layouts');
return rows
.filter((r) => r.event_id === eventId)
.sort((a, b) => Number(b.is_default) - Number(a.is_default) || a.name.localeCompare(b.name));
}
/** Insert or update a layout (matched on event_id + name). */
export async function saveBadgeLayout(input: {
event_id: string;
name: string;
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
is_default: boolean;
}): Promise<BadgeLayout> {
return rpc<BadgeLayout>('save_badge_layout', {
p_event_id: input.event_id,
p_name: input.name,
p_page_width_mm: input.page_width_mm,
p_page_height_mm: input.page_height_mm,
p_elements: input.elements,
p_is_default: input.is_default,
});
}
/** Promote a layout to the event's default (demoting the previous one). */
export async function setDefaultBadgeLayout(id: string): Promise<void> {
await rpc('set_default_badge_layout', { p_id: id });
}
/** Delete a layout (the sole default may not be removed). */
export async function deleteBadgeLayout(id: string): Promise<void> {
await rpc('delete_badge_layout', { p_id: id });
}
// ---- Sessions: speakers, material, AI feedback -------------------------------
export async function setSessionSpeakers(sessionId: string, emails: string[]): Promise<void> {
@@ -258,13 +518,34 @@ export async function setSessionSpeakers(sessionId: string, emails: string[]): P
}
}
/** Upload a session material file to the `materials` bucket and store the path. */
export async function uploadSessionMaterial(sessionId: string, file: File): Promise<string> {
/** Human filename of a material object path (`sessions/<id>/<ts>-<name>`). */
export function sessionMaterialName(path: string): string {
const base = path.slice(path.lastIndexOf('/') + 1);
return base.replace(/^\d+-/, '');
}
/** Upload a session material file to the `materials` bucket and store the
* path. Admin passes the storage write gate (`can_write_session_material`
* allows `is_admin()`), so uploads on behalf of speakers work. When replacing
* an existing file, the old object is removed best-effort after the new one
* is in place; a failed DB update rolls the fresh upload back so the session
* never points at a nonexistent path. */
export async function uploadSessionMaterial(
sessionId: string,
file: File,
previousPath?: string | null,
): Promise<string> {
const path = `sessions/${sessionId}/${Date.now()}-${file.name}`;
const { error } = await supabase.storage.from('materials').upload(path, file, { upsert: true });
if (error) throw new ApiError(error.message);
const { error: upErr } = await supabase.from('sessions').update({ material_path: path }).eq('id', sessionId);
if (upErr) throw new ApiError(upErr.message);
if (upErr) {
await supabase.storage.from('materials').remove([path]);
throw new ApiError(upErr.message);
}
if (previousPath && previousPath !== path) {
await supabase.storage.from('materials').remove([previousPath]);
}
return path;
}
@@ -272,19 +553,101 @@ export async function removeSessionMaterial(sessionId: string): Promise<void> {
const { data } = await supabase.from('sessions').select('material_path').eq('id', sessionId).maybeSingle();
const path = (data as Session | null)?.material_path;
if (path) {
await supabase.storage.from('materials').remove([path]);
// Surface storage failures instead of nulling the path and orphaning the file.
const { error: rmErr } = await supabase.storage.from('materials').remove([path]);
if (rmErr) throw new ApiError(rmErr.message);
}
const { error } = await supabase.from('sessions').update({ material_path: null }).eq('id', sessionId);
if (error) throw new ApiError(error.message);
}
export function sessionMaterialUrl(path: string): string {
const { data } = supabase.storage.from('materials').getPublicUrl(path);
return data.publicUrl;
/** Open a session material in a new tab via a short-lived signed URL (previews
* inline for browser-renderable types like PDF). The materials bucket is
* private; storage RLS always allows admins, bypassing the attendee time-lock. */
export async function openSessionMaterial(path: string): Promise<void> {
const { data, error } = await supabase.storage.from('materials').createSignedUrl(path, 600);
if (error) throw new ApiError(error.message);
window.open(data.signedUrl, '_blank');
}
/** Trigger the (stub) AI feedback evaluation for a session. */
export async function evaluateSessionFeedback(sessionId: string): Promise<Session> {
// evaluate_session_feedback returns a single composite row (a JSON object, not an array).
return await rpc<Session>('evaluate_session_feedback', { p_session_id: sessionId });
/** Save a session material to disk through authenticated storage download —
* same mechanism the attendee app uses after a session ends, always allowed
* for admins. Saves under the clean original filename. */
export async function downloadSessionMaterial(path: string): Promise<void> {
const { data, error } = await supabase.storage.from('materials').download(path);
if (error) throw new ApiError(error.message);
const url = URL.createObjectURL(data);
const a = document.createElement('a');
a.href = url;
a.download = sessionMaterialName(path);
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
async function feedbackSidecarFetch<T>(path: string, init?: RequestInit): Promise<T> {
const { data, error } = await supabase.auth.getSession();
if (error || !data.session) throw new ApiError('Sign in as an administrator');
return sidecarFetch<T>(path, {
...init,
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${data.session.access_token}` },
});
}
export const getLlmSettings = () => feedbackSidecarFetch<LlmSettings>('/llm-settings');
export const saveLlmSettings = (input: { endpoint: string; model: string; api_key?: string }) =>
feedbackSidecarFetch<LlmSettings>('/llm-settings', { method: 'PUT', body: JSON.stringify(input) });
/**
* Ask the sidecar to make one real chat request with the stored settings and
* report a verdict. Returns the verdict rather than throwing on a bad
* connection, because the reason (wrong key, unreachable host, model still
* thinking) is what the UI has to show. Only throws for transport/auth faults.
* Always reads the settings saved in the DB, never the form's current values.
*/
export const testLlmConnection = () => feedbackSidecarFetch<LlmTestResult>('/llm-test', { method: 'POST' });
export async function getFeedbackSummaries(eventId: string): Promise<FeedbackSummary[]> {
const { data, error } = await supabase.from('feedback_summaries').select('*').eq('event_id', eventId);
if (error) throw new ApiError(error.message);
return data as FeedbackSummary[];
}
export const generateFeedbackSummary = (eventId: string, sessionId?: string) =>
feedbackSidecarFetch<FeedbackSummary>('/feedback-summary', {
method: 'POST',
body: JSON.stringify({ event_id: eventId, scope: sessionId ? 'session' : 'event', ...(sessionId ? { session_id: sessionId } : {}) }),
});
// ---- Badge printing (queue + printer stations) -------------------------------
/** Admin dashboard snapshot: stations, queue counters, recent jobs, dead letters. */
export const getPrintOverview = () => rpc<PrintOverview>('get_print_overview', {});
/** Queue one attendee's badge for printing; resolves with the queue msg id. */
export const enqueueBadgePrint = (registrationId: string) =>
rpc<number>('enqueue_badge_print', { p_registration_id: registrationId });
/** Register a printer station. The token is returned only here, never again. */
export async function createPrintStation(name: string): Promise<{ id: string; token: string }> {
// create_print_station returns a one-row table (a JSON array of one object).
const rows = await rpc<{ id: string; token: string }[]>('create_print_station', { p_name: name });
if (!rows[0]) throw new ApiError('Station creation returned no token');
return rows[0];
}
/** Retire a station; its token stops working immediately. */
export const revokePrintStation = (id: string) => rpc<void>('revoke_print_station', { p_id: id });
/** Rename a station (revoked ones included); the Pi adopts the new name. */
export const renamePrintStation = (id: string, name: string) =>
rpc<void>('rename_print_station', { p_id: id, p_name: name });
/** Push a dead letter back onto the live queue; resolves with the new msg id. */
export const requeueDeadBadgePrint = (msgId: number) =>
rpc<number>('requeue_dead_badge_print', { p_msg_id: msgId });
/** Drop a dead letter without retrying it. */
export const discardDeadBadgePrint = (msgId: number) => rpc<void>('discard_dead_badge_print', { p_msg_id: msgId });
+136
View File
@@ -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 '';
}
+19
View File
@@ -0,0 +1,19 @@
export function normalizeSessionizeSource(value: string): string | null {
let source = value.trim();
if (!source) return null;
if (source.startsWith('<')) {
const document = new DOMParser().parseFromString(source, 'text/html');
const scripts = document.querySelectorAll('script[src]');
if (scripts.length !== 1) throw new Error('Paste one Sessionize script tag or URL');
source = scripts[0].getAttribute('src') || '';
}
let url: URL;
try { url = new URL(source); } catch { throw new Error('Enter a valid Sessionize URL or script tag'); }
if (url.protocol !== 'https:' || url.hostname !== 'sessionize.com' || url.port
|| url.username || url.password || !/^\/api\/v2\/[a-z0-9]+\/view\/(All|GridSmart)$/i.test(url.pathname)) {
throw new Error('Use a Sessionize HTTPS All or GridSmart endpoint');
}
url.search = '';
url.hash = '';
return url.href;
}
+339 -1
View File
@@ -1,3 +1,41 @@
export interface LlmSettings {
endpoint: string;
model: string;
has_api_key: boolean;
updated_at: string | null;
}
/**
* Verdict from the sidecar's `POST /llm-test`. Every key is always present.
* `reasoning_tokens` is null when the provider returned no usage block at all,
* so null must NOT be read as "thinking is off" — `reasoning_disabled` is the
* only field that asserts it (true means the provider reported 0 reasoning
* tokens for this exact request). A working connection that still reported
* reasoning tokens comes back `ok: true` with a `warning`.
*/
export interface LlmTestResult {
ok: boolean;
model: string;
endpoint: string;
latency_ms: number;
reasoning_disabled: boolean;
reasoning_tokens: number | null;
content: string;
warning: string | null;
error: string | null;
}
export interface FeedbackSummary {
scope: 'event' | 'session';
target_id: string;
event_id: string;
session_id: string | null;
summary: string;
response_count: number;
source_fingerprint: string;
model: string;
generated_at: string;
}
export type RegistrationType = 'attendee' | 'speaker' | 'staff' | 'sponsor';
export type SponsorType =
@@ -35,8 +73,20 @@ export interface Event {
use_realtime_clock: boolean;
/** Sessionize API URL for this event (e.g. .../api/v2/<id>/view/All). */
sessionize_endpoint: string | null;
/** Pretix organizer for this event (e.g. `appecommday`). */
pretix_organizer?: string | null;
/** Pretix event slug for this event (e.g. `tickets`). */
pretix_event_slug?: string | null;
/** Pretix API token for this event (stored in plain text, visible in settings). */
pretix_api_key?: string | null;
/** The owning organisation / company (e.g. the Pretix organizer name). */
company?: string | null;
/** When the Sessionize sync last ran for this event. */
last_synced_at: string | null;
/** Bonus points each party earns for a connection when they shared a checked-in talk (0 = off). */
talk_networking_bonus: number;
/** How many badge labels a welcome (front-desk) check-in prints, 1..4. */
badge_copies?: number;
avg_feedback: number | null;
num_sessions: number;
num_speakers: number;
@@ -108,14 +158,65 @@ export interface ExcelSyncResult {
error?: string;
}
/** The summary returned by the sync_pretix_attendees RPC. */
export interface PretixSyncSummary {
created: number;
updated: number;
skipped: number;
errors: string[];
}
/** The result of a (blocking) sidecar Pretix sync run. */
export interface PretixRun {
event_id: string;
event_name?: string;
started_at: string;
finished_at: string;
status: 'success' | 'error' | 'skipped';
reason?: string;
orders?: number;
attendees?: number;
company?: string | null;
skipped?: number;
summary?: PretixSyncSummary;
error?: string;
}
/** The response of POST /run-pretix (same shape as a successful PretixRun). */
export type PretixSyncResult = PretixRun;
/** A Pretix event (slug + name) under an organizer. */
export interface PretixEventOption {
slug: string;
name: string;
}
/** A Pretix organizer + its active events, from POST /pretix-options. */
export interface PretixOrganizerOption {
slug: string;
name: string;
events: PretixEventOption[];
}
/** The response of POST /pretix-options. */
export interface PretixOptions {
organizers: PretixOrganizerOption[];
}
/** The sidecar's /status response. */
export interface SidecarStatus {
ok: boolean;
running: boolean;
lastRun: SyncResult | null;
pretixRunning?: boolean;
lastPretixRun?: PretixRun | null;
pretixIntervalMs?: number;
pretixConfigured?: boolean;
}
export interface Registration {
import_source?: 'sessionize' | null;
external_id?: string | null;
id: string;
event_id: string;
contact_email: string;
@@ -126,6 +227,14 @@ export interface Registration {
created_at: string;
}
export interface TicketMergeResult {
source_id: string;
target_id: string;
target_email: string;
type: RegistrationType;
sessions_transferred: number;
}
export interface Sponsor {
id: string;
event_id: string;
@@ -160,6 +269,22 @@ export interface Session {
average_feedback: number | null;
ai_generated_feedback: string | null;
material_path: string | null;
/** Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). */
level: string | null;
/** Free-text area/topic classification (e.g. Power Apps, Power Automate). */
area: string | null;
/** Free-text delivery language (e.g. English, German). */
language: string | null;
created_at: string;
}
/** Event-level feedback (distinct from the per-session `feedback` table). */
export interface EventFeedback {
id: string;
event_id: string;
contact_email: string;
rating: number;
comment: string | null;
created_at: string;
}
@@ -168,6 +293,18 @@ export interface SessionSpeaker {
contact_email: string;
}
export interface DeleteEventScheduleResult {
event_id: string;
event_name: string;
slots_deleted: number;
sessions_deleted: number;
session_speakers_deleted: number;
preferences_deleted: number;
checkins_deleted: number;
feedback_deleted: number;
material_paths_unpurged: number;
}
export type ConnectionStatus = 'pending' | 'accepted' | 'rejected';
export interface Connection {
@@ -178,6 +315,8 @@ export interface Connection {
status: ConnectionStatus;
created_at: string;
resolved_at: string | null;
/** Staff auto-pairing (never a hand-made connection, never scored). */
auto: boolean;
}
export interface Checkin {
@@ -212,7 +351,7 @@ export interface PointsLogRow {
event_id: string;
contact_email: string;
delta: number;
category: 'checkin' | 'connection' | 'feedback' | 'admin';
category: 'checkin' | 'connection' | 'feedback' | 'admin' | 'talk_networking';
created_at: string;
}
@@ -220,3 +359,202 @@ export interface ResetQrResult {
email: string;
qr_token: string;
}
/** An eligible attendee returned by `get_raffle_pool` (admin raffle). */
export interface RafflePoolEntry {
contact_email: string;
full_name: string;
points: number;
}
/** A winner recorded by `draw_raffle_winner` / read from `raffle_draws`. */
export interface RaffleWinner extends RafflePoolEntry {
draw_number: number;
drawn_at: string;
}
// ---- Badge editor (per-event WYSIWYG badge layout) --------------------------
/** A bindable attendee/event field for a text element. */
export type BadgeContentField =
| 'attendee_name'
| 'full_name'
| 'email'
| 'ticket_type'
| 'event_name'
| 'company'
| 'qr_token'
| 'static';
/** A bindable payload source for a QR element. */
export type BadgeQrValue =
| 'qr_token'
| 'checkin_url'
| 'email'
| 'attendee_name'
| 'static';
export type BadgeElementType = 'text' | 'qr' | 'image';
/** Common geometry for every badge element, in millimetres / degrees. */
export interface BadgeElementBase {
id: string;
type: BadgeElementType;
x: number;
y: number;
width: number;
height: number;
rotation: number;
}
export interface BadgeTextElement extends BadgeElementBase {
type: 'text';
content: BadgeContentField;
text: string;
font: string;
font_size: number;
line_height: number;
color: string;
bold: boolean;
italic: boolean;
align_h: 'left' | 'center' | 'right';
align_v: 'top' | 'middle' | 'bottom';
transform: 'none' | 'uppercase' | 'lowercase' | 'capitalize';
}
export interface BadgeQrElement extends BadgeElementBase {
type: 'qr';
value: BadgeQrValue;
static_value: string;
}
export interface BadgeImageElement extends BadgeElementBase {
type: 'image';
src: string;
fit: 'contain' | 'cover' | 'fill';
}
export type BadgeElement = BadgeTextElement | BadgeQrElement | BadgeImageElement;
/** A saved badge layout row from `badge_layouts`. */
export interface BadgeLayout {
id: string;
event_id: string;
name: string;
is_default: boolean;
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
created_at: string;
updated_at: string;
}
/** A sample attendee used to preview a layout's bound fields. */
export interface BadgeSample {
full_name: string;
email: string;
ticket_type: string;
qr_token: string;
event_name: string;
company: string;
/** Origin used to build check-in URLs; defaults to the current page origin. */
checkin_origin?: string;
}
/** The payload handed to the standalone print renderer (`window.renderBadge`). */
export interface BadgePrintPayload {
schema: 'convivo.badge-print/v1';
kind: 'checkin' | 'reprint';
requested_at: string;
requested_by: string | null;
event: { id: string; name: string; company: string | null };
registration: { id: string; email: string; type: string };
sample: BadgeSample;
layout: {
id: string;
name: string;
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
};
}
// ---- Badge printing (queue + stations, `get_print_overview`) ----------------
/** Derived station state (`get_print_overview` computes it server-side). */
export type PrintStationState = 'ready' | 'printing' | 'error' | 'offline' | 'revoked';
/** The `last_status` heartbeat the Raspberry Pi worker writes every 10 s. */
export interface PrintStationStatus {
version?: string;
station_name?: string;
worker?: 'starting' | 'idle' | 'printing' | 'paused';
job_msg_id?: number | null;
printer?: {
connected?: boolean;
model?: string | null;
ready?: boolean;
media_type?: 'die-cut' | 'continuous' | null;
label_id?: string | null;
media_width_mm?: number | null;
media_length_mm?: number | null;
errors?: string[];
};
network?: {
state?: 'CONNECTED' | 'CONNECTING' | 'HOTSPOT' | 'UNKNOWN';
ssid?: string | null;
ip?: string | null;
};
label?: string | null;
last_error?: string | null;
uptime_s?: number;
}
export interface PrintStation {
id: string;
name: string;
created_at: string;
revoked_at: string | null;
last_seen_at: string | null;
last_status: PrintStationStatus | null;
state: PrintStationState;
}
export interface PrintQueueCounts {
pending: number;
in_flight: number;
dead_letter: number;
completed: number;
}
/** A completed (archived) badge job, newest first. */
export interface PrintRecentJob {
msg_id: number;
archived_at: string;
kind: 'checkin' | 'reprint' | string;
full_name: string | null;
email: string | null;
event_name: string | null;
registration_id: string | null;
}
/** A job that kept failing and was moved to the dead letter queue. */
export interface PrintDeadLetter {
msg_id: number;
enqueued_at: string;
failed_at: string | null;
error: string | null;
attempts: string | number | null;
kind: 'checkin' | 'reprint' | string;
full_name: string | null;
email: string | null;
event_name: string | null;
registration_id: string | null;
}
export interface PrintOverview {
stations: PrintStation[];
queue: PrintQueueCounts;
recent: PrintRecentJob[];
dead_letters: PrintDeadLetter[];
}
+92
View File
@@ -0,0 +1,92 @@
import { useCallback, useEffect, useRef } from 'react';
/** Background poll interval while the tab is visible. */
export const SILENT_POLL_MS = 5000;
/** Relaxed poll for views whose refresh pulls many tables at once. */
export const SLOW_POLL_MS = 15000;
/** How long after a write we wait before pulling fresh data (batches bursts). */
export const WRITE_SETTLE_MS = 500;
/**
* Silent background refresh for admin data.
*
* Two triggers, both deliberately invisible:
* 1. a poll every `SILENT_POLL_MS` while the tab is visible (paused when
* hidden, and refreshed the moment it becomes visible again), so the table
* shows staff scans performed on another device;
* 2. `refreshSoon()`, a debounced pull `WRITE_SETTLE_MS` after a write, which
* lets a burst of edits settle on the server before we read it back.
*
* "Silent" is the contract, and it has teeth:
* - the interval never fires on mount — the view's own `load()` owns the first
* fetch and the loading state;
* - errors are swallowed. A background tick must not write the view's `error`
* state, because these views render `if (error) return <Empty/>` and a
* single failed poll would replace a perfectly good table with an error
* screen;
* - overlapping ticks are dropped rather than queued (`inflight`), so a slow
* response can never pile up behind a fast one;
* - the callback is read from a ref, so an inline `() => load(...)` does not
* reschedule the timer on every render.
*
* Callers must supply a refresh that patches data in place: no `setLoaded(false)`,
* no re-sort that moves rows under the cursor. See Registrations, which keeps the
* existing row order and skips rows with a write in flight.
*
* `intervalMs` relaxes the poll for views whose refresh is expensive (Reports
* pulls nine tables at once). The 500 ms-after-write path is unaffected.
*/
export function useSilentRefresh(
refresh: () => Promise<unknown> | void,
options: { enabled?: boolean; refresher?: () => Promise<unknown> | void; intervalMs?: number } = {},
): { refreshSoon: () => void } {
const { enabled = true, intervalMs = SILENT_POLL_MS } = options;
const tick = options.refresher ?? refresh;
const saved = useRef(tick);
saved.current = tick;
const inflight = useRef(false);
const timer = useRef<number | null>(null);
const run = useCallback(async () => {
if (inflight.current) return;
inflight.current = true;
try {
await saved.current();
} catch {
// Silent by design — see the doc comment.
} finally {
inflight.current = false;
}
}, []);
useEffect(() => {
if (!enabled) return;
const visible = () => typeof document === 'undefined' || document.visibilityState === 'visible';
const id = window.setInterval(() => {
if (visible()) void run();
}, intervalMs);
const onVisible = () => {
if (visible()) void run();
};
document.addEventListener('visibilitychange', onVisible);
return () => {
window.clearInterval(id);
document.removeEventListener('visibilitychange', onVisible);
};
}, [enabled, intervalMs, run]);
useEffect(() => () => {
if (timer.current !== null) window.clearTimeout(timer.current);
}, []);
/** Schedule one debounced pull; repeated calls within the window collapse. */
const refreshSoon = useCallback(() => {
if (timer.current !== null) window.clearTimeout(timer.current);
timer.current = window.setTimeout(() => {
timer.current = null;
void run();
}, WRITE_SETTLE_MS);
}, [run]);
return { refreshSoon };
}
+77
View File
@@ -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;
+41 -25
View File
@@ -1,23 +1,48 @@
import { useState, type FormEvent } from 'react';
import { useEffect, useState, type FormEvent } from 'react';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import { supabase } from '../lib/supabase';
export function Login() {
const { signIn } = useAuth();
const { authError } = useAuth();
const { push } = useToast();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [error, setError] = useState<string | null>(authError);
const [sent, setSent] = useState(false);
const [cooldown, setCooldown] = useState(0);
const [resendAt, setResendAt] = useState(0);
useEffect(() => {
if (!resendAt) return;
const timer = window.setInterval(() => {
const remaining = Math.max(0, Math.ceil((resendAt - Date.now()) / 1000));
setCooldown(remaining);
if (!remaining) window.clearInterval(timer);
}, 1000);
return () => window.clearInterval(timer);
}, [resendAt]);
async function onSubmit(e: FormEvent) {
e.preventDefault();
if (!email.trim() || !password.trim()) return;
if (busy || !email.trim() || cooldown) return;
setBusy(true);
setError(null);
try {
await signIn(email.trim(), password);
push('success', 'Welcome back');
setSent(false);
const { error: sendError } = await supabase.auth.signInWithOtp({
email: email.trim(),
options: {
shouldCreateUser: false,
emailRedirectTo: new URL('/auth/callback', window.location.origin).href,
},
});
if (sendError && (sendError.status === 429 || !sendError.status || sendError.status >= 500)) {
throw new Error('Unable to send a sign-in link right now. Please try again later.');
}
setSent(true);
setCooldown(60);
setResendAt(Date.now() + 60_000);
} catch (err) {
const msg = err instanceof Error ? err.message : 'Sign in failed';
setError(msg);
@@ -34,37 +59,28 @@ export function Login() {
<div className="logo"><img src="/icon-192.png" alt="APPE" /></div>
<div>
<h1>APPE Admin</h1>
<p>Sign in with your admin email and password.</p>
<p>Sign in to your admin account.</p>
</div>
</div>
<form className="login-form" onSubmit={onSubmit}>
<div className="field">
<label>Email</label>
<label htmlFor="login-email">Email</label>
<input
id="login-email"
className="input"
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
onChange={(e) => { setEmail(e.target.value); setSent(false); }}
autoComplete="username"
disabled={busy}
required
/>
</div>
<div className="field">
<label>Password</label>
<input
className="input"
type="password"
placeholder="••••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
required
/>
</div>
{error && <div className="login-err">{error}</div>}
<button className="btn primary" type="submit" disabled={busy}>
{busy ? 'Signing in…' : 'Sign in'}
{sent && <div role="status">If this email belongs to an eligible account, a sign-in link has been sent.</div>}
{error && <div className="login-err" role="alert">{error}</div>}
<button className="btn primary" type="submit" disabled={busy || cooldown > 0}>
{busy ? 'Sending...' : cooldown ? `Resend in ${cooldown}s` : sent ? 'Resend magic link' : 'Send magic link'}
</button>
</form>
</div>
+330 -1
View File
@@ -1,3 +1,56 @@
.llm-settings { display: grid; gap: 18px; max-width: 640px; padding: 20px 0; border-top: 1px solid var(--line); }
/* Same rhythm as .llm-settings, for standalone (non-form) settings blocks.
No top border: it sits above the bordered .llm-settings block. */
.settings-section { display: grid; gap: 18px; max-width: 640px; padding: 20px 0; }
.feedback-summary { width: 100%; min-width: 0; padding: 16px 0; border-bottom: 1px solid var(--line); }
.feedback-summary-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 10px; }
.feedback-summary-head > div { min-width: 0; flex: 1 1 220px; overflow-wrap: anywhere; }
.feedback-summary-text { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 14px; line-height: 1.65; margin: 12px 0; }
.feedback-summary p { overflow-wrap: anywhere; }
.feedback-error { color: var(--red); overflow-wrap: anywhere; margin: 8px 0; }
/* ---------- AI connection test (Settings) ---------- */
.llm-test { display: grid; gap: 10px; }
.llm-test-result {
display: grid; gap: 6px; padding: 13px 15px; border-radius: 12px;
border: 1px solid var(--line); background: var(--surface-2); font-size: 13.5px; max-width: 640px;
}
/* Verdict colour carries meaning, so each variant stays above WCAG AA on its
own tint (4.5:1 for the headline, which is bold). */
.llm-test-result.good { border-color: rgba(5,150,105,.4); background: rgba(5,150,105,.08); }
.llm-test-result.good > strong { color: #046b4b; }
.llm-test-result.warn { border-color: rgba(245,158,11,.5); background: rgba(245,158,11,.1); }
.llm-test-result.warn > strong { color: #8a4b04; }
.llm-test-result.bad { border-color: rgba(213,0,0,.4); background: rgba(213,0,0,.06); }
/* A working connection whose endpoint reports no reasoning-token counter. It is
not a warning — it is simply unconfirmable from the usage block — so it gets a
neutral slate rather than the amber "still thinking" treatment. */
.llm-test-result.neutral { border-color: rgba(71,85,105,.35); background: rgba(71,85,105,.06); }
.llm-test-result > strong { font-size: 14px; font-weight: 800; color: var(--text); }
.llm-test-result p { margin: 0; overflow-wrap: anywhere; }
/* --muted (#8a8484) is only 3.67:1 on white, so body text in a verdict card is
darkened in every variant — this text explains the verdict, it is not decoration. */
.llm-test-result > p:not(.feedback-error) { color: #4a4343; }
.feedback-table { overflow-x: auto; }
.feedback-table table { min-width: 680px; }
.seg.activity-tabs { max-width: 100%; }
.seg.activity-tabs button { min-width: 0; white-space: normal; }
@media (max-width: 760px) {
.seg.activity-tabs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
.raffle { display: grid; gap: 20px; }
.raffle-stage { display: grid; gap: 18px; justify-items: center; text-align: center; padding: 32px 20px; }
.raffle-name {
min-height: 1.4em; width: 100%; max-width: 640px; font-size: clamp(24px, 5vw, 44px); font-weight: 700;
color: var(--text); overflow-wrap: anywhere;
}
.raffle-controls { display: flex; align-items: flex-end; justify-content: center; gap: 12px; flex-wrap: wrap; }
.raffle-picks { text-align: left; }
.raffle-picks input { width: 120px; }
.raffle-spin-icon { animation: raffle-rotate 0.9s linear infinite; }
@keyframes raffle-rotate { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
.raffle-spin-icon { animation: none; }
}
* { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
:root {
--bg: #f0f2f6; --surface: #ffffff; --surface-2: #f4f5f9;
@@ -78,6 +131,7 @@ body {
.btn.ghost { background: transparent; }
.btn.danger { background: rgba(213,0,0,.08); border-color: rgba(213,0,0,.35); color: var(--red); }
.btn.small { padding: 8px 12px; font-size: 12.5px; border-radius: 10px; }
.btn.active { background: var(--accent-soft); border-color: rgba(213,0,0,.4); color: var(--accent); }
.btn:disabled { opacity: .45; cursor: not-allowed; }
.icon-btn {
width: 34px; height: 34px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface);
@@ -142,6 +196,45 @@ body {
.uiverse-tooltip .uiverse-card h3 { margin: 0; font-size: 13px; font-weight: 600; color: #fff; }
.uiverse-tooltip .uiverse-card p { margin: 0; font-size: 13px; line-height: 1.5; color: #d1d5db; }
.uiverse-tooltip .uiverse-card .uiverse-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 11px; color: #9ca3af; }
/* Portal tooltip (same Uiverse dark-glass card, APPE-red themed). Rendered on
document.body so it is never clipped by table overflow. */
.tip-anchor { position: relative; display: inline-flex; }
/* Disabled buttons swallow mouse events, so make them hit-test-transparent and
let the wrapper carry the hover (and the not-allowed cursor). */
.tip-anchor > button:disabled { pointer-events: none; }
.tip-anchor:has(> button:disabled) { cursor: not-allowed; }
.tip-card {
/* left/top are computed in JS against the viewport, so the card carries no
centring transform — that transform is what made the clamp math lie about
where the card actually was. */
position: fixed; width: 250px; max-width: calc(100vw - 16px); padding: 13px 15px;
background: linear-gradient(135deg, rgba(17,24,39,.97), rgba(31,41,55,.97));
backdrop-filter: blur(8px); border: 1px solid rgba(213,0,0,.35); border-radius: 14px;
box-shadow: 0 0 26px rgba(213,0,0,.18), 0 14px 34px rgba(0,0,0,.35);
z-index: 120; pointer-events: none; animation: tip-in .18s ease;
}
@keyframes tip-in { from { opacity: 0; translate: 0 6px; } to { opacity: 1; translate: 0 0; } }
.tip-card .tip-head { display: flex; align-items: center; gap: 9px; margin-bottom: 6px; }
.tip-card .tip-head strong { font-size: 13px; font-weight: 700; color: #fff; }
.tip-card .tip-ico {
display: flex; align-items: center; justify-content: center; width: 26px; height: 26px;
border-radius: 50%; background: rgba(213,0,0,.22); color: #ff6b6b; flex-shrink: 0;
}
.tip-card p { margin: 0; font-size: 12.5px; line-height: 1.5; color: #d1d5db; }
.tip-card .tip-arrow {
/* left comes from JS (the trigger's centre, clamped inside the card), so the
arrow still points at the control after the card is pushed sideways. */
position: absolute; bottom: -6px; margin-left: -6px; transform: rotate(45deg);
width: 12px; height: 12px; background: rgba(31,41,55,.97);
border-right: 1px solid rgba(213,0,0,.35); border-bottom: 1px solid rgba(213,0,0,.35);
}
/* Flipped under a trigger that has no room above it: the arrow moves to the
top edge and points up instead. */
.tip-card.tip-below .tip-arrow {
bottom: auto; top: -6px; border: 0;
border-left: 1px solid rgba(213,0,0,.35); border-top: 1px solid rgba(213,0,0,.35);
}
/* sponsor tiers */
.pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); }
.pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; }
@@ -161,6 +254,14 @@ textarea.input { resize: none; min-height: 84px; }
.field { display: flex; flex-direction: column; gap: 6px; }
.field label { font-size: 12.5px; font-weight: 700; color: var(--muted); }
.divider { height: 1px; background: var(--line); margin: 4px 0; }
.section {
border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px;
background: var(--surface-2); display: flex; flex-direction: column; gap: 12px;
}
.section-head { display: flex; align-items: center; gap: 8px; }
.section-head .ico { font-size: 16px; }
.section-head h4 { font-size: 13px; font-weight: 800; letter-spacing: .2px; color: var(--text); margin: 0; }
.section-head .pill { margin-left: auto; }
/* ---------- Stat cards ---------- */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin-bottom: 22px; }
@@ -187,9 +288,90 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.cell-person .n { font-weight: 700; }
.cell-person .e { font-size: 12px; color: var(--muted); }
.pts { font-weight: 800; color: #b45309; }
/* Points-exempt rows (staff / organiser / @appe.at). Deliberately not the amber
score colour, and not --muted (#8a8484 = 3.67:1, fails AA on white): the note
has to stay readable because it explains why the number is missing. */
.pts.pts-exempt {
display: inline-flex; align-items: center; gap: 7px; justify-content: flex-end;
font-weight: 700; color: #6b6666; cursor: help;
}
.pts-exempt-mark {
padding: 2px 7px; border-radius: 999px; font-size: 10px; font-weight: 800;
letter-spacing: .4px; text-transform: uppercase; white-space: nowrap;
background: rgba(148,163,184,.16); border: 1px solid rgba(100,116,139,.35); color: #475569;
}
/* Explains an action that is deliberately a no-op, so it must be readable
(not --muted) and cannot be mistaken for a saved result. */
.pts-exempt-note {
margin: 0; padding: 11px 13px; border-radius: 11px; font-size: 13px; line-height: 1.5;
color: #4a4343; background: rgba(245,158,11,.1); border: 1px solid rgba(245,158,11,.42);
}
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; }
/* ---------- Column filter (Excel-style, portalled so it isn't clipped) ---------- */
.colfilter { position: relative; display: inline-flex; margin-left: 6px; vertical-align: middle; }
.colfilter-btn {
display: inline-flex; align-items: center; gap: 3px; padding: 3px 6px; border-radius: 7px;
border: 1px solid var(--line); background: var(--surface); color: var(--muted);
cursor: pointer; font: inherit; transition: all .15s ease;
}
.colfilter-btn:hover { border-color: rgba(213,0,0,.4); color: var(--accent); }
.colfilter-btn.on { background: var(--accent-soft); border-color: rgba(213,0,0,.45); color: var(--accent); }
.colfilter-count { font-size: 10px; font-weight: 800; min-width: 14px; text-align: center; }
.colfilter-pop {
position: fixed; z-index: 130; width: 220px; max-height: 300px; overflow-y: auto; padding: 8px;
background: var(--surface); border: 1px solid var(--line); border-radius: 12px;
box-shadow: 0 16px 40px rgba(66,60,60,.22); animation: colfilter-in .14s ease;
}
@keyframes colfilter-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
.colfilter-head { display: flex; align-items: center; justify-content: space-between; padding: 4px 8px 8px; border-bottom: 1px solid var(--line); margin-bottom: 6px; }
.colfilter-head strong { font-size: 12px; text-transform: uppercase; letter-spacing: .4px; color: var(--muted); }
.colfilter-clear { border: none; background: none; color: var(--accent); font-size: 12px; font-weight: 700; cursor: pointer; padding: 2px 4px; }
.colfilter-opt { display: flex; align-items: center; gap: 9px; padding: 7px 8px; border-radius: 8px; cursor: pointer; font-size: 13px; }
.colfilter-opt:hover { background: var(--surface-2); }
.colfilter-opt input { accent-color: var(--accent); width: 15px; height: 15px; cursor: pointer; }
.colfilter-opt .lbl { flex: 1; text-transform: capitalize; }
.colfilter-opt .cnt { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
/* ---------- Sessions view ---------- */
.sessions-toolbar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; padding: 14px 16px; }
.sessions-toolbar .input[type='search'] { flex: 1 1 260px; min-width: 200px; }
.sessions-toolbar select.input { flex: 0 1 300px; min-width: 220px; }
.pill-x { border: none; background: none; color: inherit; cursor: pointer; font-size: 11px; font-weight: 800; padding: 0 0 0 4px; line-height: 1; }
.pill-x:disabled { cursor: not-allowed; opacity: .5; }
.cell-when { display: flex; flex-direction: column; gap: 2px; font-variant-numeric: tabular-nums; }
.cell-when span { font-size: 11px; text-transform: uppercase; letter-spacing: .4px; }
.cell-when strong { font-size: 13px; color: var(--text); font-weight: 700; }
.cell-session { display: flex; flex-direction: column; gap: 2px; }
.cell-session .n { font-weight: 700; }
.cell-session .e { font-size: 12px; color: #6b6666; text-transform: capitalize; }
.att-count { font-weight: 800; color: var(--cyan-dark, #0f766e); font-variant-numeric: tabular-nums; }
.speaker-list { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.speaker-chip { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; padding: 2px 8px 2px 2px; border-radius: 999px; background: var(--surface-2); border: 1px solid var(--line); }
tr.row-open td { background: rgba(244,245,249,.9); }
tr.row-detail > td { padding: 0; background: var(--surface-2); border-bottom: 1px solid var(--line); }
.session-detail { padding: 16px 18px 20px; }
.session-desc { margin: 0 0 14px; font-size: 13.5px; line-height: 1.6; color: var(--text); max-width: 80ch; white-space: pre-wrap; }
.detail-cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 18px; align-items: start; }
.material-panel { display: flex; flex-direction: column; gap: 8px; }
.material-panel .material-file { font-size: 12.5px; font-weight: 650; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 340px; }
.material-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
.material-upload { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-top: 10px; }
.detail-cols h3 { font-size: 12px; font-weight: 800; text-transform: uppercase; letter-spacing: .4px; color: #5a5555; margin: 0 0 9px; }
.detail-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 7px; max-height: 280px; overflow-y: auto; }
.detail-list li { display: flex; align-items: center; gap: 9px; font-size: 13px; }
.detail-list .dl-name { font-weight: 650; }
.detail-list .dl-email { font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 22ch; }
.detail-list .dl-time { margin-left: auto; font-size: 11.5px; white-space: nowrap; font-variant-numeric: tabular-nums; }
.detail-list mark { background: rgba(245,158,11,.28); color: inherit; padding: 0 3px; border-radius: 4px; }
.summary-run-card { width: 100%; max-width: 400px; display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center; padding: 28px 26px; }
/* On the dark backdrop the usual --muted would sit under AA, so this card uses
full-strength text for its status copy. */
.summary-run-card .muted { color: var(--text); }
.summary-run-bar { width: 100%; height: 6px; border-radius: 999px; background: var(--line); overflow: hidden; }
.summary-run-bar > span { display: block; height: 100%; background: var(--accent); border-radius: 999px; transition: width .25s ease; }
/* ---------- Modal ---------- */
.backdrop { position: fixed; inset: 0; background: rgba(5,5,10,.6); backdrop-filter: blur(3px); z-index: 70; display: flex; align-items: center; justify-content: center; padding: 20px; }
.modal {
@@ -211,6 +393,8 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit; white-space: nowrap;
}
.seg button.active { background: var(--accent-soft); color: var(--accent); }
/* Compact numeric segment (badge copies): fixed-width buttons, comfortable targets. */
.seg.seg-num button { flex: 0 0 auto; min-width: 44px; padding: 10px 0; text-align: center; }
/* ---------- QR ---------- */
.qr-wrap { display: flex; flex-direction: column; align-items: center; gap: 12px; }
@@ -253,7 +437,12 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
@media (max-width: 900px) { .grid-2 { grid-template-columns: 1fr; } }
/* ---------- Toggle switch ---------- */
.toggle { display: inline-flex; align-items: center; gap: 9px; cursor: pointer; user-select: none; }
/* The vertical padding (cancelled by equal negative margins) grows the clickable
area of a 40x23 switch to ~40x41 without changing the row's visual height. */
.toggle {
display: inline-flex; align-items: center; gap: 9px; cursor: pointer; user-select: none;
padding: 9px 0; margin: -9px 0;
}
.toggle input { position: absolute; opacity: 0; width: 0; height: 0; }
.toggle .track {
width: 40px; height: 23px; border-radius: 999px; background: #d5d8e2; position: relative;
@@ -265,8 +454,24 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
}
.toggle input:checked + .track { background: var(--accent); }
.toggle input:checked + .track .knob { transform: translateX(17px); }
.toggle input:focus-visible + .track { outline: 2px solid var(--accent); outline-offset: 2px; }
.toggle input:disabled + .track { opacity: .45; cursor: default; }
.toggle-lbl { font-size: 13px; font-weight: 600; color: var(--text); }
/* ---------- Per-row write state (Registrations table) ---------- */
/* Only the row with a request in flight is marked. Deliberately light so the
row stays readable; the point is "this one is saving", not "table frozen". */
table.data tr.row-busy td { background: rgba(244,245,249,.85); }
.row-saving {
font-size: 11.5px; font-weight: 700; color: var(--muted); white-space: nowrap;
animation: row-saving-pulse 1s ease-in-out infinite;
}
@keyframes row-saving-pulse { 0%, 100% { opacity: .35; } 50% { opacity: 1; } }
@media (prefers-reduced-motion: reduce) {
.row-saving { animation: none; opacity: .8; }
.toggle .track, .toggle .knob { transition: none; }
}
/* ---------- Event card (dashboard) ---------- */
.event-card {
background: linear-gradient(135deg, rgba(213,0,0,.1), rgba(32,178,170,.08));
@@ -353,3 +558,127 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.sidebar-foot { display: none; }
.content { padding: 20px 16px 50px; }
}
/* ---------- Badge editor (per-event WYSIWYG layout) ---------- */
.badge-editor { display: grid; gap: 16px; }
.badge-event-pick select { min-width: 220px; }
.badge-toolbar {
display: flex; align-items: center; gap: 14px; flex-wrap: wrap;
padding: 10px 12px; background: var(--surface); border: 1px solid var(--line); border-radius: 14px;
}
.badge-layout-pick, .badge-tools { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.badge-tools.right { margin-left: auto; }
.badge-layout-pick select { min-width: 160px; }
.badge-tool-sep { width: 1px; height: 22px; background: var(--line); margin: 0 2px; }
.badge-workspace { display: grid; grid-template-columns: 1fr 300px; gap: 16px; align-items: start; }
.badge-canvas-wrap { display: grid; gap: 10px; min-width: 0; }
.badge-zoom { display: flex; align-items: center; gap: 8px; }
.badge-canvas-scroll {
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;
}
/* Editor-only look; the shared read-only badge rules live in components/badge-render.css. */
.badge-page { box-shadow: 0 10px 30px rgba(0,0,0,.12); }
.badge-page-empty {
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;
}
.badge-el { cursor: move; }
.badge-el.selected { outline: 1.5px solid var(--accent); }
.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-preview-stage {
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;
}
.badge-handle {
position: absolute; width: 9px; height: 9px; background: #fff; border: 1.5px solid var(--accent);
border-radius: 2px; transform: translate(-50%, -50%); z-index: 2;
}
.badge-handle-nw { left: 0; top: 0; cursor: nwse-resize; }
.badge-handle-n { left: 50%; top: 0; cursor: ns-resize; }
.badge-handle-ne { left: 100%; top: 0; cursor: nesw-resize; }
.badge-handle-e { left: 100%; top: 50%; cursor: ew-resize; }
.badge-handle-se { left: 100%; top: 100%; cursor: nwse-resize; }
.badge-handle-s { left: 50%; top: 100%; cursor: ns-resize; }
.badge-handle-sw { left: 0; top: 100%; cursor: nesw-resize; }
.badge-handle-w { left: 0; top: 50%; cursor: ew-resize; }
.badge-rotate-stem { position: absolute; left: 50%; top: -18px; width: 1.5px; height: 18px; background: var(--accent); transform: translateX(-50%); }
.badge-handle-rotate { left: 50%; top: -18px; border-radius: 50%; cursor: grab; }
.badge-props { background: var(--surface); border: 1px solid var(--line); border-radius: 14px; overflow: hidden; position: sticky; top: 16px; }
.badge-props-head { padding: 12px 14px; border-bottom: 1px solid var(--line); background: var(--surface-2); }
.badge-props-body { padding: 14px; display: grid; gap: 12px; }
.badge-field { display: grid; gap: 5px; }
.badge-field > span { font-size: 12px; font-weight: 600; color: var(--muted); }
.badge-field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.badge-color { width: 100%; height: 34px; padding: 2px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); }
.badge-btn-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.badge-props-divider { height: 1px; background: var(--line); margin: 2px 0; }
.badge-json {
margin: 14px; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word;
max-height: 560px; overflow: auto; color: var(--text);
}
@media (max-width: 900px) {
.badge-workspace { grid-template-columns: 1fr; }
.badge-props { position: static; }
}
/* Badge editor: alignment tools + multi-select */
.badge-props-head { display: flex; align-items: center; }
.badge-align-ref { width: auto; flex: 1; min-width: 110px; padding: 7px 10px; font-size: 12.5px; }
.badge-editor kbd {
font-family: inherit; font-size: 11px; font-weight: 700; padding: 1px 5px;
border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 5px; background: var(--surface-2);
}
/* Badge editor: PowerPoint-style smart guides (shown while dragging) */
.badge-guide { position: absolute; pointer-events: none; z-index: 5; }
.badge-guide-v { width: 0; border-left: 1px dashed #ff2d95; }
.badge-guide-h { height: 0; border-top: 1px dashed #ff2d95; }
.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)); }
}
+121 -12
View File
@@ -3,14 +3,19 @@ import {
getAllCheckins,
getAllConnections,
getAllContacts,
getAllFeedback,
getEventFeedback,
getEventSessionFeedback,
getActiveEvent,
getSessions,
getFeedbackSummaries,
getLlmSettings,
} from '../lib/api';
import type { Checkin, Connection, Contact, Event, Feedback, Session } from '../lib/types';
import type { Checkin, Connection, Contact, Event, EventFeedback, Feedback, FeedbackSummary, Session } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
import { useSilentRefresh } from '../lib/useSilentRefresh';
import { FeedbackSummaryPanel } from '../components/FeedbackSummaryPanel';
type Tab = 'checkins' | 'connections' | 'feedback';
type Tab = 'checkins' | 'connections' | 'feedback' | 'event_feedback';
export function Activity() {
const [event, setEvent] = useState<Event | null>(null);
@@ -21,29 +26,50 @@ export function Activity() {
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [connections, setConnections] = useState<Connection[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [eventFeedback, setEventFeedback] = useState<EventFeedback[]>([]);
const [error, setError] = useState<string | null>(null);
const [summaries, setSummaries] = useState<FeedbackSummary[]>([]);
const [llmConfigured, setLlmConfigured] = useState(false);
const [summaryError, setSummaryError] = useState<string | null>(null);
async function load() {
function updateSummary(summary: FeedbackSummary) {
setSummaries(current => [...current.filter(item => item.scope !== summary.scope || item.target_id !== summary.target_id), summary]);
}
async function load(silent = false) {
try {
const ev = await getActiveEvent();
setEvent(ev);
const [c, ck, cn, fb] = await Promise.all([
const [c, ck, cn, fb, efb] = await Promise.all([
getAllContacts(),
getAllCheckins(),
getAllConnections(),
getAllFeedback(),
ev ? getEventSessionFeedback(ev.id) : Promise.resolve([]),
ev ? getEventFeedback(ev.id) : Promise.resolve([]),
]);
setContacts(c);
if (ev) {
const ss = await getSessions(ev.id);
setSessions(ss);
setCheckins(ck.filter((x) => x.event_id === ev.id));
setConnections(cn.filter((x) => x.event_id === ev.id));
// Staff auto-pairings (connections.auto) are bookkeeping, not real
// networking — the console only shows hand-made connections.
setConnections(cn.filter((x) => x.event_id === ev.id && !x.auto));
setFeedback(fb.filter((x) => x.event_id === ev.id));
setEventFeedback(efb.filter((x) => x.event_id === ev.id));
try {
const [saved, settings] = await Promise.all([getFeedbackSummaries(ev.id), getLlmSettings()]);
setSummaries(saved);
setLlmConfigured(Boolean(settings.endpoint && settings.model));
} catch (cause) {
if (!silent) setSummaryError(cause instanceof Error ? cause.message : 'Failed to load AI settings');
}
}
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
// A failed background tick must not replace a good list with the error
// screen — this view renders `if (error) return <Empty/>`.
if (!silent) setError(e instanceof Error ? e.message : 'Failed to load');
}
}
@@ -51,6 +77,10 @@ export function Activity() {
load();
}, []);
// Live activity feed: check-ins and feedback made on phones land here without
// a reload.
useSilentRefresh(() => load(true), { enabled: loaded });
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email, c.full_name]));
return (email: string) => m.get(email) ?? email;
@@ -61,6 +91,26 @@ export function Activity() {
return (id: string) => m.get(id) ?? id;
}, [sessions]);
// Per-session feedback aggregate (avg rating + response count), for the
// post-event session feedback summary.
const sessionFeedbackSummary = useMemo(() => {
const bySession = new Map<string, { count: number; sum: number }>();
for (const f of feedback) {
const e = bySession.get(f.session_id) ?? { count: 0, sum: 0 };
e.count += 1;
e.sum += f.rating;
bySession.set(f.session_id, e);
}
return [...bySession.entries()]
.map(([session_id, e]) => ({
session_id,
title: sessionTitle(session_id),
avg: e.sum / e.count,
count: e.count,
}))
.sort((a, b) => b.avg - a.avg);
}, [feedback, sessionTitle]);
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
@@ -91,12 +141,12 @@ export function Activity() {
<div>
<h1>Activity</h1>
<div className="sub">
{event.name} · {checkins.length} check-ins · {connections.length} connections · {feedback.length} feedback.
{event.name} · {checkins.length} check-ins · {connections.length} connections · {feedback.length} session feedback · {eventFeedback.length} event feedback.
</div>
</div>
</div>
<div className="seg" style={{ marginBottom: 16 }}>
<div className="seg activity-tabs" style={{ marginBottom: 16 }}>
<button className={tab === 'checkins' ? 'active' : ''} onClick={() => setTab('checkins')}>
Check-ins
</button>
@@ -104,7 +154,10 @@ export function Activity() {
Connections
</button>
<button className={tab === 'feedback' ? 'active' : ''} onClick={() => setTab('feedback')}>
Feedback
Session feedback
</button>
<button className={tab === 'event_feedback' ? 'active' : ''} onClick={() => setTab('event_feedback')}>
Event feedback
</button>
</div>
@@ -182,10 +235,28 @@ export function Activity() {
{tab === 'feedback' && (
<div className="card">
{summaryError && <p className="feedback-error" role="alert">{summaryError}</p>}
{feedback.length === 0 ? (
<Empty icon="⭐" text="No feedback yet." />
) : (
<div className="table-wrap">
<>
{/* Per-session aggregate header (the post-event session feedback summary). */}
<div style={{ marginBottom: 12 }}>
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>
Per-session summary
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{sessionFeedbackSummary.map((s) => (
<FeedbackSummaryPanel key={s.session_id} eventId={event.id} sessionId={s.session_id}
title={`${s.title} · ${s.avg.toFixed(1)}★`} count={s.count} configured={llmConfigured}
summary={summaries.find(item => item.scope === 'session' && item.session_id === s.session_id)} onGenerated={updateSummary} />
))}
</div>
</div>
</>
)}
{feedback.length > 0 && (
<div className="table-wrap feedback-table">
<table className="data">
<thead>
<tr>
@@ -216,6 +287,44 @@ export function Activity() {
)}
</div>
)}
{tab === 'event_feedback' && (
<div className="card">
{summaryError && <p className="feedback-error" role="alert">{summaryError}</p>}
<FeedbackSummaryPanel eventId={event.id} title={event.name} count={eventFeedback.length} configured={llmConfigured}
summary={summaries.find(item => item.scope === 'event')} onGenerated={updateSummary} />
{eventFeedback.length === 0 ? (
<Empty icon="⭐" text="No event-level feedback yet." />
) : (
<div className="table-wrap feedback-table">
<table className="data">
<thead>
<tr>
<th>From</th>
<th>Rating</th>
<th>Comment</th>
<th>When</th>
</tr>
</thead>
<tbody>
{eventFeedback.map((f) => (
<tr key={f.id}>
<td>
<PersonCell name={nameOf(f.contact_email)} email={f.contact_email} />
</td>
<td>
<span className="pill amber">{'★'.repeat(f.rating)}</span>
</td>
<td className="muted">{f.comment || '—'}</td>
<td className="muted">{fmt(f.created_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)}
</div>
);
}
File diff suppressed because it is too large. Load diff
+77 -92
View File
@@ -1,24 +1,53 @@
import { useEffect, useMemo, useState } from 'react';
import { adjustPoints, getAllContacts, updateContact, upsertContact } from '../lib/api';
import { deleteContact, getAllContacts, updateContact, upsertContact } from '../lib/api';
import type { Contact } from '../lib/types';
import { useSilentRefresh } from '../lib/useSilentRefresh';
import { useToast } from '../context/ToastContext';
import { Avatar, Empty, Modal, Spinner, Toggle } from '../components/ui';
import { Avatar, ColumnFilter, Empty, Modal, Spinner, Toggle, type ColumnFilterOption } from '../components/ui';
// Multi-select column filters are Excel-style: an empty selection means "all".
const VIS_LABELS: Record<string, string> = { both: 'Both shown', email: 'Email only', linkedin: 'LinkedIn only', none: 'None shown' };
const visKey = (c: Contact) => (c.show_email && c.show_linkedin ? 'both' : c.show_email ? 'email' : c.show_linkedin ? 'linkedin' : 'none');
const ynOptions = (rows: Contact[], fn: (c: Contact) => boolean): ColumnFilterOption[] => [
{ value: 'yes', label: 'Yes', count: rows.filter(fn).length },
{ value: 'no', label: 'No', count: rows.filter((c) => !fn(c)).length },
];
export function Contacts() {
const { push } = useToast();
const [contacts, setContacts] = useState<Contact[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [fLinkedin, setFLinkedin] = useState<string[]>([]);
const [fVis, setFVis] = useState<string[]>([]);
const [fAdmin, setFAdmin] = useState<string[]>([]);
const [editing, setEditing] = useState<Contact | null>(null);
const [creating, setCreating] = useState(false);
const [pointsFor, setPointsFor] = useState<Contact | null>(null);
const [deleting, setDeleting] = useState<string | null>(null);
async function load() {
async function load(silent = false) {
try {
setContacts(await getAllContacts());
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
// A failed background tick must not replace a good table with the error
// screen — this view renders `if (error) return <Empty/>`. The server sorts
// by name, so a fresh fetch cannot reorder rows under the cursor.
if (!silent) setError(e instanceof Error ? e.message : 'Failed to load');
}
}
async function remove(c: Contact) {
if (!confirm(`Delete ${c.full_name} (${c.email})? This also removes their registrations.`)) return;
setDeleting(c.email);
try {
await deleteContact(c.email);
await load();
push('success', `Deleted ${c.full_name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setDeleting(null);
}
}
@@ -26,18 +55,43 @@ export function Contacts() {
load();
}, []);
const filtered = useMemo(() => {
// Background pull, paused while a modal is open so nothing re-renders under a
// form. Writes here already `await load()`, so no refreshSoon is needed.
useSilentRefresh(() => load(true), {
enabled: contacts !== null && !editing && !creating && !deleting,
});
// General search: first name, last name or email address.
const searched = useMemo(() => {
if (!contacts) return [];
const q = query.trim().toLowerCase();
if (!q) return contacts;
return contacts.filter(
(c) =>
c.full_name.toLowerCase().includes(q) ||
c.email.toLowerCase().includes(q) ||
(c.linkedin_url ?? '').toLowerCase().includes(q),
);
return contacts.filter((c) => {
const name = c.full_name.toLowerCase();
return name.split(/\s+/).some((part) => part.includes(q)) || name.includes(q) || c.email.toLowerCase().includes(q);
});
}, [contacts, query]);
const passLinkedin = (c: Contact) => fLinkedin.length === 0 || fLinkedin.includes(c.linkedin_url ? 'yes' : 'no');
const passVis = (c: Contact) => fVis.length === 0 || fVis.includes(visKey(c));
const passAdmin = (c: Contact) => fAdmin.length === 0 || fAdmin.includes(c.is_admin ? 'yes' : 'no');
const filtered = useMemo(
() => searched.filter((c) => passLinkedin(c) && passVis(c) && passAdmin(c)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[searched, fLinkedin, fVis, fAdmin],
);
// Option counts follow Excel: each column counts what the OTHER filters leave.
const linkedinOptions = ynOptions(searched.filter((c) => passVis(c) && passAdmin(c)), (c) => !!c.linkedin_url);
const adminOptions = ynOptions(searched.filter((c) => passLinkedin(c) && passVis(c)), (c) => c.is_admin);
const visCounts = new Map<string, number>();
for (const c of searched.filter((c) => passLinkedin(c) && passAdmin(c))) {
const k = visKey(c);
visCounts.set(k, (visCounts.get(k) ?? 0) + 1);
}
const visOptions = ['both', 'email', 'linkedin', 'none']
.filter((k) => visCounts.has(k))
.map((k) => ({ value: k, label: VIS_LABELS[k], count: visCounts.get(k)! }));
if (error) return <Empty icon="⚠️" text={error} />;
if (!contacts)
return (
@@ -51,13 +105,13 @@ export function Contacts() {
<div className="page-head">
<div>
<h1>Contacts</h1>
<div className="sub">{contacts.length} people · manage contacts and points.</div>
<div className="sub">{contacts.length} people · manage contacts.</div>
</div>
<div className="row" style={{ gap: 10 }}>
<input
className="input"
style={{ maxWidth: 260 }}
placeholder="Search name, email…"
placeholder="Search first name, last name, email…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -72,9 +126,9 @@ export function Contacts() {
<thead>
<tr>
<th>Name</th>
<th>LinkedIn</th>
<th>Visibility</th>
<th>Admin</th>
<th>LinkedIn <ColumnFilter label="LinkedIn" options={linkedinOptions} selected={fLinkedin} onChange={setFLinkedin} /></th>
<th>Visibility <ColumnFilter label="Visibility" options={visOptions} selected={fVis} onChange={setFVis} /></th>
<th>Admin <ColumnFilter label="Admin" options={adminOptions} selected={fAdmin} onChange={setFAdmin} /></th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
@@ -117,8 +171,12 @@ export function Contacts() {
<button className="btn small" onClick={() => setEditing(c)}>
Edit
</button>
<button className="btn small" onClick={() => setPointsFor(c)}>
Points
<button
className="btn small danger"
disabled={deleting === c.email}
onClick={() => remove(c)}
>
{deleting === c.email ? 'Deleting…' : 'Delete'}
</button>
</div>
</td>
@@ -152,16 +210,6 @@ export function Contacts() {
/>
)}
{pointsFor && (
<AdjustPointsModal
contact={pointsFor}
onClose={() => setPointsFor(null)}
onSaved={async (msg) => {
setPointsFor(null);
push('success', msg);
}}
/>
)}
</div>
);
}
@@ -303,66 +351,3 @@ function CreateContactModal({
</Modal>
);
}
function AdjustPointsModal({
contact,
onClose,
onSaved,
}: {
contact: Contact;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [delta, setDelta] = useState('10');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
async function save() {
const d = parseInt(delta, 10);
if (Number.isNaN(d) || d === 0) return;
setBusy(true);
try {
await adjustPoints(contact.email, d, reason.trim() || 'manual adjustment');
onSaved(`${d > 0 ? '+' : ''}${d} points for ${contact.full_name}`);
onClose();
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Adjustment failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Points — ${contact.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy} onClick={save}>
{busy ? 'Applying…' : 'Apply'}
</button>
</>
}
>
<div className="row" style={{ justifyContent: 'center', gap: 16 }}>
<Avatar name={contact.full_name} id={contact.email} size={52} fs={18} />
<div>
<div style={{ fontWeight: 700 }}>{contact.full_name}</div>
<div className="muted small">{contact.email}</div>
</div>
</div>
<div className="field">
<label>Adjustment for the active event (use a negative number to subtract)</label>
<input className="input mono" type="number" value={delta} onChange={(e) => setDelta(e.target.value)} />
</div>
<div className="field">
<label>Reason (optional)</label>
<input className="input" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. prize, correction" />
</div>
</Modal>
);
}
+24 -11
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import {
getAllCheckins,
getAllConnections,
@@ -9,6 +9,7 @@ import {
} from '../lib/api';
import type { Checkin, Connection, Contact, Event, Feedback, LeaderboardRow } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
import { useSilentRefresh } from '../lib/useSilentRefresh';
import type { View } from '../App';
export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
@@ -21,12 +22,12 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
const [lb, setLb] = useState<LeaderboardRow[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
const cancelledRef = useRef(false);
async function load(silent = false) {
try {
const ev = await getActiveEvent();
if (cancelled) return;
if (cancelledRef.current) return;
setEvent(ev);
if (!ev) {
setLoaded(true);
@@ -39,22 +40,35 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
getAllFeedback(),
getLeaderboard(),
]);
if (cancelled) return;
if (cancelledRef.current) return;
setContacts(c);
setCheckins(ck.filter((x) => x.event_id === ev.id));
setConnections(conn.filter((x) => x.event_id === ev.id));
// `auto` rows are the staff auto-pairings (migration 20261020120000):
// background bookkeeping, not real activity — keep them out of the feed.
setConnections(conn.filter((x) => x.event_id === ev.id && !x.auto));
setFeedback(f.filter((x) => x.event_id === ev.id));
setLb(l.filter((x) => x.event_id === ev.id));
setLoaded(true);
} catch (e) {
if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
// A failed background tick must not replace a good dashboard with the error
// screen — this view renders `if (error) return <Empty/>`.
if (!silent && !cancelledRef.current) setError(e instanceof Error ? e.message : 'Failed to load');
}
})();
}
useEffect(() => {
cancelledRef.current = false;
void load();
return () => {
cancelled = true;
cancelledRef.current = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Live counters: arrivals, connections and the leaderboard move as the event
// runs, without anyone pressing reload.
useSilentRefresh(() => load(true), { enabled: loaded });
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email, c.full_name]));
return (email: string) => m.get(email) ?? email;
@@ -160,7 +174,6 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
<Avatar name={r.full_name} id={r.contact_email} size={36} fs={13} />
<div className="grow">
<div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name}</div>
<div className="muted small">{r.contact_email}</div>
</div>
<span className="pts">{r.points}</span>
</div>
+311 -10
View File
@@ -1,8 +1,18 @@
import { useEffect, useState } from 'react';
import { activateEvent, deactivateEvent, getAllEvents, runSessionizeSync, upsertEvent } from '../lib/api';
import type { Event, SyncResult } from '../lib/types';
import { useEffect, useRef, useState } from 'react';
import {
activateEvent,
deactivateEvent,
fetchPretixOptions,
getAllEvents,
runPretixSync,
runSessionizeSync,
upsertEvent,
} from '../lib/api';
import type { Event, PretixOptions, PretixSyncResult, SyncResult } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner, Toggle } from '../components/ui';
import { BadgeCopiesPicker, clampBadgeCopies } from '../components/BadgeCopiesSetting';
import { normalizeSessionizeSource } from '../lib/sessionizeSource';
export function Events() {
const { push } = useToast();
@@ -12,6 +22,8 @@ export function Events() {
const [modal, setModal] = useState<{ event: Event | null } | null>(null);
const [syncingId, setSyncingId] = useState<string | null>(null);
const [syncResult, setSyncResult] = useState<SyncResult | null>(null);
const [pretixSyncingId, setPretixSyncingId] = useState<string | null>(null);
const [pretixResult, setPretixResult] = useState<PretixSyncResult | null>(null);
async function load() {
try {
@@ -56,6 +68,29 @@ export function Events() {
}
}
async function runPretix(ev: Event) {
if (!ev.pretix_organizer || !ev.pretix_event_slug || !ev.pretix_api_key) {
push('error', `Set the Pretix API key + organizer + event slug for ${ev.name} first (Edit)`);
return;
}
setPretixSyncingId(ev.id);
try {
const result = await runPretixSync(ev.id);
setPretixResult(result);
await load();
push(
'success',
result.status === 'success'
? `Pretix synced ${ev.name} (${result.attendees ?? 0} attendees)`
: `Pretix ${result.status} for ${ev.name}`,
);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Pretix sync failed');
} finally {
setPretixSyncingId(null);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
@@ -130,6 +165,23 @@ export function Events() {
>
{syncingId === ev.id ? 'Syncing…' : 'Sync'}
</button>
<button
className="btn small"
disabled={
pretixSyncingId === ev.id ||
!ev.pretix_organizer ||
!ev.pretix_event_slug ||
!ev.pretix_api_key
}
onClick={() => runPretix(ev)}
title={
ev.pretix_organizer && ev.pretix_event_slug && ev.pretix_api_key
? 'Sync with Pretix'
: 'Set the Pretix API key + organizer + event slug first (Edit)'
}
>
{pretixSyncingId === ev.id ? 'Syncing…' : 'Sync Pretix'}
</button>
<button className="btn small" onClick={() => setModal({ event: ev })}>
Edit
</button>
@@ -156,10 +208,72 @@ export function Events() {
)}
{syncResult && <SyncResultModal result={syncResult} onClose={() => setSyncResult(null)} />}
{pretixResult && <PretixResultModal result={pretixResult} onClose={() => setPretixResult(null)} />}
</div>
);
}
function PretixResultModal({ result, onClose }: { result: PretixSyncResult; onClose: () => void }) {
const s = result.summary;
return (
<Modal
open
title={`Pretix sync — ${result.event_name ?? result.event_id}`}
onClose={onClose}
footer={
<button className="btn primary" onClick={onClose}>
Close
</button>
}
>
{result.status === 'error' || result.status === 'skipped' ? (
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
{result.error ?? result.reason ?? 'Pretix sync failed'}
</div>
) : (
<>
<div className="stat-grid">
<div className="stat">
<div className="val">{result.orders ?? 0}</div>
<div className="lbl">Orders</div>
</div>
<div className="stat">
<div className="val">{result.attendees ?? 0}</div>
<div className="lbl">Attendees</div>
</div>
<div className="stat">
<div className="val">{s?.created ?? 0}</div>
<div className="lbl">Created</div>
</div>
<div className="stat">
<div className="val">{s?.updated ?? 0}</div>
<div className="lbl">Updated</div>
</div>
<div className="stat">
<div className="val">{result.skipped ?? 0}</div>
<div className="lbl">Skipped</div>
</div>
</div>
{s && s.errors.length > 0 && (
<div style={{ marginTop: 12 }}>
<div className="pill red" style={{ display: 'inline-block', marginBottom: 8 }}>
{s.errors.length} error(s)
</div>
<ul style={{ margin: 0, paddingLeft: 18 }}>
{s.errors.map((e, i) => (
<li key={i} className="small">
{e}
</li>
))}
</ul>
</div>
)}
</>
)}
</Modal>
);
}
function EventModal({
event,
onClose,
@@ -173,12 +287,60 @@ function EventModal({
const [startDate, setStartDate] = useState(event ? event.start_date.slice(0, 10) : '');
const [endDate, setEndDate] = useState(event ? event.end_date.slice(0, 10) : '');
const [location, setLocation] = useState(event?.location ?? '');
const [company, setCompany] = useState(event?.company ?? '');
const [endpoint, setEndpoint] = useState(event?.sessionize_endpoint ?? '');
const [endpointError, setEndpointError] = useState<string | null>(null);
const [pretixApiKey, setPretixApiKey] = useState(event?.pretix_api_key ?? '');
const [pretixOrganizer, setPretixOrganizer] = useState(event?.pretix_organizer ?? '');
const [pretixEventSlug, setPretixEventSlug] = useState(event?.pretix_event_slug ?? '');
const [pretixOptions, setPretixOptions] = useState<PretixOptions | null>(null);
const [pretixLoading, setPretixLoading] = useState(false);
const [pretixError, setPretixError] = useState<string | null>(null);
const [realtimeClock, setRealtimeClock] = useState(event?.use_realtime_clock ?? false);
const [talkBonus, setTalkBonus] = useState(event?.talk_networking_bonus ?? 2);
const [badgeCopies, setBadgeCopies] = useState(event?.badge_copies ?? 1);
const [busy, setBusy] = useState(false);
const lastFetchedKey = useRef<string | null>(null);
// When the API key changes, fetch the key's organizers + events (debounced)
// so the admin can pick the organizer + event slug from real data.
useEffect(() => {
const key = pretixApiKey.trim();
if (!key) {
setPretixOptions(null);
setPretixError(null);
lastFetchedKey.current = null;
return;
}
if (lastFetchedKey.current === key) return; // already fetched for this key
const t = setTimeout(async () => {
setPretixLoading(true);
setPretixError(null);
try {
const opts = await fetchPretixOptions(key);
setPretixOptions(opts);
lastFetchedKey.current = key;
// If the current selection isn't in the fetched list, keep it (it may
// be a valid slug the API just didn't return, e.g. inactive event).
} catch (e) {
setPretixError(e instanceof Error ? e.message : 'Failed to load Pretix options');
} finally {
setPretixLoading(false);
}
}, 500);
return () => clearTimeout(t);
}, [pretixApiKey]);
async function save() {
if (!name.trim() || !startDate || !endDate) return;
let source: string | null;
try {
source = normalizeSessionizeSource(endpoint);
setEndpointError(null);
} catch (error) {
setEndpointError(error instanceof Error ? error.message : 'Invalid Sessionize source');
return;
}
setBusy(true);
try {
await upsertEvent(event?.id ?? null, {
@@ -186,8 +348,14 @@ function EventModal({
start_date: startDate,
end_date: endDate,
location: location.trim() || null,
sessionize_endpoint: endpoint.trim() || null,
company: company.trim() || null,
sessionize_endpoint: source,
pretix_organizer: pretixOrganizer.trim() || null,
pretix_event_slug: pretixEventSlug.trim() || null,
pretix_api_key: pretixApiKey.trim() || null,
use_realtime_clock: realtimeClock,
talk_networking_bonus: Math.max(0, Math.min(10, Math.round(talkBonus) || 0)),
badge_copies: clampBadgeCopies(badgeCopies),
});
onSaved(event ? 'Event updated' : 'Event created');
} catch (e) {
@@ -232,16 +400,110 @@ function EventModal({
<input className="input" value={location} onChange={(e) => setLocation(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Sessionize endpoint</label>
<input
<label>Company / organizer</label>
<input className="input" value={company} onChange={(e) => setCompany(e.target.value)} placeholder="e.g. Austrian Power Platform Enthusiasts" />
<div className="muted small" style={{ marginTop: 4 }}>
The owning organisation. Auto-filled from Pretix on sync; bindable on badges.
</div>
</div>
<div className="section">
<div className="section-head">
<span className="ico">📅</span>
<h4>Sessionize</h4>
{endpoint.trim() ? <span className="pill green">configured</span> : <span className="pill">not set</span>}
</div>
<div className="field">
<label htmlFor="sessionize-source">Sessionize endpoint</label>
<textarea
id="sessionize-source"
className="input"
rows={3}
value={endpoint}
onChange={(e) => setEndpoint(e.target.value)}
placeholder="https://sessionize.com/api/v2/<id>/view/All"
onChange={(e) => { setEndpoint(e.target.value); setEndpointError(null); }}
aria-invalid={!!endpointError}
aria-describedby={endpointError ? 'sessionize-source-error' : undefined}
placeholder="https://sessionize.com/api/v2/<id>/view/GridSmart"
/>
{endpointError && <div id="sessionize-source-error" role="alert" className="error">{endpointError}</div>}
<div className="muted small" style={{ marginTop: 4 }}>
All / GridSmart URL or Sessionize script tag. Active events sync automatically every 15 minutes.
</div>
</div>
</div>
<div className="section">
<div className="section-head">
<span className="ico">🎟️</span>
<h4>Pretix</h4>
{pretixApiKey.trim() && pretixOrganizer.trim() && pretixEventSlug.trim() ? (
<span className="pill green">configured</span>
) : (
<span className="pill">not set</span>
)}
</div>
<div className="field">
<label>Pretix API key</label>
<input
className="input mono"
value={pretixApiKey}
onChange={(e) => setPretixApiKey(e.target.value)}
placeholder="Paste the Pretix API token"
autoComplete="off"
/>
<div className="muted small" style={{ marginTop: 4 }}>
The Sessionize API URL (e.g. <code>…/api/v2/&lt;id&gt;/view/All</code>). Used by the
“Run sync” button. You can also import the .xlsx export in the Interfaces menu.
Paste the token — the organizers + events below load automatically. The key is stored
with this event and stays visible here.
</div>
</div>
{pretixApiKey.trim() && pretixLoading && (
<div className="muted small">Loading Pretix organizers…</div>
)}
{pretixApiKey.trim() && pretixError && (
<div className="pill red" style={{ display: 'inline-block', alignSelf: 'flex-start' }}>
{pretixError}
</div>
)}
{pretixOptions && (
<div className="grid-2">
<div className="field">
<label>Pretix organizer</label>
<select
className="input"
value={pretixOrganizer}
onChange={(e) => {
setPretixOrganizer(e.target.value);
setPretixEventSlug('');
}}
>
<option value="">— select —</option>
{pretixOptions.organizers.map((o) => (
<option key={o.slug} value={o.slug}>
{o.name} ({o.slug})
</option>
))}
</select>
</div>
<div className="field">
<label>Pretix event slug</label>
<select
className="input"
value={pretixEventSlug}
onChange={(e) => setPretixEventSlug(e.target.value)}
disabled={!pretixOrganizer}
>
<option value="">— select —</option>
{(pretixOptions.organizers.find((o) => o.slug === pretixOrganizer)?.events || []).map(
(ev) => (
<option key={ev.slug} value={ev.slug}>
{ev.name} ({ev.slug})
</option>
),
)}
</select>
</div>
</div>
)}
<div className="muted small" style={{ maxWidth: 640 }}>
The sidecar syncs paid Pretix tickets for this event every minute using the key above.
</div>
</div>
<div className="field">
@@ -257,6 +519,45 @@ function EventModal({
<Toggle checked={realtimeClock} onChange={setRealtimeClock} label={realtimeClock ? 'On' : 'Off'} />
</div>
</div>
<div className="field">
<div className="row between" style={{ alignItems: 'center' }}>
<div>
<label>Talk networking bonus</label>
<div className="muted small" style={{ marginTop: 2, maxWidth: 420 }}>
Points each party earns when two people who were checked into the same talk accept a
connection. <b>0 disables</b> the bonus (the +5 connection award still applies).
</div>
</div>
<input
className="input mono"
type="number"
min={0}
max={10}
step={1}
style={{ width: 84, textAlign: 'center' }}
value={Number.isFinite(talkBonus) ? talkBonus : 0}
onChange={(e) => setTalkBonus(parseInt(e.target.value, 10) || 0)}
/>
</div>
</div>
<div className="field">
<div className="row between" style={{ alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
<div>
<label id="event-badge-copies-label">Badge copies on welcome check-in</label>
<div className="muted small" style={{ marginTop: 2, maxWidth: 420 }}>
How many labels print when an attendee is welcomed in at the front desk.
Manual reprints from the Registrations view always print one.
The same control lives in Settings for the active event.
</div>
</div>
<BadgeCopiesPicker
value={clampBadgeCopies(badgeCopies)}
onChange={setBadgeCopies}
disabled={busy}
labelId="event-badge-copies-label"
/>
</div>
</div>
</Modal>
);
}
+252 -13
View File
@@ -1,6 +1,22 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { getAllEvents, getSidecarStatus, getSyncRuns, importSessionizeExcel, runSessionizeSync } from '../lib/api';
import type { Event, ExcelSyncResult, SidecarStatus, SyncResult, SyncRun } from '../lib/types';
import {
getAllEvents,
getPretixRuns,
getSidecarStatus,
getSyncRuns,
importSessionizeExcel,
runPretixSync,
runSessionizeSync,
} from '../lib/api';
import type {
Event,
ExcelSyncResult,
PretixRun,
PretixSyncResult,
SidecarStatus,
SyncResult,
SyncRun,
} from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner } from '../components/ui';
@@ -18,6 +34,11 @@ export function Interfaces() {
const [excelFile, setExcelFile] = useState<File | null>(null);
const [excelBusy, setExcelBusy] = useState(false);
const [excelResult, setExcelResult] = useState<ExcelSyncResult | null>(null);
const [pretixRuns, setPretixRuns] = useState<SyncRun[]>([]);
const [pretixRunning, setPretixRunning] = useState(false);
const [pretixResult, setPretixResult] = useState<PretixSyncResult | null>(null);
const [sessionizeLogsOpen, setSessionizeLogsOpen] = useState(false);
const [pretixLogsOpen, setPretixLogsOpen] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
const loadableEvents = events.filter((e) => e.sessionize_endpoint);
@@ -52,13 +73,24 @@ export function Interfaces() {
}
}
async function loadPretixRuns(eventId: string) {
try {
setPretixRuns(await getPretixRuns(eventId));
} catch {
setPretixRuns([]);
}
}
useEffect(() => {
load();
loadStatus();
}, []);
useEffect(() => {
if (selectedId) loadRuns(selectedId);
if (selectedId) {
loadRuns(selectedId);
loadPretixRuns(selectedId);
}
}, [selectedId]);
// Poll the sidecar status while a sync is running (the run call is blocking,
@@ -67,10 +99,10 @@ export function Interfaces() {
loadStatus();
}, []);
useEffect(() => {
if (!running) return;
if (!running && !pretixRunning) return;
const t = setInterval(pollStatus, 3000);
return () => clearInterval(t);
}, [running, pollStatus]);
}, [running, pretixRunning, pollStatus]);
async function runSync() {
if (!selectedId) return;
@@ -87,6 +119,21 @@ export function Interfaces() {
}
}
async function runPretixNow() {
if (!selectedId) return;
setPretixRunning(true);
try {
const res = await runPretixSync(selectedId);
setPretixResult(res);
await Promise.all([load(), loadStatus(), loadPretixRuns(selectedId)]);
push('success', 'Pretix sync finished');
} catch (e) {
push('error', e instanceof Error ? e.message : 'Pretix sync failed');
} finally {
setPretixRunning(false);
}
}
async function importExcel() {
if (!selectedId || !excelFile) return;
setExcelBusy(true);
@@ -239,13 +286,147 @@ export function Interfaces() {
</div>
</div>
{/* Recent runs (audit) */}
<div className="card">
<h2 className="h2">📜 Recent runs {selected ? `— ${selected.name}` : ''}</h2>
{runs.length === 0 ? (
<Empty icon="📜" text="No sync runs recorded for this event yet." />
{/* Pretix */}
<div className="card" style={{ marginBottom: 18 }}>
<h2 className="h2">🎟 Pretix</h2>
<div style={{ marginBottom: 12 }}>
{status?.pretixConfigured === false ? (
<span className="pill amber" style={{ display: 'inline-block', padding: '8px 12px' }}>
Pretix not configured (no API key on the sidecar)
</span>
) : (
<div className="table-wrap">
<div className="muted small" style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<span>
Pretix auto-sync: every {status?.pretixIntervalMs ? status.pretixIntervalMs / 1000 : 60}s
</span>
{status?.lastPretixRun && (
<span>
last run {fmtTime(status.lastPretixRun.finished_at)} —{' '}
<span
className={`pill ${
status.lastPretixRun.status === 'success'
? 'green'
: status.lastPretixRun.status === 'skipped'
? 'amber'
: 'red'
}`}
>
{status.lastPretixRun.status}
</span>
{status.lastPretixRun.status === 'success' && (
<span className="muted">
{' '}
· {status.lastPretixRun.orders ?? 0} orders · {status.lastPretixRun.attendees ?? 0}{' '}
attendees · {status.lastPretixRun.skipped ?? 0} skipped
</span>
)}
{(status.lastPretixRun.status === 'error' || status.lastPretixRun.status === 'skipped') &&
(status.lastPretixRun.error || status.lastPretixRun.reason) && (
<span className="muted"> · {status.lastPretixRun.error || status.lastPretixRun.reason}</span>
)}
</span>
)}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
<select
className="input"
style={{ maxWidth: 320 }}
value={selectedId}
onChange={(e) => setSelectedId(e.target.value)}
>
{events.map((e) => (
<option key={e.id} value={e.id}>
{e.name}
</option>
))}
</select>
<button className="btn primary" disabled={pretixRunning || !selectedId} onClick={runPretixNow}>
{pretixRunning ? 'Syncing…' : 'Run Pretix now'}
</button>
</div>
</div>
{/* Recent Pretix runs (audit) — collapsible, collapsed by default */}
<CollapsibleRuns
icon="🎟"
title="Recent Pretix runs"
eventName={selected?.name}
open={pretixLogsOpen}
onToggle={() => setPretixLogsOpen((v) => !v)}
runs={pretixRuns}
emptyText="No Pretix sync runs recorded for this event yet."
/>
{/* Recent Sessionize runs (audit) — collapsible, collapsed by default */}
<CollapsibleRuns
icon="📜"
title="Recent runs"
eventName={selected?.name}
open={sessionizeLogsOpen}
onToggle={() => setSessionizeLogsOpen((v) => !v)}
runs={runs}
emptyText="No sync runs recorded for this event yet."
/>
{result && <SyncResultModal result={result} onClose={() => setResult(null)} />}
{excelResult && <ExcelResultModal result={excelResult} onClose={() => setExcelResult(null)} />}
{pretixResult && <PretixResultModal result={pretixResult} onClose={() => setPretixResult(null)} />}
</div>
);
}
/** A collapsible "recent runs" audit card. Collapsed by default. */
function CollapsibleRuns({
icon,
title,
eventName,
open,
onToggle,
runs,
emptyText,
}: {
icon: string;
title: string;
eventName?: string;
open: boolean;
onToggle: () => void;
runs: SyncRun[];
emptyText: string;
}) {
return (
<div className="card" style={{ marginBottom: 18 }}>
<button
type="button"
onClick={onToggle}
style={{
display: 'flex',
width: '100%',
alignItems: 'center',
justifyContent: 'space-between',
gap: 10,
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 0,
textAlign: 'left',
}}
aria-expanded={open}
>
<h2 className="h2" style={{ margin: 0 }}>
{icon} {title}
{eventName ? ` — ${eventName}` : ''}
</h2>
<span className="muted small" style={{ whiteSpace: 'nowrap' }}>
{runs.length} run{runs.length === 1 ? '' : 's'} {open ? '▾' : '▸'}
</span>
</button>
{open && (
runs.length === 0 ? (
<Empty icon={icon} text={emptyText} />
) : (
<div className="table-wrap" style={{ marginTop: 12 }}>
<table className="data">
<thead>
<tr>
@@ -277,12 +458,70 @@ export function Interfaces() {
</tbody>
</table>
</div>
)
)}
</div>
);
}
{result && <SyncResultModal result={result} onClose={() => setResult(null)} />}
{excelResult && <ExcelResultModal result={excelResult} onClose={() => setExcelResult(null)} />}
function PretixResultModal({ result, onClose }: { result: PretixRun; onClose: () => void }) {
const s = result.summary;
return (
<Modal
open
title={`Pretix sync — ${result.event_name ?? result.event_id}`}
onClose={onClose}
footer={
<button className="btn primary" onClick={onClose}>
Close
</button>
}
>
{result.status === 'error' || result.status === 'skipped' ? (
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
{result.error ?? result.reason ?? 'Pretix sync failed'}
</div>
) : (
<>
<div className="stat-grid">
<div className="stat">
<div className="val">{result.orders ?? 0}</div>
<div className="lbl">Orders</div>
</div>
<div className="stat">
<div className="val">{result.attendees ?? 0}</div>
<div className="lbl">Attendees</div>
</div>
<div className="stat">
<div className="val">{s?.created ?? 0}</div>
<div className="lbl">Created</div>
</div>
<div className="stat">
<div className="val">{s?.updated ?? 0}</div>
<div className="lbl">Updated</div>
</div>
<div className="stat">
<div className="val">{result.skipped ?? 0}</div>
<div className="lbl">Skipped</div>
</div>
</div>
{s && s.errors.length > 0 && (
<div style={{ marginTop: 12 }}>
<div className="pill red" style={{ display: 'inline-block', marginBottom: 8 }}>
{s.errors.length} error(s)
</div>
<ul style={{ margin: 0, paddingLeft: 18 }}>
{s.errors.map((e, i) => (
<li key={i} className="small">
{e}
</li>
))}
</ul>
</div>
)}
</>
)}
</Modal>
);
}
+425
View File
@@ -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>
);
}
+219
View File
@@ -0,0 +1,219 @@
import { useEffect, useRef, useState } from 'react';
import confetti from 'canvas-confetti';
import { RotateCcw, RotateCw } from 'lucide-react';
import {
drawRaffleWinner,
getActiveEvent,
getRafflePool,
getRaffleWinners,
resetRaffle,
} from '../lib/api';
import type { Event, RafflePoolEntry, RaffleWinner } from '../lib/types';
import { Empty, Spinner } from '../components/ui';
import { useSilentRefresh } from '../lib/useSilentRefresh';
const DEFAULT_PICKS = 5;
// Roulette timing: names flash fast, then decelerate onto the server's winner.
const SPIN_STEPS = 22;
const SPIN_MIN_MS = 45;
const SPIN_MAX_MS = 520;
// Celebrate each drawn winner with a confetti burst (skipped for reduced motion).
function celebrate() {
confetti({ particleCount: 160, spread: 80, startVelocity: 45, origin: { y: 0.6 }, disableForReducedMotion: true });
confetti({ particleCount: 60, angle: 60, spread: 60, origin: { x: 0, y: 0.7 }, disableForReducedMotion: true });
confetti({ particleCount: 60, angle: 120, spread: 60, origin: { x: 1, y: 0.7 }, disableForReducedMotion: true });
}
export function Raffle() {
const [event, setEvent] = useState<Event | null>(null);
const [pool, setPool] = useState<RafflePoolEntry[]>([]);
const [winners, setWinners] = useState<RaffleWinner[]>([]);
const [picks, setPicks] = useState(DEFAULT_PICKS);
const [loaded, setLoaded] = useState(false);
const [spinning, setSpinning] = useState(false);
const [currentName, setCurrentName] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const running = useRef(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const cancelledRef = useRef(false);
async function load(silent: boolean) {
try {
const ev = await getActiveEvent();
if (cancelledRef.current) return;
setEvent(ev);
if (!ev) { setLoaded(true); return; }
const [entries, drawn] = await Promise.all([getRafflePool(), getRaffleWinners()]);
if (cancelledRef.current) return;
setPool(entries);
setWinners(drawn);
setLoaded(true);
} catch (cause) {
// A failed background tick must not replace the draw screen with the error
// state; the spinner would have already cleared.
if (!silent && !cancelledRef.current) setError(cause instanceof Error ? cause.message : 'Failed to load raffle');
}
}
useEffect(() => {
cancelledRef.current = false;
void load(false);
return () => { cancelledRef.current = true; if (timer.current) clearTimeout(timer.current); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Keep the pool honest if another admin draws from a second machine. Never
// while the wheel is spinning — the animation reads `pool` and `finish`
// reconciles against it, so a swap mid-spin would drop the winner.
useSilentRefresh(() => load(true), { enabled: loaded && !spinning });
const total = winners.length + pool.length;
const remainingForRun = Math.max(0, picks - winners.length);
const canDraw = loaded && !spinning && !!event && winners.length < picks && pool.length > 0;
function finish(winner: RaffleWinner) {
setWinners((current) => [...current, winner]);
setPool((current) => current.filter((entry) => entry.contact_email !== winner.contact_email));
setCurrentName(winner.full_name);
running.current = false;
setSpinning(false);
celebrate();
}
function animateTo(winner: RaffleWinner) {
const others = pool.filter((entry) => entry.contact_email !== winner.contact_email).map((entry) => entry.full_name);
const sequence: string[] = [];
for (let step = 0; step < SPIN_STEPS; step += 1) {
sequence.push(others.length > 0 ? others[Math.floor(Math.random() * others.length)] : winner.full_name);
}
sequence.push(winner.full_name);
let index = 0;
const tick = () => {
setCurrentName(sequence[index]);
index += 1;
if (index < sequence.length) {
const progress = index / sequence.length;
timer.current = setTimeout(tick, SPIN_MIN_MS + Math.pow(progress, 2.6) * (SPIN_MAX_MS - SPIN_MIN_MS));
} else {
finish(winner);
}
};
tick();
}
async function draw() {
if (running.current) return;
running.current = true;
setSpinning(true);
setError(null);
try {
const winner = await drawRaffleWinner();
animateTo(winner);
} catch (cause) {
setError(cause instanceof Error ? cause.message : 'Draw failed');
running.current = false;
setSpinning(false);
}
}
async function reset() {
if (spinning) return;
setError(null);
try {
await resetRaffle();
const [entries, drawn] = await Promise.all([getRafflePool(), getRaffleWinners()]);
setPool(entries);
setWinners(drawn);
setCurrentName(null);
} catch (cause) {
setError(cause instanceof Error ? cause.message : 'Reset failed');
}
}
if (error && !loaded) return <Empty icon="⚠️" text={error} />;
if (!loaded) return <div className="loading-screen"><Spinner /></div>;
return (
<div>
<div className="page-head">
<div>
<h1>Raffle</h1>
<div className="sub">
{event ? `${event.name} · ${total} eligible attendees` : 'No active event. Set an event active in the Events view first.'}
</div>
</div>
</div>
{!event ? (
<div className="card"><Empty icon="🎟️" text="No active event. Set an event active in the Events view first." /></div>
) : (
<div className="raffle">
<section className="raffle-stage card" aria-label="Raffle roulette">
<div className="raffle-name" role="status" aria-live="polite">
{currentName ?? 'Press Spin to draw a winner'}
</div>
<div className="raffle-controls">
<label className="field raffle-picks">
<span>Picks per run</span>
<input
className="input"
type="number"
min={1}
max={Math.max(1, total)}
value={picks}
disabled={spinning || winners.length > 0}
onChange={(e) => setPicks(Math.max(1, Number(e.target.value) || 1))}
/>
</label>
<button className="btn primary" onClick={draw} disabled={!canDraw}>
<RotateCw size={16} aria-hidden="true" className={spinning ? 'raffle-spin-icon' : undefined} />
{spinning ? 'Spinning...' : winners.length >= picks ? 'Run complete' : pool.length === 0 ? 'No attendees left' : 'Spin'}
</button>
<button className="btn" onClick={reset} disabled={spinning || winners.length === 0}>
<RotateCcw size={16} aria-hidden="true" />New run
</button>
</div>
<p className="muted small" role="status">
Winners this run: {winners.length} of {picks}
{winners.length < picks && pool.length === 0 && ' · no eligible attendees left'}
</p>
{error && <p className="feedback-error" role="alert">{error}</p>}
<p className="muted small">
Excludes staff/Admin and the leaderboard top 3. Everyone can win only once per run.
</p>
</section>
<section className="card" aria-label="Raffle winners">
<div className="feedback-summary-head">
<h2 className="h2">Winners</h2>
<span className="muted small">{remainingForRun > 0 ? `${remainingForRun} to go` : 'Run complete'}</span>
</div>
{winners.length === 0 ? (
<Empty icon="🏆" text="No winners yet. Spin the roulette to draw the first attendee." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr><th>#</th><th>Attendee</th><th>Points</th><th>When</th></tr>
</thead>
<tbody>
{winners.map((w) => (
<tr key={w.contact_email}>
<td className="muted">{w.draw_number}</td>
<td style={{ fontWeight: 600 }}>{w.full_name}</td>
<td>{w.points}</td>
<td className="muted">{new Date(w.drawn_at).toLocaleTimeString()}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</div>
)}
</div>
);
}
+607 -43
View File
@@ -1,23 +1,40 @@
import { useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
adjustPoints,
createRegistration,
deleteContacts,
enqueueBadgePrint,
getBadgeLayouts,
getAllContacts,
getAllEvents,
getActiveEvent,
getRegistrations,
getSponsors,
setCheckedIn,
mergeTickets,
setRegistrationType,
upsertSponsor,
} from '../lib/api';
import type { Contact, Event, Registration, RegistrationType, Sponsor, SponsorType } from '../lib/types';
import type { BadgeLayout, BadgeSample, Contact, Event, Registration, RegistrationType, Sponsor, SponsorType } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Avatar, Empty, Modal, QrImage, Spinner, Toggle, TypeBadge } from '../components/ui';
import { useAuth } from '../context/AuthContext';
import { Avatar, ColumnFilter, Empty, Modal, QrImage, Spinner, Toggle, Tooltip, TypeBadge, type ColumnFilterOption } from '../components/ui';
import { BadgePagePreview, fitScale } from '../components/BadgeRender';
import { activeStations, aggregateState, usePrintStatus } from '../lib/printStatus';
import { useSilentRefresh } from '../lib/useSilentRefresh';
const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor'];
// Multi-select column filters are Excel-style: an empty selection means "all".
const ynOptions = (rows: Registration[], fn: (r: Registration) => boolean): ColumnFilterOption[] => [
{ value: 'yes', label: 'Yes', count: rows.filter(fn).length },
{ value: 'no', label: 'No', count: rows.filter((r) => !fn(r)).length },
];
export function Registrations() {
const { push } = useToast();
const [event, setEvent] = useState<Event | null>(null);
const { contact: me } = useAuth();
const [events, setEvents] = useState<Event[]>([]);
const [selectedId, setSelectedId] = useState('');
const [loaded, setLoaded] = useState(false);
const [contacts, setContacts] = useState<Contact[]>([]);
const [registrations, setRegistrations] = useState<Registration[]>([]);
@@ -26,17 +43,83 @@ export function Registrations() {
const [adding, setAdding] = useState(false);
const [qrFor, setQrFor] = useState<Registration | null>(null);
const [sponsorFor, setSponsorFor] = useState<Registration | null>(null);
const [busy, setBusy] = useState(false);
const [deletingAll, setDeletingAll] = useState(false);
const [mergeFor, setMergeFor] = useState<Registration | null>(null);
const [badgeFor, setBadgeFor] = useState<Registration | null>(null);
// Points adjustment. It lives here, not in Contacts, because the value sits
// on the pass (registrations.points) that this table manages row by row.
const [pointsFor, setPointsFor] = useState<Registration | null>(null);
const [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]);
const [printingIds, setPrintingIds] = useState<Set<string>>(new Set());
// Rows with a write in flight (check-in toggle or pass-type change). Per-row
// instead of one global flag: a slow request must never freeze the whole
// table, and it must be obvious WHICH row is working.
const [busyIds, setBusyIds] = 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 [fTicket, setFTicket] = useState<string[]>([]);
const [fCheckedIn, setFCheckedIn] = useState<string[]>([]);
const selectedEventId = useRef(selectedId);
selectedEventId.current = selectedId;
// Mirror of busyIds for the background refresher, which runs outside render
// and must read the CURRENT set of in-flight rows, not a captured one.
const busyIdsRef = useRef(busyIds);
busyIdsRef.current = busyIds;
const event = events.find((e) => e.id === selectedId) ?? null;
const eventRegistrations = registrations.filter((registration) => registration.event_id === selectedId);
const ticketed = eventRegistrations.filter((registration) => registration.qr_token?.trim());
// A badge is "configured" once a layout for this event actually has elements;
// an empty layout would render a blank white badge, so treat it as unconfigured.
const badgeConfigured = badgeLayouts.some((l) => Array.isArray(l.elements) && l.elements.length > 0);
async function reloadRegistrations(eventId: string) {
const rows = await getRegistrations(eventId);
if (selectedEventId.current === eventId) setRegistrations(rows);
}
/**
* Background refresh: pull fresh rows but KEEP the current order and leave any
* row with a write in flight alone. The list is sorted by points, so simply
* calling reloadRegistrations() every few seconds would make rows slide around
* under the cursor — the exact bug the per-row toggle fixed. New rows appear
* at the end; removed rows disappear.
*/
const silentRefresher = useCallback(async () => {
const eventId = selectedEventId.current;
if (!eventId) return;
const rows = await getRegistrations(eventId);
if (selectedEventId.current !== eventId) return;
const pending = busyIdsRef.current;
setRegistrations((current) => {
const fresh = new Map(rows.map((row) => [row.id, row]));
const kept: Registration[] = [];
for (const row of current) {
const next = fresh.get(row.id);
if (!next) continue; // removed elsewhere (e.g. a ticket merge)
// A row mid-write has an optimistic value the server does not agree with
// yet; overwriting it would make the checkbox flicker back.
kept.push(pending.has(row.id) ? row : next);
fresh.delete(row.id);
}
for (const row of rows) if (fresh.has(row.id)) kept.push(row);
return kept;
});
}, []);
// Background freshness: poll while the tab is visible, and settle again 500 ms
// after any write so the table self-heals to what the database really holds.
const { refreshSoon } = useSilentRefresh(silentRefresher, { enabled: loaded });
async function load() {
try {
const ev = await getActiveEvent();
setEvent(ev);
if (ev) {
const [c, r] = await Promise.all([getAllContacts(), getRegistrations(ev.id)]);
setContacts(c);
setRegistrations(r);
}
const [evs, active] = await Promise.all([getAllEvents(), getActiveEvent()]);
setEvents(evs);
// Default to the active event; otherwise the first event.
const def = active?.id ?? evs[0]?.id ?? '';
setSelectedId((cur) => cur || def);
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
@@ -47,27 +130,130 @@ export function Registrations() {
load();
}, []);
// Load the selected event's contacts + registrations whenever it changes.
useEffect(() => {
if (!selectedId) return;
let cancelled = false;
(async () => {
try {
const [c, r] = await Promise.all([getAllContacts(), getRegistrations(selectedId)]);
if (!cancelled) {
setContacts(c);
setRegistrations(r);
}
} catch (e) {
if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
}
})();
// Badge layouts are best-effort: a failure just leaves the Badge buttons
// disabled (treated as "not configured") rather than breaking the list.
getBadgeLayouts(selectedId)
.then((ls) => { if (!cancelled) setBadgeLayouts(ls); })
.catch(() => { if (!cancelled) setBadgeLayouts([]); });
return () => {
cancelled = true;
};
}, [selectedId]);
async function deleteAllContactsForEvent() {
if (!event) return;
// Never delete the contact you're logged in as (it would log you out).
const emails = [...new Set(registrations.map((r) => r.contact_email))].filter(
(e) => e !== me?.email,
);
if (emails.length === 0) {
push('error', 'No other contacts registered for this event to delete.');
return;
}
if (
!confirm(
`Delete ${emails.length} contact(s) registered for "${event.name}"? Their registrations for this event are removed (the contact is deleted entirely). Your own account is kept.`,
)
)
return;
setDeletingAll(true);
try {
await deleteContacts(emails);
await load();
push('success', `Deleted ${emails.length} contact(s) for ${event.name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setDeletingAll(false);
}
}
const byEmail = useMemo(() => new Map(contacts.map((c) => [c.email, c])), [contacts]);
const filtered = useMemo(() => {
if (!registrations) return [];
// General search: first name, last name, email address or type.
const searched = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return registrations;
return registrations.filter((r) => {
const c = byEmail.get(r.contact_email);
const rows = registrations.filter((r) => r.event_id === selectedId);
if (!q) return rows;
return rows.filter((r) => {
const name = (byEmail.get(r.contact_email)?.full_name ?? '').toLowerCase();
return (
(c?.full_name ?? '').toLowerCase().includes(q) ||
name.split(/\s+/).some((part) => part.includes(q)) ||
name.includes(q) ||
r.contact_email.toLowerCase().includes(q) ||
r.type.toLowerCase().includes(q)
);
});
}, [registrations, query, byEmail]);
}, [registrations, query, byEmail, selectedId]);
const hasTicket = (r: Registration) => !!r.qr_token?.trim();
const passType = (r: Registration) => fType.length === 0 || fType.includes(r.type);
const passTicket = (r: Registration) => fTicket.length === 0 || fTicket.includes(hasTicket(r) ? 'yes' : 'no');
const passCheckedIn = (r: Registration) => fCheckedIn.length === 0 || fCheckedIn.includes(r.checked_in ? 'yes' : 'no');
const filtered = useMemo(
() => searched.filter((r) => passType(r) && passTicket(r) && passCheckedIn(r)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[searched, fType, fTicket, fCheckedIn],
);
// Option counts follow Excel: each column counts what the OTHER filters leave.
const typeCounts = new Map<string, number>();
for (const r of searched.filter((r) => passTicket(r) && passCheckedIn(r))) typeCounts.set(r.type, (typeCounts.get(r.type) ?? 0) + 1);
const typeOptions = [...typeCounts.entries()]
.sort((a, b) => TYPES.indexOf(a[0] as RegistrationType) - TYPES.indexOf(b[0] as RegistrationType))
.map(([value, count]) => ({ value, label: value, count }));
const ticketOptions = ynOptions(searched.filter((r) => passType(r) && passCheckedIn(r)), hasTicket);
const checkedInOptions = ynOptions(searched.filter((r) => passType(r) && passTicket(r)), (r) => r.checked_in);
/**
* UI mirror of the SQL predicate `_points_eligible`: a registration earns
* points unless it is typed `staff`, its contact is an Admin, or the email is
* on the organiser domain. Kept next to the table so the two cannot drift
* silently — if that function changes, this one must change with it.
*/
const canEarnPoints = useCallback(
(r: Registration) =>
r.type !== 'staff' && !byEmail.get(r.contact_email)?.is_admin && !/@appe\.at$/i.test(r.contact_email),
[byEmail],
);
// Run a per-row write: mark that row busy, and clear it when settled. Only
// the touched row is disabled — the rest of the table stays usable.
async function withRowBusy(id: string, run: () => Promise<void>) {
if (busyIds.has(id)) return;
setBusyIds((ids) => new Set(ids).add(id));
try {
await run();
} finally {
setBusyIds((ids) => {
const next = new Set(ids);
next.delete(id);
return next;
});
}
}
async function changeType(r: Registration, type: RegistrationType) {
setBusy(true);
await withRowBusy(r.id, async () => {
try {
await setRegistrationType(r.contact_email, type);
await load();
// Update the row in place — a full reload would reorder the table and
// make the row you just touched jump somewhere else.
setRegistrations((rows) => rows.map((row) => (row.id === r.id ? { ...row, type } : row)));
push('success', `${byEmail.get(r.contact_email)?.full_name ?? r.contact_email} → ${type}`);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Update failed';
@@ -78,20 +264,56 @@ export function Registrations() {
} else {
push('error', msg);
}
} finally {
setBusy(false);
}
});
}
async function toggleCheckedIn(r: Registration, v: boolean) {
setBusy(true);
await withRowBusy(r.id, async () => {
// Optimistically flip just this row's checkbox; the row keeps its place.
setRegistrations((rows) => rows.map((row) => (row.id === r.id ? { ...row, checked_in: v } : row)));
try {
await setCheckedIn(r.id, v);
await load();
const { removed, added } = await setCheckedIn(r.id, v);
// Patch this row's points from the RPC's own numbers. We deliberately do
// NOT reload the list: it is sorted by points, so a reload moves the row
// you just toggled somewhere else on every click.
const delta = added - removed;
setRegistrations((rows) => rows.map((row) => (row.id === r.id
? { ...row, checked_in: v, points: Math.max(0, row.points + delta) }
: row)));
const name = byEmail.get(r.contact_email)?.full_name ?? r.contact_email;
if (removed > 0) push('success', `${name}: un-checked in, −${removed} check-in pts removed`);
else if (added > 0) push('success', `${name}: checked in, +${added} check-in pts restored`);
else push('success', `${name}: ${v ? 'checked in' : 'un-checked in'}`);
} catch (e) {
// Revert to the committed state — never leave the checkbox lying.
setRegistrations((rows) => rows.map((row) => (row.id === r.id
? { ...row, checked_in: r.checked_in, points: r.points }
: row)));
push('error', e instanceof Error ? e.message : 'Update failed');
}
// Pull the truth shortly after, in the background: the row may also have
// picked up scans from the front desk or another device.
refreshSoon();
});
}
// 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 {
setBusy(false);
setPrintingIds((ids) => {
const next = new Set(ids);
next.delete(r.id);
return next;
});
}
}
@@ -109,11 +331,11 @@ export function Registrations() {
<div className="page-head">
<div>
<h1>Registrations</h1>
<div className="sub">Ticket types and check-ins for the active event.</div>
<div className="sub">Ticket types and check-ins per event.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No active event. Set an event active in the Events view first." />
<Empty icon="📅" text="No events yet. Create one in the Events view first." />
</div>
</div>
);
@@ -125,20 +347,39 @@ export function Registrations() {
<div>
<h1>Registrations</h1>
<div className="sub">
{event.name} · {registrations.length} registrations · {registrations.filter((r) => r.checked_in).length} checked in.
<strong>{event.name}</strong>
{event.is_active && <span className="pill green" style={{ marginLeft: 8 }}>active</span>} ·{' '}
{ticketed.length} tickets · {ticketed.filter((r) => r.checked_in).length} checked in · {eventRegistrations.length - ticketed.length} without tickets.
</div>
</div>
<div className="row" style={{ gap: 10 }}>
<select
className="input"
style={{ maxWidth: 280 }}
value={selectedId}
disabled={mergeFor !== null}
onChange={(e) => setSelectedId(e.target.value)}
>
{events.map((e) => (
<option key={e.id} value={e.id}>
{e.name}
{e.is_active ? ' (active)' : ''}
</option>
))}
</select>
<input
className="input"
style={{ maxWidth: 240 }}
placeholder="Search name, email, type…"
style={{ maxWidth: 220 }}
placeholder="Search first name, last name, email, type…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button className="btn primary" onClick={() => setAdding(true)}>
<button className="btn" onClick={() => setAdding(true)}>
+ Register
</button>
<button className="btn danger" disabled={deletingAll} onClick={deleteAllContactsForEvent}>
{deletingAll ? 'Deleting…' : '🗑 Delete all contacts for this event'}
</button>
</div>
</div>
@@ -147,17 +388,18 @@ export function Registrations() {
<thead>
<tr>
<th>Contact</th>
<th>Type</th>
<th>QR token</th>
<th>Checked in</th>
<th>Type <ColumnFilter label="Type" options={typeOptions} selected={fType} onChange={setFType} /></th>
<th>QR token <ColumnFilter label="Ticket" options={ticketOptions} selected={fTicket} onChange={setFTicket} /></th>
<th>Checked in <ColumnFilter label="Checked in" options={checkedInOptions} selected={fCheckedIn} onChange={setFCheckedIn} /></th>
<th style={{ textAlign: 'right' }}>Points</th>
</tr>
</thead>
<tbody>
{filtered.map((r) => {
const c = byEmail.get(r.contact_email);
const rowBusy = busyIds.has(r.id);
return (
<tr key={r.id}>
<tr key={r.id} className={rowBusy ? 'row-busy' : undefined}>
<td>
<div className="cell-person">
<Avatar name={c?.full_name ?? r.contact_email} id={r.contact_email} size={38} fs={13} />
@@ -174,7 +416,7 @@ export function Registrations() {
className="input"
style={{ width: 130, padding: '6px 10px', fontSize: 12.5 }}
value={r.type}
disabled={busy}
disabled={rowBusy}
onChange={(e) => changeType(r, e.target.value as RegistrationType)}
>
{TYPES.map((t) => (
@@ -188,16 +430,73 @@ export function Registrations() {
<td>
<div className="row" style={{ gap: 8 }}>
<span className="mono small">{r.qr_token ?? '—'}</span>
<button className="btn small" onClick={() => setQrFor(r)}>
{r.qr_token?.trim() && <button className="btn small" onClick={() => setQrFor(r)}>
QR
</button>}
{badgeConfigured ? (
<button className="btn small" onClick={() => setBadgeFor(r)} title="Preview this attendee's badge">
Badge
</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>
Badge
</button>
</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' && (
<button className="btn small" onClick={() => setMergeFor(r)}>
Merge tickets
</button>
)}
</div>
</td>
<td>
<Toggle checked={r.checked_in} onChange={(v) => toggleCheckedIn(r, v)} />
<div className="row" style={{ gap: 8 }}>
<Toggle checked={r.checked_in} disabled={rowBusy} onChange={(v) => toggleCheckedIn(r, v)} />
{/* Per-row in-flight affordance: the switch is optimistic,
so show that the save is still travelling. */}
{rowBusy && <span className="row-saving" data-testid={`saving-${r.id}`}>Saving…</span>}
</div>
</td>
<td style={{ textAlign: 'right' }}>
{/* Staff and organiser accounts never earn points (the DB
guard _points_eligible drops every award). Say so rather
than showing a bare 0, which reads like a broken
check-in. Mirrors the SQL predicate exactly. */}
{canEarnPoints(r) ? (
<div className="row" style={{ gap: 8, justifyContent: 'flex-end' }}>
<span className="pts">{r.points}</span>
{event.is_active ? (
<button className="btn small" data-testid={`points-adjust-${r.id}`} onClick={() => setPointsFor(r)}>
Points
</button>
) : (
<Tooltip title="Only the active event" content="adjust_points always lands on the active event’s pass. Adjusting a different event’s row would silently change the wrong person’s other pass, so points can only be adjusted while the active event is selected.">
<button className="btn small" disabled>
Points
</button>
</Tooltip>
)}
</div>
) : (
<Tooltip title="Does not earn points" content="Staff and organiser accounts (type staff, Admin contacts, or an @appe.at address) are excluded from points and the leaderboard on purpose.">
<span className="pts pts-exempt" data-testid={`points-exempt-${r.id}`}>
— <span className="pts-exempt-mark">no points</span>
</span>
</Tooltip>
)}
</td>
</tr>
);
@@ -214,12 +513,28 @@ export function Registrations() {
onClose={() => setAdding(false)}
onSaved={async (msg) => {
setAdding(false);
await load();
await reloadRegistrations(event.id);
push('success', msg);
}}
/>
)}
{mergeFor && (
<MergeTicketsModal
source={mergeFor}
contacts={byEmail}
tickets={ticketed.filter((ticket) => ticket.id !== mergeFor.id && ticket.external_id?.trim())}
onClose={() => setMergeFor(null)}
onMerged={async (result) => {
setRegistrations((rows) => rows.filter((row) => row.id !== result.source_id).map((row) => row.id === result.target_id ? { ...row, type: result.type } : row));
try { await reloadRegistrations(mergeFor.event_id); }
catch { push('error', 'Merge saved; reload registrations to see the updated ticket.'); }
setMergeFor(null);
push('success', `Merged into ${result.target_email}; ${result.sessions_transferred} session assignment(s) transferred.`);
}}
/>
)}
{qrFor && (
<Modal
open
@@ -241,15 +556,51 @@ export function Registrations() {
</Modal>
)}
{pointsFor && (
<AdjustPointsModal
registration={pointsFor}
contact={byEmail.get(pointsFor.contact_email)}
onClose={() => setPointsFor(null)}
onSaved={(msg, appliedDelta, ok) => {
setPointsFor(null);
if (ok && appliedDelta !== null) {
// Patch in place — the list is sorted by points, a reload would
// slide this row somewhere else mid-edit (same rule as the
// check-in toggle). refreshSoon() settles the truth afterwards.
const rowId = pointsFor.id;
setRegistrations((rows) => rows.map((row) => (row.id === rowId
? { ...row, points: Math.max(0, row.points + appliedDelta) }
: row)));
refreshSoon();
}
push(ok ? 'success' : 'error', msg);
}}
/>
)}
{badgeFor && (
<BadgePreviewModal
registration={badgeFor}
contact={byEmail.get(badgeFor.contact_email)}
event={event}
layouts={badgeLayouts}
onClose={() => setBadgeFor(null)}
/>
)}
{sponsorFor && (
<SponsorLookupModal
registration={sponsorFor}
contact={byEmail.get(sponsorFor.contact_email)}
eventId={event.id}
onClose={() => setSponsorFor(null)}
onSaved={async (msg) => {
onSaved={(msg) => {
// The modal sets the registration type to sponsor; mirror it on the
// row. (Reloading events here never refreshed the rows, which left
// the type badge showing the old value.)
const savedId = sponsorFor.id;
setRegistrations((rows) => rows.map((row) => (row.id === savedId ? { ...row, type: 'sponsor' } : row)));
setSponsorFor(null);
await load();
push('success', msg);
}}
/>
@@ -258,6 +609,142 @@ export function Registrations() {
);
}
/** Renders the event's badge layout for one attendee, chosen from its layouts. */
function BadgePreviewModal({ registration, contact, event, layouts, onClose }: {
registration: Registration;
contact?: Contact;
event: Event;
layouts: BadgeLayout[];
onClose: () => void;
}) {
const hasContent = (l: BadgeLayout) => Array.isArray(l.elements) && l.elements.length > 0;
const [layoutName, setLayoutName] = useState(() => {
const def = (layouts.find((l) => l.is_default && hasContent(l)) ?? layouts.find(hasContent) ?? layouts[0]);
return def?.name ?? '';
});
const sample: BadgeSample = {
full_name: contact?.full_name ?? registration.contact_email,
email: registration.contact_email,
ticket_type: registration.type,
qr_token: registration.qr_token ?? '',
event_name: event.name,
company: event.company ?? '',
};
const layout = layouts.find((l) => l.name === layoutName) ?? null;
const name = contact?.full_name ?? registration.contact_email;
// Fit the badge to the stage's real width (responsive) and the viewport height.
const stageRef = useRef<HTMLDivElement>(null);
const [stageW, setStageW] = useState(0);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const measure = () => setStageW(el.clientWidth);
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, [layout]);
const maxH = Math.max(180, Math.min(420, Math.round(window.innerHeight * 0.45)));
const pxPerMm = layout && stageW > 0 ? fitScale(layout, stageW, maxH) : 0;
return (
<Modal
open
title={`Badge — ${name}`}
onClose={onClose}
footer={
<button className="btn primary" onClick={onClose}>
Done
</button>
}
>
{layouts.length === 0 && (
<Empty icon="🎫" text="No badge layout for this event yet. Design one in the Badges view." />
)}
{layouts.length > 0 && !layout && (
<Empty icon="🎫" text="This event's badge layout is empty. Add elements to it in the Badges view." />
)}
{layout && (
<>
{layouts.length > 1 && (
<label className="badge-field">
<span>Layout</span>
<select className="input" value={layoutName} onChange={(e) => setLayoutName(e.target.value)}>
{layouts.map((l) => (
<option key={l.id} value={l.name}>{l.name}{l.is_default ? ' ★' : ''}</option>
))}
</select>
</label>
)}
<div className="badge-preview-stage" ref={stageRef}>
{pxPerMm > 0 && <BadgePagePreview layout={layout} sample={sample} pxPerMm={pxPerMm} />}
</div>
<p className="muted small" style={{ textAlign: 'center' }}>
{layout.name} · {layout.page_width_mm} × {layout.page_height_mm} mm
</p>
</>
)}
</Modal>
);
}
function MergeTicketsModal({ source, contacts, tickets, onClose, onMerged }: {
source: Registration;
contacts: Map<string, Contact>;
tickets: Registration[];
onClose: () => void;
onMerged: (result: import('../lib/types').TicketMergeResult) => Promise<void>;
}) {
const [search, setSearch] = useState('');
const [selected, setSelected] = useState('');
const [saving, setSaving] = useState(false);
const [failure, setFailure] = useState('');
const sourceName = contacts.get(source.contact_email)?.full_name ?? source.contact_email;
const words = (name: string) => name.toLocaleLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').split(/[^a-z0-9]+/).filter(Boolean);
const sourceWords = words(sourceName);
const score = (ticket: Registration) => words(contacts.get(ticket.contact_email)?.full_name ?? '').filter((word) => sourceWords.includes(word)).length;
const options = tickets.filter((ticket) => `${contacts.get(ticket.contact_email)?.full_name ?? ''} ${ticket.contact_email}`.toLowerCase().includes(search.trim().toLowerCase()))
.sort((first, second) => score(second) - score(first) || first.contact_email.localeCompare(second.contact_email));
const target = tickets.find((ticket) => ticket.id === selected);
async function save() {
if (!target || saving) return;
setSaving(true);
setFailure('');
try { await onMerged(await mergeTickets(source.id, target.id)); }
catch (error) {
setFailure(error instanceof Error ? error.message : 'Merge failed');
setSaving(false);
}
}
return (
<Modal open title="Merge tickets" onClose={() => { if (!saving) onClose(); }} footer={
<>
<button className="btn" disabled={saving} onClick={onClose}>Cancel</button>
<button className="btn primary" disabled={!target || saving} onClick={save}>{saving ? 'Merging...' : 'Confirm merge'}</button>
</>
}>
<p><strong>{sourceName}</strong><br /><span className="muted">{source.contact_email}</span></p>
<label className="field">
<span>Destination ticket</span>
<input className="input" value={search} disabled={saving} placeholder="Search name or email" onChange={(change) => setSearch(change.target.value)} />
</label>
<div style={{ maxHeight: 280, overflowY: 'auto', marginTop: 12 }} role="radiogroup" aria-label="Destination ticket">
{options.map((ticket) => (
<label key={ticket.id} className="row" style={{ padding: '10px 0', gap: 10 }}>
<input type="radio" name="merge-ticket" disabled={saving} checked={selected === ticket.id} onChange={() => setSelected(ticket.id)} />
<span><strong>{contacts.get(ticket.contact_email)?.full_name ?? ticket.contact_email}</strong><br />{ticket.contact_email}{score(ticket) > 0 && <span className="pill green" style={{ marginLeft: 8 }}>Name match</span>}</span>
</label>
))}
{options.length === 0 && <p className="muted">No matching purchased tickets.</p>}
</div>
{target && <p>The ticket for <strong>{target.contact_email}</strong> keeps its QR, check-in and points. Session assignments and the {source.type} role transfer before the imported registration is deleted. Other events are unchanged.</p>}
{failure && <p role="alert" className="error">{failure}</p>}
</Modal>
);
}
function AddRegistrationModal({
contacts,
existing,
@@ -338,6 +825,83 @@ function AddRegistrationModal({
* 'sponsor' but no sponsor exists for that contact yet. Lets them create the
* sponsor (with a contact search) and then retry the type change.
*/
/**
* Adjust one attendee's points, from the row that owns the pass. Mirrors the
* old Contacts modal, minus the exemption note: rows that cannot earn points
* (_points_eligible mirror) never show the button, and the RPC re-checks the
* same predicate server-side. Only offered for the active event —
* adjust_points always targets the active event's pass.
*/
function AdjustPointsModal({
registration,
contact,
onClose,
onSaved,
}: {
registration: Registration;
contact?: Contact;
onClose: () => void;
onSaved: (msg: string, appliedDelta: number | null, ok: boolean) => void;
}) {
const [delta, setDelta] = useState('10');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
const name = contact?.full_name ?? registration.contact_email;
async function save() {
const d = parseInt(delta, 10);
if (Number.isNaN(d) || d === 0) return;
setBusy(true);
try {
await adjustPoints(registration.contact_email, d, reason.trim() || 'manual adjustment');
onSaved(`${d > 0 ? '+' : ''}${d} points for ${name}`, d, true);
onClose();
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Adjustment failed', null, false);
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Points — ${name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy} onClick={save} data-testid="adjust-points-apply">
{busy ? 'Applying…' : 'Apply'}
</button>
</>
}
>
<div className="row" style={{ justifyContent: 'center', gap: 16 }}>
<Avatar name={name} id={registration.contact_email} size={52} fs={18} />
<div>
<div style={{ fontWeight: 700 }}>{name}</div>
<div className="muted small">{registration.contact_email}</div>
</div>
</div>
<div className="field">
<label>Adjustment (use a negative number to subtract)</label>
<input className="input mono" type="number" value={delta} onChange={(e) => setDelta(e.target.value)} />
<span className="muted small">
Goes to this person’s pass in {registration.qr_token ? `ticket ${registration.qr_token}` : 'this registration'} —
the row you opened this from.
</span>
</div>
<div className="field">
<label>Reason (optional)</label>
<input className="input" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. prize, correction" />
</div>
</Modal>
);
}
function SponsorLookupModal({
registration,
contact,
+420
View File
@@ -0,0 +1,420 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import {
downloadReport,
exportEventReport,
getAllCheckins,
getAllConnections,
getAllContacts,
getAllEventFeedback,
getAllEvents,
getAllFeedback,
getAllPointsLog,
getLeaderboard,
getRegistrations,
getSessions,
} from '../lib/api';
import type {
Checkin,
Connection,
Contact,
Event,
EventFeedback,
Feedback,
LeaderboardRow,
PointsLogRow,
Registration,
Session,
} from '../lib/types';
import { useToast } from '../context/ToastContext';
import { SLOW_POLL_MS, useSilentRefresh } from '../lib/useSilentRefresh';
import { Empty, Spinner } from '../components/ui';
const TABLES = [
'registrations',
'checkins',
'connections',
'session_feedback',
'event_feedback',
'leaderboard',
'points_log',
] as const;
const CATEGORY_LABEL: Record<string, string> = {
checkin: 'Session check-ins',
connection: 'Connections',
feedback: 'Feedback',
talk_networking: 'Talk networking',
admin: 'Other',
};
/**
* Post-event reporting & export. For any event (active or past): an on-screen
* summary (session-feedback summary + aggregates) and CSV / Excel / PDF report
* downloads (served by the sidecar's `POST /export`).
*/
export function Reports() {
const { push } = useToast();
const [events, setEvents] = useState<Event[]>([]);
const [selectedId, setSelectedId] = useState('');
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [contacts, setContacts] = useState<Contact[]>([]);
const [registrations, setRegistrations] = useState<Registration[]>([]);
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [connections, setConnections] = useState<Connection[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [eventFeedback, setEventFeedback] = useState<EventFeedback[]>([]);
const [leaderboard, setLeaderboard] = useState<LeaderboardRow[]>([]);
const [pointsLog, setPointsLog] = useState<PointsLogRow[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [tables, setTables] = useState<Set<string>>(new Set(TABLES));
const [exporting, setExporting] = useState<'csv' | 'xlsx' | 'pdf' | null>(null);
async function load() {
try {
const evs = await getAllEvents();
setEvents(evs);
const active = evs.find((e) => e.is_active);
const first = active ?? evs[0];
if (first) setSelectedId((cur) => cur || first.id);
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
// Load the selected event's data (any event, not just the active one).
// `silent` is the background tick: it must not flip the view to the error
// screen, because Reports renders `if (error) return <Empty/>`. A sequence
// counter drops late responses, so switching events cannot be overwritten by
// the fetch for the event you just left.
const dataSeqRef = useRef(0);
async function loadEventData(silent: boolean) {
if (!selectedId) return;
const seq = ++dataSeqRef.current;
const evId = selectedId;
try {
const [c, reg, ck, cn, fb, efb, lb, pl, ss] = await Promise.all([
getAllContacts(),
getRegistrations(evId),
getAllCheckins(),
getAllConnections(),
getAllFeedback(),
getAllEventFeedback(),
getLeaderboard(),
getAllPointsLog(),
getSessions(evId),
]);
if (seq !== dataSeqRef.current) return;
setContacts(c);
setRegistrations(reg);
setCheckins(ck.filter((x) => x.event_id === evId));
setConnections(cn.filter((x) => x.event_id === evId));
setFeedback(fb.filter((x) => x.event_id === evId));
setEventFeedback(efb.filter((x) => x.event_id === evId));
setLeaderboard(lb.filter((x) => x.event_id === evId));
setPointsLog(pl.filter((x) => x.event_id === evId));
setSessions(ss);
} catch (e) {
if (!silent && seq === dataSeqRef.current) setError(e instanceof Error ? e.message : 'Failed to load event data');
}
}
// This view pulls nine tables, so it polls on a relaxed interval — still
// background-silent, but not nine round trips every five seconds. The export
// itself is built server-side from live data, so these numbers are previews.
useSilentRefresh(() => loadEventData(true), {
enabled: loaded && !!selectedId && exporting === null,
intervalMs: SLOW_POLL_MS,
});
useEffect(() => {
if (!selectedId) return;
void loadEventData(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedId]);
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email, c.full_name]));
return (email: string) => m.get(email) ?? email;
}, [contacts]);
// ---- Aggregates -----------------------------------------------------------
const byType = useMemo(() => {
const t: Record<string, number> = {};
for (const r of registrations) t[r.type] = (t[r.type] ?? 0) + 1;
return t;
}, [registrations]);
const acceptedConnections = useMemo(
() => connections.filter((c) => c.status === 'accepted').length,
[connections],
);
const sessionFeedbackAvg = useMemo(() => {
if (feedback.length === 0) return null;
return feedback.reduce((s, f) => s + f.rating, 0) / feedback.length;
}, [feedback]);
const eventFeedbackAvg = useMemo(() => {
if (eventFeedback.length === 0) return null;
return eventFeedback.reduce((s, f) => s + f.rating, 0) / eventFeedback.length;
}, [eventFeedback]);
// Per-session feedback summary (the "post-event session feedback summary").
const sessionSummary = useMemo(() => {
const bySession = new Map<string, { count: number; sum: number }>();
for (const f of feedback) {
const e = bySession.get(f.session_id) ?? { count: 0, sum: 0 };
e.count += 1;
e.sum += f.rating;
bySession.set(f.session_id, e);
}
return sessions
.map((s) => {
const e = bySession.get(s.id);
return {
title: s.title,
room: s.room,
avg: e ? e.sum / e.count : null,
count: e ? e.count : 0,
};
})
.filter((s) => s.count > 0)
.sort((a, b) => (b.avg ?? 0) - (a.avg ?? 0));
}, [sessions, feedback]);
const topLeaderboard = useMemo(
() => [...leaderboard].sort((a, b) => b.points - a.points).slice(0, 5),
[leaderboard],
);
const pointsByCategory = useMemo(() => {
const t: Record<string, number> = {};
for (const l of pointsLog) t[l.category] = (t[l.category] ?? 0) + l.delta;
return t;
}, [pointsLog]);
// ---- Export -------------------------------------------------------------
async function doExport(format: 'csv' | 'xlsx' | 'pdf') {
if (!selectedId) return;
setExporting(format);
try {
const res = await exportEventReport(selectedId, format, format === 'pdf' ? undefined : [...tables]);
downloadReport(res);
push('success', `Downloaded ${format.toUpperCase()} report`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Export failed');
} finally {
setExporting(null);
}
}
function toggleTable(t: string) {
setTables((prev) => {
const next = new Set(prev);
if (next.has(t)) next.delete(t);
else next.add(t);
return next;
});
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
const selected = events.find((e) => e.id === selectedId);
return (
<div>
<div className="page-head">
<div>
<h1>Reports</h1>
<div className="sub">Post-event summary + CSV / Excel / PDF export. Works for any event.</div>
</div>
<select
className="input"
style={{ maxWidth: 320 }}
value={selectedId}
onChange={(e) => setSelectedId(e.target.value)}
>
{events.map((e) => (
<option key={e.id} value={e.id}>
{e.name} {e.is_active ? '(active)' : ''}
</option>
))}
</select>
</div>
{!selected ? (
<div className="card">
<Empty icon="📅" text="No events yet. Create one in the Events view first." />
</div>
) : (
<>
{/* On-screen summary */}
<div className="card" style={{ marginBottom: 18 }}>
<h2 className="h2">📊 Summary — {selected.name}</h2>
<div className="muted small" style={{ marginBottom: 12 }}>
{selected.start_date} – {selected.end_date}
{selected.location ? ` · ${selected.location}` : ''}
</div>
<div className="stat-grid">
<Stat label="Registrations" value={registrations.length} />
<Stat label="Check-ins" value={checkins.length} />
<Stat label="Connections" value={connections.length} sub={`${acceptedConnections} accepted`} />
<Stat label="Session feedback" value={feedback.length} sub={sessionFeedbackAvg != null ? `avg ${sessionFeedbackAvg.toFixed(1)}★` : undefined} />
<Stat label="Event feedback" value={eventFeedback.length} sub={eventFeedbackAvg != null ? `avg ${eventFeedbackAvg.toFixed(1)}★` : undefined} />
</div>
<div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', marginTop: 14 }}>
<div>
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>Registrations by type</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{Object.entries(byType).map(([t, n]) => (
<span key={t} className="pill">{t}: {n}</span>
))}
</div>
</div>
<div>
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>Points by category</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{Object.entries(pointsByCategory).map(([c, n]) => (
<span key={c} className="pill">{CATEGORY_LABEL[c] ?? c}: +{n}</span>
))}
</div>
</div>
</div>
</div>
{/* Session feedback summary */}
<div className="card" style={{ marginBottom: 18 }}>
<h2 className="h2">⭐ Session feedback summary</h2>
{sessionSummary.length === 0 ? (
<Empty icon="⭐" text="No session feedback yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Session</th>
<th>Room</th>
<th>Avg rating</th>
<th>Responses</th>
</tr>
</thead>
<tbody>
{sessionSummary.map((s) => (
<tr key={s.title}>
<td style={{ fontWeight: 600 }}>{s.title}</td>
<td className="muted">{s.room ?? '—'}</td>
<td>
<span className="pill amber">
{s.avg != null ? `${s.avg.toFixed(1)}★` : '—'}
</span>
</td>
<td className="muted">{s.count}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Top leaderboard */}
<div className="card" style={{ marginBottom: 18 }}>
<h2 className="h2">🏆 Top points</h2>
{topLeaderboard.length === 0 ? (
<Empty icon="🏆" text="No points yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>#</th>
<th>Attendee</th>
<th>Points</th>
</tr>
</thead>
<tbody>
{topLeaderboard.map((r, i) => (
<tr key={r.contact_email}>
<td className="muted">{i + 1}</td>
<td style={{ fontWeight: 600 }}>{nameOf(r.contact_email)}</td>
<td>
<span className="pill amber">⚡ {r.points}</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Export */}
<div className="card">
<h2 className="h2">📤 Export</h2>
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 14 }}>
<button
className="btn primary"
disabled={exporting !== null || tables.size === 0}
onClick={() => void doExport('csv')}
>
{exporting === 'csv' ? 'Preparing…' : 'Download CSV'}
</button>
<button
className="btn primary"
disabled={exporting !== null || tables.size === 0}
onClick={() => void doExport('xlsx')}
>
{exporting === 'xlsx' ? 'Preparing…' : 'Download Excel'}
</button>
<button className="btn primary" disabled={exporting !== null} onClick={() => void doExport('pdf')}>
{exporting === 'pdf' ? 'Preparing…' : 'Download PDF report'}
</button>
</div>
<div className="muted small" style={{ marginBottom: 8 }}>
Tables included in CSV / Excel:
</div>
<div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
{TABLES.map((t) => (
<label key={t} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
<input
type="checkbox"
checked={tables.has(t)}
onChange={() => toggleTable(t)}
style={{ width: 16, height: 16, accentColor: 'var(--accent)' }}
/>
<span className="muted small">{t.replace('_', ' ')}</span>
</label>
))}
</div>
</div>
</>
)}
</div>
);
}
function Stat({ label, value, sub }: { label: string; value: number; sub?: string }) {
return (
<div className="stat">
<div className="val">{value}</div>
<div className="lbl">
{label}
{sub ? ` · ${sub}` : ''}
</div>
</div>
);
}
+155 -55
View File
@@ -1,19 +1,19 @@
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { supabase } from '../lib/supabase';
import {
evaluateSessionFeedback,
deleteEventSchedule,
getAllContacts,
getAllSessionSpeakers,
getActiveEvent,
getSessions,
getSlots,
removeSessionMaterial,
sessionMaterialUrl,
setSessionSpeakers,
uploadSessionMaterial,
} from '../lib/api';
import type { Contact, Event, Session, SessionSpeaker, Slot, SlotType } from '../lib/types';
import { useSilentRefresh } from '../lib/useSilentRefresh';
import { useToast } from '../context/ToastContext';
import { MaterialPanel } from '../components/MaterialPanel';
import { Empty, Modal, Spinner, TypeBadge } from '../components/ui';
const SLOT_TYPES: SlotType[] = ['session', 'service_session'];
@@ -30,11 +30,25 @@ export function Schedule() {
const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null);
const [sessModal, setSessModal] = useState<{ session: Session | null; slotId: number } | null>(null);
const [deleteModal, setDeleteModal] = useState<{
eventId: string;
eventName: string;
slotsCount: number;
sessionsCount: number;
} | null>(null);
const [busy, setBusy] = useState(false);
const [deleting, setDeleting] = useState(false);
const mountedRef = useRef(false);
const loadSeqRef = useRef(0);
async function load() {
async function load(expectedEventId?: string, silent = false) {
const seq = ++loadSeqRef.current;
try {
const ev = await getActiveEvent();
if (!mountedRef.current || seq !== loadSeqRef.current) return;
if (expectedEventId && ev?.id !== expectedEventId) {
throw new Error('Active event changed before the schedule could refresh');
}
setEvent(ev);
if (ev) {
const [s, ss, sp, c] = await Promise.all([
@@ -43,22 +57,45 @@ export function Schedule() {
getAllSessionSpeakers(),
getAllContacts(),
]);
if (!mountedRef.current || seq !== loadSeqRef.current) return;
setSlots(s);
setSessions(ss);
const ids = new Set(ss.map((x) => x.id));
setSpeakers(sp.filter((x) => ids.has(x.session_id)));
setContacts(c);
} else {
setSlots([]);
setSessions([]);
setSpeakers([]);
setContacts([]);
}
setLoaded(true);
} catch (e) {
if (!mountedRef.current || seq !== loadSeqRef.current) return;
// A failed background tick must not replace a good table with the error
// screen — this view renders `if (error) return <Empty/>` — so it stays quiet.
if (silent) return;
setError(e instanceof Error ? e.message : 'Failed to load');
throw e;
}
}
useEffect(() => {
load();
mountedRef.current = true;
void load().catch(() => {});
return () => {
mountedRef.current = false;
loadSeqRef.current++;
};
}, []);
// Pull the schedule quietly in the background. Paused while a modal is open so
// the form is never re-rendered underneath whoever is typing in it. Writes here
// already `await load()`, so no refreshSoon is needed.
useSilentRefresh(() => load(event?.id, true), {
enabled: loaded && slotModal === null && sessModal === null && deleteModal === null,
});
const speakersFor = useMemo(() => {
const m = new Map<string, string[]>();
for (const sp of speakers) {
@@ -101,16 +138,35 @@ export function Schedule() {
}
}
async function doEvaluate(sess: Session) {
setBusy(true);
async function deleteCurrentSchedule() {
const target = deleteModal;
if (!target || deleting) return;
setDeleting(true);
try {
await evaluateSessionFeedback(sess.id);
await load();
push('success', `AI feedback evaluated for ${sess.title}`);
const result = await deleteEventSchedule(target.eventId);
if (!mountedRef.current) return;
setDeleteModal(null);
try {
await load(target.eventId);
if (!mountedRef.current) return;
push(
'success',
`Deleted ${result.slots_deleted} slots and ${result.sessions_deleted} sessions from ${target.eventName}`,
);
} catch (refreshError) {
if (!mountedRef.current) return;
push(
'error',
`Schedule deleted for ${target.eventName}, but refresh failed: ${
refreshError instanceof Error ? refreshError.message : 'unknown error'
}`,
);
}
} catch (e) {
push('error', e instanceof Error ? e.message : 'Evaluation failed');
if (!mountedRef.current) return;
push('error', e instanceof Error ? e.message : 'Delete schedule failed');
} finally {
setBusy(false);
if (mountedRef.current) setDeleting(false);
}
}
@@ -138,6 +194,9 @@ export function Schedule() {
);
}
const hasSchedule = slots.length > 0 || sessions.length > 0;
const mutating = busy || deleting;
return (
<div>
<div className="page-head">
@@ -147,10 +206,26 @@ export function Schedule() {
{event.name} · {slots.length} slots · {sessions.length} sessions.
</div>
</div>
<button className="btn primary" onClick={() => setSlotModal({ slot: null })}>
<div className="row-actions">
<button
className="btn danger"
disabled={mutating || !hasSchedule}
onClick={() =>
setDeleteModal({
eventId: event.id,
eventName: event.name,
slotsCount: slots.length,
sessionsCount: sessions.length,
})
}
>
Delete current schedule
</button>
<button className="btn primary" disabled={mutating} onClick={() => setSlotModal({ slot: null })}>
+ New slot
</button>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{slots.map((slot) => {
@@ -168,13 +243,13 @@ export function Schedule() {
</div>
</div>
<div className="row-actions">
<button className="btn small" onClick={() => setSessModal({ session: null, slotId: slot.id })}>
<button className="btn small" disabled={mutating} onClick={() => setSessModal({ session: null, slotId: slot.id })}>
+ Session
</button>
<button className="btn small" onClick={() => setSlotModal({ slot })}>
<button className="btn small" disabled={mutating} onClick={() => setSlotModal({ slot })}>
Edit
</button>
<button className="btn small danger" disabled={busy} onClick={() => deleteSlot(slot)}>
<button className="btn small danger" disabled={mutating} onClick={() => deleteSlot(slot)}>
Delete
</button>
</div>
@@ -193,26 +268,18 @@ export function Schedule() {
<div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 700, fontSize: 14 }}>{s.title}</div>
<div className="muted small">
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null].filter(Boolean).join(' · ')}
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null, s.level ? `📶 ${s.level}` : null, s.area ? `🗂 ${s.area}` : null].filter(Boolean).join(' · ')}
</div>
<div className="muted small" style={{ marginTop: 4 }}>
{s.average_feedback != null && <span>⭐ {s.average_feedback.toFixed(1)}</span>}
<span> · {s.material_path ? '📎 material submitted' : '⬜ material not submitted'}</span>
{s.ai_generated_feedback && (
<span className="ai-state"> · 🤖 {s.ai_generated_feedback}</span>
)}
</div>
</div>
<div className="row-actions">
{s.ai_generated_feedback === 'Pending AI Evaluation' && (
<button className="btn small" disabled={busy} onClick={() => doEvaluate(s)}>
Evaluate
</button>
)}
<button className="btn small" onClick={() => setSessModal({ session: s, slotId: slot.id })}>
<button className="btn small" disabled={mutating} onClick={() => setSessModal({ session: s, slotId: slot.id })}>
Edit
</button>
<button className="btn small danger" disabled={busy} onClick={() => deleteSession(s)}>
<button className="btn small danger" disabled={mutating} onClick={() => deleteSession(s)}>
Delete
</button>
</div>
@@ -238,10 +305,39 @@ export function Schedule() {
}}
/>
)}
{deleteModal && (
<Modal
open
title="Delete current schedule"
onClose={() => {
if (!deleting) setDeleteModal(null);
}}
footer={
<>
<button className="btn" disabled={deleting} onClick={() => setDeleteModal(null)}>
Cancel
</button>
<button className="btn danger" disabled={deleting} onClick={deleteCurrentSchedule}>
{deleting ? 'Deleting…' : 'Delete schedule'}
</button>
</>
}
>
<p>
Delete the schedule for <strong>{deleteModal.eventName}</strong>?
</p>
<p className="muted">
This irreversibly deletes {deleteModal.slotsCount} slots and {deleteModal.sessionsCount} sessions, including speaker
links, preferences, check-ins and feedback. Registrations are preserved. Material file paths are removed with the
sessions, but Storage objects are not physically purged.
</p>
</Modal>
)}
{sessModal && (
<SessionModal
session={sessModal.session}
slotId={sessModal.slotId}
slot={slots.find((s) => s.id === sessModal.slotId)}
eventId={event.id}
contacts={contacts}
currentSpeakers={speakersFor.get(sessModal.session?.id ?? '') ?? []}
@@ -346,6 +442,7 @@ function SlotModal({
function SessionModal({
session,
slotId,
slot,
eventId,
contacts,
currentSpeakers,
@@ -354,6 +451,8 @@ function SessionModal({
}: {
session: Session | null;
slotId: number;
/** Slot this session belongs to; used to show when material unlocks for attendees. */
slot?: Slot;
eventId: string;
contacts: Contact[];
currentSpeakers: string[];
@@ -364,6 +463,8 @@ function SessionModal({
const [room, setRoom] = useState(session?.room ?? '');
const [capacity, setCapacity] = useState(session?.capacity?.toString() ?? '');
const [description, setDescription] = useState(session?.description ?? '');
const [level, setLevel] = useState(session?.level ?? '');
const [area, setArea] = useState(session?.area ?? '');
const [speakerEmails, setSpeakerEmails] = useState<string[]>(currentSpeakers);
const [material, setMaterial] = useState<File | null>(null);
const [busy, setBusy] = useState(false);
@@ -377,6 +478,8 @@ function SessionModal({
room: room.trim() || null,
capacity: capacity ? parseInt(capacity, 10) : null,
description: description.trim() || null,
level: level.trim() || null,
area: area.trim() || null,
slot_id: slotId,
event_id: eventId,
};
@@ -393,9 +496,10 @@ function SessionModal({
if (sessionId && speakerEmails.length > 0) {
await setSessionSpeakers(sessionId, speakerEmails);
}
// Material upload (if a new file was chosen).
// Material upload (if a new file was chosen). Passes the old path so a
// replacement removes the previous object instead of orphaning it.
if (sessionId && material) {
await uploadSessionMaterial(sessionId, material);
await uploadSessionMaterial(sessionId, material, session?.material_path);
}
onSaved(session ? 'Session updated' : 'Session created');
} catch (e) {
@@ -445,6 +549,16 @@ function SessionModal({
<label>Description</label>
<textarea className="input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="—" />
</div>
<div className="grid-2">
<div className="field">
<label>Level</label>
<input className="input" value={level} onChange={(e) => setLevel(e.target.value)} placeholder="e.g. 100 / Beginner" />
</div>
<div className="field">
<label>Area / Topic</label>
<input className="input" value={area} onChange={(e) => setArea(e.target.value)} placeholder="e.g. Power Apps" />
</div>
</div>
<div className="field">
<label>Speakers ({speakerEmails.length})</label>
@@ -459,37 +573,23 @@ function SessionModal({
</div>
{session && (
<div className="field">
<div className="field" data-testid="session-material">
<label>Material</label>
{session.material_path ? (
<div className="row" style={{ gap: 10 }}>
<a className="btn small" href={sessionMaterialUrl(session.material_path)} target="_blank" rel="noreferrer">
📎 View current
</a>
<button
className="btn small danger"
disabled={busy}
onClick={async () => {
try {
await removeSessionMaterial(session.id);
onSaved('Material removed');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Remove failed');
}
}}
>
Remove
</button>
</div>
) : (
<span className="muted small">No material uploaded yet.</span>
)}
<MaterialPanel
session={session}
unlocksAt={slot ? `${fmtDate(slot.slot_date)}, ${fmtTime(slot.end_time)}` : null}
onChanged={() => onSaved('Material removed')}
/>
<input
className="input"
type="file"
onChange={(e) => setMaterial(e.target.files?.[0] ?? null)}
/>
{material && <span className="muted small">Will upload: {material.name}</span>}
{material && (
<span className="muted small">
{session.material_path ? 'Replaces current file on Save' : 'Uploads on Save'}: {material.name}
</span>
)}
</div>
)}
+614
View File
@@ -0,0 +1,614 @@
import { useCallback, Fragment, useEffect, useMemo, useRef, useState } from 'react';
import { Sparkles } from 'lucide-react';
import {
generateFeedbackSummary,
getAllContacts,
getAllEvents,
getActiveEvent,
getEventCheckins,
getEventSessionFeedback,
getEventSessionSpeakers,
getFeedbackSummaries,
getLlmSettings,
getSessions,
getSlots,
sessionMaterialName,
} from '../lib/api';
import type {
Checkin,
Contact,
Event,
Feedback,
FeedbackSummary,
Session,
SessionSpeaker,
Slot,
} from '../lib/types';
import { Avatar, Empty, Spinner, Tooltip } from '../components/ui';
import { MaterialPanel, MaterialUploadRow } from '../components/MaterialPanel';
import { useSilentRefresh } from '../lib/useSilentRefresh';
const timeLabel = (slot?: Slot) => (slot ? `${slot.start_time.slice(0, 5)}–${slot.end_time.slice(0, 5)}` : '');
const fmtTime = (iso: string) => new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const fmtDay = (iso: string) => new Date(iso).toLocaleDateString([], { day: '2-digit', month: 'short' });
/**
* Sessions: who is speaking in what, who actually walked in, and how it went.
*
* The rows are joined client-side (sessions ⨝ slots ⨝ session_speakers ⨝
* checkins ⨝ feedback) rather than through PostgREST embeds, because every one of
* those tables has its own RLS policy and the admin app reads them directly
* elsewhere; keeping one shape here means no policy change is needed and the
* numbers match the other views exactly.
*/
export function Sessions() {
const [events, setEvents] = useState<Event[]>([]);
const [selectedId, setSelectedId] = useState('');
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [slots, setSlots] = useState<Slot[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [speakers, setSpeakers] = useState<SessionSpeaker[]>([]);
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [summaries, setSummaries] = useState<FeedbackSummary[]>([]);
const [contacts, setContacts] = useState<Contact[]>([]);
const [llmConfigured, setLlmConfigured] = useState(false);
const [expanded, setExpanded] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [attendee, setAttendee] = useState('');
const [summaryError, setSummaryError] = useState<string | null>(null);
// Bulk AI summary run: null when idle, otherwise a blocking overlay with a
// counter. `cancelled` lets a reload mid-run stop the loop cleanly.
const [run, setRun] = useState<{ done: number; total: number } | null>(null);
const [runResult, setRunResult] = useState<{ ok: number; failed: string[] } | null>(null);
const runningRef = useRef(false);
const cancelRef = useRef(false);
const seqRef = useRef(0);
async function load(silent: boolean, expectedEventId?: string) {
const seq = ++seqRef.current;
try {
const [evs, active] = await Promise.all([getAllEvents(), getActiveEvent()]);
if (seq !== seqRef.current) return;
setEvents(evs);
// Explicit id = the user picked an event; otherwise the active one, and if
// nothing is active the newest event, so the view is never blank by accident.
const ev = expectedEventId ? evs.find((e) => e.id === expectedEventId) ?? null : active ?? evs[0] ?? null;
setEvent(ev);
if (expectedEventId) setSelectedId(expectedEventId);
else setSelectedId((cur) => cur || ev?.id || '');
if (!ev) {
setLoaded(true);
return;
}
const [sl, ss, sp, ck, fb, saved, settings, people] = await Promise.all([
getSlots(ev.id),
getSessions(ev.id),
getEventSessionSpeakers(ev.id),
getEventCheckins(ev.id),
getEventSessionFeedback(ev.id),
getFeedbackSummaries(ev.id),
getLlmSettings(),
getAllContacts(),
]);
if (seq !== seqRef.current) return;
setSlots(sl);
setSessions(ss);
setSpeakers(sp);
setCheckins(ck);
setFeedback(fb);
setSummaries(saved);
setContacts(people);
setLlmConfigured(Boolean(settings.endpoint && settings.model));
setLoaded(true);
} catch (cause) {
// A failed background tick must not replace a good table with the error
// screen — this view renders `if (error) return <Empty/>`.
if (!silent && seq === seqRef.current) {
setError(cause instanceof Error ? cause.message : 'Failed to load sessions');
}
}
}
useEffect(() => {
void load(false);
}, []);
// Live: session check-ins made on the scanner app appear without a reload.
// Paused during a bulk summary run so polling cannot race the writes.
useSilentRefresh(() => load(true, selectedId || undefined), { enabled: loaded && run === null });
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email.toLowerCase(), c.full_name]));
return (email: string) => m.get(email.toLowerCase()) ?? email;
}, [contacts]);
const slotById = useMemo(() => new Map(slots.map((s) => [s.id, s])), [slots]);
const speakersBySession = useMemo(() => {
const m = new Map<string, string[]>();
for (const sp of speakers) {
const arr = m.get(sp.session_id) ?? [];
arr.push(sp.contact_email);
m.set(sp.session_id, arr);
}
return m;
}, [speakers]);
const checkinsBySession = useMemo(() => {
const m = new Map<string, Checkin[]>();
for (const c of checkins) {
const arr = m.get(c.session_id) ?? [];
arr.push(c);
m.set(c.session_id, arr);
}
for (const arr of m.values()) arr.sort((a, b) => a.created_at.localeCompare(b.created_at));
return m;
}, [checkins]);
const feedbackBySession = useMemo(() => {
const m = new Map<string, { count: number; sum: number; avg: number }>();
for (const f of feedback) {
const e = m.get(f.session_id) ?? { count: 0, sum: 0, avg: 0 };
e.count += 1;
e.sum += f.rating;
e.avg = e.sum / e.count;
m.set(f.session_id, e);
}
return m;
}, [feedback]);
const summaryBySession = useMemo(
() => new Map(summaries.filter((s) => s.scope === 'session').map((s) => [s.target_id, s])),
[summaries],
);
/** Sessions with at least one feedback row — the only ones worth summarising. */
const summarisable = useMemo(
() => sessions.filter((s) => (feedbackBySession.get(s.id)?.count ?? 0) > 0),
[sessions, feedbackBySession],
);
/** Everyone with at least one check-in, for the attendee filter. */
const attendees = useMemo(() => {
const byEmail = new Map<string, { email: string; name: string; count: number }>();
for (const c of checkins) {
const key = c.contact_email.toLowerCase();
const cur = byEmail.get(key);
if (cur) cur.count += 1;
else byEmail.set(key, { email: c.contact_email, name: nameOf(c.contact_email), count: 1 });
}
return [...byEmail.values()].sort((a, b) => a.name.localeCompare(b.name));
}, [checkins, nameOf]);
const rows = useMemo(() => {
const wanted = attendee.toLowerCase();
const q = query.trim().toLowerCase();
return sessions
.filter((s) => {
if (wanted && !(checkinsBySession.get(s.id) ?? []).some((c) => c.contact_email.toLowerCase() === wanted)) {
return false;
}
if (!q) return true;
const sp = (speakersBySession.get(s.id) ?? []).join(' ');
return (
s.title.toLowerCase().includes(q) ||
(s.room ?? '').toLowerCase().includes(q) ||
(s.level ?? '').toLowerCase().includes(q) ||
(s.area ?? '').toLowerCase().includes(q) ||
(s.language ?? '').toLowerCase().includes(q) ||
sp.toLowerCase().includes(q)
);
})
.sort((a, b) => {
const sa = slotById.get(a.slot_id);
const sb = slotById.get(b.slot_id);
if (!sa || !sb) return a.title.localeCompare(b.title);
const d = `${sa.slot_date} ${sa.start_time}`.localeCompare(`${sb.slot_date} ${sb.start_time}`);
return d !== 0 ? d : a.title.localeCompare(b.title);
});
}, [sessions, attendee, query, checkinsBySession, speakersBySession, slotById]);
const pickedEmails = useMemo(() => {
if (!attendee) return new Set<string>();
return new Set(
checkins.filter((c) => c.contact_email.toLowerCase() === attendee.toLowerCase()).map((c) => c.contact_email),
);
}, [attendee, checkins]);
async function generateAll() {
if (runningRef.current || summarisable.length === 0) return;
runningRef.current = true;
cancelRef.current = false;
setRunResult(null);
setSummaryError(null);
// One request per session that has feedback. Concurrency is capped at 3: the
// gateway is a single vLLM worker, and firing N requests at once only makes
// each one slower. The UI stays blocked until every request has settled.
const queue = [...summarisable];
const total = queue.length;
const failed: string[] = [];
let done = 0;
const generated: FeedbackSummary[] = [];
setRun({ done: 0, total });
const worker = async () => {
for (;;) {
if (cancelRef.current) return;
const s = queue.shift();
if (!s) return;
try {
generated.push(await generateFeedbackSummary(selectedId, s.id));
} catch (cause) {
failed.push(`${s.title}: ${cause instanceof Error ? cause.message : 'failed'}`);
} finally {
done += 1;
setRun({ done, total });
}
}
};
try {
await Promise.all([worker(), worker(), worker()]);
if (generated.length) {
setSummaries((current) => {
const ids = new Set(generated.map((g) => g.target_id));
return [...current.filter((c) => c.scope !== 'session' || !ids.has(c.target_id)), ...generated];
});
}
setRunResult({ ok: generated.length, failed });
} finally {
runningRef.current = false;
setRun(null);
}
}
const toggleRow = useCallback((id: string) => setExpanded((cur) => (cur === id ? null : id)), []);
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
if (!event) {
return (
<div>
<div className="page-head">
<div>
<h1>Sessions</h1>
<div className="sub">Attendance, speakers, and AI feedback summaries.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No event selected. Create one in the Events view first." />
</div>
</div>
);
}
const attendedCount = attendee ? rows.length : 0;
const canGenerate = llmConfigured && summarisable.length > 0 && run === null;
return (
<div>
{/* Blocking overlay: the run is synchronous from the user's point of view,
so nothing behind it is reachable until every request has settled. */}
{run && (
<div className="backdrop" role="alertdialog" aria-busy="true" aria-label="Generating AI feedback summaries" data-testid="summary-overlay">
<div className="card summary-run-card">
<Spinner />
<h2 className="h2">Generating AI feedback summaries</h2>
<p className="muted" role="status" data-testid="summary-progress">
{run.done} of {run.total} sessions
</p>
<div className="summary-run-bar" aria-hidden="true">
<span style={{ width: `${run.total === 0 ? 0 : Math.round((run.done / run.total) * 100)}%` }} />
</div>
<p className="muted small">One request per session that has feedback. Keep this page open.</p>
<button className="btn small danger" onClick={() => { cancelRef.current = true; }}>
Stop
</button>
</div>
</div>
)}
<div className="page-head">
<div>
<h1>Sessions</h1>
<div className="sub">
<strong>{event.name}</strong> · {sessions.length} sessions · {checkins.length} check-ins ·{' '}
{feedback.length} feedback · {summarisable.length} with feedback
</div>
</div>
<div className="row" style={{ gap: 10, flexWrap: 'wrap' }}>
{events.length > 1 && (
<select
className="input"
style={{ maxWidth: 240 }}
value={selectedId}
disabled={run !== null}
onChange={(e) => {
setExpanded(null);
setAttendee('');
void load(false, e.target.value);
}}
>
{events.map((e) => (
<option key={e.id} value={e.id}>
{e.name}
</option>
))}
</select>
)}
<Tooltip
title={!llmConfigured ? 'LLM not configured' : summarisable.length === 0 ? 'No session feedback yet' : 'Generate AI summaries'}
content={
!llmConfigured
? 'Set the LLM endpoint and model in Settings first.'
: summarisable.length === 0
? 'Every AI summary needs at least one feedback response on a session.'
: `Sends ${summarisable.length} request${summarisable.length === 1 ? '' : 's'} — one per session that has feedback — and stores each result. The page stays blocked until all of them finish.`
}
>
<button
className="btn primary"
onClick={generateAll}
disabled={!canGenerate}
data-testid="generate-all-summaries"
>
<Sparkles size={16} aria-hidden="true" />
{run ? `Generating… ${run.done}/${run.total}` : 'Generate AI Feedback Summary'}
</button>
</Tooltip>
</div>
</div>
{!llmConfigured && (
<p className="muted small" data-testid="sessions-llm-unconfigured">
AI summaries are unavailable — set the LLM endpoint and model in Settings.
</p>
)}
{summaryError && <p className="feedback-error" role="alert">{summaryError}</p>}
{runResult && (
<p className={runResult.failed.length ? 'feedback-error' : 'muted small'} role="status" data-testid="summary-run-result">
{runResult.ok} session summar{runResult.ok === 1 ? 'y' : 'ies'} stored
{runResult.failed.length > 0 && ` · ${runResult.failed.length} failed: ${runResult.failed.join(' · ')}`}
</p>
)}
<div className="card sessions-toolbar" data-testid="sessions-toolbar">
<input
className="input"
type="search"
placeholder="Search title, room, level, area, language or speaker"
value={query}
onChange={(e) => setQuery(e.target.value)}
aria-label="Search sessions"
/>
<select
className="input"
value={attendee}
onChange={(e) => {
setAttendee(e.target.value);
setExpanded(null);
}}
aria-label="Filter by attendee"
data-testid="attendee-filter"
disabled={run !== null}
>
<option value="">All attendees — every session</option>
{attendees.map((a) => (
<option key={a.email} value={a.email}>
{a.name} ({a.count})
</option>
))}
</select>
{attendee && (
<span className="pill cyan" data-testid="attendee-summary">
{nameOf(attendee)} attended {attendedCount} session{attendedCount === 1 ? '' : 's'}
<button className="pill-x" onClick={() => setAttendee('')} aria-label="Clear attendee filter" disabled={run !== null}>
✕
</button>
</span>
)}
{(query || attendee) && (
<span className="muted small">
{rows.length} of {sessions.length}
</span>
)}
</div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>When</th>
<th>Session</th>
<th>Speakers</th>
<th>Material</th>
<th style={{ textAlign: 'right' }}>Check-ins</th>
<th style={{ textAlign: 'right' }}>Feedback</th>
<th>AI summary</th>
</tr>
</thead>
<tbody>
{rows.map((s) => {
const slot = slotById.get(s.slot_id);
const att = checkinsBySession.get(s.id) ?? [];
const fb = feedbackBySession.get(s.id);
const sp = speakersBySession.get(s.id) ?? [];
const summary = summaryBySession.get(s.id);
const open = expanded === s.id;
const stale = summary && fb && summary.response_count !== fb.count;
return (
<Fragment key={s.id}>
<tr className={open ? 'row-open' : ''} onClick={() => toggleRow(s.id)} style={{ cursor: 'pointer' }}>
<td className="muted">
<div className="cell-when">
<span>{fmtDay(slot?.slot_date ?? s.created_at)}</span>
<strong>{timeLabel(slot)}</strong>
</div>
</td>
<td>
<div className="cell-session">
<span className="n">{s.title}</span>
<span className="e">
{s.room ?? 'no room'}
{s.level ? ` · ${s.level}` : ''}
{s.area ? ` · ${s.area}` : ''}
{s.language ? ` · ${s.language}` : ''}
</span>
</div>
</td>
<td>
{sp.length === 0 ? (
<span className="muted small">—</span>
) : (
<div className="speaker-list">
{sp.slice(0, 3).map((e) => (
<span key={e} className="speaker-chip">
<Avatar name={nameOf(e)} id={e} size={22} fs={9} />
{nameOf(e)}
</span>
))}
{sp.length > 3 && <span className="muted small">+{sp.length - 3}</span>}
</div>
)}
</td>
<td>
{s.material_path ? (
<Tooltip title={sessionMaterialName(s.material_path)} content="Manage it in the expanded row">
<span className="pill green" data-testid={`material-yes-${s.id}`}>
uploaded
</span>
</Tooltip>
) : (
<span className="muted small" data-testid={`material-none-${s.id}`}>
—
</span>
)}
</td>
<td style={{ textAlign: 'right' }}>
<span className={att.length > 0 ? 'att-count' : 'muted'}>{att.length}</span>
{s.capacity ? <span className="muted small"> / {s.capacity}</span> : null}
</td>
<td style={{ textAlign: 'right' }}>
{fb ? (
<span className="pill amber">
{fb.avg.toFixed(1)}★ · {fb.count}
</span>
) : (
<span className="muted small">—</span>
)}
</td>
<td>
{summary ? (
stale ? (
<Tooltip title="Outdated" content={`Stored from ${summary.response_count} responses; there are now ${fb?.count ?? 0}. Generate again to refresh.`}>
<span className="pill amber" data-testid={`summary-stale-${s.id}`}>stale</span>
</Tooltip>
) : (
<span className="pill green" data-testid={`summary-done-${s.id}`}>ready</span>
)
) : (
<span className="muted small">{fb ? 'not generated' : 'no feedback'}</span>
)}
</td>
</tr>
{open && (
<tr className="row-detail">
<td colSpan={7}>
<div className="session-detail">
{s.description && <p className="session-desc">{s.description}</p>}
<div className="detail-cols">
<section>
<h3 className="h3">Speakers ({sp.length})</h3>
{sp.length === 0 ? (
<p className="muted small">No speakers linked. Add them in Schedule.</p>
) : (
<ul className="detail-list">
{sp.map((e) => (
<li key={e}>
<Avatar name={nameOf(e)} id={e} size={26} fs={10} />
<span className="dl-name">{nameOf(e)}</span>
<span className="dl-email muted">{e}</span>
</li>
))}
</ul>
)}
</section>
<section>
<h3 className="h3">Checked in ({att.length})</h3>
{att.length === 0 ? (
<p className="muted small">Nobody has scanned into this session yet.</p>
) : (
<ul className="detail-list">
{att.map((c) => (
<li key={c.id} data-testid={`detail-checkin-${c.id}`}>
<Avatar name={nameOf(c.contact_email)} id={c.contact_email} size={26} fs={10} />
<span className="dl-name">
{pickedEmails.has(c.contact_email) ? (
<mark>{nameOf(c.contact_email)}</mark>
) : (
nameOf(c.contact_email)
)}
</span>
<span className="dl-email muted">{c.contact_email}</span>
<span className="dl-time muted">
{fmtDay(c.created_at)} {fmtTime(c.created_at)} · by {nameOf(c.staff_email)}
</span>
</li>
))}
</ul>
)}
</section>
<section>
<h3 className="h3">AI feedback summary</h3>
{summary ? (
<>
<div className="feedback-summary-text">{summary.summary}</div>
<p className="muted small">
AI-generated · {summary.response_count} responses · {summary.model} ·{' '}
{new Date(summary.generated_at).toLocaleString()}
</p>
</>
) : (
<p className="muted small">
{fb ? 'Not generated yet — use Generate AI Feedback Summary above.' : 'No feedback has been submitted for this session.'}
</p>
)}
</section>
<section>
<h3 className="h3">Material</h3>
<MaterialPanel
session={s}
unlocksAt={slot ? `${fmtDay(slot.slot_date)}, ${slot.end_time.slice(0, 5)}` : null}
onChanged={() => void load(true)}
/>
<MaterialUploadRow session={s} onUploaded={() => void load(true)} />
</section>
</div>
</div>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</table>
{rows.length === 0 && (
<div style={{ padding: 16 }}>
<Empty icon="🗓️" text={attendee ? 'This attendee has no check-ins matching the search' : 'No sessions in this event'} />
</div>
)}
</div>
</div>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { useEffect, useState, type FormEvent } from 'react';
import { PlugZap, Save } from 'lucide-react';
import { getActiveEvent, getLlmSettings, saveLlmSettings, testLlmConnection } from '../lib/api';
import type { Event, LlmTestResult } from '../lib/types';
import { Spinner } from '../components/ui';
import { BadgeCopiesSetting } from '../components/BadgeCopiesSetting';
export function Settings() {
const [endpoint, setEndpoint] = useState('');
const [model, setModel] = useState('');
const [apiKey, setApiKey] = useState('');
const [hasKey, setHasKey] = useState(false);
const [clearKey, setClearKey] = useState(false);
const [loaded, setLoaded] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState<LlmTestResult | null>(null);
// What is actually stored in the DB. The sidecar tests the stored settings
// (the API key never reaches the browser), so unsaved edits cannot be tested —
// this is what lets the UI say "save first" instead of testing stale values.
const [baseline, setBaseline] = useState({ endpoint: '', model: '', has_api_key: false });
// Badge printing is per event, so it follows the active event.
const [activeEvent, setActiveEvent] = useState<Event | null>(null);
useEffect(() => {
let active = true;
getLlmSettings().then(settings => {
if (!active) return;
setEndpoint(settings.endpoint);
setModel(settings.model);
setHasKey(settings.has_api_key);
setBaseline({ endpoint: settings.endpoint, model: settings.model, has_api_key: settings.has_api_key });
setLoaded(true);
}).catch(cause => { if (active) setError(cause instanceof Error ? cause.message : 'Failed to load settings'); });
// Best-effort: a failure here just hides the badge section, it must not
// break the Feedback AI settings below.
getActiveEvent()
.then(event => { if (active) setActiveEvent(event); })
.catch(() => { if (active) setActiveEvent(null); });
return () => { active = false; };
}, []);
// Unsaved edits mean a test would measure something other than what's on
// screen, so the button stays disabled with an explanation instead.
const pendingChanges =
endpoint.trim() !== baseline.endpoint || model.trim() !== baseline.model || clearKey || apiKey.length > 0;
async function save(event: FormEvent) {
event.preventDefault();
setBusy(true);
setSaved(false);
setError(null);
try {
const settings = await saveLlmSettings({ endpoint: endpoint.trim(), model: model.trim(), ...(clearKey ? { api_key: '' } : apiKey ? { api_key: apiKey } : {}) });
setEndpoint(settings.endpoint);
setHasKey(settings.has_api_key);
setBaseline({ endpoint: settings.endpoint, model: settings.model, has_api_key: settings.has_api_key });
setApiKey('');
setClearKey(false);
setSaved(true);
// Saving changes what a test would measure, so any old verdict is void.
setTestResult(null);
} catch (cause) { setError(cause instanceof Error ? cause.message : 'Failed to save settings'); }
finally { setBusy(false); }
}
async function testConnection() {
if (testing) return;
setTesting(true);
setTestResult(null);
setError(null);
try {
setTestResult(await testLlmConnection());
} catch (cause) {
setError(cause instanceof Error ? cause.message : 'Could not reach the sync sidecar (is it running?)');
} finally { setTesting(false); }
}
return (
<div>
<div className="page-head"><h1>Settings</h1></div>
{error && <p className="feedback-error" role="alert">{error}</p>}
{!loaded && !error && <Spinner />}
{activeEvent && (
<section className="settings-section" aria-labelledby="badge-printing-h" data-testid="settings-badge-printing">
<h2 className="h2" id="badge-printing-h">Badge printing</h2>
<BadgeCopiesSetting eventId={activeEvent.id} initialCopies={activeEvent.badge_copies ?? 1} eventName={activeEvent.name} />
</section>
)}
{loaded && <form className="llm-settings" onSubmit={save} onChange={() => setSaved(false)}>
<h2 className="h2">Feedback AI</h2>
<div className="field">
<label htmlFor="llm-endpoint">LLM endpoint (OpenAI-compatible)</label>
<input id="llm-endpoint" className="input" type="url" placeholder="https://api.example.com/v1/chat/completions" required value={endpoint} disabled={busy} onChange={event => setEndpoint(event.target.value)} />
</div>
<div className="field">
<label htmlFor="llm-model">Model</label>
<input id="llm-model" className="input" required maxLength={200} value={model} disabled={busy} onChange={event => setModel(event.target.value)} />
</div>
<div className="field">
<label htmlFor="llm-key">API key (optional)</label>
<input id="llm-key" className="input" type="password" autoComplete="new-password" maxLength={4096} value={apiKey} disabled={busy || clearKey} placeholder={hasKey ? 'Key configured' : ''} onChange={event => setApiKey(event.target.value)} />
</div>
{hasKey && <label className="row"><input type="checkbox" checked={clearKey} disabled={busy} onChange={event => setClearKey(event.target.checked)} />Remove stored API key</label>}
<div className="row">
<button className="btn primary" type="submit" disabled={busy}><Save size={16} aria-hidden="true" />{busy ? 'Saving...' : 'Save'}</button>
{saved && <span role="status">Settings saved</span>}
</div>
<div className="llm-test">
<div className="row">
{/* type=button: inside the form, a submit would save instead of test. */}
<button className="btn" type="button" onClick={testConnection} data-testid="llm-test-button"
disabled={busy || testing || pendingChanges}
title={pendingChanges ? 'Save these settings first — the test uses what is stored on the server' : 'Sends one request to the endpoint and reports what came back'}>
<PlugZap size={16} aria-hidden="true" />{testing ? 'Testing...' : 'Validate AI connection'}
</button>
{pendingChanges && <span className="muted small" data-testid="llm-test-dirty">Save first — the test uses the stored settings.</span>}
</div>
{testing && <p className="muted small" role="status" data-testid="llm-test-progress">Sending one request to {model.trim() || 'the configured model'}…</p>}
{/* The verdict stays on the page rather than in a toast: the latency and
the reasoning-token line are the parts people need to read twice. */}
{testResult && (() => {
// Three states, not two. Our gateway reports no reasoning-token
// counter at all (`completion_tokens_details: {}`), so "null" is the
// normal healthy answer here — colouring it amber and saying "still
// thinking" would flag a working configuration as broken.
const unknown = testResult.ok && testResult.reasoning_tokens === null;
const tone = !testResult.ok ? 'bad' : testResult.reasoning_disabled ? 'good' : unknown ? 'neutral' : 'warn';
return (
<div className={`llm-test-result ${tone}`}
role="status" data-testid="llm-test-result" data-ok={String(testResult.ok)}
data-reasoning-disabled={String(testResult.reasoning_disabled)}>
<strong data-testid="llm-test-headline">
{!testResult.ok
? 'Connection failed'
: testResult.reasoning_disabled
? `Connection works — replied in ${testResult.latency_ms} ms`
: unknown
? `Connection works — replied in ${testResult.latency_ms} ms`
: 'Connection works, but the model is still thinking'}
</strong>
{testResult.model && <p className="muted small">{testResult.model} at {testResult.endpoint}</p>}
{testResult.error && <p className="feedback-error" data-testid="llm-test-error">{testResult.error}</p>}
{testResult.warning && <p data-testid="llm-test-warning">{testResult.warning}</p>}
{testResult.ok && (
<p className="muted small" data-testid="llm-test-reasoning">
{testResult.reasoning_tokens === null
? 'This endpoint does not report a reasoning-token count, so thinking cannot be confirmed from here — the request was still sent with thinking disabled.'
: `Reasoning tokens: ${testResult.reasoning_tokens}`}
{testResult.content ? ` · reply: “${testResult.content.slice(0, 60)}”` : ''}
</p>
)}
</div>
);
})()}
</div>
</form>}
</div>
);
}
+1 -1
View File
@@ -9,5 +9,5 @@
"strict": true,
"noEmit": true
},
"include": ["vite.config.ts"]
"include": ["vite.config.ts", "vite.print.config.ts"]
}
+5 -5
View File
@@ -1,17 +1,17 @@
import { defineConfig } from 'vite';
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
// Dev server proxies /auth, /rest, /realtime, /storage to the local Supabase
// stack so the app can use relative URLs (works in Docker + localhost).
const SUPABASE_TARGET = 'http://127.0.0.1:54321';
export default defineConfig({
export default defineConfig(({ mode }) => ({
plugins: [react()],
server: {
host: true,
port: 3001,
proxy: {
'/auth': { target: SUPABASE_TARGET, changeOrigin: true },
'/auth/v1': { target: SUPABASE_TARGET, changeOrigin: true },
'/rest': { target: SUPABASE_TARGET, changeOrigin: true },
'/realtime': { target: SUPABASE_TARGET, changeOrigin: true, ws: true },
'/storage': { target: SUPABASE_TARGET, changeOrigin: true },
@@ -20,10 +20,10 @@ export default defineConfig({
// Strip the /sidecar prefix so /sidecar/run -> http://127.0.0.1:3002/run
// (mirrors the nginx `location /sidecar/ { proxy_pass .../; }` rewrite).
'/sidecar': {
target: 'http://127.0.0.1:3002',
target: loadEnv(mode, '.', 'SIDECAR_').SIDECAR_TARGET || 'http://127.0.0.1:3002',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/sidecar/, ''),
},
},
},
});
}));
+14
View File
@@ -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' },
},
});
+1
View File
@@ -2,6 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="referrer" content="no-referrer" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+7
View File
@@ -35,6 +35,13 @@ server {
try_files $uri =404;
}
location = /auth/callback {
access_log off;
add_header Cache-Control "no-store";
add_header Referrer-Policy "no-referrer";
try_files /index.html =404;
}
# ---- Supabase same-origin proxy -------------------------------------
# No trailing slash on proxy_pass => the original URI is passed through
# unchanged (e.g. /auth/v1/token -> http://<target>/auth/v1/token).
+10
View File
@@ -10,6 +10,7 @@
"dependencies": {
"@supabase/supabase-js": "^2.45.4",
"html5-qrcode": "^2.3.8",
"lucide-react": "^1.14.0",
"qrcode.react": "^4.0.1",
"react": "^18.3.1",
"react-dom": "^18.3.1"
@@ -1604,6 +1605,15 @@
"yallist": "^3.0.2"
}
},
"node_modules/lucide-react": {
"version": "1.14.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.14.0.tgz",
"integrity": "sha512-+1mdWcfSJVUsaTIjN9zoezmUhfXo5l0vP7ekBMPo3jcS/aIkxHnXqAPsByszMZx/Y8oQBRJxJx5xg+RH3urzxA==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+1
View File
@@ -11,6 +11,7 @@
"dependencies": {
"@supabase/supabase-js": "^2.45.4",
"html5-qrcode": "^2.3.8",
"lucide-react": "^1.14.0",
"qrcode.react": "^4.0.1",
"react": "^18.3.1",
"react-dom": "^18.3.1"
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+76 -4
View File
@@ -9,9 +9,12 @@ import { Connections } from './screens/Connections';
import { Leaderboard } from './screens/Leaderboard';
import { Profile } from './screens/Profile';
import { Feedback } from './screens/Feedback';
import { Spinner } from './components/ui';
import { EventFeedback } from './screens/EventFeedback';
import { QrImage, Spinner } from './components/ui';
import { getMyConnections } from './lib/api';
import { usePolling } from './lib/usePolling';
import { isSpeakerPortal } from './lib/speakerPortal';
import { SpeakerPortal } from './screens/SpeakerPortal';
type Tab = 'home' | 'agenda' | 'scan' | 'connections' | 'profile' | 'leaderboard';
const TABS: { id: Tab; ico: string; label: string }[] = [
@@ -23,10 +26,25 @@ const TABS: { id: Tab; ico: string; label: string }[] = [
];
function Shell() {
const { session, contact, loading } = useAuth();
const { session, contact, registration, loading, refresh, signOut } = useAuth();
const [tab, setTab] = useState<Tab>('home');
const [feedbackSession, setFeedbackSession] = useState<string | null>(null);
const [eventFeedbackOpen, setEventFeedbackOpen] = useState(false);
const [pendingIncoming, setPendingIncoming] = useState(0);
// Which sub-tab the Connect screen opens on (default 'mine'; 'networking'
// when reached via the Home "Networking" quick action).
const [connectionsTab, setConnectionsTab] = useState<'mine' | 'req' | 'networking'>('mine');
// Home's `go` handles the tab ids; 'networking' routes into the Connect
// screen's networking sub-tab.
const go = (t: string) => {
if (t === 'networking') {
setConnectionsTab('networking');
setTab('connections');
return;
}
setTab(t as Tab);
};
const email = contact?.email ?? '';
@@ -46,6 +64,13 @@ function Shell() {
// Keep the Connect red-dot fresh: poll every 5s while visible.
usePolling(() => void loadPending(), 5000, !!email);
// Gate: a non-staff member must be checked in by staff before using the app.
// (Staff are never gated — they're the ones doing the checking in.)
const isGated = !!contact && !contact.is_admin && !registration?.checked_in;
// While gated, poll so the gate lifts as soon as staff checks them in.
usePolling(() => { if (isGated) void refresh(); }, 4000, isGated);
// Recalc immediately when a connection is accepted/declined/sent.
useEffect(() => {
const onChanged = () => void loadPending();
@@ -71,6 +96,42 @@ function Shell() {
);
}
// Not checked in yet: a non-staff member must be checked in by staff before
// they can use the app. The gate lifts automatically (4s poll) once staff
// checks them in.
if (isGated) {
return (
<div className="app">
<div className="center" data-testid="checkin-required-gate" style={{ flex: 1, flexDirection: 'column', gap: 14, padding: 24, textAlign: 'center' }}>
<div style={{ fontSize: 56 }}>🏷️</div>
<div className="h1" style={{ textAlign: 'center' }}>Please see a staff member</div>
<div className="muted" style={{ textAlign: 'center', maxWidth: 320 }}>
You haven’t been checked in yet. Find a staff member and have them
scan your lanyard to get checked in — then you can start using the app.
</div>
{registration?.qr_token && (
<div className="card qr-wrap" style={{ marginTop: 4 }}>
<div className="h2" style={{ textAlign: 'center' }}>Your QR code</div>
<QrImage value={registration.qr_token} size={180} />
<div className="muted small" style={{ textAlign: 'center' }}>
Show this to <b>staff</b> to get checked in.
</div>
</div>
)}
<div className="muted small" style={{ opacity: 0.6 }}>
Checking in… this screen updates automatically.
</div>
<button className="btn ghost" onClick={() => void refresh()}>
I’ve been checked in — refresh
</button>
<button className="btn ghost" onClick={() => void signOut()}>
Log out
</button>
</div>
</div>
);
}
// Feedback is a full-screen takeover (no tab bar).
if (feedbackSession) {
return (
@@ -80,16 +141,25 @@ function Shell() {
);
}
// Event-level feedback is also a full-screen takeover (no tab bar).
if (eventFeedbackOpen) {
return (
<div className="app">
<EventFeedback onDone={() => { setEventFeedbackOpen(false); setTab('home'); }} />
</div>
);
}
// The home page (incl. the tab bar) is identical for every role. Staff keep
// their check-in capability inside the Scan screen (Attendee/Staff toggle).
const scanLabel = 'Scan';
return (
<div className="app">
{tab === 'home' && <Home go={(t) => setTab(t as Tab)} />}
{tab === 'home' && <Home go={go} onEventFeedback={() => setEventFeedbackOpen(true)} openFeedback={(id) => setFeedbackSession(id)} />}
{tab === 'agenda' && <Agenda openFeedback={(id) => setFeedbackSession(id)} />}
{tab === 'scan' && <Scan />}
{tab === 'connections' && <Connections />}
{tab === 'connections' && <Connections initialTab={connectionsTab} />}
{tab === 'profile' && <Profile />}
{tab === 'leaderboard' && <Leaderboard />}
@@ -97,6 +167,7 @@ function Shell() {
{TABS.map((t) => (
<button
key={t.id}
data-testid={`tab-${t.id}`}
className={`tab ${t.id === 'scan' ? 'tab-scan' : ''} ${tab === t.id ? 'active' : ''}`}
onClick={() => setTab(t.id)}
>
@@ -117,6 +188,7 @@ function Shell() {
}
export default function App() {
if (isSpeakerPortal) return <SpeakerPortal />;
return (
<ToastProvider>
<AuthProvider>
@@ -0,0 +1,231 @@
import { useRef } from 'react';
import {
clearPreference,
downloadSessionMaterial,
removeSessionMaterial,
setPreference,
uploadSessionMaterial,
} from '../lib/api';
import { fmtRange, fmtTime, slotStatus } from '../lib/time';
import type { Session, Slot } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Sheet } from './ui';
/**
* The session detail bottom sheet — the single source of truth for what a
* session looks like when opened. Used by the Agenda list and by Home's
* "My picks today" chips, so tapping a pick on Home shows exactly the same
* detail as tapping it in the Agenda.
*/
export function SessionDetail({
session,
slot,
now,
checkedIn,
isSpeaker,
picked,
onClose,
onPickChanged,
onGiveFeedback,
onMaterialChanged,
}: {
session: Session | null;
slot: Slot | undefined;
now: Date;
checkedIn: boolean;
isSpeaker: boolean;
picked: boolean;
onClose: () => void;
/** Persist a pick/un-pick; the parent refreshes its own preference list. */
onPickChanged: () => Promise<void> | void;
onGiveFeedback?: (sessionId: string) => void;
/** Refresh the agenda after a material upload/remove. */
onMaterialChanged?: () => void;
}) {
const { toast } = useToast();
const fileRef = useRef<HTMLInputElement>(null);
if (!session || !slot) return null;
const status = slotStatus(slot, now);
const isService = slot.type === 'service_session';
// Service sessions have no material requirement (and no mic), so the
// pending-material notice never applies to them.
const needsMaterial = isSpeaker && !session.material_path && !isService;
// Feedback never applies to a service session: attendees cannot check in to
// one (so there is nothing to rate) and every staff member is auto-assigned
// as its speaker (so staff would otherwise see a "Your session feedback"
// block on a break/lunch card).
const showFeedback = !isService;
async function togglePick() {
try {
if (picked) {
await clearPreference(slot!.id);
toast('Pick removed');
} else {
await setPreference(session!.id);
toast('Pick saved ✓', 'ok');
}
await onPickChanged();
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not update pick', 'err');
}
}
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file || !session) return;
try {
await uploadSessionMaterial(session.id, file);
toast('Material uploaded ✓', 'ok');
onClose();
onMaterialChanged?.();
} catch (err) {
toast(err instanceof Error ? err.message : 'Upload failed', 'err');
} finally {
if (fileRef.current) fileRef.current.value = '';
}
}
async function handleDeleteMaterial() {
if (!session) return;
if (!confirm('Remove this material? You can upload a new one.')) return;
try {
await removeSessionMaterial(session.id);
toast('Material removed', 'ok');
onClose();
onMaterialChanged?.();
} catch (err) {
toast(err instanceof Error ? err.message : 'Could not remove material', 'err');
}
}
async function handleDownloadMaterial() {
if (!session?.material_path) return;
try {
await downloadSessionMaterial(session.material_path);
} catch (err) {
toast(err instanceof Error ? err.message : 'Download failed', 'err');
}
}
const range = fmtRange(slot);
// Talk slots are auto-named "Slot 10:15–11:00", which merely repeats the
// time range shown next to it, and service slots are often named exactly
// like their session (the title is already the heading). Show the slot name
// only when it actually adds information.
const showSlotName = slot.name !== `Slot ${range}` && slot.name !== session.title;
return (
<Sheet open onClose={onClose}>
<div className="row between">
<div>
<h3>{session.title}</h3>
<div className="sub">
{showSlotName && <>{slot.name} · </>}{range} · {session.room}
</div>
</div>
<button className="btn ghost small" onClick={onClose}>✕</button>
</div>
{/* The feed (Sessionize / Excel) carries real line breaks — .sd-desc
preserves them instead of collapsing the text into one block. */}
<div className="muted small sd-desc" id="sd-desc">
{session.description}
</div>
<div className="row" style={{ gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
<span className="pill">{isService ? '' : '🎤 '}{session.speakers}</span>
{session.level && <span className="pill violet">📶 {session.level}</span>}
{session.area && <span className="pill cyan">🗂 {session.area}</span>}
{session.language && <span className="pill">🌐 {session.language}</span>}
{session.capacity && <span className="pill">👥 {session.capacity}</span>}
{checkedIn && <span className="pill green">✓ Checked in</span>}
</div>
{/* Speaker material: non-dismissible notification until uploaded. */}
{needsMaterial && (
<div className="material-notice" data-testid="material-upload-notice">
<div className="mn-title">📎 Upload your session material</div>
<div className="muted small" style={{ marginBottom: 10 }}>
Attendees can download your slides/notes from this session.
</div>
<input ref={fileRef} type="file" data-testid="material-upload" className="input" onChange={handleUpload} />
</div>
)}
{/* Speaker feedback: visible only after the session is over, and never
for a service session. */}
{isSpeaker && showFeedback && status === 'done' && (
<div className="feedback-review">
<div className="fr-title">⭐ Your session feedback</div>
{session.average_feedback != null ? (
<div className="fr-rating">
<span className="fr-stars">
{[1, 2, 3, 4, 5].map((n) => (
<span key={n} className={n <= Math.round(session.average_feedback!) ? 'on' : ''}>★</span>
))}
</span>
<span className="fr-num">{session.average_feedback.toFixed(1)}</span>
</div>
) : (
<div className="muted small">No feedback yet.</div>
)}
{session.ai_generated_feedback && (
<div className="fr-summary">
<div className="muted small" style={{ fontWeight: 700, marginBottom: 4 }}>AI summary</div>
<div className="fr-text">{session.ai_generated_feedback}</div>
</div>
)}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{showFeedback && status === 'done' && checkedIn && onGiveFeedback && (
<button className="btn primary" data-testid="give-feedback" onClick={() => onGiveFeedback(session.id)}>
Give feedback ⭐
</button>
)}
{showFeedback && status === 'done' && !checkedIn && (
<div className="muted small" style={{ textAlign: 'center' }}>
You weren’t checked in to this session.
</div>
)}
{isService ? (
<div className="muted small" style={{ textAlign: 'center' }}>
No pick needed for this slot.
</div>
) : (
<button className={`btn ${picked ? 'danger' : 'primary'}`} onClick={togglePick}>
{picked ? 'Remove my pick' : 'Pick this session'}
</button>
)}
{/* Material: its existence is ALWAYS surfaced once uploaded, but the
download stays locked until the session's scheduled end so slides
don't distract mid-session. `status === 'done'` (client) mirrors
the server-side storage RLS rule; speakers bypass the lock for
their own talk. After the end anyone can download — attendance is
not required, only the clock. */}
{session.material_path && (
isSpeaker || status === 'done' ? (
<button className="btn primary" data-testid="material-download" onClick={handleDownloadMaterial}>
📎 Download material
</button>
) : (
<div className="material-notice" data-testid="material-locked">
<div className="mn-title">📎 Material uploaded</div>
<div className="muted small">
The speaker has uploaded material for this session.
The download unlocks when the session ends at {fmtTime(slot.end_time)}.
</div>
</div>
)
)}
{/* Speakers can remove their own material to re-upload. */}
{isSpeaker && session.material_path && (
<button className="btn danger" onClick={handleDeleteMaterial}>
🗑 Remove material
</button>
)}
</div>
</Sheet>
);
}
+34 -10
View File
@@ -53,14 +53,16 @@ export function Toggle({
checked,
onChange,
label,
testId,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label: string;
testId?: string;
}) {
return (
<label className="toggle">
<input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
<input type="checkbox" data-testid={testId} checked={checked} onChange={(e) => onChange(e.target.checked)} />
<span className="track">
<span className="knob" />
</span>
@@ -83,13 +85,27 @@ export function QrImage({ value, size = 180 }: { value: string; size?: number })
* decoded text. The camera only works on a secure context (https or localhost);
* the manual field always works.
*/
export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (text: string) => void; label?: string }) {
export function Scanner({ onResult, label = 'Scan a lanyard QR', entryLabel = 'QR code', placeholder = '…or type the code (e.g. CVV-XXX-NNNN)', submitLabel = 'Go', disabled = false, submitDisabled = false, onEntryChange, paused = false }: { onResult: (text: string) => void; label?: string; entryLabel?: string; placeholder?: string; submitLabel?: string; disabled?: boolean; submitDisabled?: boolean; onEntryChange?: (text: string) => void; paused?: boolean }) {
const [manual, setManual] = useState('');
const [camError, setCamError] = useState<string | null>(null);
const scannerRef = useRef<Html5Qrcode | null>(null);
const [camOn, setCamOn] = useState(false);
// The camera runs only while `paused` is false. The parent sets `paused`
// while it is busy or a result sheet is open, so a scan stops the camera
// (one code at a time) and closing the sheet restarts it automatically —
// no need to navigate away to re-arm it.
// The camera callback below is registered once per start; without a ref it
// would keep calling the FIRST render's onResult, whose closures over
// parent state (welcome mode, selected session) are stale. Always invoke
// the latest handler through this ref.
const onResultRef = useRef(onResult);
onResultRef.current = onResult;
// Guards against the callback firing again for the same lanyard in the
// frames between the decode and the camera actually stopping.
const scannedRef = useRef(false);
useEffect(() => {
if (paused) return;
let cancelled = false;
const el = document.getElementById('qr-reader');
if (!el) return;
@@ -106,6 +122,7 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
}
let scanner: Html5Qrcode | null = null;
scannedRef.current = false;
try {
scanner = new Html5Qrcode('qr-reader');
scannerRef.current = scanner;
@@ -114,10 +131,13 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
{ facingMode: 'environment' },
{ fps: 10, qrbox: { width: 220, height: 220 } },
(text) => {
if (cancelled) return;
if (cancelled || scannedRef.current) return;
scannedRef.current = true;
setCamOn(false);
// One code at a time: stop the camera now; the parent's `paused`
// (busy / sheet open) keeps it off, and clearing it restarts it.
scanner?.stop().catch(() => {});
onResult(text);
onResultRef.current(text);
},
() => {},
)
@@ -139,8 +159,7 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
/* ignore */
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [paused]);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
@@ -160,12 +179,17 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
<div className="row" style={{ gap: 8 }}>
<input
className="input mono"
placeholder="…or type the code (e.g. CVV-XXX-NNNN)"
type="text"
data-testid="scanner-manual-code"
aria-label={entryLabel}
placeholder={placeholder}
disabled={disabled}
value={manual}
onChange={(e) => setManual(e.target.value)}
onChange={(e) => { setManual(e.target.value); onEntryChange?.(e.target.value); }}
onKeyDown={(e) => { if (e.key === 'Enter' && manual.trim() && !disabled && !submitDisabled) onResult(manual.trim()); }}
/>
<button className="btn primary small" disabled={!manual.trim()} onClick={() => onResult(manual.trim())}>
Go
<button className="btn primary small" data-testid="scanner-manual-go" disabled={disabled || submitDisabled || !manual.trim()} onClick={() => onResult(manual.trim())}>
{submitLabel}
</button>
</div>
</div>
+51 -26
View File
@@ -1,7 +1,7 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import type { Session as SbSession, User } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
import { getMyContact, getMyRegistration } from '../lib/api';
import { adminCallbackPending, consumeAdminCallback, hasAdminCallback, invalidAdminLink, loadEntryProfile, type EntryProfile } from '../lib/adminEntry';
import type { Contact, Registration } from '../lib/types';
interface AuthContextValue {
@@ -10,6 +10,7 @@ interface AuthContextValue {
contact: Contact | null;
registration: Registration | null;
loading: boolean;
authError: string | null;
refresh: () => Promise<void>;
signOut: () => Promise<void>;
}
@@ -21,42 +22,66 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [contact, setContact] = useState<Contact | null>(null);
const [registration, setRegistration] = useState<Registration | null>(null);
const [loading, setLoading] = useState(true);
const [authError, setAuthError] = useState<string | null>(null);
const load = useCallback(async (email: string) => {
try {
const [c, r] = await Promise.all([getMyContact(email), getMyRegistration(email)]);
setContact(c);
setRegistration(r);
} catch (e) {
console.error('Failed to load contact', e);
}
const applyProfile = useCallback((profile: EntryProfile) => {
setSession(profile.session);
setContact(profile.contact);
setRegistration(profile.registration);
setAuthError(profile.error);
}, []);
useEffect(() => {
let active = true;
supabase.auth.getSession().then(({ data }) => {
if (!active) return;
setSession(data.session);
if (data.session?.user?.email) void load(data.session.user.email);
setLoading(false);
});
const { data: sub } = supabase.auth.onAuthStateChange((_event, newSession) => {
setSession(newSession);
if (newSession?.user?.email) void load(newSession.user.email);
else {
setContact(null);
setRegistration(null);
let revision = 0;
const emptyProfile: EntryProfile = { session: null, contact: null, registration: null, error: null };
async function restore(next: SbSession | null, currentRevision: number) {
try {
const profile = next ? await loadEntryProfile(next) : emptyProfile;
if (active && revision === currentRevision) applyProfile(profile);
} catch {
if (!active || revision !== currentRevision) return;
applyProfile({ ...emptyProfile, error: invalidAdminLink });
await supabase.auth.signOut({ scope: 'local' });
} finally {
if (active && revision === currentRevision) setLoading(false);
}
}
async function init() {
if (hasAdminCallback) {
const profile = await consumeAdminCallback();
if (active) { applyProfile(profile); setLoading(false); }
return;
}
const currentRevision = revision;
const { data } = await supabase.auth.getSession();
if (active && revision === currentRevision) await restore(data.session, currentRevision);
}
void init().catch(() => { if (active) { setAuthError(invalidAdminLink); setLoading(false); } });
const { data: sub } = supabase.auth.onAuthStateChange((event, newSession) => {
if (!active || adminCallbackPending || event === 'INITIAL_SESSION') return;
const currentRevision = ++revision;
if (!newSession) {
applyProfile(emptyProfile);
setLoading(false);
return;
}
setLoading(true);
window.setTimeout(() => {
if (active && revision === currentRevision) void restore(newSession, currentRevision);
}, 0);
});
return () => {
active = false;
sub.subscription.unsubscribe();
};
}, [load]);
}, [applyProfile]);
const refresh = useCallback(async () => {
if (session?.user?.email) await load(session.user.email);
}, [session, load]);
if (session) applyProfile(await loadEntryProfile(session));
}, [session, applyProfile]);
const signOut = useCallback(async () => {
await supabase.auth.signOut();
@@ -65,8 +90,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, []);
const value = useMemo<AuthContextValue>(
() => ({ session, user: session?.user ?? null, contact, registration, loading, refresh, signOut }),
[session, contact, registration, loading, refresh, signOut],
() => ({ session, user: session?.user ?? null, contact, registration, loading, authError, refresh, signOut }),
[session, contact, registration, loading, authError, refresh, signOut],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
+76
View File
@@ -0,0 +1,76 @@
import type { Session } from '@supabase/supabase-js';
import { supabase } from './supabase';
import { getMyContact, getMyRegistration } from './api';
import type { Contact, Registration } from './types';
export const invalidAdminLink = 'This sign-in link is invalid or expired. Please request a new link.';
export const adminLinkNotice = 'If this email belongs to an eligible admin account, a sign-in link has been sent.';
export const adminLinkFailure = 'Unable to send a sign-in link right now. Please try again later.';
export function isEmailEntry(value: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
}
export async function requestAdminLink(email: string): Promise<void> {
const normalizedEmail = email.trim().toLowerCase();
const { data: eligible, error: eligibilityError } = await supabase.rpc('can_request_admin_magic_link', { p_email: normalizedEmail });
if (eligibilityError) throw new Error(adminLinkFailure);
if (eligible !== true) return;
const { error } = await supabase.auth.signInWithOtp({
email: normalizedEmail,
options: { shouldCreateUser: false, emailRedirectTo: `${window.location.origin}/auth/callback` },
});
if (error && error.status !== 400 && error.status !== 422) throw new Error(adminLinkFailure);
}
const entryUrl = new URL(window.location.href);
const entryHash = new URLSearchParams(entryUrl.hash.slice(1));
export const hasAdminCallback = entryUrl.pathname === '/auth/callback' ||
(entryUrl.pathname === '/' && ['access_token', 'refresh_token', 'error', 'error_code'].some((key) => entryHash.has(key))) ||
(entryUrl.pathname === '/' && ['code', 'error', 'error_code'].some((key) => entryUrl.searchParams.has(key)));
if (hasAdminCallback) window.history.replaceState(null, '', '/');
export let adminCallbackPending = hasAdminCallback;
export interface EntryProfile {
session: Session | null;
contact: Contact | null;
registration: Registration | null;
error: string | null;
}
export async function loadEntryProfile(session: Session, adminOnly = false): Promise<EntryProfile> {
const { data: verified, error: userError } = await supabase.auth.getUser(session.access_token);
if (userError || !verified.user?.email || verified.user.id !== session.user.id) throw new Error(invalidAdminLink);
const { data: isAdmin, error: adminError } = await supabase.rpc('is_admin');
if (adminError) throw new Error(invalidAdminLink);
if (adminOnly && isAdmin !== true) throw new Error('This account is not an admin.');
const [contact, registration] = await Promise.all([
getMyContact(verified.user.email), getMyRegistration(verified.user.email),
]);
if (!contact) throw new Error(invalidAdminLink);
return { session: { ...session, user: verified.user }, contact: { ...contact, is_admin: isAdmin === true }, registration, error: null };
}
let callbackResult: Promise<EntryProfile> | null = null;
export function consumeAdminCallback(): Promise<EntryProfile> {
if (!callbackResult) callbackResult = (async () => {
try {
if (['error', 'error_code'].some((key) => entryHash.has(key) || entryUrl.searchParams.has(key))) throw new Error(invalidAdminLink);
const accessToken = entryHash.get('access_token');
const refreshToken = entryHash.get('refresh_token');
const code = entryUrl.searchParams.get('code');
const result = accessToken && refreshToken
? await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken })
: code && !accessToken && !refreshToken ? await supabase.auth.exchangeCodeForSession(code) : null;
if (!result || result.error || !result.data.session) throw new Error(invalidAdminLink);
return await loadEntryProfile(result.data.session, true);
} catch (failure) {
await supabase.auth.signOut({ scope: 'local' }).catch(() => {});
return { session: null, contact: null, registration: null, error: failure instanceof Error && failure.message === 'This account is not an admin.' ? failure.message : invalidAdminLink };
} finally {
adminCallbackPending = false;
}
})();
return callbackResult;
}
+24
View File
@@ -0,0 +1,24 @@
import type { Session, Slot } from './types';
type AgendaBlock = { slot: Slot; sessions: Session[] };
export function mergeAgendaPlaceholders(slots: AgendaBlock[]): AgendaBlock[] {
const blocks = slots.map(block => ({ slot: block.slot, sessions: [...block.sessions] }));
const merged = new Set<number>();
for (const block of blocks) {
if (block.slot.type !== 'service_session') continue;
const target = blocks.find(candidate => candidate.slot.type === 'session'
&& candidate.slot.slot_date === block.slot.slot_date
&& candidate.slot.start_time === block.slot.start_time
&& candidate.slot.end_time === block.slot.end_time);
if (!target) continue;
const placeholders = block.sessions.filter(session => session.slot_type === 'service_session'
&& session.title.trim().toLowerCase() === 'placeholder');
if (!placeholders.length) continue;
target.sessions.push(...placeholders);
const transferred = new Set(placeholders.map(session => session.id));
block.sessions = block.sessions.filter(session => !transferred.has(session.id));
if (!block.sessions.length) merged.add(block.slot.id);
}
return blocks.filter(block => !merged.has(block.slot.id));
}
+90 -16
View File
@@ -5,6 +5,7 @@ import type {
Connection,
Contact,
Event,
EventFeedback,
Feedback,
FeedbackResult,
LeaderboardRow,
@@ -15,6 +16,9 @@ import type {
Session,
Slot,
WelcomeCheckinResult,
WelcomeCheckinPreview,
AcceptConnectionResult,
TalkCohortMember,
} from './types';
export class ApiError extends Error {}
@@ -74,11 +78,38 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
ai_generated_feedback: r.ai_generated_feedback,
material_path: r.material_path,
speakers: r.speakers,
level: r.level,
area: r.area,
language: r.language,
created_at: '',
});
}
}
return [...map.values()].sort((a, b) => a.slot.id - b.slot.id);
// A service slot is only meaningful with a session behind it (break / lunch /
// closing …). An orphan service slot — left over from an earlier feed or a
// manual edit with no session row — would render as a header-only card,
// inconsistent with every other service card. Drop those (mirroring how the
// agenda already hides empty talk slots) so the list, its slot count, and
// Home's Now/Next all agree.
return [...map.values()]
.filter(({ slot, sessions }) => slot.type !== 'service_session' || sessions.length > 0)
.sort((first, second) =>
first.slot.slot_date.localeCompare(second.slot.slot_date)
|| first.slot.start_time.localeCompare(second.slot.start_time)
|| first.slot.end_time.localeCompare(second.slot.end_time)
|| first.slot.id - second.slot.id);
}
/** Submit (or update) the current user's event-level feedback. */
export async function submitEventFeedback(rating: number, comment: string): Promise<{ feedback_id: string; points: number; earned: number }> {
const rows = await rpc<{ feedback_id: string; points: number; earned: number }[]>('submit_event_feedback', { p_rating: rating, p_comment: comment });
return rows[0];
}
/** Read the current user's own event-level feedback (null if not yet submitted). */
export async function getMyEventFeedback(): Promise<EventFeedback | null> {
const rows = await rpc<EventFeedback[]>('get_my_event_feedback', {});
return rows[0] ?? null;
}
/** The signed-in contact's own row (filter by email — admins can see all rows). */
@@ -90,7 +121,9 @@ export async function getMyContact(email: string): Promise<Contact | null> {
/** The signed-in contact's registration for the active event. */
export async function getMyRegistration(email: string): Promise<Registration | null> {
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).maybeSingle();
const event = await getActiveEvent();
if (!event) return null;
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).eq('event_id', event.id).maybeSingle();
if (error) throw new ApiError(error.message);
return (data as Registration) ?? null;
}
@@ -139,8 +172,9 @@ export async function createConnectionRequest(targetQr: string): Promise<Connect
return rpc<Connection>('create_connection_request', { p_target_qr: targetQr });
}
export async function acceptConnection(id: string): Promise<Connection> {
return rpc<Connection>('accept_connection', { p_connection_id: id });
export async function acceptConnection(id: string): Promise<AcceptConnectionResult> {
// accept_connection returns a single composite row (a JSON object).
return rpc<AcceptConnectionResult>('accept_connection', { p_connection_id: id });
}
export async function rejectConnection(id: string): Promise<Connection> {
@@ -154,6 +188,11 @@ export async function getMyCheckins(email: string): Promise<string[]> {
return (data as { session_id: string }[]).map((c) => c.session_id);
}
/** Other attendees (staff excluded, self excluded) checked into the same talk. */
export async function getTalkCohort(sessionId: string): Promise<TalkCohortMember[]> {
return rpc<TalkCohortMember[]>('get_talk_cohort', { p_session_id: sessionId });
}
export async function checkinAttendee(sessionId: string, attendeeQr: string): Promise<CheckinResult> {
const rows = await rpc<CheckinResult[]>('checkin_attendee', { p_session_id: sessionId, p_attendee_qr: attendeeQr });
return rows[0];
@@ -165,6 +204,13 @@ export async function welcomeCheckin(attendeeQr: string): Promise<WelcomeCheckin
return rows[0];
}
/** Read-only preview of a welcome check-in: resolves the attendee and reports
* whether confirming will print their badge. Checks nobody in. */
export async function previewWelcomeCheckin(attendeeQr: string): Promise<WelcomeCheckinPreview> {
const rows = await rpc<WelcomeCheckinPreview[]>('preview_welcome_checkin', { p_attendee_qr: attendeeQr });
return rows[0];
}
export async function getMyFeedback(email: string): Promise<Feedback[]> {
const { data, error } = await supabase.from('feedback').select('*').eq('contact_email', email);
if (error) throw new ApiError(error.message);
@@ -190,10 +236,28 @@ export async function getMyPointsLog(email: string): Promise<PointsLogRow[]> {
return data as PointsLogRow[];
}
/** Public URL for a session material stored in the `materials` bucket. */
export function sessionMaterialUrl(path: string): string {
const { data } = supabase.storage.from('materials').getPublicUrl(path);
return data.publicUrl;
/** Filename of a material object path (`sessions/<id>/<ts>-<name>`). */
export function materialFilename(path: string): string {
const base = path.slice(path.lastIndexOf('/') + 1);
return base.replace(/^\d+-/, '');
}
/** Download a session material through authenticated storage. The materials
* bucket is private and server-side RLS only releases the file to the
* session's own speakers/admins at any time, and to everyone else once the
* session's scheduled end has passed — so this legitimately fails before the
* end for plain attendees even if the UI clock disagrees. */
export async function downloadSessionMaterial(path: string): Promise<void> {
const { data, error } = await supabase.storage.from('materials').download(path);
if (error) throw new ApiError('Download failed — material unlocks when the session ends.');
const url = URL.createObjectURL(data);
const a = document.createElement('a');
a.href = url;
a.download = materialFilename(path);
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
/** Session ids the signed-in contact is a speaker of (for material upload). */
@@ -210,14 +274,23 @@ export async function getMySpeakerSessions(email: string): Promise<string[]> {
* The path is persisted via the `set_session_material` RPC (the sessions table
* is admin-write only, so speakers need the security-definer RPC). */
export async function uploadSessionMaterial(sessionId: string, file: File): Promise<string> {
const path = `sessions/${sessionId}/${Date.now()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`;
const { error: upErr } = await supabase.storage.from('materials').upload(path, file, { upsert: true });
const { data: previous, error: readError } = await supabase.from('sessions').select('material_path').eq('id', sessionId).single();
if (readError) throw new ApiError(readError.message);
const path = `sessions/${sessionId}/${crypto.randomUUID()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`;
const { error: upErr } = await supabase.storage.from('materials').upload(path, file, { upsert: false });
if (upErr) throw new ApiError(upErr.message);
const { error: dbErr } = await supabase.rpc('set_session_material', {
p_session_id: sessionId,
p_material_path: path,
});
if (dbErr) throw new ApiError(dbErr.message);
if (dbErr) {
const { error: cleanupError } = await supabase.storage.from('materials').remove([path]);
throw new ApiError(`${dbErr.message}${cleanupError ? ' The unattached upload could not be cleaned up.' : ''}`);
}
if (previous.material_path && previous.material_path !== path) {
const { error: cleanupError } = await supabase.storage.from('materials').remove([previous.material_path]);
if (cleanupError) throw new ApiError('Material saved, but the previous file could not be removed. Refresh to see the saved material.');
}
return path;
}
@@ -225,15 +298,16 @@ export async function uploadSessionMaterial(sessionId: string, file: File): Prom
* can delete their own material to re-upload; the path is cleared via the
* `set_session_material` RPC (sessions is admin-write only). */
export async function removeSessionMaterial(sessionId: string): Promise<void> {
const { data } = await supabase.from('sessions').select('material_path').eq('id', sessionId).maybeSingle();
const { data, error: readError } = await supabase.from('sessions').select('material_path').eq('id', sessionId).single();
if (readError) throw new ApiError(readError.message);
const path = (data as Session | null)?.material_path;
if (path) {
const { error: rmErr } = await supabase.storage.from('materials').remove([path]);
if (rmErr) throw new ApiError(rmErr.message);
}
const { error: dbErr } = await supabase.rpc('set_session_material', {
p_session_id: sessionId,
p_material_path: null,
});
if (dbErr) throw new ApiError(dbErr.message);
if (path) {
const { error: rmErr } = await supabase.storage.from('materials').remove([path]);
if (rmErr) throw new ApiError('Material detached, but the file could not be removed from storage.');
}
}
+56
View File
@@ -0,0 +1,56 @@
import type { Session } from '@supabase/supabase-js';
import { supabase } from './supabase';
export const isSpeakerPortal = /^\/speaker(?:\/secret)?\/?$/.test(window.location.pathname);
export interface SpeakerSession {
session_id: string;
title: string;
description: string | null;
room: string | null;
material_path: string | null;
event_id: string;
event_name: string;
event_start_date: string;
event_end_date: string;
is_active: boolean;
slot_date: string;
start_time: string;
end_time: string;
}
async function consumeCallback(): Promise<Session | null> {
const url = new URL(window.location.href);
const hash = new URLSearchParams(url.hash.slice(1));
const accessToken = hash.get('access_token');
const refreshToken = hash.get('refresh_token');
const code = url.searchParams.get('code');
const callbackError = hash.get('error') || url.searchParams.get('error');
const hasCallback = accessToken || refreshToken || code || callbackError;
if (hasCallback) window.history.replaceState(null, '', window.location.pathname);
if (callbackError) throw new Error('This sign-in link has expired or is invalid. Request a new link.');
if (accessToken || refreshToken) {
if (!accessToken || !refreshToken) throw new Error('Incomplete sign-in link. Request a new link.');
const { data, error } = await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken });
if (error) throw new Error('This sign-in link has expired or is invalid. Request a new link.');
return data.session;
}
if (code) {
const { data, error } = await supabase.auth.exchangeCodeForSession(code);
if (error) throw new Error('This sign-in link could not be opened on this device. Request a new link.');
return data.session;
}
const { data, error } = await supabase.auth.getSession();
if (error) throw error;
return data.session;
}
export const speakerPortalSession = isSpeakerPortal
? consumeCallback().then((session) => ({ session, error: null }), (error: Error) => ({ session: null, error }))
: Promise.resolve({ session: null, error: null });
export async function getSpeakerPortalSessions(): Promise<SpeakerSession[]> {
const { data, error } = await supabase.rpc('get_my_speaker_sessions');
if (error) throw new Error(error.message);
return data as SpeakerSession[];
}
+3 -6
View File
@@ -1,11 +1,8 @@
import type { Slot } from './types';
/** The event day (from the seed). All slot times are on this date. */
export const EVENT_DATE = '2026-02-20';
/** Simulated "now" used for the demo (10:20 on event day → Slot 2 is live,
* Slot 3 is next). Matches the mockup's "Good morning" greeting. */
export const DEFAULT_NOW = new Date(`${EVENT_DATE}T10:20:00`);
export function demoNow(eventDate: string): Date {
return new Date(`${eventDate}T10:20:00`);
}
export type SlotStatus = 'done' | 'now' | 'next';
+56 -1
View File
@@ -35,6 +35,8 @@ export interface Event {
is_active: boolean;
/** When true, the app uses the real system clock for slot status (Live/Next/Done). */
use_realtime_clock: boolean;
/** Bonus points each party earns for a connection when they shared a checked-in talk (0 = off). */
talk_networking_bonus: number;
avg_feedback: number | null;
num_sessions: number;
num_speakers: number;
@@ -68,6 +70,12 @@ export interface Session {
material_path: string | null;
/** Comma-separated speaker names (from the get_agenda RPC). */
speakers: string | null;
/** Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). */
level: string | null;
/** Free-text area/topic classification (e.g. Power Apps, Power Automate). */
area: string | null;
/** Free-text delivery language (e.g. English, German). */
language: string | null;
created_at: string;
}
@@ -88,6 +96,19 @@ export interface AgendaRow {
ai_generated_feedback: string | null;
material_path: string | null;
speakers: string | null;
level: string | null;
area: string | null;
language: string | null;
}
/** Event-level feedback (distinct from the per-session `feedback` table). */
export interface EventFeedback {
id: string;
event_id: string;
contact_email: string;
rating: number;
comment: string | null;
created_at: string;
}
export interface Preference {
@@ -141,7 +162,7 @@ export interface PointsLogRow {
event_id: string;
contact_email: string;
delta: number;
category: 'checkin' | 'connection' | 'feedback' | 'admin';
category: 'checkin' | 'connection' | 'feedback' | 'admin' | 'talk_networking';
created_at: string;
}
@@ -160,6 +181,8 @@ export interface CheckinResult {
attendee_name: string;
points: number;
already: boolean;
/** False for staff / Admin contacts, who never earn points. */
points_awarded: boolean;
}
/** Result of a staff welcome check-in (marks an attendee present at the event). */
@@ -167,6 +190,38 @@ export interface WelcomeCheckinResult {
attendee_email: string;
attendee_name: string;
already: boolean;
/** Points balance after the check-in. */
points: number;
/** False when this person does not earn points (staff or Admin contact), so
* the sheet must not promise a +10 the database never granted. */
points_awarded: boolean;
}
/** Read-only preview of a welcome check-in (shown before confirming). */
export interface WelcomeCheckinPreview {
attendee_email: string;
attendee_name: string;
already: boolean;
/** True when confirming will enqueue a badge print (first check-in + a layout exists). */
will_print: boolean;
/** How many labels confirming will print (0 when nothing prints). */
copies: number;
/** True when confirming will award check-in points (false for staff/Admin). */
points_awarded: boolean;
}
/** Result of accepting a connection (the connection row + the shared-talk flag). */
export interface AcceptConnectionResult extends Connection {
/** True when both parties were checked into the same session (talk). */
shared_talk: boolean;
}
/** A person checked into the same talk (from get_talk_cohort). */
export interface TalkCohortMember {
email: string;
full_name: string;
registration_type: RegistrationType | null;
qr_token: string | null;
}
export interface FeedbackResult {
+2 -2
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { getActiveEvent, getAgenda, groupAgenda } from './api';
import { DEFAULT_NOW } from './time';
import { demoNow } from './time';
import type { Event, Session, Slot } from './types';
export interface EventData {
@@ -53,7 +53,7 @@ export function useEvent(): EventData {
// The event's `use_realtime_clock` flag decides the clock: the real system
// time, or the simulated mid-event clock (so the demo always looks live).
const clockMode: 'simulated' | 'realtime' = event?.use_realtime_clock ? 'realtime' : 'simulated';
const now = clockMode === 'realtime' ? new Date() : DEFAULT_NOW;
const now = clockMode === 'simulated' && event ? demoNow(event.start_date) : new Date();
return {
event,
+115 -168
View File
@@ -1,20 +1,12 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import {
clearPreference,
getMyCheckins,
getMyPreferences,
getMySpeakerSessions,
removeSessionMaterial,
sessionMaterialUrl,
setPreference,
uploadSessionMaterial,
} from '../lib/api';
import { mergeAgendaPlaceholders } from '../lib/agendaBlocks';
import { getMyCheckins, getMyPreferences, getMySpeakerSessions } from '../lib/api';
import { capWords, fmtRange, slotStatus } from '../lib/time';
import type { Preference, Session } from '../lib/types';
import { Sheet, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
import { Spinner } from '../components/ui';
import { SessionDetail } from '../components/SessionDetail';
export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) => void }) {
const { contact } = useAuth();
@@ -23,11 +15,40 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
const [checkins, setCheckins] = useState<string[]>([]);
const [mySpeakerSessions, setMySpeakerSessions] = useState<string[]>([]);
const [selected, setSelected] = useState<Session | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const { toast } = useToast();
// Agenda filters: level + area + language (free-text, dynamic — built from
// the distinct values actually present in the agenda, so it works for
// numeric levels (100/200/300) or text levels (Beginner/Intermediate) alike.
const [levelFilter, setLevelFilter] = useState<string>('');
const [areaFilter, setAreaFilter] = useState<string>('');
const [languageFilter, setLanguageFilter] = useState<string>('');
const email = contact?.email ?? '';
// Distinct level + area + language values present in the agenda (for the
// filter dropdowns).
const levelOptions = useMemo(() => {
const set = new Set<string>();
for (const { sessions } of slots) for (const s of sessions) if (s.level) set.add(s.level);
return [...set].sort();
}, [slots]);
const areaOptions = useMemo(() => {
const set = new Set<string>();
for (const { sessions } of slots) for (const s of sessions) if (s.area) set.add(s.area);
return [...set].sort();
}, [slots]);
const languageOptions = useMemo(() => {
const set = new Set<string>();
for (const { sessions } of slots) for (const s of sessions) if (s.language) set.add(s.language);
return [...set].sort();
}, [slots]);
const matchesFilter = (s: Session) =>
(!levelFilter || s.level === levelFilter) &&
(!areaFilter || s.area === areaFilter) &&
(!languageFilter || s.language === languageFilter);
const displayBlocks = mergeAgendaPlaceholders(slots);
useEffect(() => {
let active = true;
(async () => {
@@ -76,60 +97,7 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
const pickFor = (slotId: number) => prefs.find((p) => p.slot_id === slotId)?.session_id;
async function togglePick(slotId: number, sessionId: string) {
const current = pickFor(slotId);
try {
if (current === sessionId) {
await clearPreference(slotId);
toast('Pick removed');
} else {
await setPreference(sessionId);
toast('Pick saved ✓', 'ok');
}
const p = await getMyPreferences();
setPrefs(p);
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not update pick', 'err');
}
}
const selSlot = selected ? slots.find((s) => s.slot.id === selected.slot_id)?.slot : undefined;
const selStatus = selSlot ? slotStatus(selSlot, now) : 'next';
const selCheckedIn = selected ? checkins.includes(selected.id) : false;
const selISpeaker = selected ? mySpeakerSessions.includes(selected.id) : false;
const selIsService = selSlot?.type === 'service_session';
// Service sessions have no material requirement (and no mic), so the
// pending-material notice never applies to them.
const selNeedsMaterial = selISpeaker && !selected?.material_path && !selIsService;
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file || !selected) return;
try {
await uploadSessionMaterial(selected.id, file);
toast('Material uploaded ✓', 'ok');
setSelected(null);
// Refresh agenda so material_path updates.
reload();
} catch (err) {
toast(err instanceof Error ? err.message : 'Upload failed', 'err');
} finally {
if (fileRef.current) fileRef.current.value = '';
}
}
async function handleDeleteMaterial() {
if (!selected) return;
if (!confirm('Remove this material? You can upload a new one.')) return;
try {
await removeSessionMaterial(selected.id);
toast('Material removed', 'ok');
setSelected(null);
reload();
} catch (err) {
toast(err instanceof Error ? err.message : 'Could not remove material', 'err');
}
}
return (
<section className="screen">
@@ -138,15 +106,78 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
<div className="h1">Agenda</div>
<div className="muted small">{event.name}</div>
</div>
<span className="pill violet">{slots.length} slots</span>
<span className="pill violet">{displayBlocks.length} slots</span>
</div>
<div className="muted small" style={{ marginTop: -4 }}>
Pick <b>one session per slot</b> — you can change until the slot starts.
</div>
{/* Agenda filters: level + area + language (only shown if there are values to filter by). */}
{(levelOptions.length > 0 || areaOptions.length > 0 || languageOptions.length > 0) && (
<div className="row" style={{ gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
{levelOptions.length > 0 && (
<select
className="input"
style={{ flex: 1, minWidth: 120 }}
value={levelFilter}
onChange={(e) => setLevelFilter(e.target.value)}
aria-label="Filter by level"
>
<option value="">All levels</option>
{levelOptions.map((l) => (
<option key={l} value={l}>{l}</option>
))}
</select>
)}
{areaOptions.length > 0 && (
<select
className="input"
style={{ flex: 1, minWidth: 120 }}
value={areaFilter}
onChange={(e) => setAreaFilter(e.target.value)}
aria-label="Filter by area"
>
<option value="">All areas</option>
{areaOptions.map((a) => (
<option key={a} value={a}>{a}</option>
))}
</select>
)}
{languageOptions.length > 0 && (
<select
className="input"
style={{ flex: 1, minWidth: 120 }}
value={languageFilter}
onChange={(e) => setLanguageFilter(e.target.value)}
aria-label="Filter by language"
>
<option value="">All languages</option>
{languageOptions.map((l) => (
<option key={l} value={l}>{l}</option>
))}
</select>
)}
{(levelFilter || areaFilter || languageFilter) && (
<button
className="btn ghost small"
onClick={() => { setLevelFilter(''); setAreaFilter(''); setLanguageFilter(''); }}
aria-label="Clear filters"
>
✕
</button>
)}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{slots.map(({ slot, sessions }) => {
{displayBlocks.map(({ slot, sessions }) => {
const status = slotStatus(slot, now);
const isServiceSlot = slot.type === 'service_session';
// Apply the level/area/language filter to non-service sessions only
// (service sessions have none of these and are always shown).
const visibleSessions = sessions.filter(session => session.slot_type === 'service_session' || matchesFilter(session));
// Skip the slot if it's a talk slot and all its sessions are filtered out.
if (!isServiceSlot && visibleSessions.length === 0) return null;
return (
<div className="slot-card" key={slot.id}>
<div className="slot-head">
@@ -160,10 +191,10 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
{status === 'now' && <span className="pill violet">● Live</span>}
{status === 'next' && <span className="pill cyan">Up next</span>}
</div>
{sessions.map((s) => {
{visibleSessions.map((s) => {
const picked = pickFor(slot.id) === s.id;
const isMySession = mySpeakerSessions.includes(s.id);
const isService = slot.type === 'service_session';
const isService = s.slot_type === 'service_session';
return (
<button key={s.id} className={`sess ${picked ? 'picked' : ''}`} onClick={() => setSelected(s)}>
<div className="grow">
@@ -187,102 +218,18 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
})}
</div>
<Sheet open={!!selected} onClose={() => setSelected(null)}>
{selected && selSlot && (
<>
<div className="row between">
<div>
<h3>{selected.title}</h3>
<div className="sub">
{selSlot.name} · {fmtRange(selSlot)} · {selected.room}
</div>
</div>
<button className="btn ghost small" onClick={() => setSelected(null)}>✕</button>
</div>
<div className="muted small" id="sd-desc" style={{ margin: '12px 0', lineHeight: 1.55 }}>
{selected.description}
</div>
<div className="row" style={{ gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
<span className="pill">{selIsService ? '' : '🎤 '}{selected.speakers}</span>
{selected.capacity && <span className="pill">👥 {selected.capacity}</span>}
{selCheckedIn && <span className="pill green">✓ Checked in</span>}
</div>
{/* Speaker material: non-dismissible notification until uploaded. */}
{selNeedsMaterial && (
<div className="material-notice">
<div className="mn-title">📎 Upload your session material</div>
<div className="muted small" style={{ marginBottom: 10 }}>
Attendees can download your slides/notes from this session.
</div>
<input ref={fileRef} type="file" className="input" onChange={handleUpload} />
</div>
)}
{/* Speaker feedback: visible only after the session is over. */}
{selISpeaker && selStatus === 'done' && (
<div className="feedback-review">
<div className="fr-title">⭐ Your session feedback</div>
{selected.average_feedback != null ? (
<div className="fr-rating">
<span className="fr-stars">
{[1, 2, 3, 4, 5].map((n) => (
<span key={n} className={n <= Math.round(selected.average_feedback!) ? 'on' : ''}>★</span>
))}
</span>
<span className="fr-num">{selected.average_feedback.toFixed(1)}</span>
</div>
) : (
<div className="muted small">No feedback yet.</div>
)}
{selected.ai_generated_feedback && (
<div className="fr-summary">
<div className="muted small" style={{ fontWeight: 700, marginBottom: 4 }}>AI summary</div>
<div style={{ lineHeight: 1.5 }}>{selected.ai_generated_feedback}</div>
</div>
)}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{selStatus === 'done' && selCheckedIn && (
<button className="btn primary" onClick={() => openFeedback(selected.id)}>
Give feedback ⭐
</button>
)}
{selStatus === 'done' && !selCheckedIn && (
<div className="muted small" style={{ textAlign: 'center' }}>
You weren’t checked in to this session.
</div>
)}
{selSlot.type === 'service_session' ? (
<div className="muted small" style={{ textAlign: 'center' }}>
No pick needed for this slot.
</div>
) : (
<button
className={`btn ${pickFor(selected.slot_id) === selected.id ? 'danger' : 'primary'}`}
onClick={() => togglePick(selected.slot_id, selected.id)}
>
{pickFor(selected.slot_id) === selected.id ? 'Remove my pick' : 'Pick this session'}
</button>
)}
{/* Material download (all attendees) — pinned to the bottom. */}
{selected.material_path && (
<a className="btn primary" href={sessionMaterialUrl(selected.material_path)} target="_blank" rel="noreferrer">
📎 Download material
</a>
)}
{/* Speakers can remove their own material to re-upload. */}
{selISpeaker && selected.material_path && (
<button className="btn danger" onClick={handleDeleteMaterial}>
🗑 Remove material
</button>
)}
</div>
</>
)}
</Sheet>
<SessionDetail
session={selected}
slot={selSlot}
now={now}
checkedIn={!!selected && checkins.includes(selected.id)}
isSpeaker={!!selected && mySpeakerSessions.includes(selected.id)}
picked={!!selected && pickFor(selected.slot_id) === selected.id}
onClose={() => setSelected(null)}
onPickChanged={async () => setPrefs(await getMyPreferences())}
onGiveFeedback={openFeedback}
onMaterialChanged={reload}
/>
</section>
);
}
+20 -7
View File
@@ -6,10 +6,20 @@ import { capWords } from '../lib/time';
import type { Connection, PublicContact } from '../lib/types';
import { Avatar, Empty, Sheet, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
import { NetworkingPanel } from './Networking';
export function Connections() {
export function Connections({
initialTab = 'mine',
}: {
initialTab?: 'mine' | 'req' | 'networking';
}) {
const { contact } = useAuth();
const [tab, setTab] = useState<'mine' | 'req'>('mine');
const [tab, setTab] = useState<'mine' | 'req' | 'networking'>(initialTab);
// A deep-link (e.g. the Home "Networking" quick action) re-targets the tab.
useEffect(() => {
setTab(initialTab);
}, [initialTab]);
const [conns, setConns] = useState<Connection[]>([]);
const [people, setPeople] = useState<Map<string, PublicContact>>(new Map());
const [points, setPoints] = useState<Map<string, number>>(new Map());
@@ -71,12 +81,13 @@ export function Connections() {
return (
<section className="screen">
<div className="h1">Connections</div>
<div className="h1">{tab === 'networking' ? 'Networking' : 'Connections'}</div>
<div className="seg">
<button className={tab === 'mine' ? 'active' : ''} onClick={() => setTab('mine')}>My connections</button>
<button className={tab === 'req' ? 'active' : ''} onClick={() => setTab('req')}>
<button className={tab === 'mine' ? 'active' : ''} data-testid="connections-tab-mine" onClick={() => setTab('mine')}>My connections</button>
<button className={tab === 'req' ? 'active' : ''} data-testid="connections-tab-req" onClick={() => setTab('req')}>
Requests {incoming.length + outgoing.length > 0 && <span className="pill violet" style={{ marginLeft: 4 }}>{incoming.length + outgoing.length}</span>}
</button>
<button className={tab === 'networking' ? 'active' : ''} data-testid="connections-tab-networking" onClick={() => setTab('networking')}>🗣 Networking</button>
</div>
{tab === 'mine' &&
@@ -120,8 +131,8 @@ export function Connections() {
)}
</div>
</div>
<button className="btn primary small" onClick={() => resolve(c.id, true)}>Accept</button>
<button className="btn small" onClick={() => resolve(c.id, false)}>Decline</button>
<button className="btn primary small" data-testid="connection-accept" onClick={() => resolve(c.id, true)}>Accept</button>
<button className="btn small" data-testid="connection-decline" onClick={() => resolve(c.id, false)}>Decline</button>
</div>
))}
</div>
@@ -146,6 +157,8 @@ export function Connections() {
</div>
)}
{tab === 'networking' && <NetworkingPanel />}
{detail && (() => {
const p = people.get(detail.email);
const t = p?.registration_type ?? null;
+121
View File
@@ -0,0 +1,121 @@
import { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import { getMyEventFeedback, submitEventFeedback } from '../lib/api';
import { Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
/**
* Event-level feedback (distinct from the per-session Feedback screen).
* Any registered participant can rate the event overall (1–5) + leave a
* comment. Idempotent: one row per (event, contact) — re-submitting updates
* the existing row.
*/
export function EventFeedback({ onDone }: { onDone: () => void }) {
const { contact } = useAuth();
const { event, loading } = useEvent();
const [rating, setRating] = useState(0);
const [comment, setComment] = useState('');
const [busy, setBusy] = useState(false);
const [submitted, setSubmitted] = useState(false);
const { toast } = useToast();
// Pre-fill with the user's existing event feedback (if any).
useEffect(() => {
let active = true;
(async () => {
try {
const existing = await getMyEventFeedback();
if (!active || !existing) return;
setRating(existing.rating);
setComment(existing.comment ?? '');
setSubmitted(true);
} catch {
/* non-fatal */
}
})();
return () => {
active = false;
};
}, []);
if (loading || !event) {
return (
<section className="screen no-tab">
<div className="center" style={{ flex: 1 }}>
<Spinner />
</div>
</section>
);
}
async function submit() {
if (rating === 0) return;
setBusy(true);
try {
const res = await submitEventFeedback(rating, comment.trim());
toast(res.earned > 0 ? `Thanks! +${res.earned} pts ⭐` : 'Thanks for your feedback! ⭐', 'ok');
setSubmitted(true);
onDone();
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not submit feedback', 'err');
} finally {
setBusy(false);
}
}
return (
<section className="screen no-tab">
<div className="row" style={{ marginBottom: 14 }}>
<button className="btn ghost small" onClick={onDone}>← Back</button>
<div className="grow" style={{ textAlign: 'center' }}>
<div className="h2">Rate this event</div>
</div>
<span style={{ width: 60 }} />
</div>
<div className="card" style={{ textAlign: 'center' }}>
<div className="h2">{event.name}</div>
<div className="muted small" style={{ marginTop: 4 }}>
{event.location ? `${event.location} · ` : ''}
{event.start_date}
</div>
</div>
<div className="stars" style={{ justifyContent: 'center', margin: '20px 0' }}>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
data-testid={`event-feedback-star-${n}`}
className={`star ${n <= rating ? 'on' : ''}`}
onClick={() => setRating(n)}
aria-label={`${n} star${n > 1 ? 's' : ''}`}
>
★
</button>
))}
</div>
<textarea
className="input"
data-testid="event-feedback-comment"
placeholder="Share your thoughts about the event (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
/>
<button
className="btn primary"
data-testid="event-feedback-submit"
disabled={busy || rating === 0}
onClick={submit}
>
{busy ? 'Submitting…' : submitted ? 'Update feedback' : 'Submit feedback'}
</button>
<div className="muted small" style={{ textAlign: 'center', marginTop: 8 }}>
{contact ? `Signing in as ${contact.full_name}` : ''}
</div>
</section>
);
}
+3 -1
View File
@@ -58,6 +58,7 @@ export function Feedback({ sessionId, onDone }: { sessionId: string; onDone: ()
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
data-testid={`feedback-star-${n}`}
className={`star ${n <= rating ? 'on' : ''}`}
onClick={() => setRating(n)}
aria-label={`${n} star${n > 1 ? 's' : ''}`}
@@ -69,13 +70,14 @@ export function Feedback({ sessionId, onDone }: { sessionId: string; onDone: ()
<textarea
className="input"
data-testid="feedback-comment"
placeholder="Add a comment (optional) — comments earn bonus points"
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
/>
<button className="btn primary" disabled={busy || rating === 0} onClick={submit}>
<button className="btn primary" data-testid="feedback-submit" disabled={busy || rating === 0} onClick={submit}>
{busy ? 'Submitting…' : 'Submit feedback'}
</button>
<div className="muted small" style={{ textAlign: 'center', marginTop: 8 }}>
+54 -15
View File
@@ -5,6 +5,7 @@ import { getMyCheckins, getMyFeedback, getMyPreferences, getMySpeakerSessions }
import { fmtRange, greeting, slotStatus } from '../lib/time';
import type { Feedback, Preference, Session } from '../lib/types';
import { Sheet, Spinner } from '../components/ui';
import { SessionDetail } from '../components/SessionDetail';
/** A single session block inside the Now/Next card (title + room + speaker). */
function SessionBlock({ session, checkedIn }: { session: Session; checkedIn?: boolean }) {
@@ -25,8 +26,11 @@ function SessionBlock({ session, checkedIn }: { session: Session; checkedIn?: bo
);
}
/** The list of concurrent sessions shown when the user has no pick for the slot. */
function ConcurrentList({ sessions }: { sessions: Session[] }) {
/** The list of concurrent sessions shown when the user has no pick for the slot.
* The "No pick yet" nudge only makes sense for someone who has never picked;
* once the user has any pick it would contradict the "My picks today" list
* below, so it is hidden (hasPicks). */
function ConcurrentList({ sessions, hasPicks }: { sessions: Session[]; hasPicks: boolean }) {
return (
<div className="now-list">
{sessions.map((s) => (
@@ -35,21 +39,27 @@ function ConcurrentList({ sessions }: { sessions: Session[] }) {
<div className="muted small">{s.room} · {s.speakers}</div>
</div>
))}
{!hasPicks && (
<div className="muted small" style={{ marginTop: 10 }}>
No pick yet — tap a session in the Agenda to choose.
</div>
)}
</div>
);
}
export function Home({ go }: { go: (tab: string) => void }) {
export function Home({ go, onEventFeedback, openFeedback }: { go: (tab: string) => void; onEventFeedback?: () => void; openFeedback?: (sessionId: string) => void }) {
const { contact, registration } = useAuth();
const { event, slots, sessionById, slotById, now, clockMode, loading } = useEvent();
const { event, slots, sessionById, slotById, now, loading, reload } = useEvent();
const [prefs, setPrefs] = useState<Preference[]>([]);
const [checkins, setCheckins] = useState<string[]>([]);
const [mySpeakerSessions, setMySpeakerSessions] = useState<string[]>([]);
const [myFeedback, setMyFeedback] = useState<Feedback[]>([]);
const [materialSheetOpen, setMaterialSheetOpen] = useState(false);
// The pick the user tapped in "My picks today" — opened in the same detail
// sheet the Agenda uses, so a pick shows the full session info in place
// instead of bouncing to the Agenda tab.
const [selected, setSelected] = useState<Session | null>(null);
const email = contact?.email ?? '';
@@ -141,15 +151,10 @@ export function Home({ go }: { go: (tab: string) => void }) {
<div>
<div className="h1">{greeting(now)}, {firstName} 👋</div>
<div className="muted small">{event.name}</div>
{clockMode === 'simulated' && (
<div className="muted small" style={{ marginTop: 2 }}>
🎬 Demo clock
</div>
)}
</div>
<div className="row" style={{ gap: 8 }}>
{pendingMaterial.length > 0 && (
<div className="material-pill" onClick={() => setMaterialSheetOpen(true)}>
<div className="material-pill" data-testid="material-pill" onClick={() => setMaterialSheetOpen(true)}>
📎 {pendingMaterial.length}
</div>
)}
@@ -159,7 +164,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
{/* Pending feedback: nudge to rate a session they attended. */}
{feedbackPending.length > 0 && (
<button className="feedback-pill" onClick={() => go('agenda')}>
<button className="feedback-pill" data-testid="feedback-pill" onClick={() => go('agenda')}>
⭐ {feedbackPending.length === 1 ? 'Rate your last session' : `Rate ${feedbackPending.length} sessions`}
</button>
)}
@@ -174,7 +179,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
{nowPick ? (
<SessionBlock session={nowPick} checkedIn={checkins.includes(nowPick.id)} />
) : current.sessions.length > 0 ? (
<ConcurrentList sessions={current.sessions} />
<ConcurrentList sessions={current.sessions} hasPicks={picks.length > 0} />
) : (
<div className="muted small" style={{ marginTop: 10 }}>Nothing scheduled right now.</div>
)}
@@ -191,7 +196,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
{nextPick ? (
<SessionBlock session={nextPick} />
) : next.sessions.length > 0 ? (
<ConcurrentList sessions={next.sessions} />
<ConcurrentList sessions={next.sessions} hasPicks={picks.length > 0} />
) : (
<div className="muted small" style={{ marginTop: 10 }}>Nothing scheduled next.</div>
)}
@@ -207,7 +212,12 @@ export function Home({ go }: { go: (tab: string) => void }) {
{picks.length > 0 ? (
<div style={{ display: 'flex', flexDirection: 'column' }}>
{picks.map((r) => (
<button key={r.session.id} className="pick-chip" onClick={() => go('agenda')}>
<button
key={r.session.id}
className="pick-chip"
data-testid="home-pick"
onClick={() => setSelected(r.session)}
>
<span className="t">{fmtRange(r.slot)}</span>
<span className="grow" style={{ fontWeight: 600, textAlign: 'left' }}>
{r.session.title}
@@ -236,11 +246,20 @@ export function Home({ go }: { go: (tab: string) => void }) {
<span className="ico">🤝</span>
<span className="lbl">Connections</span>
</div>
<div className="qa" onClick={() => go('networking')}>
<span className="ico">🗣</span>
<span className="lbl">Networking</span>
</div>
<div className="qa" onClick={() => go('leaderboard')}>
<span className="ico">🏆</span>
<span className="lbl">Leaderboard</span>
</div>
</div>
{onEventFeedback && (
<button className="btn ghost" style={{ width: '100%', marginTop: 10 }} onClick={onEventFeedback}>
⭐ Rate this event
</button>
)}
<div style={{ height: 8 }} />
{/* Pending material popup (speakers only, when a session is missing its attachment) */}
@@ -256,9 +275,14 @@ export function Home({ go }: { go: (tab: string) => void }) {
<button
key={s.id}
className="pick-chip"
data-testid={`pending-material-${s.id}`}
onClick={() => {
// Open this session's detail sheet directly — the same sheet
// "My picks today" opens — instead of dropping the speaker on
// the Agenda and making them hunt for the very talk they were
// just told about. The detail sheet carries the upload form.
setMaterialSheetOpen(false);
go('agenda');
setSelected(s);
}}
>
<span className="t">{slot ? fmtRange(slot) : ''}</span>
@@ -274,6 +298,21 @@ export function Home({ go }: { go: (tab: string) => void }) {
Got it
</button>
</Sheet>
{/* Tapping one of "My picks today" opens the same session detail sheet the
Agenda shows — no round trip to the Agenda tab. */}
<SessionDetail
session={selected}
slot={selected ? slotById.get(selected.slot_id) : undefined}
now={now}
checkedIn={!!selected && checkins.includes(selected.id)}
isSpeaker={!!selected && mySpeakerSessions.includes(selected.id)}
picked={!!selected && pickFor(selected.slot_id) === selected.id}
onClose={() => setSelected(null)}
onPickChanged={async () => setPrefs(await getMyPreferences())}
onGiveFeedback={openFeedback}
onMaterialChanged={reload}
/>
</section>
);
}
+13 -3
View File
@@ -5,6 +5,16 @@ import { getLeaderboard } from '../lib/api';
import type { LeaderboardRow } from '../lib/types';
import { Avatar, Spinner } from '../components/ui';
/**
* Leaderboard display name: first name + the initial of the last name
* ("Max Muster" → "Max M.") — surnames stay private on a public screen.
*/
function maskedName(fullName: string): string {
const parts = fullName.trim().split(/\s+/).filter(Boolean);
if (parts.length < 2) return parts[0] ?? fullName;
return `${parts[0]} ${parts[parts.length - 1].charAt(0).toUpperCase()}.`;
}
export function Leaderboard() {
const { contact } = useAuth();
const [rows, setRows] = useState<LeaderboardRow[]>([]);
@@ -72,7 +82,7 @@ export function Leaderboard() {
return (
<div className="pod" key={r.contact_email}>
<div className={`bar ${cls}`}>{r.points}</div>
<div className="pname">{r.full_name.split(' ')[0]}</div>
<div className="pname">{maskedName(r.full_name)}</div>
<div className="ppoints">#{idx + 1}</div>
</div>
);
@@ -87,9 +97,9 @@ export function Leaderboard() {
return (
<div className={`lb-row ${isMe ? 'me' : ''}`} key={r.contact_email}>
<span className="rank">{rank}</span>
<Avatar name={r.full_name} id={r.contact_email} size={38} fs={13} />
<Avatar name={maskedName(r.full_name)} id={r.contact_email} size={38} fs={13} />
<div className="grow">
<div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name} {isMe && <span className="muted small">(you)</span>}</div>
<div style={{ fontWeight: 700, fontSize: 14 }}>{maskedName(r.full_name)} {isMe && <span className="muted small">(you)</span>}</div>
</div>
<span className="pts">{r.points}</span>
</div>
+58 -9
View File
@@ -1,29 +1,64 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { supabase } from '../lib/supabase';
import { lanyardLookup } from '../lib/api';
import { capWords } from '../lib/time';
import type { PublicContact } from '../lib/types';
import { Avatar, Scanner } from '../components/ui';
import { useToast } from '../context/ToastContext';
import { useAuth } from '../context/AuthContext';
import { adminLinkFailure, adminLinkNotice, isEmailEntry, requestAdminLink } from '../lib/adminEntry';
type Step = 'splash' | 'scan' | 'confirm';
export function Login() {
const [step, setStep] = useState<Step>('splash');
const { authError } = useAuth();
const [step, setStep] = useState<Step>(authError ? 'scan' : 'splash');
const [qrToken, setQrToken] = useState('');
const [found, setFound] = useState<PublicContact | null>(null);
const [email, setEmail] = useState('');
const [staffPassword, setStaffPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [error, setError] = useState<string | null>(authError);
const [entry, setEntry] = useState('');
const [sent, setSent] = useState(false);
const [cooldown, setCooldown] = useState(0);
const requestPending = useRef(false);
const { toast } = useToast();
useEffect(() => {
if (!cooldown) return;
const timer = window.setTimeout(() => setCooldown((remaining) => remaining - 1), 1000);
return () => window.clearTimeout(timer);
}, [cooldown]);
// Staff log in with QR + their admin password; everyone else with QR + email.
const isStaff = found?.registration_type === 'staff';
async function handleScan(text: string) {
const token = text.trim();
if (!token) return;
if (!token || requestPending.current) return;
if (isEmailEntry(token)) {
if (cooldown) return;
requestPending.current = true;
setBusy(true);
setError(null);
setSent(false);
try {
await requestAdminLink(token);
setSent(true);
setCooldown(60);
} catch {
setError(adminLinkFailure);
} finally {
requestPending.current = false;
setBusy(false);
}
return;
}
if (token.includes('@')) {
setError('Enter a valid email address.');
return;
}
setQrToken(token);
setError(null);
try {
@@ -41,7 +76,7 @@ export function Login() {
// Attendees: QR + the ticket email (the QR token is the auth password).
const loginEmail = isStaff ? found?.email : email.trim();
const loginPassword = isStaff ? staffPassword : qrToken;
if (!loginEmail || !loginPassword) return;
if (!loginEmail || !loginPassword || busy) return;
setBusy(true);
setError(null);
try {
@@ -68,7 +103,7 @@ export function Login() {
if (step === 'splash') {
return (
<section className="screen no-tab splash" onClick={() => setStep('scan')}>
<section className="screen no-tab splash" data-testid="login-splash" onClick={() => setStep('scan')}>
<div className="logo"><img src="/icon-192.png" alt="APPE" /></div>
<div className="splash-title">APPE</div>
<div className="splash-tag">Break the ice. Earn the points.</div>
@@ -81,8 +116,19 @@ export function Login() {
return (
<section className="screen no-tab">
<div className="h1">Welcome back 👋</div>
<div className="muted small">Scan the QR code on your lanyard to log in.</div>
<Scanner onResult={handleScan} label="Point your camera at your lanyard QR" />
<Scanner
onResult={handleScan}
paused={busy}
label="Point your camera at your lanyard QR"
entryLabel="QR Code"
placeholder="QR Code"
disabled={busy}
submitDisabled={isEmailEntry(entry) && cooldown > 0}
submitLabel={busy ? 'Sending...' : isEmailEntry(entry) ? cooldown ? `Resend in ${cooldown}s` : sent ? 'Resend magic link' : 'Send magic link' : 'Go'}
onEntryChange={(value) => { setEntry(value); setSent(false); setError(null); }}
/>
{sent && <p role="status">{adminLinkNotice}</p>}
{error && <p role="alert" data-testid="login-error">{error}</p>}
</section>
);
}
@@ -112,6 +158,7 @@ export function Login() {
<input
className="input"
type="password"
data-testid="staff-login-password"
placeholder="••••••••••"
value={staffPassword}
onChange={(e) => setStaffPassword(e.target.value)}
@@ -128,6 +175,7 @@ export function Login() {
<input
className="input"
type="email"
data-testid="attendee-login-email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
@@ -137,9 +185,10 @@ export function Login() {
</>
)}
</div>
{error && <div className="muted small" style={{ color: 'var(--red)' }}>{error}</div>}
{error && <div role="alert" className="muted small" data-testid="login-error" style={{ color: 'var(--red)' }}>{error}</div>}
<button
className="btn primary"
data-testid="login-confirm"
disabled={busy || (isStaff ? !staffPassword : !email.trim())}
onClick={confirm}
>
+219
View File
@@ -0,0 +1,219 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import {
createConnectionRequest,
getMyCheckins,
getMyConnections,
getTalkCohort,
} from '../lib/api';
import { capWords } from '../lib/time';
import type { Connection, TalkCohortMember } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
/**
* Networking around talks (an embeddable panel, shown as a tab inside the
* Connect screen). For every talk the user was checked into, list the other
* attendees who were also in that talk (the "talk cohort") so the user can
* make a connection. Accepting a connection with a shared talk earns the
* per-event talk networking bonus (see `events.talk_networking_bonus`).
*/
export function NetworkingPanel() {
const { contact } = useAuth();
const { event, sessionById, loading } = useEvent();
const [myCheckins, setMyCheckins] = useState<string[]>([]);
const [cohorts, setCohorts] = useState<Record<string, TalkCohortMember[]>>({});
const [loadingCohorts, setLoadingCohorts] = useState(false);
const [connecting, setConnecting] = useState<string | null>(null);
// The user's existing connections, so a Connect button can show the current
// state ("Sent" / "Connected" / …) instead of allowing duplicate requests.
const [conns, setConns] = useState<Connection[]>([]);
const { toast } = useToast();
const email = contact?.email ?? '';
const loadConns = useCallback(async () => {
try {
setConns(await getMyConnections());
} catch {
/* non-fatal */
}
}, []);
useEffect(() => {
if (email) void loadConns();
}, [email, loadConns]);
// Keep the connection states fresh (a peer may accept while the panel is open).
useEffect(() => {
window.addEventListener('connections-changed', loadConns);
return () => window.removeEventListener('connections-changed', loadConns);
}, [loadConns]);
/** The existing connection to a given person (any status), or null. */
const connWith = (theirEmail: string) =>
conns.find((c) => (c.from_email === email && c.to_email === theirEmail) ||
(c.from_email === theirEmail && c.to_email === email)) ?? null;
// Load the sessions the user is checked into, then each talk's cohort.
useEffect(() => {
if (!email) return;
let active = true;
(async () => {
try {
const ids = await getMyCheckins(email);
if (!active) return;
setMyCheckins(ids);
if (ids.length === 0) return;
setLoadingCohorts(true);
const results = await Promise.all(
ids.map(async (sid): Promise<[string, TalkCohortMember[]]> => {
try {
return [sid, await getTalkCohort(sid)];
} catch {
return [sid, []];
}
}),
);
if (!active) return;
const map: Record<string, TalkCohortMember[]> = {};
for (const [sid, list] of results) map[sid] = list;
setCohorts(map);
} catch {
/* non-fatal */
} finally {
if (active) setLoadingCohorts(false);
}
})();
return () => {
active = false;
};
}, [email]);
// Only show talks that actually exist in the agenda (check-ins for a
// service session or a removed session are skipped).
const myTalks = useMemo(
() => myCheckins.filter((sid) => sessionById.has(sid)).map((sid) => sessionById.get(sid)!),
[myCheckins, sessionById],
);
if (loading || !contact) {
return (
<div className="center" style={{ flex: 1 }}>
<Spinner />
</div>
);
}
async function connect(member: TalkCohortMember) {
if (!member.qr_token) {
toast('No QR token for this attendee', 'err');
return;
}
// Never allow a duplicate request: if a connection already exists (any
// status), the button is disabled — this is the backstop.
if (connWith(member.email)) return;
setConnecting(member.email);
try {
const conn = await createConnectionRequest(member.qr_token);
if (conn.status === 'accepted') toast(`Connected with ${member.full_name}! 🤝`, 'ok');
else if (conn.status === 'pending') toast(`Request sent to ${member.full_name}`, 'ok');
else toast('Request already resolved');
window.dispatchEvent(new Event('connections-changed'));
await loadConns();
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not send request', 'err');
} finally {
setConnecting(null);
}
}
/** The Connect button state for a person: 'connect' | 'sent' | 'connected' | 'requested' | 'declined'. */
function connState(theirEmail: string): { label: string; kind: string } {
const c = connWith(theirEmail);
if (!c) return { label: 'Connect', kind: 'connect' };
if (c.status === 'accepted') return { label: 'Connected', kind: 'connected' };
if (c.status === 'pending') {
return c.from_email === email
? { label: 'Sent', kind: 'sent' }
: { label: 'Requested', kind: 'requested' };
}
return { label: 'Declined', kind: 'declined' };
}
const bonus = event?.talk_networking_bonus ?? 0;
return (
<div data-testid="networking-panel">
<div className="muted small" style={{ marginBottom: 14 }}>
People who were in the same talk as you.
{bonus > 0 ? (
<> Connect with them to earn <b>+{bonus} pts</b> (shared talk).</>
) : (
<> Connect with people you met at a talk.</>
)}
</div>
{myTalks.length === 0 ? (
<Empty icon="🗣" text="You haven’t been checked into a talk yet. Get checked in by staff to see who else was there." />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{myTalks.map((talk) => {
const members = (cohorts[talk.id] ?? []).filter((m) => m.email !== email);
return (
<div className="card" key={talk.id} data-testid={`networking-talk-${talk.id}`}>
<div className="h2" style={{ marginBottom: 2 }}>{talk.title}</div>
<div className="muted small" style={{ marginBottom: 10 }}>
{talk.room ? `${talk.room} · ` : ''}
{talk.speakers ? `🎤 ${talk.speakers}` : ''}
</div>
{loadingCohorts && (
<div className="center" style={{ padding: 8 }}>
<Spinner />
</div>
)}
{!loadingCohorts && members.length === 0 && (
<div className="muted small">No one else was checked in here yet.</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{members.map((m) => (
<div className="conn" key={m.email} data-testid={`networking-member-${m.email}`}>
<Avatar name={m.full_name} id={m.email} size={40} />
<div className="grow">
<div className="name">{m.full_name}</div>
{m.registration_type && (
<div className="meta">{capWords(m.registration_type)}</div>
)}
</div>
{(() => {
const s = connState(m.email);
const disabled = s.kind !== 'connect' || connecting === m.email;
return (
<button
className={
s.kind === 'connected'
? 'btn small'
: s.kind === 'connect'
? 'btn primary small'
: 'btn ghost small'
}
data-testid={`networking-connect-${m.email}`}
disabled={disabled}
onClick={() => void connect(m)}
>
{connecting === m.email ? '…' : s.label}
</button>
);
})()}
</div>
))}
</div>
</div>
);
})}
</div>
)}
</div>
);
}
+21 -5
View File
@@ -10,12 +10,16 @@ const CATEGORY_LABEL: Record<PointsLogRow['category'], string> = {
checkin: 'Session check-ins',
connection: 'Connections',
feedback: 'Feedback',
talk_networking: 'Talk networking',
admin: 'Other',
};
const MANFRED_POSES = ['confident', 'coffee', 'celebrating', 'waving'];
export function Profile() {
const { contact, registration, signOut, refresh } = useAuth();
const { toast } = useToast();
const [manfredPose] = useState(() => MANFRED_POSES[Math.floor(Math.random() * MANFRED_POSES.length)]);
const [log, setLog] = useState<PointsLogRow[]>([]);
const [loading, setLoading] = useState(true);
@@ -69,7 +73,18 @@ export function Profile() {
return (
<section className="screen">
<div className="h1">Profile</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
<div className="h1" style={{ marginBottom: 0 }}>Profile</div>
<img
src={`/manfred/${manfredPose}.webp`}
alt="Manfred"
title="Manfred"
data-testid="profile-manfred"
width={76}
height={76}
style={{ objectFit: 'contain', flexShrink: 0 }}
/>
</div>
<div className="card" style={{ textAlign: 'center' }}>
<Avatar name={contact.full_name} id={contact.email} size={72} fs={26} />
<div className="h2" style={{ marginTop: 10 }}>{contact.full_name}</div>
@@ -103,16 +118,17 @@ export function Profile() {
<input
className="input"
type="url"
data-testid="profile-linkedin-url"
placeholder="https://linkedin.com/in/you"
value={linkedin}
onChange={(e) => setLinkedin(e.target.value)}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 14 }}>
<Toggle checked={showEmail} onChange={setShowEmail} label="Show my email" />
<Toggle checked={showLinkedin} onChange={setShowLinkedin} label="Show my LinkedIn" />
<Toggle checked={showEmail} onChange={setShowEmail} label="Show my email" testId="profile-show-email" />
<Toggle checked={showLinkedin} onChange={setShowLinkedin} label="Show my LinkedIn" testId="profile-show-linkedin" />
</div>
<button className="btn primary" disabled={saving} onClick={() => void saveProfile()}>
<button className="btn primary" data-testid="profile-save" disabled={saving} onClick={() => void saveProfile()}>
{saving ? 'Saving…' : 'Save profile'}
</button>
</div>
@@ -139,7 +155,7 @@ export function Profile() {
)}
</div>
<button className="btn danger" onClick={() => void signOut()}>Log out</button>
<button className="btn danger" data-testid="profile-logout" onClick={() => void signOut()}>Log out</button>
</section>
);
}
+120 -24
View File
@@ -1,12 +1,17 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import { checkinAttendee, createConnectionRequest, lanyardLookup, welcomeCheckin } from '../lib/api';
import { checkinAttendee, createConnectionRequest, lanyardLookup, previewWelcomeCheckin, welcomeCheckin } from '../lib/api';
import { capWords } from '../lib/time';
import type { CheckinResult, PublicContact, WelcomeCheckinResult } from '../lib/types';
import type { CheckinResult, PublicContact, WelcomeCheckinPreview, WelcomeCheckinResult } from '../lib/types';
import { Avatar, Scanner, Sheet, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
/** How the scanner describes the number of labels a welcome check-in prints. */
function printPhrase(copies: number): string {
return copies > 1 ? `their badge ${copies} times` : 'this person’s label';
}
export function Scan() {
const { contact } = useAuth();
const { slots, loading } = useEvent();
@@ -17,16 +22,25 @@ export function Scan() {
const [connectTarget, setConnectTarget] = useState<{ contact: PublicContact; qr: string } | null>(null);
const [checkin, setCheckin] = useState<CheckinResult | null>(null);
const [welcome, setWelcome] = useState<WelcomeCheckinResult | null>(null);
// A welcome scan is previewed first and only committed after the staff
// confirms that they want to check the person in (and print their badge).
const [pendingWelcome, setPendingWelcome] = useState<{ token: string; preview: WelcomeCheckinPreview } | null>(null);
// A session scan for an attendee who has not been through the front desk
// (welcome) check-in is blocked; we surface a dedicated sheet for it.
const [frontDesk, setFrontDesk] = useState(false);
const [busy, setBusy] = useState(false);
const { toast } = useToast();
// The first checkable (non-service) session, computed synchronously so a fast
// scan never races the async default-selection effect below.
const defaultSessionId = useMemo(
() => slots.flatMap((s) => s.sessions).find((s) => s.slot_type !== 'service_session')?.id ?? '',
[slots],
);
useEffect(() => {
if (slots.length > 0 && !sessionId) {
// Default to the first checkable (non-service) session.
const first = slots.flatMap((s) => s.sessions).find((s) => s.slot_type !== 'service_session');
if (first) setSessionId(first.id);
}
}, [slots, sessionId]);
if (defaultSessionId && !sessionId) setSessionId(defaultSessionId);
}, [defaultSessionId, sessionId]);
if (loading || !contact) {
return (
@@ -46,14 +60,19 @@ export function Scan() {
try {
if (activeStaff) {
if (welcomeMode) {
const res = await welcomeCheckin(token);
setWelcome(res);
// Preview first: resolve the name and whether a badge will print, then
// wait for the staff to confirm before checking in.
const preview = await previewWelcomeCheckin(token);
setPendingWelcome({ token, preview });
} else {
if (!sessionId) {
// Fall back to the first checkable session so a fast scan (before the
// async default-selection effect runs) never fails with "pick a session".
const targetSession = sessionId || defaultSessionId;
if (!targetSession) {
toast('Pick a session first', 'err');
return;
}
const res = await checkinAttendee(sessionId, token);
const res = await checkinAttendee(targetSession, token);
setCheckin(res);
}
} else {
@@ -68,6 +87,24 @@ export function Scan() {
}
setConnectTarget({ contact: found, qr: token });
}
} catch (e) {
const m = e instanceof Error ? e.message : 'Something went wrong';
// The front-desk gate is a blocking state, not a transient error: show a
// persistent sheet instead of a quick toast so staff can relay it.
if (/front desk/i.test(m)) setFrontDesk(true);
else toast(m, 'err');
} finally {
setBusy(false);
}
}
async function confirmWelcome() {
if (!pendingWelcome) return;
setBusy(true);
try {
const res = await welcomeCheckin(pendingWelcome.token);
setWelcome(res);
setPendingWelcome(null);
} catch (e) {
toast(e instanceof Error ? e.message : 'Something went wrong', 'err');
} finally {
@@ -103,8 +140,8 @@ export function Scan() {
</div>
{isStaff && (
<div className="seg" style={{ width: 170 }}>
<button className={mode === 'attendee' ? 'active' : ''} onClick={() => setMode('attendee')}>Attendee</button>
<button className={mode === 'staff' ? 'active' : ''} onClick={() => setMode('staff')}>Staff</button>
<button className={mode === 'attendee' ? 'active' : ''} data-testid="scan-mode-attendee" onClick={() => setMode('attendee')}>Attendee</button>
<button className={mode === 'staff' ? 'active' : ''} data-testid="scan-mode-staff" onClick={() => setMode('staff')}>Staff</button>
</div>
)}
</div>
@@ -113,7 +150,7 @@ export function Scan() {
<div>
<div className="row between" style={{ marginBottom: 10 }}>
<span className="muted small" style={{ fontWeight: 700 }}>Check-in type</span>
<label className="uiverse-toggle" title={welcomeMode ? 'Welcome check-in' : 'Session check-in'}>
<label className="uiverse-toggle" data-testid="welcome-checkin-toggle" title={welcomeMode ? 'Welcome check-in' : 'Session check-in'}>
<input
type="checkbox"
checked={welcomeMode}
@@ -128,7 +165,7 @@ export function Scan() {
) : (
<>
<div className="muted small" style={{ marginBottom: 7 }}>Checking in to session</div>
<select className="input" value={sessionId} onChange={(e) => setSessionId(e.target.value)}>
<select className="input" data-testid="session-selector" value={sessionId} onChange={(e) => setSessionId(e.target.value)}>
{slots
.filter(({ slot }) => slot.type !== 'service_session')
.map(({ slot, sessions }) => (
@@ -144,7 +181,7 @@ export function Scan() {
</div>
)}
<Scanner onResult={handleScan} label={activeStaff ? 'Point at an attendee’s lanyard' : 'Point at a peer’s lanyard'} />
<Scanner onResult={handleScan} paused={busy || !!connectTarget || !!checkin || !!pendingWelcome || !!welcome || frontDesk} label={activeStaff ? 'Point at an attendee’s lanyard' : 'Point at a peer’s lanyard'} />
{busy && <div className="center"><Spinner /></div>}
{activeStaff && !welcomeMode && selSession && (
<div className="muted small" style={{ textAlign: 'center', opacity: 0.6 }}>
@@ -169,7 +206,7 @@ export function Scan() {
</div>
)}
<div style={{ marginTop: 16 }}>
<button className="btn primary" disabled={busy} onClick={confirmConnect}>
<button className="btn primary" data-testid="connection-send" disabled={busy} onClick={confirmConnect}>
{busy ? 'Sending…' : 'Connect 🤝'}
</button>
<button className="btn ghost" style={{ marginTop: 8 }} onClick={() => setConnectTarget(null)}>
@@ -183,15 +220,17 @@ export function Scan() {
{/* Check-in result sheet */}
<Sheet open={!!checkin} onClose={() => setCheckin(null)}>
{checkin && (
<div style={{ textAlign: 'center' }}>
<div style={{ textAlign: 'center' }} data-testid="session-checkin-result">
<div style={{ fontSize: 52 }}>{checkin.already ? '⚠️' : '✅'}</div>
<h3 style={{ marginTop: 10 }}>{checkin.attendee_name}</h3>
<div className="sub">{checkin.already ? 'Already checked in' : 'Checked in'}</div>
<div style={{ marginTop: 14 }}>
{checkin.already ? (
<span className="pill amber">No extra points</span>
<span className="pill amber" data-testid="session-points">No extra points</span>
) : checkin.points_awarded ? (
<span className="pill green" data-testid="session-points">+10 pts · now {checkin.points}</span>
) : (
<span className="pill green">+10 pts · now {checkin.points}</span>
<span className="pill amber" data-testid="session-points">Checked in · staff earn no points</span>
)}
</div>
<button className="btn primary" style={{ marginTop: 18 }} onClick={() => setCheckin(null)}>
@@ -201,15 +240,72 @@ export function Scan() {
)}
</Sheet>
{/* Front-desk gate: session check-in blocked until a welcome check-in. */}
<Sheet open={frontDesk} onClose={() => setFrontDesk(false)}>
<div style={{ textAlign: 'center' }} data-testid="front-desk-required">
<div style={{ fontSize: 52 }}>🛑</div>
<h3 style={{ marginTop: 10 }}>Not checked in yet</h3>
<p className="sub" style={{ marginTop: 8 }}>
This attendee needs to be checked in at the front desk before they can be
scanned into a session.
</p>
<button className="btn primary" style={{ marginTop: 18 }} data-testid="front-desk-ok" onClick={() => setFrontDesk(false)}>
OK
</button>
</div>
</Sheet>
{/* Welcome check-in confirmation (shown before checking in / printing) */}
<Sheet open={!!pendingWelcome} onClose={() => !busy && setPendingWelcome(null)}>
{pendingWelcome && (
<div style={{ textAlign: 'center' }} data-testid="welcome-checkin-confirm">
<div style={{ fontSize: 52 }}>{pendingWelcome.preview.will_print ? '🏷️' : '👋'}</div>
<h3 style={{ marginTop: 10 }}>{pendingWelcome.preview.attendee_name}</h3>
<p className="sub" style={{ marginTop: 8 }}>
{pendingWelcome.preview.already
? 'Already checked in to the event.'
: pendingWelcome.preview.will_print
? `You are checking in ${pendingWelcome.preview.attendee_name}. By confirming, you will print ${printPhrase(pendingWelcome.preview.copies)}.`
: `You are checking in ${pendingWelcome.preview.attendee_name}.`}
</p>
{!pendingWelcome.preview.will_print && !pendingWelcome.preview.already && (
<div className="muted small" style={{ marginTop: 6 }}>No badge will print (no layout for this event).</div>
)}
{pendingWelcome.preview.points_awarded && (
<div className="muted small" style={{ marginTop: 6 }}>Checking in awards +10 points.</div>
)}
{!pendingWelcome.preview.points_awarded && !pendingWelcome.preview.already && (
<div className="muted small" style={{ marginTop: 6 }}>This person does not earn points (staff or organiser).</div>
)}
<div style={{ marginTop: 16 }}>
<button className="btn primary" data-testid="welcome-checkin-confirm-yes" disabled={busy} onClick={confirmWelcome}>
{busy ? 'Checking in…' : 'Yes, check in'}
</button>
<button className="btn ghost" style={{ marginTop: 8 }} disabled={busy} onClick={() => setPendingWelcome(null)}>
No
</button>
</div>
</div>
)}
</Sheet>
{/* Welcome check-in result sheet */}
<Sheet open={!!welcome} onClose={() => setWelcome(null)}>
{welcome && (
<div style={{ textAlign: 'center' }}>
<div style={{ textAlign: 'center' }} data-testid="welcome-checkin-result">
<div style={{ fontSize: 52 }}>{welcome.already ? '⚠️' : '👋'}</div>
<h3 style={{ marginTop: 10 }}>{welcome.attendee_name}</h3>
<div className="sub">{welcome.already ? 'Already checked in to the event' : 'Welcome to the event!'}</div>
<div style={{ marginTop: 14 }}>
<span className="pill green">✓ Checked in</span>
{welcome.already ? (
<span className="pill amber" data-testid="welcome-points">No extra points</span>
) : welcome.points_awarded ? (
<span className="pill green" data-testid="welcome-points">+10 pts · now {welcome.points}</span>
) : (
// Staff / Admin contacts never earn points; say so instead of
// showing a +10 the database deliberately refused to award.
<span className="pill amber" data-testid="welcome-points">Checked in · staff earn no points</span>
)}
</div>
<button className="btn primary" style={{ marginTop: 18 }} onClick={() => setWelcome(null)}>
Scan next
+133
View File
@@ -0,0 +1,133 @@
import { useEffect, useState, type FormEvent } from 'react';
import type { Session } from '@supabase/supabase-js';
import { LoaderCircle, Paperclip } from 'lucide-react';
import { supabase } from '../lib/supabase';
import { getSpeakerPortalSessions, speakerPortalSession, type SpeakerSession } from '../lib/speakerPortal';
import { downloadSessionMaterial, removeSessionMaterial, uploadSessionMaterial } from '../lib/api';
const MAX_FILE_SIZE = 50 * 1024 * 1024;
const FILE_TYPES = '.pdf,.ppt,.pptx,.odp,.zip,.txt';
function messageOf(error: unknown) {
return error instanceof Error ? error.message : 'Something went wrong. Please try again.';
}
export function SpeakerPortal() {
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
const [email, setEmail] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [notice, setNotice] = useState('');
const [talks, setTalks] = useState<SpeakerSession[]>([]);
const [talksLoading, setTalksLoading] = useState(false);
const [talksError, setTalksError] = useState('');
const [reload, setReload] = useState(0);
const [workingTalk, setWorkingTalk] = useState<string | null>(null);
useEffect(() => {
let active = true;
setTalks([]);
setTalksError('');
if (!session) return;
setTalksLoading(true);
void getSpeakerPortalSessions().then((rows) => {
if (active) setTalks(rows);
}).catch((failure: unknown) => {
if (active) setTalksError(messageOf(failure));
}).finally(() => { if (active) setTalksLoading(false); });
return () => { active = false; };
}, [session?.user.id, reload]);
useEffect(() => {
let active = true;
void speakerPortalSession.then((result) => {
if (!active) return;
setSession(result.session);
setError(result.error?.message || '');
setLoading(false);
});
const { data } = supabase.auth.onAuthStateChange((_event, next) => {
if (active) setSession(next);
});
return () => { active = false; data.subscription.unsubscribe(); };
}, []);
async function sendLink(event: FormEvent) {
event.preventDefault();
setBusy(true);
setError('');
setNotice('');
try {
const { error: authError } = await supabase.auth.signInWithOtp({
email: email.trim().toLowerCase(),
options: { shouldCreateUser: false, emailRedirectTo: `${window.location.origin}/speaker/secret` },
});
if (authError) throw authError;
setNotice('Sign-in link requested. Check your email.');
} catch {
setError('Unable to send a sign-in link. Check your registered email or try again later.');
} finally { setBusy(false); }
}
async function logout() {
setBusy(true);
const { error: authError } = await supabase.auth.signOut({ scope: 'local' });
if (authError) setError(authError.message);
else { setSession(null); setNotice(''); }
setBusy(false);
}
async function changeMaterial(talk: SpeakerSession, file?: File) {
setError('');
setNotice('');
if (file && (!file.size || file.size > MAX_FILE_SIZE || !/\.(pdf|ppt|pptx|odp|zip|txt)$/i.test(file.name))) {
setError('Choose a non-empty PDF, PowerPoint, ODP, ZIP or TXT file, up to 50 MB.');
return;
}
if (!file && !window.confirm(`Remove materials for "${talk.title}"?`)) return;
setWorkingTalk(talk.session_id);
try {
if (file) await uploadSessionMaterial(talk.session_id, file);
else await removeSessionMaterial(talk.session_id);
setNotice(file ? 'Material saved.' : 'Material removed.');
} catch (failure) { setError(messageOf(failure)); }
finally { setWorkingTalk(null); setReload((value) => value + 1); }
}
return <div className="app speaker-app"><main className="screen no-tab speaker-portal" data-testid="speaker-portal">
<header className="row between"><h1 className="h1">Speaker Portal</h1>
{session && <button className="btn small ghost" onClick={() => void logout()} disabled={busy || !!workingTalk}>Sign out</button>}
</header>
{error && <p role="alert">{error}</p>}
{notice && <p role="status">{notice}</p>}
{loading ? <p role="status">Signing in...</p> : session ? <>
<p className="small muted">{session.user.email}</p>
<h2 className="h2">My Talk Materials</h2>
{talksLoading ? <p role="status">Loading talks...</p> : talksError ? <>
<p role="alert">{talksError}</p><button className="btn" onClick={() => setReload((value) => value + 1)}>Retry</button>
</> : !talks.length ? <p role="status">No assigned talks for your speaker or staff registrations.</p> : talks.map((talk) => <article className="speaker-talk" key={talk.session_id} data-testid={`speaker-talk-${talk.session_id}`}>
<p className="small muted">{talk.event_name} · {talk.is_active ? 'Active event' : 'Inactive event'}</p>
<h3 className="h2">{talk.title}</h3>
<p className="small">{talk.slot_date} · {talk.start_time.slice(0, 5)} - {talk.end_time.slice(0, 5)}{talk.room && ` · ${talk.room}`}</p>
{talk.material_path ? <button className="speaker-download" onClick={async () => { try { await downloadSessionMaterial(talk.material_path!); } catch (failure) { setError(messageOf(failure)); } }}>Download material</button> : <p className="small muted">No material uploaded</p>}
<label className="speaker-upload" htmlFor={`material-${talk.session_id}`}>
{workingTalk === talk.session_id ? <LoaderCircle aria-hidden="true" className="speaker-upload-spinner" /> : <Paperclip aria-hidden="true" />}
<span>{workingTalk === talk.session_id ? 'Saving material...' : talk.material_path ? 'Replace material' : 'Upload material'}</span>
<input className="input" id={`material-${talk.session_id}`} aria-label={`${talk.material_path ? 'Replace' : 'Upload'} material for ${talk.title}`} aria-describedby={`material-help-${talk.session_id}`} type="file" accept={FILE_TYPES} disabled={!!workingTalk || busy} onChange={(event) => {
const file = event.target.files?.[0];
event.target.value = '';
if (file) void changeMaterial(talk, file);
}} />
</label>
<p id={`material-help-${talk.session_id}`} className="small muted">PDF, PowerPoint, ODP, ZIP, TXT · Max 50 MB</p>
{workingTalk === talk.session_id && <><progress aria-label="Saving material" /><p role="status">Saving material...</p></>}
{talk.material_path && <button className="btn small danger" disabled={!!workingTalk || busy} onClick={() => void changeMaterial(talk)}>Remove material</button>}
</article>)}
</> : <form onSubmit={(event) => void sendLink(event)}>
<label htmlFor="speaker-email">Email</label>
<input className="input" id="speaker-email" type="email" autoComplete="email" required value={email} onChange={(event) => setEmail(event.target.value)} />
<button className="btn primary" type="submit" disabled={busy}>{busy ? 'Sending...' : 'Send sign-in link'}</button>
</form>}
</main></div>;
}
+78
View File
@@ -1,4 +1,77 @@
* { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
.speaker-portal { letter-spacing: 0; }
.speaker-portal .h1 { letter-spacing: 0; }
.speaker-portal header { flex-wrap: wrap; }
.speaker-portal form { display: grid; gap: 14px; }
.speaker-portal p, .speaker-portal h3, .speaker-download { overflow-wrap: anywhere; }
.speaker-talk { display: grid; gap: 10px; padding: 18px 0; border-top: 1px solid var(--line); }
.speaker-portal input { width: 100%; min-width: 0; }
.speaker-portal progress { width: 100%; accent-color: var(--accent-2); }
.speaker-download { color: var(--accent-2); background: none; border: 0; padding: 0; cursor: pointer; text-decoration: underline; }
.speaker-upload {
position: relative;
display: flex;
align-items: center;
gap: 8px;
min-height: 46px;
padding: 12px;
border: 1px solid var(--accent);
border-radius: 8px;
background: var(--accent-soft);
color: var(--accent);
font-size: 13px;
font-weight: 600;
cursor: pointer;
}
.speaker-upload svg {
flex-shrink: 0;
}
.speaker-upload span {
min-width: 0;
overflow-wrap: anywhere;
}
.speaker-portal .speaker-upload input[type="file"] {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
opacity: 0;
padding: 0;
cursor: pointer;
}
.speaker-upload:focus-within {
outline: 2px solid var(--accent);
outline-offset: 3px;
}
.speaker-upload:has(input:disabled) {
opacity: 0.55;
cursor: not-allowed;
}
.speaker-upload:has(input:disabled) input[type="file"] {
cursor: not-allowed;
}
.speaker-upload-spinner {
animation: speaker-upload-rotate 900ms linear infinite;
}
@keyframes speaker-upload-rotate {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.speaker-upload-spinner {
animation: none;
}
}
:root {
--bg: #f0f2f6; --phone-bg: #ffffff; --surface: #ffffff; --surface-2: #f4f5f9;
--line: #e4e6ee; --text: #423c3c; --muted: #8a8484;
@@ -88,6 +161,8 @@ body {
.feedback-review .fr-stars .on { color: #f59e0b; }
.feedback-review .fr-num { font-weight: 800; font-size: 16px; }
.feedback-review .fr-summary { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; }
/* The AI summary is free text written by the model with real paragraphs. */
.feedback-review .fr-text { line-height: 1.5; white-space: pre-line; overflow-wrap: anywhere; }
.avatar { display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: 800; color: #fff; flex-shrink: 0; }
.input {
width: 100%; padding: 15px 16px; border-radius: 14px; border: 1px solid var(--line);
@@ -239,6 +314,9 @@ textarea.input { resize: none; min-height: 96px; }
.sheet .grab { width: 44px; height: 5px; border-radius: 3px; background: var(--line); margin: 0 auto 14px; }
.sheet h3 { font-size: 19px; font-weight: 800; letter-spacing: -.3px; }
.sheet .sub { color: var(--muted); font-size: 13px; margin-top: 3px; }
/* Session description: the Sessionize/Excel feed carries line breaks and blank
lines, so keep them instead of collapsing everything into one block. */
.sd-desc { margin: 12px 0; line-height: 1.55; white-space: pre-line; overflow-wrap: anywhere; }
/* ---------- Scan: uiverse check-in type toggle (Shoh2008 / brown-bulldog-12) ---------- */
.uiverse-toggle { display: inline-flex; }
+1 -1
View File
@@ -11,7 +11,7 @@ export default defineConfig({
host: true,
port: 3000,
proxy: {
'/auth': { target: SUPABASE_TARGET, changeOrigin: true },
'/auth/v1': { target: SUPABASE_TARGET, changeOrigin: true },
'/rest': { target: SUPABASE_TARGET, changeOrigin: true },
'/realtime': { target: SUPABASE_TARGET, changeOrigin: true, ws: true },
'/storage': { target: SUPABASE_TARGET, changeOrigin: true },
+337
View File
@@ -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.
+36
View File
@@ -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"]
+19
View File
@@ -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
+57
View File
@@ -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"
+298
View File
@@ -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"
+585
View File
@@ -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()
+1
View File
@@ -0,0 +1 @@
pytest==9.1.1
+4
View File
@@ -0,0 +1,4 @@
brother_ql_next==0.12.0
pillow==13.0.0
httpx==0.28.1
playwright==1.55.0
+110
View File
@@ -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
+74
View File
@@ -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
+312
View File
@@ -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
+36
View File
@@ -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
+263
View File
@@ -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
+103
View File
@@ -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"
+75
View File
@@ -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"
+18
View File
@@ -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)
+1
View File
@@ -0,0 +1 @@
"""Convivo badge-printer worker package."""
+3
View File
@@ -0,0 +1,3 @@
from .main import main
raise SystemExit(main())
+81
View File
@@ -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",
)
+90
View File
@@ -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
+349
View File
@@ -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
+39
View File
@@ -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"),
}
+136
View File
@@ -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"}
+122
View File
@@ -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
+91
View File
@@ -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 {}
+79
View File
@@ -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"],
)
+2 -2
View File
@@ -13,8 +13,8 @@ FROM node:20-alpine
WORKDIR /app
COPY package.json ./
RUN npm install --omit=dev
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src/ ./src/
ENV NODE_ENV=production
+1484
View File
File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -5,9 +5,13 @@
"description": "Convivo Sessionize sync sidecar (on-demand, driven by APPE Admin).",
"main": "src/server.js",
"scripts": {
"start": "node src/server.js"
"start": "node src/server.js",
"test": "node --test tests/*.test.js"
},
"dependencies": {
"cheerio": "1.0.0",
"ipaddr.js": "2.2.0",
"pdfkit": "^0.15.0",
"xlsx": "^0.18.5"
}
}
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff. Show more