feat: finalize ticket merging and speaker-aware imports

This commit is contained in:
Lago committed 2026-10-10 13:28:18 +02:00
1 parent 648daa0794
commit 4e71e9b797
35 files changed
+1772 -348

No files matched your search

+3 -1
View File
@@ -91,14 +91,16 @@ export function Toggle({
checked,
onChange,
label,
disabled = false,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label?: string;
disabled?: boolean;
}) {
return (
<label className="toggle" title={label}>
<input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
<input type="checkbox" checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
<span className="track">
<span className="knob" />
</span>
+5 -1
View File
@@ -153,10 +153,14 @@ export async function setRegistrationType(contactEmail: string, type: Registrati
}
export async function setCheckedIn(registrationId: string, checkedIn: boolean): Promise<void> {
const { error } = await supabase.from('registrations').update({ checked_in: checkedIn }).eq('id', registrationId);
const { data, error } = await supabase.from('registrations').update({ checked_in: checkedIn }).eq('id', registrationId).select('id').single();
if (error) throw new ApiError(error.message);
if (!data) throw new ApiError('Registration no longer exists');
}
export const mergeTickets = (sourceId: string, targetId: string) =>
rpc<import('./types').TicketMergeResult>('merge_tickets', { p_source_id: sourceId, p_target_id: targetId });
// ---- Sponsors ----------------------------------------------------------------
export async function upsertSponsor(
+10
View File
@@ -172,6 +172,8 @@ export interface SidecarStatus {
}
export interface Registration {
import_source?: 'sessionize' | null;
external_id?: string | null;
id: string;
event_id: string;
contact_email: string;
@@ -182,6 +184,14 @@ export interface Registration {
created_at: string;
}
export interface TicketMergeResult {
source_id: string;
target_id: string;
target_email: string;
type: RegistrationType;
sessions_transferred: number;
}
export interface Sponsor {
id: string;
event_id: string;
+100 -10
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import {
createRegistration,
deleteContacts,
@@ -8,6 +8,7 @@ import {
getRegistrations,
getSponsors,
setCheckedIn,
mergeTickets,
setRegistrationType,
upsertSponsor,
} from '../lib/api';
@@ -33,8 +34,18 @@ export function Registrations() {
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 selectedEventId = useRef(selectedId);
selectedEventId.current = selectedId;
const event = events.find((e) => e.id === selectedId) ?? null;
const eventRegistrations = registrations.filter((registration) => registration.event_id === selectedId);
const ticketed = eventRegistrations.filter((registration) => registration.qr_token?.trim());
async function reloadRegistrations(eventId: string) {
const rows = await getRegistrations(eventId);
if (selectedEventId.current === eventId) setRegistrations(rows);
}
async function load() {
try {
@@ -106,8 +117,9 @@ export function Registrations() {
const filtered = useMemo(() => {
if (!registrations) return [];
const q = query.trim().toLowerCase();
if (!q) return registrations;
if (!q) return registrations.filter((r) => r.event_id === selectedId);
return registrations.filter((r) => {
if (r.event_id !== selectedId) return false;
const c = byEmail.get(r.contact_email);
return (
(c?.full_name ?? '').toLowerCase().includes(q) ||
@@ -115,13 +127,13 @@ export function Registrations() {
r.type.toLowerCase().includes(q)
);
});
}, [registrations, query, byEmail]);
}, [registrations, query, byEmail, selectedId]);
async function changeType(r: Registration, type: RegistrationType) {
setBusy(true);
try {
await setRegistrationType(r.contact_email, type);
await load();
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';
@@ -139,10 +151,11 @@ export function Registrations() {
async function toggleCheckedIn(r: Registration, v: boolean) {
setBusy(true);
setRegistrations((rows) => rows.map((row) => row.id === r.id ? { ...row, checked_in: v } : row));
try {
await setCheckedIn(r.id, v);
await load();
} 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);
@@ -181,7 +194,7 @@ export function Registrations() {
<div className="sub">
<strong>{event.name}</strong>
{event.is_active && <span className="pill green" style={{ marginLeft: 8 }}>active</span>} ·{' '}
{registrations.length} registrations · {registrations.filter((r) => r.checked_in).length} checked in.
{ticketed.length} tickets · {ticketed.filter((r) => r.checked_in).length} checked in · {eventRegistrations.length - ticketed.length} without tickets.
</div>
</div>
<div className="row" style={{ gap: 10 }}>
@@ -189,6 +202,7 @@ export function Registrations() {
className="input"
style={{ maxWidth: 280 }}
value={selectedId}
disabled={busy || mergeFor !== null}
onChange={(e) => setSelectedId(e.target.value)}
>
{events.map((e) => (
@@ -260,13 +274,18 @@ export function Registrations() {
<td>
<div className="row" style={{ gap: 8 }}>
<span className="mono small">{r.qr_token ?? '—'}</span>
<button className="btn small" onClick={() => setQrFor(r)}>
{r.qr_token?.trim() && <button className="btn small" onClick={() => setQrFor(r)}>
QR
</button>
</button>}
{!r.qr_token?.trim() && r.import_source === 'sessionize' && (
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
Merge tickets
</button>
)}
</div>
</td>
<td>
<Toggle checked={r.checked_in} onChange={(v) => toggleCheckedIn(r, v)} />
<Toggle checked={r.checked_in} disabled={busy} onChange={(v) => toggleCheckedIn(r, v)} />
</td>
<td style={{ textAlign: 'right' }}>
<span className="pts">{r.points}</span>
@@ -286,12 +305,28 @@ export function Registrations() {
onClose={() => setAdding(false)}
onSaved={async (msg) => {
setAdding(false);
await load();
await reloadRegistrations(event.id);
push('success', msg);
}}
/>
)}
{mergeFor && (
<MergeTicketsModal
source={mergeFor}
contacts={byEmail}
tickets={ticketed.filter((ticket) => ticket.id !== mergeFor.id && ticket.external_id?.trim())}
onClose={() => setMergeFor(null)}
onMerged={async (result) => {
setRegistrations((rows) => rows.filter((row) => row.id !== result.source_id).map((row) => row.id === result.target_id ? { ...row, type: result.type } : row));
try { await reloadRegistrations(mergeFor.event_id); }
catch { push('error', 'Merge saved; reload registrations to see the updated ticket.'); }
setMergeFor(null);
push('success', `Merged into ${result.target_email}; ${result.sessions_transferred} session assignment(s) transferred.`);
}}
/>
)}
{qrFor && (
<Modal
open
@@ -330,6 +365,61 @@ export function Registrations() {
);
}
function MergeTicketsModal({ source, contacts, tickets, onClose, onMerged }: {
source: Registration;
contacts: Map<string, Contact>;
tickets: Registration[];
onClose: () => void;
onMerged: (result: import('../lib/types').TicketMergeResult) => Promise<void>;
}) {
const [search, setSearch] = useState('');
const [selected, setSelected] = useState('');
const [saving, setSaving] = useState(false);
const [failure, setFailure] = useState('');
const sourceName = contacts.get(source.contact_email)?.full_name ?? source.contact_email;
const words = (name: string) => name.toLocaleLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').split(/[^a-z0-9]+/).filter(Boolean);
const sourceWords = words(sourceName);
const score = (ticket: Registration) => words(contacts.get(ticket.contact_email)?.full_name ?? '').filter((word) => sourceWords.includes(word)).length;
const options = tickets.filter((ticket) => `${contacts.get(ticket.contact_email)?.full_name ?? ''} ${ticket.contact_email}`.toLowerCase().includes(search.trim().toLowerCase()))
.sort((first, second) => score(second) - score(first) || first.contact_email.localeCompare(second.contact_email));
const target = tickets.find((ticket) => ticket.id === selected);
async function save() {
if (!target || saving) return;
setSaving(true);
setFailure('');
try { await onMerged(await mergeTickets(source.id, target.id)); }
catch (error) {
setFailure(error instanceof Error ? error.message : 'Merge failed');
setSaving(false);
}
}
return (
<Modal open title="Merge tickets" onClose={() => { if (!saving) onClose(); }} footer={
<>
<button className="btn" disabled={saving} onClick={onClose}>Cancel</button>
<button className="btn primary" disabled={!target || saving} onClick={save}>{saving ? 'Merging...' : 'Confirm merge'}</button>
</>
}>
<p><strong>{sourceName}</strong><br /><span className="muted">{source.contact_email}</span></p>
<label className="field">
<span>Destination ticket</span>
<input className="input" value={search} disabled={saving} placeholder="Search name or email" onChange={(change) => setSearch(change.target.value)} />
</label>
<div style={{ maxHeight: 280, overflowY: 'auto', marginTop: 12 }} role="radiogroup" aria-label="Destination ticket">
{options.map((ticket) => (
<label key={ticket.id} className="row" style={{ padding: '10px 0', gap: 10 }}>
<input type="radio" name="merge-ticket" disabled={saving} checked={selected === ticket.id} onChange={() => setSelected(ticket.id)} />
<span><strong>{contacts.get(ticket.contact_email)?.full_name ?? ticket.contact_email}</strong><br />{ticket.contact_email}{score(ticket) > 0 && <span className="pill green" style={{ marginLeft: 8 }}>Name match</span>}</span>
</label>
))}
{options.length === 0 && <p className="muted">No matching purchased tickets.</p>}
</div>
{target && <p>The ticket for <strong>{target.contact_email}</strong> keeps its QR, check-in and points. Session assignments and the {source.type} role transfer before the imported registration is deleted. Other events are unchanged.</p>}
{failure && <p role="alert" className="error">{failure}</p>}
</Modal>
);
}
function AddRegistrationModal({
contacts,
existing,
+1
View File
@@ -2,6 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="referrer" content="no-referrer" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+7
View File
@@ -35,6 +35,13 @@ server {
try_files $uri =404;
}
location = /auth/callback {
access_log off;
add_header Cache-Control "no-store";
add_header Referrer-Policy "no-referrer";
try_files /index.html =404;
}
# ---- Supabase same-origin proxy -------------------------------------
# No trailing slash on proxy_pass => the original URI is passed through
# unchanged (e.g. /auth/v1/token -> http://<target>/auth/v1/token).
+9 -5
View File
@@ -85,7 +85,7 @@ export function QrImage({ value, size = 180 }: { value: string; size?: number })
* decoded text. The camera only works on a secure context (https or localhost);
* the manual field always works.
*/
export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (text: string) => void; label?: string }) {
export function Scanner({ onResult, label = 'Scan a lanyard QR', entryLabel = 'QR code', placeholder = '…or type the code (e.g. CVV-XXX-NNNN)', submitLabel = 'Go', disabled = false, submitDisabled = false, onEntryChange }: { onResult: (text: string) => void; label?: string; entryLabel?: string; placeholder?: string; submitLabel?: string; disabled?: boolean; submitDisabled?: boolean; onEntryChange?: (text: string) => void }) {
const [manual, setManual] = useState('');
const [camError, setCamError] = useState<string | null>(null);
const scannerRef = useRef<Html5Qrcode | null>(null);
@@ -162,13 +162,17 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
<div className="row" style={{ gap: 8 }}>
<input
className="input mono"
type="text"
data-testid="scanner-manual-code"
placeholder="…or type the code (e.g. CVV-XXX-NNNN)"
aria-label={entryLabel}
placeholder={placeholder}
disabled={disabled}
value={manual}
onChange={(e) => setManual(e.target.value)}
onChange={(e) => { setManual(e.target.value); onEntryChange?.(e.target.value); }}
onKeyDown={(e) => { if (e.key === 'Enter' && manual.trim() && !disabled && !submitDisabled) onResult(manual.trim()); }}
/>
<button className="btn primary small" data-testid="scanner-manual-go" disabled={!manual.trim()} onClick={() => onResult(manual.trim())}>
Go
<button className="btn primary small" data-testid="scanner-manual-go" disabled={disabled || submitDisabled || !manual.trim()} onClick={() => onResult(manual.trim())}>
{submitLabel}
</button>
</div>
</div>
+51 -26
View File
@@ -1,7 +1,7 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import type { Session as SbSession, User } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
import { getMyContact, getMyRegistration } from '../lib/api';
import { adminCallbackPending, consumeAdminCallback, hasAdminCallback, invalidAdminLink, loadEntryProfile, type EntryProfile } from '../lib/adminEntry';
import type { Contact, Registration } from '../lib/types';
interface AuthContextValue {
@@ -10,6 +10,7 @@ interface AuthContextValue {
contact: Contact | null;
registration: Registration | null;
loading: boolean;
authError: string | null;
refresh: () => Promise<void>;
signOut: () => Promise<void>;
}
@@ -21,42 +22,66 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [contact, setContact] = useState<Contact | null>(null);
const [registration, setRegistration] = useState<Registration | null>(null);
const [loading, setLoading] = useState(true);
const [authError, setAuthError] = useState<string | null>(null);
const load = useCallback(async (email: string) => {
try {
const [c, r] = await Promise.all([getMyContact(email), getMyRegistration(email)]);
setContact(c);
setRegistration(r);
} catch (e) {
console.error('Failed to load contact', e);
}
const applyProfile = useCallback((profile: EntryProfile) => {
setSession(profile.session);
setContact(profile.contact);
setRegistration(profile.registration);
setAuthError(profile.error);
}, []);
useEffect(() => {
let active = true;
supabase.auth.getSession().then(({ data }) => {
if (!active) return;
setSession(data.session);
if (data.session?.user?.email) void load(data.session.user.email);
setLoading(false);
});
const { data: sub } = supabase.auth.onAuthStateChange((_event, newSession) => {
setSession(newSession);
if (newSession?.user?.email) void load(newSession.user.email);
else {
setContact(null);
setRegistration(null);
let revision = 0;
const emptyProfile: EntryProfile = { session: null, contact: null, registration: null, error: null };
async function restore(next: SbSession | null, currentRevision: number) {
try {
const profile = next ? await loadEntryProfile(next) : emptyProfile;
if (active && revision === currentRevision) applyProfile(profile);
} catch {
if (!active || revision !== currentRevision) return;
applyProfile({ ...emptyProfile, error: invalidAdminLink });
await supabase.auth.signOut({ scope: 'local' });
} finally {
if (active && revision === currentRevision) setLoading(false);
}
}
async function init() {
if (hasAdminCallback) {
const profile = await consumeAdminCallback();
if (active) { applyProfile(profile); setLoading(false); }
return;
}
const currentRevision = revision;
const { data } = await supabase.auth.getSession();
if (active && revision === currentRevision) await restore(data.session, currentRevision);
}
void init().catch(() => { if (active) { setAuthError(invalidAdminLink); setLoading(false); } });
const { data: sub } = supabase.auth.onAuthStateChange((event, newSession) => {
if (!active || adminCallbackPending || event === 'INITIAL_SESSION') return;
const currentRevision = ++revision;
if (!newSession) {
applyProfile(emptyProfile);
setLoading(false);
return;
}
setLoading(true);
window.setTimeout(() => {
if (active && revision === currentRevision) void restore(newSession, currentRevision);
}, 0);
});
return () => {
active = false;
sub.subscription.unsubscribe();
};
}, [load]);
}, [applyProfile]);
const refresh = useCallback(async () => {
if (session?.user?.email) await load(session.user.email);
}, [session, load]);
if (session) applyProfile(await loadEntryProfile(session));
}, [session, applyProfile]);
const signOut = useCallback(async () => {
await supabase.auth.signOut();
@@ -65,8 +90,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, []);
const value = useMemo<AuthContextValue>(
() => ({ session, user: session?.user ?? null, contact, registration, loading, refresh, signOut }),
[session, contact, registration, loading, refresh, signOut],
() => ({ session, user: session?.user ?? null, contact, registration, loading, authError, refresh, signOut }),
[session, contact, registration, loading, authError, refresh, signOut],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
+76
View File
@@ -0,0 +1,76 @@
import type { Session } from '@supabase/supabase-js';
import { supabase } from './supabase';
import { getMyContact, getMyRegistration } from './api';
import type { Contact, Registration } from './types';
export const invalidAdminLink = 'This sign-in link is invalid or expired. Please request a new link.';
export const adminLinkNotice = 'If this email belongs to an eligible admin account, a sign-in link has been sent.';
export const adminLinkFailure = 'Unable to send a sign-in link right now. Please try again later.';
export function isEmailEntry(value: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
}
export async function requestAdminLink(email: string): Promise<void> {
const normalizedEmail = email.trim().toLowerCase();
const { data: eligible, error: eligibilityError } = await supabase.rpc('can_request_admin_magic_link', { p_email: normalizedEmail });
if (eligibilityError) throw new Error(adminLinkFailure);
if (eligible !== true) return;
const { error } = await supabase.auth.signInWithOtp({
email: normalizedEmail,
options: { shouldCreateUser: false, emailRedirectTo: `${window.location.origin}/auth/callback` },
});
if (error && error.status !== 400 && error.status !== 422) throw new Error(adminLinkFailure);
}
const entryUrl = new URL(window.location.href);
const entryHash = new URLSearchParams(entryUrl.hash.slice(1));
export const hasAdminCallback = entryUrl.pathname === '/auth/callback' ||
(entryUrl.pathname === '/' && ['access_token', 'refresh_token', 'error', 'error_code'].some((key) => entryHash.has(key))) ||
(entryUrl.pathname === '/' && ['code', 'error', 'error_code'].some((key) => entryUrl.searchParams.has(key)));
if (hasAdminCallback) window.history.replaceState(null, '', '/');
export let adminCallbackPending = hasAdminCallback;
export interface EntryProfile {
session: Session | null;
contact: Contact | null;
registration: Registration | null;
error: string | null;
}
export async function loadEntryProfile(session: Session, adminOnly = false): Promise<EntryProfile> {
const { data: verified, error: userError } = await supabase.auth.getUser(session.access_token);
if (userError || !verified.user?.email || verified.user.id !== session.user.id) throw new Error(invalidAdminLink);
const { data: isAdmin, error: adminError } = await supabase.rpc('is_admin');
if (adminError) throw new Error(invalidAdminLink);
if (adminOnly && isAdmin !== true) throw new Error('This account is not an admin.');
const [contact, registration] = await Promise.all([
getMyContact(verified.user.email), getMyRegistration(verified.user.email),
]);
if (!contact) throw new Error(invalidAdminLink);
return { session: { ...session, user: verified.user }, contact: { ...contact, is_admin: isAdmin === true }, registration, error: null };
}
let callbackResult: Promise<EntryProfile> | null = null;
export function consumeAdminCallback(): Promise<EntryProfile> {
if (!callbackResult) callbackResult = (async () => {
try {
if (['error', 'error_code'].some((key) => entryHash.has(key) || entryUrl.searchParams.has(key))) throw new Error(invalidAdminLink);
const accessToken = entryHash.get('access_token');
const refreshToken = entryHash.get('refresh_token');
const code = entryUrl.searchParams.get('code');
const result = accessToken && refreshToken
? await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken })
: code && !accessToken && !refreshToken ? await supabase.auth.exchangeCodeForSession(code) : null;
if (!result || result.error || !result.data.session) throw new Error(invalidAdminLink);
return await loadEntryProfile(result.data.session, true);
} catch (failure) {
await supabase.auth.signOut({ scope: 'local' }).catch(() => {});
return { session: null, contact: null, registration: null, error: failure instanceof Error && failure.message === 'This account is not an admin.' ? failure.message : invalidAdminLink };
} finally {
adminCallbackPending = false;
}
})();
return callbackResult;
}
+3 -1
View File
@@ -106,7 +106,9 @@ export async function getMyContact(email: string): Promise<Contact | null> {
/** The signed-in contact's registration for the active event. */
export async function getMyRegistration(email: string): Promise<Registration | null> {
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).maybeSingle();
const event = await getActiveEvent();
if (!event) return null;
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).eq('event_id', event.id).maybeSingle();
if (error) throw new ApiError(error.message);
return (data as Registration) ?? null;
}
+53 -8
View File
@@ -1,29 +1,64 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { supabase } from '../lib/supabase';
import { lanyardLookup } from '../lib/api';
import { capWords } from '../lib/time';
import type { PublicContact } from '../lib/types';
import { Avatar, Scanner } from '../components/ui';
import { useToast } from '../context/ToastContext';
import { useAuth } from '../context/AuthContext';
import { adminLinkFailure, adminLinkNotice, isEmailEntry, requestAdminLink } from '../lib/adminEntry';
type Step = 'splash' | 'scan' | 'confirm';
export function Login() {
const [step, setStep] = useState<Step>('splash');
const { authError } = useAuth();
const [step, setStep] = useState<Step>(authError ? 'scan' : 'splash');
const [qrToken, setQrToken] = useState('');
const [found, setFound] = useState<PublicContact | null>(null);
const [email, setEmail] = useState('');
const [staffPassword, setStaffPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [error, setError] = useState<string | null>(authError);
const [entry, setEntry] = useState('');
const [sent, setSent] = useState(false);
const [cooldown, setCooldown] = useState(0);
const requestPending = useRef(false);
const { toast } = useToast();
useEffect(() => {
if (!cooldown) return;
const timer = window.setTimeout(() => setCooldown((remaining) => remaining - 1), 1000);
return () => window.clearTimeout(timer);
}, [cooldown]);
// Staff log in with QR + their admin password; everyone else with QR + email.
const isStaff = found?.registration_type === 'staff';
async function handleScan(text: string) {
const token = text.trim();
if (!token) return;
if (!token || requestPending.current) return;
if (isEmailEntry(token)) {
if (cooldown) return;
requestPending.current = true;
setBusy(true);
setError(null);
setSent(false);
try {
await requestAdminLink(token);
setSent(true);
setCooldown(60);
} catch {
setError(adminLinkFailure);
} finally {
requestPending.current = false;
setBusy(false);
}
return;
}
if (token.includes('@')) {
setError('Enter a valid email address.');
return;
}
setQrToken(token);
setError(null);
try {
@@ -41,7 +76,7 @@ export function Login() {
// Attendees: QR + the ticket email (the QR token is the auth password).
const loginEmail = isStaff ? found?.email : email.trim();
const loginPassword = isStaff ? staffPassword : qrToken;
if (!loginEmail || !loginPassword) return;
if (!loginEmail || !loginPassword || busy) return;
setBusy(true);
setError(null);
try {
@@ -81,8 +116,18 @@ export function Login() {
return (
<section className="screen no-tab">
<div className="h1">Welcome back 👋</div>
<div className="muted small">Scan the QR code on your lanyard to log in.</div>
<Scanner onResult={handleScan} label="Point your camera at your lanyard QR" />
<Scanner
onResult={handleScan}
label="Point your camera at your lanyard QR"
entryLabel="QR code or admin email"
placeholder="QR code or admin email"
disabled={busy}
submitDisabled={isEmailEntry(entry) && cooldown > 0}
submitLabel={busy ? 'Sending...' : isEmailEntry(entry) ? cooldown ? `Resend in ${cooldown}s` : sent ? 'Resend magic link' : 'Send magic link' : 'Go'}
onEntryChange={(value) => { setEntry(value); setSent(false); setError(null); }}
/>
{sent && <p role="status">{adminLinkNotice}</p>}
{error && <p role="alert" data-testid="login-error">{error}</p>}
</section>
);
}
@@ -139,7 +184,7 @@ export function Login() {
</>
)}
</div>
{error && <div className="muted small" data-testid="login-error" style={{ color: 'var(--red)' }}>{error}</div>}
{error && <div role="alert" className="muted small" data-testid="login-error" style={{ color: 'var(--red)' }}>{error}</div>}
<button
className="btn primary"
data-testid="login-confirm"
+1 -1
View File
@@ -11,7 +11,7 @@ export default defineConfig({
host: true,
port: 3000,
proxy: {
'/auth': { target: SUPABASE_TARGET, changeOrigin: true },
'/auth/v1': { target: SUPABASE_TARGET, changeOrigin: true },
'/rest': { target: SUPABASE_TARGET, changeOrigin: true },
'/realtime': { target: SUPABASE_TARGET, changeOrigin: true, ws: true },
'/storage': { target: SUPABASE_TARGET, changeOrigin: true },
+29 -11
View File
@@ -1,4 +1,5 @@
const XLSX = require('xlsx');
const { createHash } = require('node:crypto');
function excelSerialToTime(serial, durationMin) {
const ms = Math.round((serial - 25569) * 86400 * 1000);
@@ -21,13 +22,17 @@ function firstNonempty(row, headers) {
function transformExcel(buffer) {
const workbook = XLSX.read(buffer, { type: 'buffer' });
const readRows = (sheetName) => sheetName
? XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' }).map((row) =>
Object.fromEntries(Object.entries(row).map(([header, value]) => [header.trim().toLowerCase(), value])))
: [];
const toRows = (kind, otherKind) => {
const sheetName = workbook.SheetNames.find((name) =>
const sheetNames = workbook.SheetNames.filter((name) =>
kind !== 'session' || !name.toLowerCase().includes('service'));
const sheetName = sheetNames.find((name) =>
name.toLowerCase().includes(kind) && !name.toLowerCase().includes(otherKind))
|| workbook.SheetNames.find((name) => name.toLowerCase().includes(kind));
if (!sheetName) return [];
return XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' }).map((row) =>
Object.fromEntries(Object.entries(row).map(([header, value]) => [header.trim().toLowerCase(), value])));
|| sheetNames.find((name) => name.toLowerCase().includes(kind));
return readRows(sheetName);
};
const speakerById = new Map();
@@ -50,21 +55,34 @@ function transformExcel(buffer) {
}
const sessionsById = new Map();
for (const row of toRows('session', 'speaker')) {
const id = firstNonempty(row, ['Session Id']);
const serviceSheet = workbook.SheetNames.find((name) => name.trim().toLowerCase() === 'service sessions');
const sessionRows = [
...toRows('session', 'speaker').map((row) => ({ row, serviceSheet: false })),
...readRows(serviceSheet).map((row) => ({ row, serviceSheet: true })),
];
for (const entry of sessionRows) {
const { row } = entry;
const title = firstNonempty(row, ['Title']);
const scheduledAt = Number(row['scheduled at']);
const duration = Number(row['scheduled duration']);
if (!id || !title || !scheduledAt) continue;
if (!title || !Number.isFinite(scheduledAt) || scheduledAt <= 0) continue;
const isServiceSession = entry.serviceSheet
|| /service|break|lunch|closing|plenum/i.test(firstNonempty(row, ['Session Format']));
const room = firstNonempty(row, ['Room']) || null;
const timing = excelSerialToTime(scheduledAt, Number.isFinite(duration) ? duration : 0);
const id = firstNonempty(row, ['Session Id']) || (isServiceSession
? `excel-service:${createHash('sha256').update(JSON.stringify([title, room, timing.date, timing.start_time])).digest('hex')}`
: '');
if (!id) continue;
const area = firstNonempty(row, ['Themenfeld / Area of Topic', 'Area', 'Topic']) || null;
if (!sessionsById.has(id)) {
sessionsById.set(id, {
external_id: id,
title,
description: firstNonempty(row, ['Description']) || null,
room: firstNonempty(row, ['Room']) || null,
...excelSerialToTime(scheduledAt, duration),
is_service_session: /service|break|lunch|closing|plenum/i.test(firstNonempty(row, ['Session Format'])),
room,
...timing,
is_service_session: isServiceSession,
level: firstNonempty(row, ['Level']) || null,
area,
speakers: [],
@@ -89,4 +89,54 @@ test('service session classification and unscheduled-row filtering remain unchan
assert.equal(payload.sessions.length, formats.length);
assert.deepEqual(payload.sessions.map((session) => session.is_service_session), [true, true, true, true, true, false]);
assert.ok(payload.sessions.every((session) => session.speakers.length === 0));
});
test('explicit service sheet imports ID-less services alongside flattened talks without duplicates', () => {
const service = { Title: 'Arrival & Coffee', Room: 'Main hall', 'Scheduled At': 46305.35416666667,
'Scheduled Duration': 30 };
const sheets = { 'Accepted sessions and speakers': [{ ...sessionRow, ...speakerRow }],
' Service Sessions ': [service, service, { ...service, Title: 'Lunch', 'Scheduled At': 46305.5 },
{ ...service, 'Session Id': 'service-existing', Title: 'Opening Keynote' }] };
const first = transformSheets(sheets);
assert.equal(first.sessions.length, 4);
assert.equal(first.speakers.length, 1);
assert.deepEqual(first.sessions[0].speakers, ['[email protected]']);
assert.equal(first.sessions[0].external_id, 'session-1');
const arrival = first.sessions[1];
assert.match(arrival.external_id, /^excel-service:[a-f0-9]{64}$/);
assert.equal(arrival.start_time, '08:30:00');
assert.equal(arrival.end_time, '09:00:00');
assert.equal(first.sessions[3].external_id, 'service-existing');
for (const session of first.sessions.slice(1)) {
assert.equal(session.is_service_session, true);
assert.deepEqual(session.speakers, []);
}
assert.deepEqual(transformSheets(sheets), first);
const reordered = transformSheets({ ...sheets, ' Service Sessions ': [...sheets[' Service Sessions ']].reverse() });
assert.deepEqual(reordered.sessions.map(session => session.external_id).sort(),
first.sessions.map(session => session.external_id).sort());
});
test('ID-less format-marked services import but missing IDs on talks and missing titles never do', () => {
const payload = transformSheets({ 'Accepted sessions': [
{ ...sessionRow, 'Session Id': '', Title: 'Coffee break', 'Session Format': 'Coffee break' },
{ ...sessionRow, 'Session Id': '', Title: 'Talk without ID' },
{ ...sessionRow, Title: '', 'Session Format': '' },
{ ...sessionRow, Title: '', 'Session Format': 'Service' },
{ ...sessionRow, Title: 'Invalid schedule', 'Scheduled At': 'not a date' },
] });
assert.equal(payload.sessions.length, 1);
assert.equal(payload.sessions[0].title, 'Coffee break');
assert.equal(payload.sessions[0].is_service_session, true);
});
test('service-only workbook uses title, room, date and start as identity, not duration or row order', () => {
const row = { Title: 'Break', Room: 'Hall A', 'Scheduled At': 46305.5, 'Scheduled Duration': 15 };
const first = transformSheets({ 'Service sessions': [row] });
const edited = transformSheets({ 'Service sessions': [{ ...row, 'Scheduled Duration': 30, Description: 'Updated' }] });
assert.equal(first.sessions[0].external_id, edited.sessions[0].external_id);
assert.equal(edited.sessions[0].end_time, '12:30:00');
const distinct = transformSheets({ 'Service sessions': [row, { ...row, Room: 'Hall B' },
{ ...row, 'Scheduled At': 46305.6 }, { ...row, 'Scheduled At': 46306.5 }, { ...row, Title: 'Lunch' }] });
assert.equal(new Set(distinct.sessions.map(session => session.external_id)).size, 5);
});