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]>
This commit is contained in:
committed 2026-10-19 15:10:20 +02:00
1 parent d3531e1fac
commit 17473916a6
27 files changed
+1378 -73

No files matched your search

+1
View File
@@ -46,3 +46,4 @@ test-results/
# Python bytecode
__pycache__/
*.pyc
.scratch/
@@ -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>
);
}
+13
View File
@@ -233,6 +233,7 @@ export async function upsertEvent(
pretix_api_key?: string | null;
use_realtime_clock?: boolean;
talk_networking_bonus?: number;
badge_copies?: number;
},
): Promise<void> {
if (id) {
@@ -244,6 +245,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).
+2
View File
@@ -65,6 +65,8 @@ export interface 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;
+27 -1
View File
@@ -1,4 +1,7 @@
.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; }
@@ -301,6 +304,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; }
@@ -343,7 +348,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;
@@ -355,8 +365,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));
+21
View File
@@ -11,6 +11,7 @@ import {
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() {
@@ -297,6 +298,7 @@ function EventModal({
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);
@@ -353,6 +355,7 @@ function EventModal({
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) {
@@ -537,6 +540,24 @@ function EventModal({
/>
</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>
);
}
+75 -39
View File
@@ -41,12 +41,15 @@ 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);
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));
@@ -174,43 +177,66 @@ export function Registrations() {
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);
async function changeType(r: Registration, type: RegistrationType) {
setBusy(true);
// 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 setRegistrationType(r.contact_email, type);
await reloadRegistrations(r.event_id);
push('success', `${byEmail.get(r.contact_email)?.full_name ?? r.contact_email} → ${type}`);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Update failed';
// A sponsor registration needs a sponsor lookup — open the in-place
// sponsor popup instead of just failing.
if (type === 'sponsor' && /sponsor lookup/i.test(msg)) {
setSponsorFor(r);
} else {
push('error', msg);
}
await run();
} finally {
setBusy(false);
setBusyIds((ids) => {
const next = new Set(ids);
next.delete(id);
return next;
});
}
}
async function toggleCheckedIn(r: Registration, v: boolean) {
setBusy(true);
setRegistrations((rows) => rows.map((row) => row.id === r.id ? { ...row, checked_in: v } : row));
try {
const removed = await setCheckedIn(r.id, v);
if (removed > 0) {
push('success', `${byEmail.get(r.contact_email)?.full_name ?? r.contact_email}: un-checked in, −${removed} check-in pts removed`);
async function changeType(r: Registration, type: RegistrationType) {
await withRowBusy(r.id, async () => {
try {
await setRegistrationType(r.contact_email, type);
// 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';
// A sponsor registration needs a sponsor lookup — open the in-place
// sponsor popup instead of just failing.
if (type === 'sponsor' && /sponsor lookup/i.test(msg)) {
setSponsorFor(r);
} else {
push('error', msg);
}
}
// The RPC may have changed this attendee's points — refresh so the
// points column and leaderboard stay truthful.
await reloadRegistrations(r.event_id);
} catch (e) {
setRegistrations((rows) => rows.map((row) => row.id === r.id ? { ...row, checked_in: r.checked_in } : row));
push('error', e instanceof Error ? e.message : 'Update failed');
} finally {
setBusy(false);
}
});
}
async function toggleCheckedIn(r: Registration, v: boolean) {
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 {
const removed = await setCheckedIn(r.id, v);
// Patch this row's points from the RPC's own number. 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.
setRegistrations((rows) => rows.map((row) => (row.id === r.id
? { ...row, checked_in: v, points: Math.max(0, row.points - removed) }
: 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 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');
}
});
}
// Queue this attendee's badge. Works while the printer is offline/error —
@@ -272,7 +298,7 @@ export function Registrations() {
className="input"
style={{ maxWidth: 280 }}
value={selectedId}
disabled={busy || mergeFor !== null}
disabled={mergeFor !== null}
onChange={(e) => setSelectedId(e.target.value)}
>
{events.map((e) => (
@@ -312,8 +338,9 @@ export function Registrations() {
<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} />
@@ -330,7 +357,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) => (
@@ -370,14 +397,19 @@ export function Registrations() {
</Tooltip>
)}
{!r.qr_token?.trim() && r.import_source === 'sessionize' && (
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
<button className="btn small" onClick={() => setMergeFor(r)}>
Merge tickets
</button>
)}
</div>
</td>
<td>
<Toggle checked={r.checked_in} disabled={busy} 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' }}>
<span className="pts">{r.points}</span>
@@ -456,9 +488,13 @@ export function Registrations() {
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);
}}
/>
+16 -1
View File
@@ -1,7 +1,9 @@
import { useEffect, useState, type FormEvent } from 'react';
import { Save } from 'lucide-react';
import { getLlmSettings, saveLlmSettings } from '../lib/api';
import { getActiveEvent, getLlmSettings, saveLlmSettings } from '../lib/api';
import type { Event } from '../lib/types';
import { Spinner } from '../components/ui';
import { BadgeCopiesSetting } from '../components/BadgeCopiesSetting';
export function Settings() {
const [endpoint, setEndpoint] = useState('');
@@ -13,6 +15,8 @@ export function Settings() {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
// Badge printing is per event, so it follows the active event.
const [activeEvent, setActiveEvent] = useState<Event | null>(null);
useEffect(() => {
let active = true;
@@ -23,6 +27,11 @@ export function Settings() {
setHasKey(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; };
}, []);
@@ -47,6 +56,12 @@ export function Settings() {
<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">
+2
View File
@@ -194,6 +194,8 @@ export interface WelcomeCheckinPreview {
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;
}
/** Result of accepting a connection (the connection row + the shared-talk flag). */
+30 -3
View File
@@ -7,6 +7,11 @@ import type { CheckinResult, PublicContact, WelcomeCheckinPreview, WelcomeChecki
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();
@@ -20,6 +25,9 @@ export function Scan() {
// 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();
@@ -80,7 +88,11 @@ export function Scan() {
setConnectTarget({ contact: found, qr: token });
}
} catch (e) {
toast(e instanceof Error ? e.message : 'Something went wrong', 'err');
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);
}
@@ -169,7 +181,7 @@ export function Scan() {
</div>
)}
<Scanner onResult={handleScan} paused={busy || !!connectTarget || !!checkin || !!pendingWelcome || !!welcome} 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 }}>
@@ -226,6 +238,21 @@ 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 && (
@@ -236,7 +263,7 @@ export function Scan() {
{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 this person's label.`
? `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 && (
+22 -4
View File
@@ -99,7 +99,7 @@ cross-reference list.
| Function | Purpose |
|---|---|
| `enqueue_badge_print(p_registration_id)` | Manual reprint: queue the badge of one registration (`kind = reprint`); returns the queue msg id |
| `enqueue_badge_print(p_registration_id)` | Manual reprint: queue the badge of one registration (`kind = reprint`); returns the queue msg id. Always **one** label — `events.badge_copies` belongs to the welcome check-in, so reprinting a lost badge never produces a stack |
| `create_print_station(p_name)` | Register a station. Generates `cvp_<64 hex>` (32 random bytes), stores only its **SHA-256 hex digest**, returns the plaintext token **once** |
| `rename_print_station(p_id, p_name)` | Rename (trimmed, required, ≤ 80 chars). Revoked stations stay renamable so history remains readable |
| `revoke_print_station(p_id)` | Sets `revoked_at`; the token stops working immediately |
@@ -125,15 +125,33 @@ worker) and stamps `last_seen_at`.
behaviour, plus the `badge_print` enqueue for a **genuine first check-in** only,
inside the same transaction (see [rpcs.md](./rpcs.md#welcome_checkinp_attendee_qr--attendee_email-attendee_name-already)).
### How many labels one welcome prints
`events.badge_copies` (`1..4`, default `1`, added in
[`20261019110000_front_desk_gate_and_badge_copies.sql`](../../supabase/migrations/20261019110000_front_desk_gate_and_badge_copies.sql))
is the per-event copy count for the **front desk**. `welcome_checkin` builds the
payload once and calls `pgmq.send` that many times in the same transaction; the
worker already prints exactly one label per job, so **N jobs = N labels** and no
worker, renderer or queue change was needed. The value is clamped with
`greatest(1, least(4, …))` *inside* the function too, so a hand-edited row can
never flood the queue, and the same clamp is used by
`preview_welcome_checkin`'s `copies` column so the popup states the true number
(*"you will print their badge 3 times"*). Re-welcoming an already-checked-in
attendee prints nothing, copies included. Admins set it in **Settings → Badge
printing** (the active event) or on the Events form; both write the single
column, never the whole row.
The staff scanner (attendee app → Scan → Welcome check-in) does **not** fire
`welcome_checkin` directly. It first calls the read-only
`preview_welcome_checkin(qr)` and shows a confirmation — *"You are checking in
[Name]. By confirming, you will print this person's label."* — with **Yes/No**.
[Name]. By confirming, you will print this person's label"* (or *"…their badge 3
times"*, from `copies`) — with **Yes/No**.
Only **Yes** runs `welcome_checkin`. The preview's `will_print` mirrors the exact
enqueue condition (first check-in **and** a layout exists), so the popup never
promises a print that won't happen; when it is `false` the popup says the person
is checked in without mentioning a label. Session check-in is unchanged and never
prints. (Added in `20261019090000_welcome_checkin_preview.sql`.)
prints. (Added in `20261019090000_welcome_checkin_preview.sql`, `copies` in
`20261019110000_front_desk_gate_and_badge_copies.sql`.)
## 5. Station tokens & security model
@@ -280,7 +298,7 @@ and staged (`STAGE_APP` / `STAGE_WIFI_PORTAL` / `REBOOT`):
## 12. Tests
- **SQL:** [`supabase/tests/badge_print_tests.sql`](../../supabase/tests/badge_print_tests.sql)
— rollback-only, **101 assertions**; run it **combined with the migration**
— rollback-only, **113 assertions**; run it **combined with the migration**
(idempotent, works before and after apply):
```sh
(echo 'begin;'; \
+38 -2
View File
@@ -124,6 +124,14 @@ Staff checks an attendee into a session.
- **Role check:** `is_staff_or_admin()` (i.e. `is_admin()`) or it raises
`staff or admin only`.
- Resolves the attendee by `qr_token`.
- **Front-desk gate:** when the attendee's `registrations.checked_in` is not
`true`, it raises `This attendee needs to be checked in at the front desk
first.` Nobody can be checked into a session before the **welcome** check-in at
the front desk has marked them present at the event. The scanner shows this as
its own sheet instead of a generic error (see
[../frontend/screens.md](../frontend/screens.md)). `checkin_attendee` also
stopped setting `checked_in = true` as a side effect — the welcome check-in
(or an admin's Registrations toggle) is now the only way to earn it.
- **Service-session guard:** if the session's slot is a `service_session`, it
raises `service sessions cannot be checked in` (there's nothing to check into —
everyone is in the room).
@@ -148,9 +156,13 @@ from `checkin_attendee`, which checks someone into a specific session).
check-in's job).
- `already` is `true` if the attendee was already checked in to the event.
- On a **first** check-in (and only when the event has a badge layout), enqueues
a `badge_print` job in the same transaction (see [printing.md](printing.md)).
`events.badge_copies` identical `badge_print` jobs in the same transaction — the
Pi worker prints exactly one label per job, so N jobs = N labels (see
[printing.md](printing.md)). The value is clamped to `1..4` inside the function,
so a bad row can never flood the queue. A re-check-in (`already`) enqueues
nothing. Manual reprint (`enqueue_badge_print`) still prints **one** label.
### `preview_welcome_checkin(p_attendee_qr)` → `(attendee_email, attendee_name, already, will_print)`
### `preview_welcome_checkin(p_attendee_qr)` → `(attendee_email, attendee_name, already, will_print, copies)`
Read-only preview shown by the staff scanner **before** a welcome check-in is
committed, so the confirmation popup can name the attendee and be honest about
printing.
@@ -161,6 +173,10 @@ printing.
- `will_print` is `true` only for a genuine first check-in **and** when the
event has a badge layout with elements — exactly the condition under which
`welcome_checkin` enqueues a job.
- `copies` is the number of labels a confirm would queue — the same
clamp `welcome_checkin` applies, and `0` when nothing would print. The popup
uses it to say "print their badge 3 times" instead of a fixed "this person's
label", so it can never over- or under-promise.
- Checks nobody in and enqueues nothing; it is a pure lookup.
### `merge_tickets(p_source_id, p_target_id)` -> `jsonb`
@@ -507,6 +523,26 @@ genuine **first** check-in it enqueues the badge job in the same transaction
when the event has a layout with elements (see
[welcome_checkin](#welcome_checkinp_attendee_qr--attendee_email-attendee_name-already).
## Front-desk gate and badge copies
Source of truth:
[`supabase/migrations/20261019110000_front_desk_gate_and_badge_copies.sql`](../../supabase/migrations/20261019110000_front_desk_gate_and_badge_copies.sql)
(see [release record](../releases/2026-10-19.md)).
- `events.badge_copies` — new `integer not null default 1` with
`check (badge_copies between 1 and 4)`. Admins edit it from **Settings → Badge
printing** for the active event, and when creating/editing an event (see
[../frontend/admin-app.md](../frontend/admin-app.md)).
- `checkin_attendee` re-creates: adds the **front-desk gate** and drops the
`checked_in = true` side effect.
- `welcome_checkin` re-creates: enqueues `badge_copies` jobs instead of one.
- `preview_welcome_checkin` **drops and re-creates** (the return type gained
`copies`, and Postgres cannot `create or replace` across a signature change);
grants are re-applied in the same migration.
`checkins` has no `INSERT` policy, so `checkin_attendee` is the only write path
for session check-ins — the gate cannot be bypassed from the API.
## Error handling
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
+2 -1
View File
@@ -81,6 +81,7 @@ queries everything for the active event and handles "no active event" gracefully
| `sessionize_endpoint` | `text` | nullable — the Sessionize API URL for this event (see [sidecar.md](./sidecar.md)) |
| `use_realtime_clock` | `boolean` | default `false` — when `true`, the attendee app drives slot status (Live/Next/Done) from the real system clock; when `false` it uses the simulated mid-event clock (see [../frontend/app-structure.md](../frontend/app-structure.md)) |
| `talk_networking_bonus` | `integer` | default `2` — bonus points awarded to **each** party when two people who were checked into the same session (talk) accept a connection. `0` disables the feature (the +5 connection award still applies). Awarded with the `talk_networking` points category (see [rpcs.md](./rpcs.md#accept_connectionp_connection_id-uuid)) |
| `badge_copies` | `integer` | default `1`, `check (between 1 and 4)` — how many badge labels a **welcome (front-desk) check-in** prints. Enforced again inside `welcome_checkin`, so a hand-edited row cannot flood the queue. Manual reprint ignores it and always prints one. Set from **Settings → Badge printing** (see [printing.md](./printing.md)) |
| `last_synced_at` | `timestamptz` | nullable — when the Sessionize sync last ran |
| `created_at` | `timestamptz` | |
@@ -98,7 +99,7 @@ Points are scoped **per event** here (one row per contact per event).
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `contact_email` | `text` FK → `contacts` | `on delete cascade` |
| `type` | `registration_type` (enum) | `attendee` \| `speaker` \| `staff` \| `sponsor` (default `attendee`) |
| `checked_in` | `boolean` | default `false` |
| `checked_in` | `boolean` | default `false` — **the front-desk flag.** Set by the welcome check-in (or an admin's Registrations toggle); it is what makes someone eligible for session check-ins. `checkin_attendee` refuses anyone with this flag `false` |
| `points` | `integer` | `>= 0`, default 0 |
| `qr_token` | `text` | nullable — the lanyard token; **doubles as the Auth password** (generated per event) |
| `external_id` | `text` | nullable — reserved for an external system's id (currently unused) |
+49 -1
View File
@@ -1,3 +1,50 @@
# Front-Desk Gate + Badge Copies Regression
After applying `20261019110000_front_desk_gate_and_badge_copies.sql`, run the
SQL suite **combined with the migration** in one transaction (the migration is
`create or replace`, so the same stream also re-verifies an already-applied
database):
```sh
(echo 'begin;'; \
cat supabase/migrations/20261019110000_front_desk_gate_and_badge_copies.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
docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres \
-v ON_ERROR_STOP=1 < supabase/tests/set_registration_checked_in_tests.sql
CONVIVO_BASE_URL=http://127.0.0.1:3000 npm test --prefix e2e -- front-desk-gate.spec.ts --project=chromium
CONVIVO_BASE_URL=http://127.0.0.1:3000 npm test --prefix e2e -- welcome-badge-copies.spec.ts --project=chromium
CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- registration-checkin-toggle.spec.ts --project=chromium
```
The SQL fixture is rollback-only: **113 assertions** — six of them added with the
gate and the copies (the badge-print suite owns both functions) — cover the gate
refusing a session check-in for an attendee with no front-desk check-in
(`session check-in requires a front-desk check-in`), the copies loop
(`badge_copies = 3` queues three more labels) and the savepoint that returns the
queue to one so the rest of the run is unaffected, plus
`preview_welcome_checkin`'s new `copies` column: `1` by default, `0` when nothing
would print, `3` after the event is changed. The pre-existing "session check-in
records / enqueues nothing" case now flips `checked_in` on first, because the
gate makes it a precondition.
`set_registration_checked_in_tests.sql` (**15 assertions**) covers the admin
toggle that grants and revokes the same flag, with its points accounting.
`front-desk-gate.spec.ts` and `welcome-badge-copies.spec.ts` are real-browser
suites against the local stack (real Auth + PostgREST + pgmq): they provision a
disposable attendee, assert the scanner shows its **"Not checked in yet"** sheet
while recording no check-in, that a session check-in no longer sets the
front-desk flag by itself, that the same scan succeeds once the welcome check-in
is done, that the queue grows by exactly `badge_copies` messages, and
that a re-welcome prints nothing. They delete their own rows and restore
`badge_copies = 1`. `registration-checkin-toggle.spec.ts` is API-mocked and
covers the table behaviour the old build got wrong: no refetch on a toggle or a
type change, row order preserved, only the touched row busy while its checkbox
is disabled, other rows still usable, rollback on a rejected RPC, and the
Settings copies picker saving and reloading.
See [release record](../releases/2026-10-19.md) for the bug this started with.
# Badge Print Queue Regression
After applying `20261018170000_badge_print_queue`, run the SQL suite **combined
@@ -13,7 +60,8 @@ CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- printing.spec.t
pytest apps/printer/tests # worker unit tests (no hardware, no browser)
```
The SQL fixture is rollback-only: **101 assertions** cover queue creation and
The SQL fixture is rollback-only: **113 assertions** (six of them the front-desk
gate and badge copies, covered in the section above) cover queue creation and
migration idempotency, pgmq/API isolation, the self-contained payload shape and
layout resolution (default-with-elements, fallback, none → no job), first-scan
enqueue inside `welcome_checkin` (re-scan enqueues nothing), station token
+11 -5
View File
@@ -16,15 +16,15 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
|---|---|
| **Dashboard** | Active event card (name, dates, location, aggregates: avg feedback, #sessions, #speakers, #registrations, #checked-in) + top points + recent activity. |
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) A general search matches **first name, last name or email address**; the **LinkedIn**, **Visibility** and **Admin** columns each have an Excel-style **multi-select filter** with live counts. |
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company), plus a **Print** button that queues the badge on the print station ([../backend/printing.md](../backend/printing.md)). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. |
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company), plus a **Print** button that queues the badge on the print station ([../backend/printing.md](../backend/printing.md)). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. The **checked-in toggle is per-row and optimistic**: it patches that one row (and its points) in place — **no list reload**, so rows never jump or vanish mid-edit (the list is sorted by points) — while a small "Saving…" pulse marks the busy row and only that checkbox is disabled; other rows stay live and a second row can be toggled concurrently. A rejected write rolls the row back to the server's values. Changing the type behaves the same way. The toggle is what grants front-desk eligibility from the console (see [../backend/rpcs.md](../backend/rpcs.md)). |
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). |
| **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. |
| **Activity** | Tables of check-ins, connections, and feedback (per active event), with manual **Generate AI Summary** controls for the event and individual sessions. |
| **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). |
| **Badges** | A **per-event WYSIWYG badge / PDF layout editor** (modelled on pretix's PDF Editor). Pick the event, then design one or more named **layouts** (a **Default** per event, switchable / creatable / deletable). Add **text boxes**, **QR codes** and **images** to a millimetre canvas; drag to move, use the 8 resize handles + rotation handle, **Shift-click to multi-select**, and **press `Del`** to remove. While dragging, **PowerPoint-style smart guides** appear — dashed alignment lines (edges / centres, page and neighbouring items) plus equal-spacing lines — and the element **snaps** to them. A **Word-style align** toolbar (left / center / right, top / middle / bottom) plus **PowerPoint-style** object alignment — align to the **page** or to the **selection**, and **distribute** horizontally / vertically — with the same controls in the properties panel. Text binds to attendee fields (name, email, ticket type, QR token, event name, **company / organizer**, or static) with font, size, line-height, colour, bold/italic, a labelled **Align text in box** section (horizontal left / center / right and vertical top / middle / bottom, inside the element's own frame) and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo** (`Ctrl`+`Z` / `Ctrl`+`Y`, also `Ctrl`+`Shift`+`Z`), a **Preview** mode (no handles), a **JSON** view of the layout, and **Save**. Previewed against a real sample registration. See [../backend/rpcs.md#badge-editor](../backend/rpcs.md#badge-editor). |
| **Printing** | Badge-print control center: printer stations (add / inline **rename** / **revoke**, the `cvp_…` token shown **once** on creation), live station cards with state + staff hints, queue counters (pending / in flight / dead letters / completed), the last completed jobs with **Reprint**, and dead letters with **Requeue** / **Discard**. Backed by `get_print_overview` (polled every 5 s) — see [../backend/printing.md](../backend/printing.md). |
| **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. |
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
| **Settings** | **Badge printing** section first: how many labels a front-desk (welcome) check-in prints for the **active event** — a 1–4 segmented picker (`events.badge_copies`), saving on its own single-column write with a "Copies saved" confirmation; it renders even when the LLM/sidecar call fails. Then the global LLM endpoint, model and optional API key for feedback summaries. See [../backend/printing.md](../backend/printing.md). |
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default) + the **badge copies** picker (same 1–4 control as Settings). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
| **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). |
## Sessionize Source Editing
@@ -129,12 +129,18 @@ apps/admin/src/
├─ Sponsors.tsx # sponsor CRUD
├─ Schedule.tsx # slots + sessions + speakers + material
├─ Activity.tsx # check-ins / connections / feedback tables
├─ Events.tsx # event management (+ sessionize_endpoint + per-row Sync + talk networking bonus)
├─ Events.tsx # event management (+ sessionize_endpoint + per-row Sync + talk networking bonus + badge copies)
├─ Interfaces.tsx # sidecar status / run / recent runs
├─ Reports.tsx # post-event summary + CSV / Excel / PDF export (sidecar /export)
└─ Settings.tsx # server-only LLM configuration (redacted key)
└─ Settings.tsx # badge-print copies (active event) + server-only LLM configuration (redacted key)
```
Shared component: `components/BadgeCopiesSetting.tsx` exports the presentational
1–4 segmented picker (`BadgeCopiesPicker`), the clamping helper
(`clampBadgeCopies`) and the self-saving Settings card (`BadgeCopiesSetting`,
which writes `events.badge_copies` through `setBadgeCopies` — one column, so it
can never clobber the rest of the row).
## Data access
The admin app uses the **anon key + the admin's session JWT** — no service-role
+15 -3
View File
@@ -241,10 +241,22 @@ is role-aware — staff (`contact.is_admin`) default to **Staff** mode, attendee
no extra points" (the `already` flag from the RPC). The `checkin_attendee`
RPC also rejects a service session server-side ("service sessions cannot be
checked in").
**Front-desk gate:** if the lanyard belongs to someone the front desk has
not welcomed yet, the RPC refuses and the screen shows its own sheet —
**🛑 "Not checked in yet" / "…needs to be checked in at the front desk before
they can be scanned into a session."** — instead of a generic error toast.
Nothing is recorded and no points move; **OK** dismisses it and re-arms the
camera. The gate is enforced in the database, not here (see
[../backend/rpcs.md](../backend/rpcs.md)).
- **Welcome check-in** — no session dropdown; scanning an attendee's lanyard →
`welcomeCheckin(qr)` marks them present at the **event**
(`registrations.checked_in = true`, no points). Result sheet: "👋 {name} —
Welcome to the event! — ✓ Checked in" (or "Already checked in to the event").
read-only `previewWelcomeCheckin(qr)` → a **confirm sheet** ("You are
checking in {name}. By confirming, you will print their badge {N} times" /
"…this person's label" when `copies` is 1; the print sentence is dropped when
nothing would print) → **Yes** runs `welcomeCheckin(qr)`, which marks them
present at the **event** (`registrations.checked_in = true`, no points) and
queues `events.badge_copies` labels. Result sheet: "👋 {name} — Welcome to
the event! — ✓ Checked in" (or "Already checked in to the event"). This is
the scan that opens the session gate above.
Data: `useEvent()` (for the session list) + the RPCs above.
+163
View File
@@ -159,3 +159,166 @@ Badge queued correctly; test data cleaned afterwards.
**Deployed to production 2026-10-19**: attendee app only (`convivo-app`
rebuilt; no migration, admin/sidecar untouched).
---
# Follow-up: Registrations toggle feels buggy; front-desk gate; badge copies (2026-10-19)
## Symptoms (reported from production)
1. The admin **Registrations** table "feels buggy", especially when checking
someone in or out.
2. Request: nobody should be scannable into a **session** before the front desk
has checked them in — and the app should say so.
3. Request: an admin setting for **how many badge copies** a welcome check-in
prints (default 1, up to 4).
## Root cause of (1)
Not a render bug — a regression the previous change introduced, **and it was
never deployed**, which is why "it doesn't work" at all.
Commit `316f131` (un-check-in removes points) made both row actions do:
```
setBusy(true) → write → await reloadRegistrations(event_id) → setBusy(false)
```
Two things went wrong from there:
- The list is **sorted by points**. Reloading after a toggle re-sorts it, so the
row you just clicked *moves*, and with a **Checked in** filter applied it
disappears entirely. Clicking the same place again hits a different person.
- `busy` was **one flag for the whole table**, so during every request the event
selector, every type dropdown, every checkbox and the Merge buttons all went
dead at once, with no indication of which row was working. A second click in
that window either did nothing or fired a second write for the same row.
**Fix** (`apps/admin/src/views/Registrations.tsx`):
- `busyIds: Set<string>` + a `withRowBusy(id, run)` helper — **per-row** in
flight state. Only the touched row's control is disabled; it gets a
`.row-busy` background and a "Saving…" pulse (`data-testid="saving-<id>"`,
motion-respecting). Other rows stay live, and two rows can be saved at the
same time. A double click on the same row is ignored while its write runs.
- **No reload.** The toggle patches its own row — `checked_in` plus the points
delta the RPC itself returns (`points_removed`) — and the type change patches
`type` (`set_registration_type` only mutates that column, and the sponsor
lookup modal's `onSaved` now patches to `sponsor` instead of reloading). Rows
therefore keep their place; the leaderboard and totals are untouched because
the server is the source of truth either way.
- Rollback on failure restores **both** `checked_in` and `points` from the row
that was clicked, so the checkbox never lies.
Accessibility/ergonomics in the same pass (`apps/admin/src/styles.css`): the
toggle's hit area is now 40×41 px (`padding: 9px 0; margin: -9px 0`) instead of
the bare track, the hidden checkbox gets a `:focus-visible` ring on the track,
and a disabled track reads as disabled.
## Design of (2) — the front-desk gate
`checkin_attendee` now reads the attendee's `registrations.checked_in` and
raises **`This attendee needs to be checked in at the front desk first.`** when
it is not `true`. It also **stopped setting `checked_in = true` as a side
effect**, which is what let a session scan make someone "checked in to the
event" without anyone welcoming them. The welcome check-in (and the admin
Registrations toggle, i.e. the front desk acting from the console) are now the
only ways to earn that flag.
Enforced in the database on purpose: `checkins` has **no INSERT policy**, so the
RPC is the only write path and the gate cannot be bypassed from the API.
The scanner (`apps/convivo/src/screens/Scan.tsx`) treats this as a *state*, not
a transient error: instead of a toast it opens its own sheet — **🛑 "Not checked
in yet" / "This attendee needs to be checked in at the front desk before they
can be scanned into a session."** with **OK** (`data-testid="front-desk-required"`
/ `front-desk-ok`). The camera stays paused behind it and re-arms on **OK**.
## Design of (3) — badge copies
- New column `events.badge_copies` `integer not null default 1
check (badge_copies between 1 and 4)`. Per-event is the right data model; the
setting is surfaced in **Settings → Badge printing** for the active event
because that is where admins expect one global knob, and also on the Events
form.
- `welcome_checkin` builds the payload once and calls `pgmq.send` **N times** in
the same transaction. The Pi worker prints exactly one label per job, so
**N jobs = N labels** and nothing in `apps/printer` changed. The value is
clamped again inside the function (`greatest(1, least(4, …))`) so a
hand-edited row cannot flood the queue.
- `preview_welcome_checkin` gained a **`copies`** column (drop + recreate — the
return type changed, and Postgres refuses `create or replace` across that), so
the confirmation popup tells the truth: *"you will print their badge 3 times"*
instead of a fixed *"this person's label"*. `copies` is `0` when nothing would
print.
- **Manual reprint (`enqueue_badge_print`) still prints exactly one label** —
reprinting a lost badge must not produce a stack.
- Saving uses `setBadgeCopies(eventId, copies)`, a **single-column** update, so
it can never clobber the rest of the event row. The picker is
`components/BadgeCopiesSetting.tsx` (shared segmented 1–4 control + the
self-saving card with a "Copies saved" confirmation). The Settings view loads
the active event **independently of** `getLlmSettings()`, so the badge section
still renders when the LLM/sidecar call fails.
## Tests
- `supabase/tests/badge_print_tests.sql`: **+6 assertions → 113** — gate refuses
an un-welcomed session scan; `badge_copies = 3` queues three more labels; the
savepoint restores the queue to one; `preview.copies` = `1` / `0` / `3`. The
pre-existing session-check-in case now sets `checked_in` first, since the gate
made it a precondition.
- `supabase/tests/leaderboard_tests.sql`: **+1 assertion → 47**, fixtures
checked-in (plus a fresh, un-checked-in attendee to drive the gate).
- `supabase/tests/rpc_tests.sql`: fixtures checked-in so the session path is
reachable.
- New `e2e/tests/registration-checkin-toggle.spec.ts` — **6** mocked-admin tests:
toggle fires exactly one request and **zero refetches**, row order unchanged,
the busy row shows "Saving…" with its checkbox disabled while other rows stay
enabled, a second row saves concurrently, un-check reports `−30`, a rejected
write rolls back, type change without refetch, and the Settings picker
persisting 1–4.
- New `e2e/tests/front-desk-gate.spec.ts` — **3** real-browser tests
(CONV-GATE-001..003): the refusal sheet with **no check-in recorded**, the same
scan succeeding after the welcome, and a session check-in not setting the
event flag by itself.
- New `e2e/tests/welcome-badge-copies.spec.ts` — **3** real-browser tests
(CONV-COPIES-001..003): `badge_copies = 3` → exactly 3 queue messages for that
attendee, `1` → 1 with the singular wording, re-welcome → **+0**.
- `e2e/tests/registration-ticket-merge.spec.ts` (pre-existing, **broken by
`316f131`**): its rollback test mocked a `registrations` PATCH the toggle
stopped using when it moved to `set_registration_checked_in`; the mock now
targets the RPC, so the test exercises what the UI actually calls.
- Also fixed by this work: `feedback-ai-summary.spec.ts` was picking up an
ambiguous `Save` button once the badge card added one — the card's button is
labelled **"Save copies" / "Copies saved"**, which resolves the collision for
both screen-reader users and the test. `checkin-attendee.spec.ts`'s print-copy
assertion now tolerates the typographic apostrophe in the popup text.
- Pre-existing, **not** caused by this change set: `session-checkin.spec.ts`,
`checkin-attendee.spec.ts` and `rpc_tests.sql` still fail locally because the
seeded demo identities (`CVV-ATT-1000`…`CVV-ATT-1005`, the `37ab7060-…`
session) no longer exist — pretix-imported data replaced them. The identical 8
`rpc_tests` failures occur at HEAD, and the same specs failed with everything
stashed. The new specs deliberately provision their own fixtures so they do
not depend on that drift; the fixtures should be re-seeded separately.
- Both apps typecheck clean and build (`admin` `index-DSNhW0mZ.js`,
`convivo` `index-CXd2kxEv.js`, print `print-CaBuVVFf.js`).
## Deployment
**Not deployed.** Production is still missing everything from this change set:
`events.badge_copies` does not exist, `checkin_attendee` has no gate,
`welcome_checkin` prints one label, and `admin.appe.at` serves the pre-fix
bundle `index-Czkxg0C-.js` (which is exactly the reload-everything behaviour
described above). `set_registration_checked_in` already exists there with the
same signature, so the migration will not conflict.
**One data consequence to decide on before shipping:** in production 2 people
already have session check-ins without `checked_in = true`, so the gate would
lock 1 of them out of further session scans until the front desk welcomes them.
Either backfill `checked_in = true` for anyone with an existing check-in as part
of the rollout, or accept that the front desk re-welcomes them (they print a
badge on the way back through).
To ship: apply `20261019110000_front_desk_gate_and_badge_copies.sql` (records
41 → 42), rebuild `convivo-app` **and** `convivo-admin`, then re-run the suites
above against prod.
+11
View File
@@ -77,6 +77,17 @@ export class ScanPage {
return this.page.getByTestId('welcome-checkin-result');
}
/** The front-desk gate sheet: scanning an attendee into a SESSION is refused
* until they have been through the welcome (front desk) check-in. */
frontDeskSheet(): ReturnType<Page['locator']> {
return this.page.getByTestId('front-desk-required');
}
/** Acknowledge the front-desk gate sheet. */
async dismissFrontDesk(): Promise<void> {
await this.page.getByTestId('front-desk-ok').click();
}
/** The welcome check-in confirmation popup (shown after a welcome scan,
* before the attendee is actually checked in). */
welcomeConfirm(): ReturnType<Page['locator']> {
+3 -1
View File
@@ -74,7 +74,9 @@ test.describe('Welcome Check-In + attendee access', () => {
const confirm = scan.welcomeConfirm();
await expect(confirm).toBeVisible();
await expect(confirm).toContainText(/You are checking in/);
await expect(confirm).toContainText(/print this person's label/i);
// One label by default, so the singular wording applies. `.` covers the
// typographic apostrophe in the app copy.
await expect(confirm).toContainText(/print this person.s label/i);
expect(db.isWelcomeCheckedIn(ID.attendeeNew.email)).toBe(false);
// "No" dismisses the popup and leaves the attendee unchecked in.
+158
View File
@@ -0,0 +1,158 @@
import { test, expect } from './base';
import { APP_URL, EVENT_ID, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { db, psql, psqlScalar, sqlQuote } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
/**
* Front-desk gate: an attendee must be checked in to the EVENT (the welcome
* check-in at the front desk) before they can be scanned into any SESSION.
* The database enforces it (`checkin_attendee` raises); the scanner turns that
* into a dedicated sheet so staff can relay it to the attendee.
*
* These specs provision their own attendee and pick a real session from the
* active event instead of relying on seeded demo rows, so they survive data
* re-imports (the historic fixtures were replaced by imported pretix data).
*/
const GATE_EMAIL = '[email protected]';
const GATE_TOKEN = 'CVV-GATE-TEST-01';
const GATE_NAME = 'Gate Test Attendee';
/** Ensure a known ticketed attendee exists in the active event, unchecked in. */
function ensureGateAttendee(): void {
psql(`insert into public.contacts (email, full_name, is_admin)
values (${sqlQuote(GATE_EMAIL)}, ${sqlQuote(GATE_NAME)}, false)
on conflict (email) do update set full_name = excluded.full_name`);
psql(`insert into public.registrations (event_id, contact_email, type, checked_in, points, qr_token)
values (${sqlQuote(EVENT_ID)}, ${sqlQuote(GATE_EMAIL)}, 'attendee', false, 0, ${sqlQuote(GATE_TOKEN)})
on conflict (event_id, contact_email)
do update set checked_in = false, points = 0, qr_token = excluded.qr_token, type = 'attendee'`);
}
function removeGateAttendee(): void {
psql(`delete from public.checkins where contact_email = ${sqlQuote(GATE_EMAIL)}`);
// The welcome scan in CONV-GATE-002 legitimately queued a label; with no Pi
// attached locally it would sit in the queue forever, so drop it here.
psql(`delete from pgmq.q_badge_print where message->'sample'->>'email' = ${sqlQuote(GATE_EMAIL)}`);
psql(`delete from public.registrations where contact_email = ${sqlQuote(GATE_EMAIL)}`);
psql(`delete from public.contacts where email = ${sqlQuote(GATE_EMAIL)}`);
}
/** Any checkable (non-service) session of the active event. */
function someSessionId(): string {
return psqlScalar(`select s.id from public.sessions s
join public.slots sl on sl.id = s.slot_id
where s.event_id = ${sqlQuote(EVENT_ID)} and sl.type <> 'service_session'
order by sl.id, s.id limit 1`);
}
function setWelcome(checkedIn: boolean): void {
psql(`update public.registrations set checked_in = ${checkedIn}
where contact_email = ${sqlQuote(GATE_EMAIL)} and event_id = ${sqlQuote(EVENT_ID)}`);
}
test.describe('Front-desk gate (no session check-in before welcome check-in)', () => {
test.beforeEach(() => {
ensureGateAttendee();
removeGateAttendeeCheckins();
});
test.afterAll(() => removeGateAttendee());
test('CONV-GATE-001 a session scan of an unchecked attendee is refused with a front-desk message', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
const session = someSessionId();
expect(session, 'the active event needs at least one checkable session').toBeTruthy();
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
await app.gotoTab('scan');
await scan.setStaffMode();
await scan.setSessionMode();
await scan.selectSession(session);
await scan.scanCode(GATE_TOKEN);
// A blocking sheet, not a transient toast.
await expect(scan.frontDeskSheet()).toBeVisible();
await expect(scan.frontDeskSheet()).toContainText(/front desk/i);
// No session result, and nothing persisted.
await expect(scan.sessionResult()).toHaveCount(0);
expect(db.sessionCheckins(GATE_EMAIL)).toEqual([]);
expect(db.isWelcomeCheckedIn(GATE_EMAIL)).toBe(false);
// Acknowledging clears it (and re-arms the camera via `paused`).
await scan.dismissFrontDesk();
await expect(scan.frontDeskSheet()).toHaveCount(0);
});
test('CONV-GATE-002 after the welcome check-in the same session scan succeeds', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
const session = someSessionId();
expect(session).toBeTruthy();
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
await app.gotoTab('scan');
await scan.setStaffMode();
// 1. Blocked in session mode.
await scan.setSessionMode();
await scan.selectSession(session);
await scan.scanCode(GATE_TOKEN);
await expect(scan.frontDeskSheet()).toBeVisible();
await scan.dismissFrontDesk();
// 2. Welcome (front desk) check-in.
await scan.setWelcomeMode();
await scan.scanWelcome(GATE_TOKEN);
expect(await db.waitForWelcomeCheckedIn(GATE_EMAIL)).toBe(true);
await scan.dismissResult();
// 3. The very same session scan now goes through.
await scan.setSessionMode();
await scan.selectSession(session);
await scan.scanCode(GATE_TOKEN);
await expect(scan.sessionResult()).toBeVisible();
expect(await db.waitForSessionCheckin(GATE_EMAIL, session)).toBe(true);
});
test('CONV-GATE-003 a session check-in no longer checks the attendee into the event by itself', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
const session = someSessionId();
expect(session).toBeTruthy();
// Front desk already done, so the gate is open — but the event flag is then
// cleared by hand to prove the session check-in does not set it again.
setWelcome(true);
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
await app.gotoTab('scan');
await scan.setStaffMode();
await scan.setSessionMode();
await scan.selectSession(session);
setWelcome(false); // undo the precondition: now the gate must refuse
await scan.scanCode(GATE_TOKEN);
await expect(scan.frontDeskSheet()).toBeVisible();
expect(db.sessionCheckins(GATE_EMAIL)).toEqual([]);
setWelcome(true);
await scan.dismissFrontDesk();
await scan.scanCode(GATE_TOKEN);
await expect(scan.sessionResult()).toBeVisible();
expect(await db.waitForSessionCheckin(GATE_EMAIL, session)).toBe(true);
});
});
function removeGateAttendeeCheckins(): void {
psql(`delete from public.checkins where contact_email = ${sqlQuote(GATE_EMAIL)}`);
psql(`delete from pgmq.q_badge_print where message->'sample'->>'email' = ${sqlQuote(GATE_EMAIL)}`);
psql(`update public.registrations set checked_in = false, points = 0
where contact_email = ${sqlQuote(GATE_EMAIL)}`);
}
@@ -0,0 +1,210 @@
import { test, expect, type Page, type Route } from '@playwright/test';
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const user = { id: '99999999-9999-4999-8999-999999999999', email: '[email protected]', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
/**
* The check-in toggle must feel instant and stay put. The regression this
* guards: the handler used to set a GLOBAL busy flag and reload the whole
* registration list after every toggle. Because the table is sorted by points,
* the reload moved the row you had just touched somewhere else, a column filter
* could make it vanish, and every control in the table went dead mid-request.
*/
type Reg = {
id: string; event_id: string; contact_email: string; type: string; qr_token: string | null;
external_id: null; import_source: null; checked_in: boolean; points: number; created_at: string;
};
const mkRegs = (): Reg[] => [
{ id: 'r1', event_id: eventId, contact_email: '[email protected]', type: 'attendee', qr_token: 'CV-A', external_id: null, import_source: null, checked_in: false, points: 40, created_at: 'x' },
{ id: 'r2', event_id: eventId, contact_email: '[email protected]', type: 'attendee', qr_token: 'CV-B', external_id: null, import_source: null, checked_in: false, points: 30, created_at: 'x' },
{ id: 'r3', event_id: eventId, contact_email: '[email protected]', type: 'speaker', qr_token: 'CV-C', external_id: null, import_source: null, checked_in: false, points: 20, created_at: 'x' },
{ id: 'r4', event_id: eventId, contact_email: '[email protected]', type: 'staff', qr_token: 'CV-D', external_id: null, import_source: null, checked_in: false, points: 10, created_at: 'x' },
];
const contacts = [
{ email: '[email protected]', full_name: 'Admin User', linkedin_url: null, show_email: true, show_linkedin: true, is_admin: true, created_at: 'x' },
{ email: '[email protected]', full_name: 'Ann A', linkedin_url: null, show_email: true, show_linkedin: false, is_admin: false, created_at: 'x' },
{ email: '[email protected]', full_name: 'Bob B', linkedin_url: null, show_email: true, show_linkedin: false, is_admin: false, created_at: 'x' },
{ email: '[email protected]', full_name: 'Cid C', linkedin_url: null, show_email: true, show_linkedin: false, is_admin: false, created_at: 'x' },
{ email: '[email protected]', full_name: 'Dee D', linkedin_url: null, show_email: true, show_linkedin: false, is_admin: false, created_at: 'x' },
];
const event = {
id: eventId, name: 'Toggle Conference', company: 'APPE', is_active: true, location: null,
start_date: '2026-11-01', end_date: '2026-11-01', use_realtime_clock: false, sessionize_endpoint: null,
pretix_organizer: null, pretix_event_slug: null, pretix_api_key: null, last_synced_at: null,
talk_networking_bonus: 2, badge_copies: 1, num_registrations: 4, num_checked_in_registrations: 0,
num_sessions: 0, num_speakers: 1, avg_feedback: null, created_at: 'x',
};
/** Mutable per-test fixtures so a handler can observe its own writes. */
type Harness = { regs: Reg[]; registrationFetches: number; setCheckedInDelayMs: number };
async function openAdmin(page: Page, view: 'Registrations' | 'Settings', h: Harness) {
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'r', expires_in: 3600, token_type: 'bearer' };
await page.route('**/auth/v1/**', (r) => r.fulfill({ json: new URL(r.request().url()).pathname.endsWith('/user') ? user : session }));
await page.route('**/rest/v1/**', async (route: Route) => {
const u = new URL(route.request().url());
const t = u.pathname.split('/').pop();
const method = route.request().method();
if (t === 'contacts') return route.fulfill({ json: u.searchParams.has('email') ? contacts[0] : contacts });
if (t === 'registrations' && method === 'GET') { h.registrationFetches++; return route.fulfill({ json: h.regs }); }
if (t === 'badge_layouts') return route.fulfill({ json: [] });
if (t === 'events') {
if (method === 'PATCH') {
const patch = JSON.parse(route.request().postData() || '{}') as Record<string, unknown>;
Object.assign(event, patch);
return route.fulfill({ status: 204, json: {} });
}
return route.fulfill({ json: u.searchParams.has('is_active') ? event : [event] });
}
if (t === 'rpc' || u.pathname.includes('/rpc/')) return route.fulfill({ json: [] });
return route.fulfill({ json: [] });
});
// PostgREST RPC urls end with the function name, so the check-in write is
// matched here (registered after, so it wins over the catch-all above).
await page.route('**/rpc/set_registration_checked_in*', async (route: Route) => {
if (h.setCheckedInDelayMs) await new Promise((r) => setTimeout(r, h.setCheckedInDelayMs));
const body = JSON.parse(route.request().postData() || '{}') as { p_registration_id: string; p_checked_in: boolean };
const row = h.regs.find((x) => x.id === body.p_registration_id);
const removed = row && !body.p_checked_in ? row.points : 0;
if (row) { row.checked_in = body.p_checked_in; if (!body.p_checked_in) row.points = 0; }
return route.fulfill({ json: [{ registration_id: body.p_registration_id, checked_in: body.p_checked_in, points_removed: removed }] });
});
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=r&type=magiclink`);
await expect(page.locator('.nav')).toBeVisible();
await page.locator('.nav').getByRole('button', { name: new RegExp(view) }).click();
}
const rows = (page: Page) => page.locator('table.data tbody tr');
const order = (page: Page) => rows(page).locator('.cell-person .n').allTextContents();
const rowToggle = (page: Page, rowText: string) =>
rows(page).filter({ hasText: rowText }).first().locator('.toggle .track');
test.describe('Registrations check-in toggle', () => {
test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
});
test('toggling does not refetch the list, so rows keep their order', async ({ page }) => {
const h: Harness = { regs: mkRegs(), registrationFetches: 0, setCheckedInDelayMs: 0 };
await openAdmin(page, 'Registrations', h);
await expect(rows(page)).toHaveCount(4);
const before = await order(page);
const fetchesAfterLoad = h.registrationFetches;
await rowToggle(page, 'Ann A').click();
await expect(page.getByText(/Ann A: checked in/)).toBeVisible();
// The whole point: no list reload, therefore no re-sort and no jumping row.
expect(h.registrationFetches, 'the toggle must not refetch registrations').toBe(fetchesAfterLoad);
expect(await order(page)).toEqual(before);
// The row still shows the new state.
await expect(rows(page).filter({ hasText: 'Ann A' }).locator('input[type=checkbox]')).toBeChecked();
});
test('only the toggled row is busy; the rest of the table stays usable', async ({ page }) => {
const h: Harness = { regs: mkRegs(), registrationFetches: 0, setCheckedInDelayMs: 1500 };
await openAdmin(page, 'Registrations', h);
await expect(rows(page)).toHaveCount(4);
await rowToggle(page, 'Ann A').click();
// In flight: the touched row says so and its controls pause.
const busyRow = rows(page).filter({ hasText: 'Ann A' }).first();
await expect(busyRow.getByTestId('saving-r1')).toBeVisible();
await expect(busyRow.locator('input[type=checkbox]')).toBeDisabled();
// Optimistic value is already shown, so the click feels instant.
await expect(busyRow.locator('input[type=checkbox]')).toBeChecked();
// Other rows are untouched — not disabled, no busy marker.
const otherRow = rows(page).filter({ hasText: 'Bob B' }).first();
await expect(otherRow.locator('input[type=checkbox]')).toBeEnabled();
await expect(otherRow.locator('.row-saving')).toHaveCount(0);
await expect(otherRow.locator('select')).toBeEnabled();
// The event selector is not frozen either.
await expect(page.locator('select.input').first()).toBeEnabled();
// And a second row can be toggled while the first one is still saving.
await rowToggle(page, 'Cid C').click();
await expect(rows(page).filter({ hasText: 'Cid C' }).getByTestId('saving-r3')).toBeVisible();
await expect(page.locator('.row-saving')).toHaveCount(0, { timeout: 10_000 });
await expect(rows(page).filter({ hasText: 'Ann A' }).locator('input[type=checkbox]')).toBeChecked();
await expect(rows(page).filter({ hasText: 'Cid C' }).locator('input[type=checkbox]')).toBeChecked();
});
test('un-checking removes the check-in points on that row', async ({ page }) => {
const h: Harness = { regs: mkRegs(), registrationFetches: 0, setCheckedInDelayMs: 0 };
h.regs[1].checked_in = true; // Bob already checked in with 30 pts
await openAdmin(page, 'Registrations', h);
await expect(rows(page).filter({ hasText: 'Bob B' })).toContainText('30');
await rowToggle(page, 'Bob B').click();
await expect(page.getByText(/un-checked in, −30/)).toBeVisible();
await expect(rows(page).filter({ hasText: 'Bob B' })).toContainText('0');
await expect(rows(page).filter({ hasText: 'Bob B' }).locator('input[type=checkbox]')).not.toBeChecked();
});
test('a rejected toggle rolls the checkbox back', async ({ page }) => {
const h: Harness = { regs: mkRegs(), registrationFetches: 0, setCheckedInDelayMs: 0 };
await openAdmin(page, 'Registrations', h);
// Make the backend refuse the write.
await page.unroute('**/rpc/set_registration_checked_in*');
await page.route('**/rpc/set_registration_checked_in*', (route) =>
route.fulfill({ status: 400, json: { message: 'This attendee needs to be checked in at the front desk first.' } }));
await rowToggle(page, 'Ann A').click();
await expect(page.getByText(/front desk/)).toBeVisible();
// The optimistic flip must not survive a failed write.
await expect(rows(page).filter({ hasText: 'Ann A' }).locator('input[type=checkbox]')).not.toBeChecked();
await expect(rows(page).filter({ hasText: 'Ann A' }).locator('.row-saving')).toHaveCount(0);
});
test('changing the pass type does not refetch or reorder the table', async ({ page }) => {
const h: Harness = { regs: mkRegs(), registrationFetches: 0, setCheckedInDelayMs: 0 };
await openAdmin(page, 'Registrations', h);
await page.route('**/rpc/set_registration_type*', (route) =>
route.fulfill({ json: { ...h.regs[0], type: 'sponsor' } }));
await expect(rows(page)).toHaveCount(4);
const before = await order(page);
const fetches = h.registrationFetches;
await rows(page).filter({ hasText: 'Ann A' }).first().locator('select').selectOption('staff');
await expect(page.getByText(/Ann A → staff/)).toBeVisible();
expect(h.registrationFetches).toBe(fetches);
expect(await order(page)).toEqual(before);
await expect(rows(page).filter({ hasText: 'Ann A' }).first().locator('select')).toHaveValue('staff');
});
});
test.describe('Settings — badge copies', () => {
test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
});
test('the active event controls how many labels a welcome check-in prints', async ({ page }) => {
const h: Harness = { regs: mkRegs(), registrationFetches: 0, setCheckedInDelayMs: 0 };
await openAdmin(page, 'Settings', h);
const section = page.getByTestId('settings-badge-printing');
await expect(section).toBeVisible();
const picker = section.getByTestId('badge-copies');
// Default 1, and exactly four choices (1..4) — no free-text to mistype.
await expect(picker.getByRole('button')).toHaveCount(4);
await expect(picker.locator('button.active')).toHaveText('1');
await picker.getByRole('button', { name: '3', exact: true }).click();
await expect(section.getByTestId('badge-copies-save')).toBeEnabled();
await section.getByTestId('badge-copies-save').click();
await expect(section.getByTestId('badge-copies-save')).toHaveText('Copies saved');
// Persisted on the event.
expect(event.badge_copies).toBe(3);
// Save is disabled when there is nothing to save.
await expect(section.getByTestId('badge-copies-save')).toBeDisabled();
});
});
+11 -8
View File
@@ -7,7 +7,7 @@ const targetId = '22222222-2222-4222-8222-222222222222';
const otherId = '33333333-3333-4333-8333-333333333333';
const manualId = '44444444-4444-4444-8444-444444444444';
async function openRegistrations(page: Page, options: { patchFailure?: boolean; mergeFailure?: boolean } = {}) {
async function openRegistrations(page: Page, options: { checkinFailure?: boolean; mergeFailure?: boolean } = {}) {
const user = { id: '99999999-9999-4999-8999-999999999999', email: '[email protected]', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'mock-refresh-token', expires_in: 3600, token_type: 'bearer' };
@@ -43,13 +43,16 @@ async function openRegistrations(page: Page, options: { patchFailure?: boolean;
}
if (table === 'contacts') return route.fulfill({ json: url.searchParams.has('email') ? contacts[0] : contacts });
if (table === 'events') return route.fulfill({ json: url.searchParams.has('is_active') ? event : [event] });
// The check-in toggle goes through the set_registration_checked_in RPC
// (the single admin path — it also reverses check-in points), not a PATCH.
if (table === 'set_registration_checked_in') {
const body = route.request().postDataJSON() as { p_registration_id: string; p_checked_in: boolean };
if (options.checkinFailure) return route.fulfill({ status: 500, json: { message: 'Check-in failed' } });
const row = registrations.find((r) => r.id === body.p_registration_id);
registrations = registrations.map(r => r.id === body.p_registration_id ? { ...r, checked_in: body.p_checked_in } : r);
return route.fulfill({ json: [{ registration_id: body.p_registration_id, checked_in: body.p_checked_in, points_removed: 0 }] });
}
if (table === 'registrations') {
if (route.request().method() === 'PATCH') {
if (options.patchFailure) return route.fulfill({ status: 500, json: { message: 'Check-in failed' } });
const id = url.searchParams.get('id')!.replace('eq.', '');
registrations = registrations.map(row => row.id === id ? { ...row, ...route.request().postDataJSON() } : row);
return route.fulfill({ json: { id } });
}
return route.fulfill({ json: registrations });
}
return route.fulfill({ json: [] });
@@ -71,7 +74,7 @@ test('counts only QR tickets and check-in slides without refresh', async ({ page
});
test('failed check-in rolls the toggle back', async ({ page }) => {
await openRegistrations(page, { patchFailure: true });
await openRegistrations(page, { checkinFailure: true });
const row = page.getByRole('row').filter({ hasText: '[email protected]' });
await row.locator('label.toggle').click();
await expect(page.getByText('Check-in failed', { exact: true })).toBeVisible();
+124
View File
@@ -0,0 +1,124 @@
import { test, expect } from './base';
import { APP_URL, EVENT_ID, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { db, psql, sqlQuote } from '../src/helpers/db';
import { ScanPage } from '../src/pages/ScanPage';
/**
* Welcome check-in prints `events.badge_copies` labels (1..4, default 1), and
* the confirmation popup states that number so staff are not surprised by a
* small run of labels. A manual reprint always prints one, and a second welcome
* scan of an already-checked-in attendee prints nothing.
*
* The suite provisions its own attendee + badge layout: printing depends on the
* event having a layout with elements, which is operator data and not seeded.
*/
const EMAIL = '[email protected]';
const TOKEN = 'CVV-BADGE-COPIES-01';
const LAYOUT = 'e2e badge copies layout';
/** One QR element is enough for a printable payload. */
const ELEMENTS = JSON.stringify([{
id: 'e2e-qr', type: 'qr', content: 'qr_token', static_value: '', x: 2, y: 2,
width: 24, height: 24, rotation: 0,
}]);
function provision(copies: number): void {
psql(`insert into public.contacts (email, full_name, is_admin)
values (${sqlQuote(EMAIL)}, 'Copies Test', false)
on conflict (email) do update set full_name = excluded.full_name`);
psql(`insert into public.registrations (event_id, contact_email, type, checked_in, points, qr_token)
values (${sqlQuote(EVENT_ID)}, ${sqlQuote(EMAIL)}, 'attendee', false, 0, ${sqlQuote(TOKEN)})
on conflict (event_id, contact_email)
do update set checked_in = false, points = 0, qr_token = excluded.qr_token`);
psql(`insert into public.badge_layouts (event_id, name, is_default, page_width_mm, page_height_mm, elements)
values (${sqlQuote(EVENT_ID)}, ${sqlQuote(LAYOUT)}, false, 101, 30, ${sqlQuote(ELEMENTS)}::jsonb)
on conflict do nothing`);
psql(`update public.events set badge_copies = ${copies}`);
clearJobs();
}
function clearJobs(): void {
psql(`delete from pgmq.q_badge_print where message->'sample'->>'email' = ${sqlQuote(EMAIL)}`);
}
const queuedLabels = (): number =>
Number(psql(`select count(*) from pgmq.q_badge_print
where message->'sample'->>'email' = ${sqlQuote(EMAIL)}`) || '0');
function teardown(): void {
clearJobs();
psql(`delete from public.badge_layouts where name = ${sqlQuote(LAYOUT)}`);
psql(`delete from public.checkins where contact_email = ${sqlQuote(EMAIL)}`);
psql(`delete from public.registrations where contact_email = ${sqlQuote(EMAIL)}`);
psql(`delete from public.contacts where email = ${sqlQuote(EMAIL)}`);
psql(`update public.events set badge_copies = 1`);
}
test.describe('Welcome check-in badge copies', () => {
test.afterAll(() => teardown());
test('CONV-COPIES-001 a welcome check-in queues badge_copies labels', async ({ page }) => {
const scan = new ScanPage(page);
provision(3);
await login(page, APP_URL, ID.staff);
await page.getByTestId('tab-scan').click();
await scan.setStaffMode();
await scan.setWelcomeMode();
await scan.scanCode(TOKEN);
await expect(scan.welcomeConfirm()).toBeVisible();
// The popup states the real count instead of promising a single label.
await expect(scan.welcomeConfirm()).toContainText(/their badge 3 times/i);
await scan.confirmWelcome();
await expect(scan.welcomeResult()).toBeVisible();
expect(queuedLabels()).toBe(3);
});
test('CONV-COPIES-002 with copies = 1 the popup keeps the single-label wording', async ({ page }) => {
const scan = new ScanPage(page);
provision(1);
await login(page, APP_URL, ID.staff);
await page.getByTestId('tab-scan').click();
await scan.setStaffMode();
await scan.setWelcomeMode();
await scan.scanCode(TOKEN);
await expect(scan.welcomeConfirm()).toContainText(/label/i);
await expect(scan.welcomeConfirm()).not.toContainText(/badge 1 times/i);
await scan.confirmWelcome();
await expect(scan.welcomeResult()).toBeVisible();
expect(queuedLabels()).toBe(1);
});
test('CONV-COPIES-003 welcoming an already checked-in attendee prints nothing', async ({ page }) => {
const scan = new ScanPage(page);
provision(4); // even at the maximum, a repeat must not print
await login(page, APP_URL, ID.staff);
await page.getByTestId('tab-scan').click();
await scan.setStaffMode();
await scan.setWelcomeMode();
// First welcome prints 4.
await scan.scanCode(TOKEN);
await scan.confirmWelcome();
await expect(scan.welcomeResult()).toBeVisible();
expect(queuedLabels()).toBe(4);
await scan.dismissResult();
// Second welcome: flagged as already checked in, nothing added to the queue.
await scan.scanCode(TOKEN);
await expect(scan.welcomeConfirm()).toContainText(/Already checked in/i);
await scan.confirmWelcome();
await expect(scan.welcomeResult()).toBeVisible();
expect(queuedLabels()).toBe(4);
expect(db.isWelcomeCheckedIn(EMAIL)).toBe(true);
});
});
@@ -0,0 +1,194 @@
-- -----------------------------------------------------------------------------
-- Front-desk gate + configurable welcome badge copies.
--
-- 1. Front-desk gate: an attendee must be checked in to the EVENT (the welcome
-- check-in at the front desk sets registrations.checked_in) before they can
-- be checked into any SESSION. Previously checkin_attendee silently marked
-- the attendee checked in as a side effect; that is removed and replaced by
-- a hard requirement with a clear message.
--
-- 2. Badge copies: events.badge_copies (1..4, default 1) controls how many
-- labels a welcome check-in prints. welcome_checkin enqueues that many
-- identical jobs (the Pi worker prints one label per job, so no worker
-- change is needed). Manual reprint (enqueue_badge_print) still prints one.
-- -----------------------------------------------------------------------------
alter table public.events
add column if not exists badge_copies integer not null default 1
check (badge_copies between 1 and 4);
comment on column public.events.badge_copies is
'How many badge labels a welcome (front-desk) check-in prints, 1..4.';
-- -----------------------------------------------------------------------------
-- 1. checkin_attendee — require a prior front-desk (welcome) check-in.
-- Recreated from 20260833000000 with two changes:
-- * resolves the registration's checked_in and raises a clear message when
-- the attendee has not been checked in at the front desk;
-- * no longer sets checked_in = true (that is the welcome check-in's job).
-- -----------------------------------------------------------------------------
create or replace function public.checkin_attendee(p_session_id uuid, p_attendee_qr text)
returns table (checkin_id uuid, attendee_email text, attendee_name text,
points integer, already boolean)
language plpgsql security definer set search_path = public as $$
declare
v_staff text := public.current_email();
v_attendee text;
v_name text;
v_event_id uuid;
v_slot_type public.slot_type;
v_new_id uuid;
v_points integer;
v_already boolean := false;
v_checked boolean;
begin
if v_staff is null then raise exception 'not authenticated'; end if;
if not public.is_staff_or_admin() then raise exception 'staff or admin only'; end if;
select r.contact_email, c.full_name, r.checked_in into v_attendee, v_name, v_checked
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.qr_token = p_attendee_qr
and r.event_id = (select id from public.events where is_active limit 1);
if v_attendee is null then raise exception 'no attendee found for that QR code'; end if;
-- Front-desk gate: no session check-in before the welcome check-in.
if coalesce(v_checked, false) is not true then
raise exception 'This attendee needs to be checked in at the front desk first.';
end if;
select se.event_id, s.type into v_event_id, v_slot_type
from public.sessions se
join public.slots s on s.id = se.slot_id
where se.id = p_session_id;
if v_event_id is null then raise exception 'session not found'; end if;
if v_slot_type = 'service_session' then
raise exception 'service sessions cannot be checked in';
end if;
insert into public.checkins (event_id, contact_email, session_id, staff_email)
values (v_event_id, v_attendee, p_session_id, v_staff)
on conflict (event_id, contact_email, session_id) do nothing
returning id into v_new_id;
if v_new_id is null then
v_already := true;
select id into v_new_id from public.checkins
where event_id = v_event_id and contact_email = v_attendee and session_id = p_session_id;
else
perform public._award_points(v_event_id, v_attendee, 10, 'checkin');
end if;
select r.points into v_points from public.registrations r
where r.event_id = v_event_id and r.contact_email = v_attendee;
return query select v_new_id, v_attendee, v_name, coalesce(v_points, 0), v_already;
end;
$$;
-- -----------------------------------------------------------------------------
-- 2. welcome_checkin — enqueue events.badge_copies labels on a first check-in.
-- Recreated from 20261018170000 with the copies loop; everything else is
-- unchanged (guard, resolution, already flag, transactional enqueue).
-- -----------------------------------------------------------------------------
create or replace function public.welcome_checkin(p_attendee_qr text)
returns table (attendee_email text, attendee_name text, already boolean)
language plpgsql security definer set search_path = public as $$
declare
v_staff text := public.current_email();
v_attendee text;
v_name text;
v_event_id uuid;
v_checked boolean;
v_reg_id uuid;
v_payload jsonb;
v_copies integer;
v_i integer;
begin
if v_staff is null then raise exception 'not authenticated'; end if;
if not public.is_staff_or_admin() then raise exception 'staff or admin only'; end if;
select id into v_event_id from public.events where is_active limit 1;
if v_event_id is null then raise exception 'no active event'; end if;
select r.contact_email, c.full_name, r.id into v_attendee, v_name, v_reg_id
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.qr_token = p_attendee_qr
and r.event_id = v_event_id;
if v_attendee is null then raise exception 'no attendee found for that QR code'; end if;
select checked_in into v_checked
from public.registrations
where event_id = v_event_id and contact_email = v_attendee;
update public.registrations set checked_in = true
where event_id = v_event_id and contact_email = v_attendee;
-- Badge printing: only for a genuine first check-in, and only when the event
-- actually has a badge layout. No payload -> no job. Print badge_copies labels.
if v_checked is not true then
v_payload := public._badge_print_payload(v_reg_id, 'checkin', v_staff);
if v_payload is not null then
select coalesce(e.badge_copies, 1) into v_copies
from public.events e where e.id = v_event_id;
v_copies := greatest(1, least(4, coalesce(v_copies, 1)));
v_i := 0;
while v_i < v_copies loop
perform pgmq.send('badge_print', v_payload);
v_i := v_i + 1;
end loop;
end if;
end if;
return query select v_attendee, v_name, coalesce(v_checked, false);
end;
$$;
-- -----------------------------------------------------------------------------
-- 3. preview_welcome_checkin — now also reports HOW MANY labels a confirm will
-- print, so the scanner popup states the truth instead of "this person's
-- label". Recreated from 20261019090000 with the extra `copies` column; the
-- signature changes, so it has to be dropped first (Postgres will not
-- replace a function with a different return type). Everything else —
-- guards, resolution, `already`, and the `will_print` condition that mirrors
-- welcome_checkin — is unchanged.
-- -----------------------------------------------------------------------------
drop function if exists public.preview_welcome_checkin(text);
create or replace function public.preview_welcome_checkin(p_attendee_qr text)
returns table (attendee_email text, attendee_name text, already boolean,
will_print boolean, copies integer)
language plpgsql stable security definer set search_path = public as $$
declare
v_staff text := public.current_email();
v_attendee text;
v_name text;
v_event_id uuid;
v_checked boolean;
v_reg_id uuid;
begin
if v_staff is null then raise exception 'not authenticated'; end if;
if not public.is_staff_or_admin() then raise exception 'staff or admin only'; end if;
select id into v_event_id from public.events where is_active limit 1;
if v_event_id is null then raise exception 'no active event'; end if;
select r.contact_email, c.full_name, r.id into v_attendee, v_name, v_reg_id
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.qr_token = p_attendee_qr
and r.event_id = v_event_id;
if v_attendee is null then raise exception 'no attendee found for that QR code'; end if;
select checked_in into v_checked
from public.registrations
where event_id = v_event_id and contact_email = v_attendee;
-- A badge prints only on a genuine first check-in AND when the event has a
-- layout with elements (the same condition welcome_checkin uses to enqueue).
will_print := coalesce(v_checked, false) is not true
and public._badge_print_payload(v_reg_id, 'checkin', v_staff) is not null;
-- Same clamp welcome_checkin applies, so the preview never over-promises.
copies := case when will_print then
greatest(1, least(4, coalesce(
(select e.badge_copies from public.events e where e.id = v_event_id), 1)))
else 0 end;
return query select v_attendee, v_name, coalesce(v_checked, false), will_print, copies;
end;
$$;
revoke execute on function public.preview_welcome_checkin(text) from public, anon;
grant execute on function public.preview_welcome_checkin(text) to authenticated;
notify pgrst, 'reload schema';
+44 -1
View File
@@ -238,7 +238,9 @@ select pg_temp.assert_bp(
(select count(*) = 1 from pgmq.q_badge_print), 'event without a layout enqueues nothing');
update public.events set is_active = true where id = 'b9d00001-0000-0000-0000-00000000000a';
-- The regular session check-in must not print badges.
-- The regular session check-in must not print badges. It now requires a prior
-- front-desk (welcome) check-in, so mark the attendee checked in first.
update public.registrations set checked_in = true where contact_email = '[email protected]';
select public.checkin_attendee('b9d00003-0000-0000-0000-00000000000a', 'BPQR-ATT-3');
select pg_temp.assert_bp(
(select count(*) = 1 from public.checkins where session_id = 'b9d00003-0000-0000-0000-00000000000a'),
@@ -246,6 +248,18 @@ select pg_temp.assert_bp(
select pg_temp.assert_bp(
(select count(*) = 1 from pgmq.q_badge_print), 'session check-in enqueues nothing');
-- Front-desk gate: an attendee not checked in at the event cannot be scanned
-- into a session (raises a clear message, records nothing).
do $$ begin
begin
perform public.checkin_attendee('b9d00003-0000-0000-0000-00000000000a', 'BPQR-ATT-5');
raise exception 'front-desk gate allowed a session check-in';
exception when raise_exception then
if sqlerrm not like '%front desk%' then raise; end if;
end;
perform pg_temp.assert_bp(true, 'session check-in requires a front-desk check-in');
end; $$;
-- A direct write of checked_in (admin edit) must not print badges either.
update public.registrations set checked_in = true where contact_email = '[email protected]';
select pg_temp.assert_bp(
@@ -262,6 +276,20 @@ select pg_temp.assert_bp(
(select not checked_in from public.registrations where contact_email = '[email protected]'),
'rolled back check-in leaves the attendee unchecked');
-- Badge copies: a welcome check-in prints events.badge_copies labels (default
-- 1 is covered by the first check-in above). Isolated in a savepoint so the
-- queue returns to one for the rest of the run.
savepoint bp_copies;
update public.events set badge_copies = 3 where id = 'b9d00001-0000-0000-0000-00000000000a';
select public.welcome_checkin('BPQR-ATT-5');
select pg_temp.assert_bp(
(select count(*) = 4 from pgmq.q_badge_print),
'welcome check-in enqueues badge_copies (3) labels');
rollback to savepoint bp_copies;
select pg_temp.assert_bp(
(select count(*) = 1 from pgmq.q_badge_print),
'copies test rolled back cleanly');
-- -----------------------------------------------------------------------------
-- 2b. WELCOME CHECK-IN PREVIEW (read-only: resolves the name + will_print)
-- -----------------------------------------------------------------------------
@@ -291,6 +319,21 @@ select pg_temp.assert_bp(
(select already = true and will_print = false from bp_prev2),
'preview of a checked-in attendee reports no print');
-- The preview also states how many labels a confirm would print, so the scanner
-- popup can be truthful about the copy count instead of "this person's label".
select pg_temp.assert_bp(
(select copies = 1 from bp_prev1),
'preview reports copies = 1 by default');
select pg_temp.assert_bp(
(select copies = 0 from bp_prev2),
'preview reports no copies when nothing will print');
savepoint bp_prev_copies;
update public.events set badge_copies = 3 where id = 'b9d00001-0000-0000-0000-00000000000a';
select pg_temp.assert_bp(
(select copies = 3 from public.preview_welcome_checkin('BPQR-ATT-5')),
'preview reports the event badge_copies');
rollback to savepoint bp_prev_copies;
-- An event without a badge layout: check-in would work but nothing prints.
-- (bp-attb was checked in by the section-2 scan; reset it so the preview
-- isolates the "no layout" reason rather than "already checked in".)
+21 -2
View File
@@ -19,11 +19,12 @@ values ('[email protected]', 'Player', false), ('[email protected]', 'Pe
('[email protected]', 'Other', false), ('[email protected]', 'Speaker', false),
('[email protected]', 'Staff', false), ('[email protected]', 'Admin', true),
('[email protected]', 'Domain Admin', false), ('[email protected]', 'Orphan', false);
insert into public.registrations (event_id, contact_email, type, qr_token, points)
insert into public.registrations (event_id, contact_email, type, qr_token, points, checked_in)
select 'a0150000-0000-0000-0000-000000000001'::uuid, email,
case when email = '[email protected]' then 'staff'
when email = '[email protected]' then 'speaker' else 'attendee' end::public.registration_type,
'LB-' || email, case when is_admin or email = '[email protected]' then 99 else 0 end
'LB-' || email, case when is_admin or email = '[email protected]' then 99 else 0 end,
true
from public.contacts where email in ('[email protected]', '[email protected]', '[email protected]',
'[email protected]', '[email protected]', '[email protected]', '[email protected]');
insert into public.registrations (event_id, contact_email, type, qr_token, points)
@@ -36,6 +37,13 @@ values ('a0150000-0000-0000-0000-000000000011', 'a0150000-0000-0000-0000-0000000
('a0150000-0000-0000-0000-000000000012', 'a0150000-0000-0000-0000-000000000001', -151001, 'Talk two'),
('a0150000-0000-0000-0000-000000000013', 'a0150000-0000-0000-0000-000000000001', -151002, 'Service');
-- A front-desk-UNCHECKED attendee: has a registration but checked_in = false,
-- so a session check-in must be blocked by the front-desk gate.
insert into public.contacts (email, full_name, is_admin)
values ('[email protected]', 'Fresh Face', false);
insert into public.registrations (event_id, contact_email, type, qr_token, points, checked_in)
values ('a0150000-0000-0000-0000-000000000001', '[email protected]', 'attendee', '[email protected]', 0, false);
do $$
declare
event_one uuid := 'a0150000-0000-0000-0000-000000000001';
@@ -63,6 +71,17 @@ begin
if sqlerrm <> 'service sessions cannot be checked in' then raise; end if;
end;
perform pg_temp.assert_board(true, 'service check-in rejected');
-- Front-desk gate: an attendee not checked in at the event cannot be scanned
-- into a session; the RPC raises a clear message.
begin
perform public.checkin_attendee(talk_one, '[email protected]');
raise exception 'front-desk gate allowed a session check-in';
exception when raise_exception then
if sqlerrm not like '%front desk%' then raise; end if;
end;
perform pg_temp.assert_board(
(select not exists (select 1 from public.checkins where contact_email = '[email protected]')),
'front-desk gate blocks session check-in');
foreach excluded_email in array array['[email protected]','[email protected]','[email protected]'] loop
perform set_config('request.jwt.claims', json_build_object('email', excluded_email)::text, true);
select * into feedback_result from public.submit_feedback(talk_one, 5, 'Review');
+7 -1
View File
@@ -61,6 +61,9 @@ declare
begin
select id into v_session from public.sessions where slot_id = 2 limit 1;
perform set_user('[email protected]');
-- Front-desk (welcome) check-in first: a session check-in now requires the
-- attendee to be checked in to the event.
perform public.welcome_checkin('CVV-ATT-1000');
select points into v_res_points from public.checkin_attendee(v_session, 'CVV-ATT-1000');
select points into v_points from public.registrations
where contact_email = '[email protected]'
@@ -72,7 +75,7 @@ begin
v_ok := exists (select 1 from public.registrations
where contact_email = '[email protected]' and checked_in);
v_msg := 'registration not marked checked_in';
insert into test_results values ('checkin marks checked_in', v_ok, case when v_ok then null else v_msg end);
insert into test_results values ('front-desk check-in marks checked_in', v_ok, case when v_ok then null else v_msg end);
exception when others then
insert into test_results values ('checkin (1)', false, 'error: ' || sqlerrm);
end;
@@ -119,6 +122,9 @@ begin
where slot_id in (select id from public.slots where type = 'service_session')
limit 1;
perform set_user('[email protected]');
-- Front-desk check-in first so the service-session guard (not the front-desk
-- gate) is what rejects this scan.
perform public.welcome_checkin('CVV-ATT-1001');
begin
perform public.checkin_attendee(v_session, 'CVV-ATT-1001');
insert into test_results values ('service session check-in rejected', false,