Files
Convivo/apps/convivo/src/screens/Scan.tsx
T
17473916a6 fix(admin): per-row check-in toggle; feat(db): front-desk gate + badge copies
Registrations table felt buggy because both row actions did
setBusy(true) -> write -> reloadRegistrations() -> setBusy(false):
the list is sorted by points, so a reload made the row you just
touched jump (or vanish under a Checked-in filter), and the single
`busy` flag disabled every control in the table for the whole
request. The fix is per-row in-flight state (busyIds + withRowBusy)
and no reload at all: the toggle patches its own row's checked_in
plus the points delta the RPC returns, the type change patches
`type`; a rejected write rolls both back. Only the touched row is
disabled, shows a "Saving…" pulse, and two rows can save at once.
Toggle hit area is now 40x41 px with a focus-visible ring.

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

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

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

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 15:10:20 +02:00

303 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useMemo, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import { checkinAttendee, createConnectionRequest, lanyardLookup, previewWelcomeCheckin, welcomeCheckin } from '../lib/api';
import { capWords } from '../lib/time';
import type { CheckinResult, PublicContact, WelcomeCheckinPreview, WelcomeCheckinResult } from '../lib/types';
import { Avatar, Scanner, Sheet, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
/** How the scanner describes the number of labels a welcome check-in prints. */
function printPhrase(copies: number): string {
return copies > 1 ? `their badge ${copies} times` : 'this person’s label';
}
export function Scan() {
const { contact } = useAuth();
const { slots, loading } = useEvent();
const isStaff = !!contact?.is_admin;
const [mode, setMode] = useState<'attendee' | 'staff'>(isStaff ? 'staff' : 'attendee');
const [sessionId, setSessionId] = useState<string>('');
const [welcomeMode, setWelcomeMode] = useState(false);
const [connectTarget, setConnectTarget] = useState<{ contact: PublicContact; qr: string } | null>(null);
const [checkin, setCheckin] = useState<CheckinResult | null>(null);
const [welcome, setWelcome] = useState<WelcomeCheckinResult | null>(null);
// A welcome scan is previewed first and only committed after the staff
// confirms that they want to check the person in (and print their badge).
const [pendingWelcome, setPendingWelcome] = useState<{ token: string; preview: WelcomeCheckinPreview } | null>(null);
// A session scan for an attendee who has not been through the front desk
// (welcome) check-in is blocked; we surface a dedicated sheet for it.
const [frontDesk, setFrontDesk] = useState(false);
const [busy, setBusy] = useState(false);
const { toast } = useToast();
// The first checkable (non-service) session, computed synchronously so a fast
// scan never races the async default-selection effect below.
const defaultSessionId = useMemo(
() => slots.flatMap((s) => s.sessions).find((s) => s.slot_type !== 'service_session')?.id ?? '',
[slots],
);
useEffect(() => {
if (defaultSessionId && !sessionId) setSessionId(defaultSessionId);
}, [defaultSessionId, sessionId]);
if (loading || !contact) {
return (
<section className="screen">
<div className="center" style={{ flex: 1 }}>
<Spinner />
</div>
</section>
);
}
const meEmail = contact.email;
const activeStaff = mode === 'staff' && isStaff;
async function handleScan(token: string) {
setBusy(true);
try {
if (activeStaff) {
if (welcomeMode) {
// Preview first: resolve the name and whether a badge will print, then
// wait for the staff to confirm before checking in.
const preview = await previewWelcomeCheckin(token);
setPendingWelcome({ token, preview });
} else {
// Fall back to the first checkable session so a fast scan (before the
// async default-selection effect runs) never fails with "pick a session".
const targetSession = sessionId || defaultSessionId;
if (!targetSession) {
toast('Pick a session first', 'err');
return;
}
const res = await checkinAttendee(targetSession, token);
setCheckin(res);
}
} else {
const found = await lanyardLookup(token);
if (!found) {
toast('No attendee found for that code', 'err');
return;
}
if (found.email === meEmail) {
toast('That’s your own lanyard 🙂', 'err');
return;
}
setConnectTarget({ contact: found, qr: token });
}
} catch (e) {
const m = e instanceof Error ? e.message : 'Something went wrong';
// The front-desk gate is a blocking state, not a transient error: show a
// persistent sheet instead of a quick toast so staff can relay it.
if (/front desk/i.test(m)) setFrontDesk(true);
else toast(m, 'err');
} finally {
setBusy(false);
}
}
async function confirmWelcome() {
if (!pendingWelcome) return;
setBusy(true);
try {
const res = await welcomeCheckin(pendingWelcome.token);
setWelcome(res);
setPendingWelcome(null);
} catch (e) {
toast(e instanceof Error ? e.message : 'Something went wrong', 'err');
} finally {
setBusy(false);
}
}
async function confirmConnect() {
if (!connectTarget) return;
setBusy(true);
try {
const conn = await createConnectionRequest(connectTarget.qr);
if (conn.status === 'accepted') toast('You’re connected! 🤝', 'ok');
else if (conn.status === 'pending') toast('Connection request sent', 'ok');
else toast('Request already resolved');
window.dispatchEvent(new Event('connections-changed'));
setConnectTarget(null);
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not send request', 'err');
} finally {
setBusy(false);
}
}
const selSession = slots.flatMap((s) => s.sessions).find((s) => s.id === sessionId);
return (
<section className="screen">
<div className="row between">
<div>
<div className="h1">{activeStaff ? 'Check-in' : 'Scan'}</div>
<div className="muted small">{activeStaff ? 'Scan attendees to check them in' : 'Scan a peer’s lanyard to connect'}</div>
</div>
{isStaff && (
<div className="seg" style={{ width: 170 }}>
<button className={mode === 'attendee' ? 'active' : ''} data-testid="scan-mode-attendee" onClick={() => setMode('attendee')}>Attendee</button>
<button className={mode === 'staff' ? 'active' : ''} data-testid="scan-mode-staff" onClick={() => setMode('staff')}>Staff</button>
</div>
)}
</div>
{activeStaff && (
<div>
<div className="row between" style={{ marginBottom: 10 }}>
<span className="muted small" style={{ fontWeight: 700 }}>Check-in type</span>
<label className="uiverse-toggle" data-testid="welcome-checkin-toggle" title={welcomeMode ? 'Welcome check-in' : 'Session check-in'}>
<input
type="checkbox"
checked={welcomeMode}
onChange={(e) => setWelcomeMode(e.target.checked)}
/>
</label>
</div>
{welcomeMode ? (
<div className="muted small" style={{ padding: '10px 12px', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 12 }}>
🏷 <b>Welcome check-in</b> — marks the attendee present at the event.
</div>
) : (
<>
<div className="muted small" style={{ marginBottom: 7 }}>Checking in to session</div>
<select className="input" data-testid="session-selector" value={sessionId} onChange={(e) => setSessionId(e.target.value)}>
{slots
.filter(({ slot }) => slot.type !== 'service_session')
.map(({ slot, sessions }) => (
<optgroup key={slot.id} label={`${slot.name} · ${slot.start_time.slice(0, 5)}`}>
{sessions.map((s) => (
<option key={s.id} value={s.id}>{s.title}</option>
))}
</optgroup>
))}
</select>
</>
)}
</div>
)}
<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 }}>
{selSession.room} · {selSession.speakers}
</div>
)}
{/* Connect sheet */}
<Sheet open={!!connectTarget} onClose={() => setConnectTarget(null)}>
{connectTarget && (
<div style={{ textAlign: 'center' }}>
<Avatar name={connectTarget.contact.full_name} id={connectTarget.contact.email} size={72} fs={26} />
<h3 style={{ marginTop: 12 }}>{connectTarget.contact.full_name}</h3>
{connectTarget.contact.registration_type && (
<span className={`pill reg-${connectTarget.contact.registration_type}`} style={{ marginTop: 8 }}>
{capWords(connectTarget.contact.registration_type)}
</span>
)}
{connectTarget.contact.linkedin_url && (
<div className="sub" style={{ marginTop: 6 }}>
<a href={connectTarget.contact.linkedin_url} target="_blank" rel="noreferrer">LinkedIn</a>
</div>
)}
<div style={{ marginTop: 16 }}>
<button className="btn primary" data-testid="connection-send" disabled={busy} onClick={confirmConnect}>
{busy ? 'Sending…' : 'Connect 🤝'}
</button>
<button className="btn ghost" style={{ marginTop: 8 }} onClick={() => setConnectTarget(null)}>
Not now
</button>
</div>
</div>
)}
</Sheet>
{/* Check-in result sheet */}
<Sheet open={!!checkin} onClose={() => setCheckin(null)}>
{checkin && (
<div style={{ textAlign: 'center' }} data-testid="session-checkin-result">
<div style={{ fontSize: 52 }}>{checkin.already ? '⚠️' : '✅'}</div>
<h3 style={{ marginTop: 10 }}>{checkin.attendee_name}</h3>
<div className="sub">{checkin.already ? 'Already checked in' : 'Checked in'}</div>
<div style={{ marginTop: 14 }}>
{checkin.already ? (
<span className="pill amber">No extra points</span>
) : (
<span className="pill green">+10 pts · now {checkin.points}</span>
)}
</div>
<button className="btn primary" style={{ marginTop: 18 }} onClick={() => setCheckin(null)}>
Scan next
</button>
</div>
)}
</Sheet>
{/* Front-desk gate: session check-in blocked until a welcome check-in. */}
<Sheet open={frontDesk} onClose={() => setFrontDesk(false)}>
<div style={{ textAlign: 'center' }} data-testid="front-desk-required">
<div style={{ fontSize: 52 }}>🛑</div>
<h3 style={{ marginTop: 10 }}>Not checked in yet</h3>
<p className="sub" style={{ marginTop: 8 }}>
This attendee needs to be checked in at the front desk before they can be
scanned into a session.
</p>
<button className="btn primary" style={{ marginTop: 18 }} data-testid="front-desk-ok" onClick={() => setFrontDesk(false)}>
OK
</button>
</div>
</Sheet>
{/* Welcome check-in confirmation (shown before checking in / printing) */}
<Sheet open={!!pendingWelcome} onClose={() => !busy && setPendingWelcome(null)}>
{pendingWelcome && (
<div style={{ textAlign: 'center' }} data-testid="welcome-checkin-confirm">
<div style={{ fontSize: 52 }}>{pendingWelcome.preview.will_print ? '🏷️' : '👋'}</div>
<h3 style={{ marginTop: 10 }}>{pendingWelcome.preview.attendee_name}</h3>
<p className="sub" style={{ marginTop: 8 }}>
{pendingWelcome.preview.already
? 'Already checked in to the event.'
: pendingWelcome.preview.will_print
? `You are checking in ${pendingWelcome.preview.attendee_name}. By confirming, you will print ${printPhrase(pendingWelcome.preview.copies)}.`
: `You are checking in ${pendingWelcome.preview.attendee_name}.`}
</p>
{!pendingWelcome.preview.will_print && !pendingWelcome.preview.already && (
<div className="muted small" style={{ marginTop: 6 }}>No badge will print (no layout for this event).</div>
)}
<div style={{ marginTop: 16 }}>
<button className="btn primary" data-testid="welcome-checkin-confirm-yes" disabled={busy} onClick={confirmWelcome}>
{busy ? 'Checking in…' : 'Yes, check in'}
</button>
<button className="btn ghost" style={{ marginTop: 8 }} disabled={busy} onClick={() => setPendingWelcome(null)}>
No
</button>
</div>
</div>
)}
</Sheet>
{/* Welcome check-in result sheet */}
<Sheet open={!!welcome} onClose={() => setWelcome(null)}>
{welcome && (
<div style={{ textAlign: 'center' }} data-testid="welcome-checkin-result">
<div style={{ fontSize: 52 }}>{welcome.already ? '⚠️' : '👋'}</div>
<h3 style={{ marginTop: 10 }}>{welcome.attendee_name}</h3>
<div className="sub">{welcome.already ? 'Already checked in to the event' : 'Welcome to the event!'}</div>
<div style={{ marginTop: 14 }}>
<span className="pill green">✓ Checked in</span>
</div>
<button className="btn primary" style={{ marginTop: 18 }} onClick={() => setWelcome(null)}>
Scan next
</button>
</div>
)}
</Sheet>
</section>
);
}