import { useEffect, useMemo, useState } from 'react'; import { adjustPoints, deleteContact, getAllContacts, updateContact, upsertContact } from '../lib/api'; import type { Contact } from '../lib/types'; import { useSilentRefresh } from '../lib/useSilentRefresh'; import { useToast } from '../context/ToastContext'; import { Avatar, ColumnFilter, Empty, Modal, Spinner, Toggle, type ColumnFilterOption } from '../components/ui'; // Multi-select column filters are Excel-style: an empty selection means "all". const VIS_LABELS: Record = { both: 'Both shown', email: 'Email only', linkedin: 'LinkedIn only', none: 'None shown' }; const visKey = (c: Contact) => (c.show_email && c.show_linkedin ? 'both' : c.show_email ? 'email' : c.show_linkedin ? 'linkedin' : 'none'); const ynOptions = (rows: Contact[], fn: (c: Contact) => boolean): ColumnFilterOption[] => [ { value: 'yes', label: 'Yes', count: rows.filter(fn).length }, { value: 'no', label: 'No', count: rows.filter((c) => !fn(c)).length }, ]; export function Contacts() { const { push } = useToast(); const [contacts, setContacts] = useState(null); const [error, setError] = useState(null); const [query, setQuery] = useState(''); const [fLinkedin, setFLinkedin] = useState([]); const [fVis, setFVis] = useState([]); const [fAdmin, setFAdmin] = useState([]); const [editing, setEditing] = useState(null); const [creating, setCreating] = useState(false); const [pointsFor, setPointsFor] = useState(null); const [deleting, setDeleting] = useState(null); async function load(silent = false) { try { setContacts(await getAllContacts()); } catch (e) { // A failed background tick must not replace a good table with the error // screen — this view renders `if (error) return `. The server sorts // by name, so a fresh fetch cannot reorder rows under the cursor. if (!silent) setError(e instanceof Error ? e.message : 'Failed to load'); } } async function remove(c: Contact) { if (!confirm(`Delete ${c.full_name} (${c.email})? This also removes their registrations.`)) return; setDeleting(c.email); try { await deleteContact(c.email); await load(); push('success', `Deleted ${c.full_name}`); } catch (e) { push('error', e instanceof Error ? e.message : 'Delete failed'); } finally { setDeleting(null); } } useEffect(() => { load(); }, []); // Background pull, paused while a modal is open so nothing re-renders under a // form. Writes here already `await load()`, so no refreshSoon is needed. useSilentRefresh(() => load(true), { enabled: contacts !== null && !editing && !creating && !pointsFor && !deleting, }); // General search: first name, last name or email address. const searched = useMemo(() => { if (!contacts) return []; const q = query.trim().toLowerCase(); if (!q) return contacts; return contacts.filter((c) => { const name = c.full_name.toLowerCase(); return name.split(/\s+/).some((part) => part.includes(q)) || name.includes(q) || c.email.toLowerCase().includes(q); }); }, [contacts, query]); const passLinkedin = (c: Contact) => fLinkedin.length === 0 || fLinkedin.includes(c.linkedin_url ? 'yes' : 'no'); const passVis = (c: Contact) => fVis.length === 0 || fVis.includes(visKey(c)); const passAdmin = (c: Contact) => fAdmin.length === 0 || fAdmin.includes(c.is_admin ? 'yes' : 'no'); const filtered = useMemo( () => searched.filter((c) => passLinkedin(c) && passVis(c) && passAdmin(c)), // eslint-disable-next-line react-hooks/exhaustive-deps [searched, fLinkedin, fVis, fAdmin], ); // Option counts follow Excel: each column counts what the OTHER filters leave. const linkedinOptions = ynOptions(searched.filter((c) => passVis(c) && passAdmin(c)), (c) => !!c.linkedin_url); const adminOptions = ynOptions(searched.filter((c) => passLinkedin(c) && passVis(c)), (c) => c.is_admin); const visCounts = new Map(); for (const c of searched.filter((c) => passLinkedin(c) && passAdmin(c))) { const k = visKey(c); visCounts.set(k, (visCounts.get(k) ?? 0) + 1); } const visOptions = ['both', 'email', 'linkedin', 'none'] .filter((k) => visCounts.has(k)) .map((k) => ({ value: k, label: VIS_LABELS[k], count: visCounts.get(k)! })); if (error) return ; if (!contacts) return (
); return (

Contacts

{contacts.length} people · manage contacts and points.
setQuery(e.target.value)} />
{filtered.map((c) => ( ))}
Name LinkedIn Visibility Admin Actions
{c.full_name}
{c.email}
{c.linkedin_url ? ( linkedin ) : ( — )}
{c.show_email ? '📧' : '🙈'} {c.show_linkedin ? '💼' : '🙈'}
{c.is_admin ? admin : —}
{filtered.length === 0 &&
}
{editing && ( setEditing(null)} onSaved={async (msg) => { setEditing(null); await load(); push('success', msg); }} /> )} {creating && ( setCreating(false)} onSaved={async (msg) => { setCreating(false); await load(); push('success', msg); }} /> )} {pointsFor && ( setPointsFor(null)} onSaved={async (msg) => { setPointsFor(null); push('success', msg); }} /> )}
); } function EditContactModal({ contact, onClose, onSaved, }: { contact: Contact; onClose: () => void; onSaved: (msg: string) => void; }) { const [name, setName] = useState(contact.full_name); const [linkedin, setLinkedin] = useState(contact.linkedin_url ?? ''); const [showEmail, setShowEmail] = useState(contact.show_email); const [showLinkedin, setShowLinkedin] = useState(contact.show_linkedin); const [isAdmin, setIsAdmin] = useState(contact.is_admin); const [busy, setBusy] = useState(false); async function save() { setBusy(true); try { await updateContact(contact.email, { full_name: name.trim(), linkedin_url: linkedin.trim() || null, show_email: showEmail, show_linkedin: showLinkedin, is_admin: isAdmin, }); onSaved(`Updated ${name.trim()}`); } catch (e) { onSaved(e instanceof Error ? e.message : 'Update failed'); } finally { setBusy(false); } } return ( } >
setName(e.target.value)} />
setLinkedin(e.target.value)} placeholder="—" />
); } function CreateContactModal({ onClose, onSaved, }: { onClose: () => void; onSaved: (msg: string) => void; }) { const [email, setEmail] = useState(''); const [name, setName] = useState(''); const [linkedin, setLinkedin] = useState(''); const [isAdmin, setIsAdmin] = useState(false); const [busy, setBusy] = useState(false); async function save() { if (!email.trim() || !name.trim()) return; setBusy(true); try { await upsertContact({ email: email.trim(), full_name: name.trim(), linkedin_url: linkedin.trim() || null, is_admin: isAdmin, }); onSaved(`Created ${name.trim()}`); } catch (e) { onSaved(e instanceof Error ? e.message : 'Create failed'); } finally { setBusy(false); } } return ( } >
setName(e.target.value)} placeholder="e.g. Ana Silva" />
setEmail(e.target.value)} placeholder="ana@example.com" />
setLinkedin(e.target.value)} placeholder="—" />

A QR token is generated when the contact is registered for an event — it becomes the login password.

); } function AdjustPointsModal({ contact, onClose, onSaved, }: { contact: Contact; onClose: () => void; onSaved: (msg: string) => void; }) { const [delta, setDelta] = useState('10'); const [reason, setReason] = useState(''); const [busy, setBusy] = useState(false); // Mirrors the contact-side half of the SQL predicate `_points_eligible` // (which additionally requires a non-staff registration in the active event). const canEarn = !contact.is_admin && !/@appe\.at$/i.test(contact.email); async function save() { const d = parseInt(delta, 10); if (Number.isNaN(d) || d === 0) return; setBusy(true); try { await adjustPoints(contact.email, d, reason.trim() || 'manual adjustment'); onSaved(`${d > 0 ? '+' : ''}${d} points for ${contact.full_name}`); onClose(); } catch (e) { onSaved(e instanceof Error ? e.message : 'Adjustment failed'); } finally { setBusy(false); } } return ( } >
{contact.full_name}
{contact.email}
setDelta(e.target.value)} /> {/* _points_eligible needs a registration row in the ACTIVE event; without one the award is a no-op, so the target of the adjustment is worth stating explicitly. */} Goes to this person’s pass for the active event — with no pass there, nothing can be awarded.
setReason(e.target.value)} placeholder="e.g. prize, correction" />
{/* adjust_points routes through _award_points, which no-ops for staff, admin contacts and @appe.at addresses — and returns void, so the call would "succeed" having changed nothing. Say so up front instead of letting the admin believe the score moved. */} {!canEarn && (

This person does not earn points (Admin/staff contact or an @appe.at address), so {delta.trim().startsWith('-') ? ' subtracting' : ' adding'} points changes nothing and they stay off the leaderboard. That is deliberate — change their type in Registrations if it is wrong.

)}
); }