Files
Convivo/apps/admin/src/views/Contacts.tsx
T
d3083b7940 fix(points): welcome check-in awards +10; add Sessions view, AI connection test, silent reload
The front-desk check-in set checked_in and printed badges but awarded nothing,
so the +10 depended on which check-in a person happened to get. Every award
path was reviewed:

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

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

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

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

450 lines
16 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 { 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<string, string> = { both: 'Both shown', email: 'Email only', linkedin: 'LinkedIn only', none: 'None shown' };
const visKey = (c: Contact) => (c.show_email && c.show_linkedin ? 'both' : c.show_email ? 'email' : c.show_linkedin ? 'linkedin' : 'none');
const ynOptions = (rows: Contact[], fn: (c: Contact) => boolean): ColumnFilterOption[] => [
{ value: 'yes', label: 'Yes', count: rows.filter(fn).length },
{ value: 'no', label: 'No', count: rows.filter((c) => !fn(c)).length },
];
export function Contacts() {
const { push } = useToast();
const [contacts, setContacts] = useState<Contact[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [fLinkedin, setFLinkedin] = useState<string[]>([]);
const [fVis, setFVis] = useState<string[]>([]);
const [fAdmin, setFAdmin] = useState<string[]>([]);
const [editing, setEditing] = useState<Contact | null>(null);
const [creating, setCreating] = useState(false);
const [pointsFor, setPointsFor] = useState<Contact | null>(null);
const [deleting, setDeleting] = useState<string | null>(null);
async function load(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 <Empty/>`. The server sorts
// by name, so a fresh fetch cannot reorder rows under the cursor.
if (!silent) setError(e instanceof Error ? e.message : 'Failed to load');
}
}
async function remove(c: Contact) {
if (!confirm(`Delete ${c.full_name} (${c.email})? This also removes their registrations.`)) return;
setDeleting(c.email);
try {
await deleteContact(c.email);
await load();
push('success', `Deleted ${c.full_name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setDeleting(null);
}
}
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<string, number>();
for (const c of searched.filter((c) => passLinkedin(c) && passAdmin(c))) {
const k = visKey(c);
visCounts.set(k, (visCounts.get(k) ?? 0) + 1);
}
const visOptions = ['both', 'email', 'linkedin', 'none']
.filter((k) => visCounts.has(k))
.map((k) => ({ value: k, label: VIS_LABELS[k], count: visCounts.get(k)! }));
if (error) return <Empty icon="⚠️" text={error} />;
if (!contacts)
return (
<div className="loading-screen">
<Spinner />
</div>
);
return (
<div>
<div className="page-head">
<div>
<h1>Contacts</h1>
<div className="sub">{contacts.length} people · manage contacts and points.</div>
</div>
<div className="row" style={{ gap: 10 }}>
<input
className="input"
style={{ maxWidth: 260 }}
placeholder="Search first name, last name, email…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button className="btn primary" onClick={() => setCreating(true)}>
+ New contact
</button>
</div>
</div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Name</th>
<th>LinkedIn <ColumnFilter label="LinkedIn" options={linkedinOptions} selected={fLinkedin} onChange={setFLinkedin} /></th>
<th>Visibility <ColumnFilter label="Visibility" options={visOptions} selected={fVis} onChange={setFVis} /></th>
<th>Admin <ColumnFilter label="Admin" options={adminOptions} selected={fAdmin} onChange={setFAdmin} /></th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{filtered.map((c) => (
<tr key={c.email}>
<td>
<div className="cell-person">
<Avatar name={c.full_name} id={c.email} size={38} fs={13} />
<div>
<div className="n">{c.full_name}</div>
<div className="e">{c.email}</div>
</div>
</div>
</td>
<td>
{c.linkedin_url ? (
<a className="muted small" href={c.linkedin_url} target="_blank" rel="noreferrer">
linkedin
</a>
) : (
<span className="muted small">—</span>
)}
</td>
<td>
<div className="row" style={{ gap: 10 }}>
<span className="muted small" title="Show email">
{c.show_email ? '📧' : '🙈'}
</span>
<span className="muted small" title="Show LinkedIn">
{c.show_linkedin ? '💼' : '🙈'}
</span>
</div>
</td>
<td>
{c.is_admin ? <span className="pill admin">admin</span> : <span className="muted small">—</span>}
</td>
<td>
<div className="row-actions">
<button className="btn small" onClick={() => setEditing(c)}>
Edit
</button>
<button className="btn small" onClick={() => setPointsFor(c)}>
Points
</button>
<button
className="btn small danger"
disabled={deleting === c.email}
onClick={() => remove(c)}
>
{deleting === c.email ? 'Deleting…' : 'Delete'}
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{filtered.length === 0 && <div style={{ padding: 16 }}><Empty icon="🔍" text="No matches" /></div>}
</div>
{editing && (
<EditContactModal
contact={editing}
onClose={() => setEditing(null)}
onSaved={async (msg) => {
setEditing(null);
await load();
push('success', msg);
}}
/>
)}
{creating && (
<CreateContactModal
onClose={() => setCreating(false)}
onSaved={async (msg) => {
setCreating(false);
await load();
push('success', msg);
}}
/>
)}
{pointsFor && (
<AdjustPointsModal
contact={pointsFor}
onClose={() => setPointsFor(null)}
onSaved={async (msg) => {
setPointsFor(null);
push('success', msg);
}}
/>
)}
</div>
);
}
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 (
<Modal
open
title={`Edit — ${contact.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !name.trim()} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="field">
<label>Full name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="field">
<label>Email</label>
<input className="input" value={contact.email} disabled />
</div>
<div className="field">
<label>LinkedIn URL</label>
<input className="input" value={linkedin} onChange={(e) => setLinkedin(e.target.value)} placeholder="—" />
</div>
<div className="row" style={{ gap: 20, flexWrap: 'wrap' }}>
<Toggle checked={showEmail} onChange={setShowEmail} label="Show email" />
<Toggle checked={showLinkedin} onChange={setShowLinkedin} label="Show LinkedIn" />
<Toggle checked={isAdmin} onChange={setIsAdmin} label="Admin / staff" />
</div>
</Modal>
);
}
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 (
<Modal
open
title="New contact"
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !email.trim() || !name.trim()} onClick={save}>
{busy ? 'Creating…' : 'Create'}
</button>
</>
}
>
<div className="field">
<label>Full name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Ana Silva" />
</div>
<div className="field">
<label>Email</label>
<input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" />
</div>
<div className="field">
<label>LinkedIn URL</label>
<input className="input" value={linkedin} onChange={(e) => setLinkedin(e.target.value)} placeholder="—" />
</div>
<div className="row">
<Toggle checked={isAdmin} onChange={setIsAdmin} label="Admin / staff" />
</div>
<p className="muted small">A QR token is generated when the contact is registered for an event — it becomes the login password.</p>
</Modal>
);
}
function AdjustPointsModal({
contact,
onClose,
onSaved,
}: {
contact: Contact;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [delta, setDelta] = useState('10');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
// 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 (
<Modal
open
title={`Points — ${contact.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !canEarn} onClick={save} data-testid="adjust-points-apply"
title={canEarn ? undefined : 'This contact is excluded from points, so there is nothing to apply'}>
{busy ? 'Applying…' : 'Apply'}
</button>
</>
}
>
<div className="row" style={{ justifyContent: 'center', gap: 16 }}>
<Avatar name={contact.full_name} id={contact.email} size={52} fs={18} />
<div>
<div style={{ fontWeight: 700 }}>{contact.full_name}</div>
<div className="muted small">{contact.email}</div>
</div>
</div>
<div className="field">
<label>Adjustment for the active event (use a negative number to subtract)</label>
<input className="input mono" type="number" value={delta} onChange={(e) => setDelta(e.target.value)} />
{/* _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. */}
<span className="muted small">Goes to this person’s pass for the active event — with no pass there, nothing can be awarded.</span>
</div>
<div className="field">
<label>Reason (optional)</label>
<input className="input" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. prize, correction" />
</div>
{/* 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 && (
<p className="pts-exempt-note" data-testid="adjust-points-exempt">
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.
</p>
)}
</Modal>
);
}