Files
Convivo/apps/admin/src/views/Sessions.tsx
T
Lago fdb6045966 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.
2026-10-19 20:14:03 +02:00

588 lines
24 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 { useCallback, Fragment, useEffect, useMemo, useRef, useState } from 'react';
import { Sparkles } from 'lucide-react';
import {
generateFeedbackSummary,
getAllContacts,
getAllEvents,
getActiveEvent,
getEventCheckins,
getEventSessionFeedback,
getEventSessionSpeakers,
getFeedbackSummaries,
getLlmSettings,
getSessions,
getSlots,
} from '../lib/api';
import type {
Checkin,
Contact,
Event,
Feedback,
FeedbackSummary,
Session,
SessionSpeaker,
Slot,
} from '../lib/types';
import { Avatar, Empty, Spinner, Tooltip } from '../components/ui';
import { useSilentRefresh } from '../lib/useSilentRefresh';
const timeLabel = (slot?: Slot) => (slot ? `${slot.start_time.slice(0, 5)}–${slot.end_time.slice(0, 5)}` : '');
const fmtTime = (iso: string) => new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const fmtDay = (iso: string) => new Date(iso).toLocaleDateString([], { day: '2-digit', month: 'short' });
/**
* Sessions: who is speaking in what, who actually walked in, and how it went.
*
* The rows are joined client-side (sessions ⨝ slots ⨝ session_speakers ⨝
* checkins ⨝ feedback) rather than through PostgREST embeds, because every one of
* those tables has its own RLS policy and the admin app reads them directly
* elsewhere; keeping one shape here means no policy change is needed and the
* numbers match the other views exactly.
*/
export function Sessions() {
const [events, setEvents] = useState<Event[]>([]);
const [selectedId, setSelectedId] = useState('');
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [slots, setSlots] = useState<Slot[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [speakers, setSpeakers] = useState<SessionSpeaker[]>([]);
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [summaries, setSummaries] = useState<FeedbackSummary[]>([]);
const [contacts, setContacts] = useState<Contact[]>([]);
const [llmConfigured, setLlmConfigured] = useState(false);
const [expanded, setExpanded] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [attendee, setAttendee] = useState('');
const [summaryError, setSummaryError] = useState<string | null>(null);
// Bulk AI summary run: null when idle, otherwise a blocking overlay with a
// counter. `cancelled` lets a reload mid-run stop the loop cleanly.
const [run, setRun] = useState<{ done: number; total: number } | null>(null);
const [runResult, setRunResult] = useState<{ ok: number; failed: string[] } | null>(null);
const runningRef = useRef(false);
const cancelRef = useRef(false);
const seqRef = useRef(0);
async function load(silent: boolean, expectedEventId?: string) {
const seq = ++seqRef.current;
try {
const [evs, active] = await Promise.all([getAllEvents(), getActiveEvent()]);
if (seq !== seqRef.current) return;
setEvents(evs);
// Explicit id = the user picked an event; otherwise the active one, and if
// nothing is active the newest event, so the view is never blank by accident.
const ev = expectedEventId ? evs.find((e) => e.id === expectedEventId) ?? null : active ?? evs[0] ?? null;
setEvent(ev);
if (expectedEventId) setSelectedId(expectedEventId);
else setSelectedId((cur) => cur || ev?.id || '');
if (!ev) {
setLoaded(true);
return;
}
const [sl, ss, sp, ck, fb, saved, settings, people] = await Promise.all([
getSlots(ev.id),
getSessions(ev.id),
getEventSessionSpeakers(ev.id),
getEventCheckins(ev.id),
getEventSessionFeedback(ev.id),
getFeedbackSummaries(ev.id),
getLlmSettings(),
getAllContacts(),
]);
if (seq !== seqRef.current) return;
setSlots(sl);
setSessions(ss);
setSpeakers(sp);
setCheckins(ck);
setFeedback(fb);
setSummaries(saved);
setContacts(people);
setLlmConfigured(Boolean(settings.endpoint && settings.model));
setLoaded(true);
} catch (cause) {
// A failed background tick must not replace a good table with the error
// screen — this view renders `if (error) return <Empty/>`.
if (!silent && seq === seqRef.current) {
setError(cause instanceof Error ? cause.message : 'Failed to load sessions');
}
}
}
useEffect(() => {
void load(false);
}, []);
// Live: session check-ins made on the scanner app appear without a reload.
// Paused during a bulk summary run so polling cannot race the writes.
useSilentRefresh(() => load(true, selectedId || undefined), { enabled: loaded && run === null });
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email.toLowerCase(), c.full_name]));
return (email: string) => m.get(email.toLowerCase()) ?? email;
}, [contacts]);
const slotById = useMemo(() => new Map(slots.map((s) => [s.id, s])), [slots]);
const speakersBySession = useMemo(() => {
const m = new Map<string, string[]>();
for (const sp of speakers) {
const arr = m.get(sp.session_id) ?? [];
arr.push(sp.contact_email);
m.set(sp.session_id, arr);
}
return m;
}, [speakers]);
const checkinsBySession = useMemo(() => {
const m = new Map<string, Checkin[]>();
for (const c of checkins) {
const arr = m.get(c.session_id) ?? [];
arr.push(c);
m.set(c.session_id, arr);
}
for (const arr of m.values()) arr.sort((a, b) => a.created_at.localeCompare(b.created_at));
return m;
}, [checkins]);
const feedbackBySession = useMemo(() => {
const m = new Map<string, { count: number; sum: number; avg: number }>();
for (const f of feedback) {
const e = m.get(f.session_id) ?? { count: 0, sum: 0, avg: 0 };
e.count += 1;
e.sum += f.rating;
e.avg = e.sum / e.count;
m.set(f.session_id, e);
}
return m;
}, [feedback]);
const summaryBySession = useMemo(
() => new Map(summaries.filter((s) => s.scope === 'session').map((s) => [s.target_id, s])),
[summaries],
);
/** Sessions with at least one feedback row — the only ones worth summarising. */
const summarisable = useMemo(
() => sessions.filter((s) => (feedbackBySession.get(s.id)?.count ?? 0) > 0),
[sessions, feedbackBySession],
);
/** Everyone with at least one check-in, for the attendee filter. */
const attendees = useMemo(() => {
const byEmail = new Map<string, { email: string; name: string; count: number }>();
for (const c of checkins) {
const key = c.contact_email.toLowerCase();
const cur = byEmail.get(key);
if (cur) cur.count += 1;
else byEmail.set(key, { email: c.contact_email, name: nameOf(c.contact_email), count: 1 });
}
return [...byEmail.values()].sort((a, b) => a.name.localeCompare(b.name));
}, [checkins, nameOf]);
const rows = useMemo(() => {
const wanted = attendee.toLowerCase();
const q = query.trim().toLowerCase();
return sessions
.filter((s) => {
if (wanted && !(checkinsBySession.get(s.id) ?? []).some((c) => c.contact_email.toLowerCase() === wanted)) {
return false;
}
if (!q) return true;
const sp = (speakersBySession.get(s.id) ?? []).join(' ');
return (
s.title.toLowerCase().includes(q) ||
(s.room ?? '').toLowerCase().includes(q) ||
(s.level ?? '').toLowerCase().includes(q) ||
(s.area ?? '').toLowerCase().includes(q) ||
sp.toLowerCase().includes(q)
);
})
.sort((a, b) => {
const sa = slotById.get(a.slot_id);
const sb = slotById.get(b.slot_id);
if (!sa || !sb) return a.title.localeCompare(b.title);
const d = `${sa.slot_date} ${sa.start_time}`.localeCompare(`${sb.slot_date} ${sb.start_time}`);
return d !== 0 ? d : a.title.localeCompare(b.title);
});
}, [sessions, attendee, query, checkinsBySession, speakersBySession, slotById]);
const pickedEmails = useMemo(() => {
if (!attendee) return new Set<string>();
return new Set(
checkins.filter((c) => c.contact_email.toLowerCase() === attendee.toLowerCase()).map((c) => c.contact_email),
);
}, [attendee, checkins]);
async function generateAll() {
if (runningRef.current || summarisable.length === 0) return;
runningRef.current = true;
cancelRef.current = false;
setRunResult(null);
setSummaryError(null);
// One request per session that has feedback. Concurrency is capped at 3: the
// gateway is a single vLLM worker, and firing N requests at once only makes
// each one slower. The UI stays blocked until every request has settled.
const queue = [...summarisable];
const total = queue.length;
const failed: string[] = [];
let done = 0;
const generated: FeedbackSummary[] = [];
setRun({ done: 0, total });
const worker = async () => {
for (;;) {
if (cancelRef.current) return;
const s = queue.shift();
if (!s) return;
try {
generated.push(await generateFeedbackSummary(selectedId, s.id));
} catch (cause) {
failed.push(`${s.title}: ${cause instanceof Error ? cause.message : 'failed'}`);
} finally {
done += 1;
setRun({ done, total });
}
}
};
try {
await Promise.all([worker(), worker(), worker()]);
if (generated.length) {
setSummaries((current) => {
const ids = new Set(generated.map((g) => g.target_id));
return [...current.filter((c) => c.scope !== 'session' || !ids.has(c.target_id)), ...generated];
});
}
setRunResult({ ok: generated.length, failed });
} finally {
runningRef.current = false;
setRun(null);
}
}
const toggleRow = useCallback((id: string) => setExpanded((cur) => (cur === id ? null : id)), []);
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
if (!event) {
return (
<div>
<div className="page-head">
<div>
<h1>Sessions</h1>
<div className="sub">Attendance, speakers, and AI feedback summaries.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No event selected. Create one in the Events view first." />
</div>
</div>
);
}
const attendedCount = attendee ? rows.length : 0;
const canGenerate = llmConfigured && summarisable.length > 0 && run === null;
return (
<div>
{/* Blocking overlay: the run is synchronous from the user's point of view,
so nothing behind it is reachable until every request has settled. */}
{run && (
<div className="backdrop" role="alertdialog" aria-busy="true" aria-label="Generating AI feedback summaries" data-testid="summary-overlay">
<div className="card summary-run-card">
<Spinner />
<h2 className="h2">Generating AI feedback summaries</h2>
<p className="muted" role="status" data-testid="summary-progress">
{run.done} of {run.total} sessions
</p>
<div className="summary-run-bar" aria-hidden="true">
<span style={{ width: `${run.total === 0 ? 0 : Math.round((run.done / run.total) * 100)}%` }} />
</div>
<p className="muted small">One request per session that has feedback. Keep this page open.</p>
<button className="btn small danger" onClick={() => { cancelRef.current = true; }}>
Stop
</button>
</div>
</div>
)}
<div className="page-head">
<div>
<h1>Sessions</h1>
<div className="sub">
<strong>{event.name}</strong> · {sessions.length} sessions · {checkins.length} check-ins ·{' '}
{feedback.length} feedback · {summarisable.length} with feedback
</div>
</div>
<div className="row" style={{ gap: 10, flexWrap: 'wrap' }}>
{events.length > 1 && (
<select
className="input"
style={{ maxWidth: 240 }}
value={selectedId}
disabled={run !== null}
onChange={(e) => {
setExpanded(null);
setAttendee('');
void load(false, e.target.value);
}}
>
{events.map((e) => (
<option key={e.id} value={e.id}>
{e.name}
</option>
))}
</select>
)}
<Tooltip
title={!llmConfigured ? 'LLM not configured' : summarisable.length === 0 ? 'No session feedback yet' : 'Generate AI summaries'}
content={
!llmConfigured
? 'Set the LLM endpoint and model in Settings first.'
: summarisable.length === 0
? 'Every AI summary needs at least one feedback response on a session.'
: `Sends ${summarisable.length} request${summarisable.length === 1 ? '' : 's'} — one per session that has feedback — and stores each result. The page stays blocked until all of them finish.`
}
>
<button
className="btn primary"
onClick={generateAll}
disabled={!canGenerate}
data-testid="generate-all-summaries"
>
<Sparkles size={16} aria-hidden="true" />
{run ? `Generating… ${run.done}/${run.total}` : 'Generate AI Feedback Summary'}
</button>
</Tooltip>
</div>
</div>
{!llmConfigured && (
<p className="muted small" data-testid="sessions-llm-unconfigured">
AI summaries are unavailable — set the LLM endpoint and model in Settings.
</p>
)}
{summaryError && <p className="feedback-error" role="alert">{summaryError}</p>}
{runResult && (
<p className={runResult.failed.length ? 'feedback-error' : 'muted small'} role="status" data-testid="summary-run-result">
{runResult.ok} session summar{runResult.ok === 1 ? 'y' : 'ies'} stored
{runResult.failed.length > 0 && ` · ${runResult.failed.length} failed: ${runResult.failed.join(' · ')}`}
</p>
)}
<div className="card sessions-toolbar" data-testid="sessions-toolbar">
<input
className="input"
type="search"
placeholder="Search title, room, level, area or speaker"
value={query}
onChange={(e) => setQuery(e.target.value)}
aria-label="Search sessions"
/>
<select
className="input"
value={attendee}
onChange={(e) => {
setAttendee(e.target.value);
setExpanded(null);
}}
aria-label="Filter by attendee"
data-testid="attendee-filter"
disabled={run !== null}
>
<option value="">All attendees — every session</option>
{attendees.map((a) => (
<option key={a.email} value={a.email}>
{a.name} ({a.count})
</option>
))}
</select>
{attendee && (
<span className="pill cyan" data-testid="attendee-summary">
{nameOf(attendee)} attended {attendedCount} session{attendedCount === 1 ? '' : 's'}
<button className="pill-x" onClick={() => setAttendee('')} aria-label="Clear attendee filter" disabled={run !== null}>
✕
</button>
</span>
)}
{(query || attendee) && (
<span className="muted small">
{rows.length} of {sessions.length}
</span>
)}
</div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>When</th>
<th>Session</th>
<th>Speakers</th>
<th style={{ textAlign: 'right' }}>Check-ins</th>
<th style={{ textAlign: 'right' }}>Feedback</th>
<th>AI summary</th>
</tr>
</thead>
<tbody>
{rows.map((s) => {
const slot = slotById.get(s.slot_id);
const att = checkinsBySession.get(s.id) ?? [];
const fb = feedbackBySession.get(s.id);
const sp = speakersBySession.get(s.id) ?? [];
const summary = summaryBySession.get(s.id);
const open = expanded === s.id;
const stale = summary && fb && summary.response_count !== fb.count;
return (
<Fragment key={s.id}>
<tr className={open ? 'row-open' : ''} onClick={() => toggleRow(s.id)} style={{ cursor: 'pointer' }}>
<td className="muted">
<div className="cell-when">
<span>{fmtDay(slot?.slot_date ?? s.created_at)}</span>
<strong>{timeLabel(slot)}</strong>
</div>
</td>
<td>
<div className="cell-session">
<span className="n">{s.title}</span>
<span className="e">
{s.room ?? 'no room'}
{s.level ? ` · ${s.level}` : ''}
{s.area ? ` · ${s.area}` : ''}
</span>
</div>
</td>
<td>
{sp.length === 0 ? (
<span className="muted small">—</span>
) : (
<div className="speaker-list">
{sp.slice(0, 3).map((e) => (
<span key={e} className="speaker-chip">
<Avatar name={nameOf(e)} id={e} size={22} fs={9} />
{nameOf(e)}
</span>
))}
{sp.length > 3 && <span className="muted small">+{sp.length - 3}</span>}
</div>
)}
</td>
<td style={{ textAlign: 'right' }}>
<span className={att.length > 0 ? 'att-count' : 'muted'}>{att.length}</span>
{s.capacity ? <span className="muted small"> / {s.capacity}</span> : null}
</td>
<td style={{ textAlign: 'right' }}>
{fb ? (
<span className="pill amber">
{fb.avg.toFixed(1)}★ · {fb.count}
</span>
) : (
<span className="muted small">—</span>
)}
</td>
<td>
{summary ? (
stale ? (
<Tooltip title="Outdated" content={`Stored from ${summary.response_count} responses; there are now ${fb?.count ?? 0}. Generate again to refresh.`}>
<span className="pill amber" data-testid={`summary-stale-${s.id}`}>stale</span>
</Tooltip>
) : (
<span className="pill green" data-testid={`summary-done-${s.id}`}>ready</span>
)
) : (
<span className="muted small">{fb ? 'not generated' : 'no feedback'}</span>
)}
</td>
</tr>
{open && (
<tr className="row-detail">
<td colSpan={6}>
<div className="session-detail">
{s.description && <p className="session-desc">{s.description}</p>}
<div className="detail-cols">
<section>
<h3 className="h3">Speakers ({sp.length})</h3>
{sp.length === 0 ? (
<p className="muted small">No speakers linked. Add them in Schedule.</p>
) : (
<ul className="detail-list">
{sp.map((e) => (
<li key={e}>
<Avatar name={nameOf(e)} id={e} size={26} fs={10} />
<span className="dl-name">{nameOf(e)}</span>
<span className="dl-email muted">{e}</span>
</li>
))}
</ul>
)}
</section>
<section>
<h3 className="h3">Checked in ({att.length})</h3>
{att.length === 0 ? (
<p className="muted small">Nobody has scanned into this session yet.</p>
) : (
<ul className="detail-list">
{att.map((c) => (
<li key={c.id} data-testid={`detail-checkin-${c.id}`}>
<Avatar name={nameOf(c.contact_email)} id={c.contact_email} size={26} fs={10} />
<span className="dl-name">
{pickedEmails.has(c.contact_email) ? (
<mark>{nameOf(c.contact_email)}</mark>
) : (
nameOf(c.contact_email)
)}
</span>
<span className="dl-email muted">{c.contact_email}</span>
<span className="dl-time muted">
{fmtDay(c.created_at)} {fmtTime(c.created_at)} · by {nameOf(c.staff_email)}
</span>
</li>
))}
</ul>
)}
</section>
<section>
<h3 className="h3">AI feedback summary</h3>
{summary ? (
<>
<div className="feedback-summary-text">{summary.summary}</div>
<p className="muted small">
AI-generated · {summary.response_count} responses · {summary.model} ·{' '}
{new Date(summary.generated_at).toLocaleString()}
</p>
</>
) : (
<p className="muted small">
{fb ? 'Not generated yet — use Generate AI Feedback Summary above.' : 'No feedback has been submitted for this session.'}
</p>
)}
</section>
</div>
</div>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</table>
{rows.length === 0 && (
<div style={{ padding: 16 }}>
<Empty icon="🗓️" text={attendee ? 'This attendee has no check-ins matching the search' : 'No sessions in this event'} />
</div>
)}
</div>
</div>
);
}