Files
Convivo/apps/admin/src/views/Schedule.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

685 lines
23 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, useRef, useState } from 'react';
import { supabase } from '../lib/supabase';
import {
deleteEventSchedule,
getAllContacts,
getAllSessionSpeakers,
getActiveEvent,
getSessions,
getSlots,
removeSessionMaterial,
sessionMaterialUrl,
setSessionSpeakers,
uploadSessionMaterial,
} from '../lib/api';
import type { Contact, Event, Session, SessionSpeaker, Slot, SlotType } from '../lib/types';
import { useSilentRefresh } from '../lib/useSilentRefresh';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner, TypeBadge } from '../components/ui';
const SLOT_TYPES: SlotType[] = ['session', 'service_session'];
export function Schedule() {
const { push } = useToast();
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [slots, setSlots] = useState<Slot[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [speakers, setSpeakers] = useState<SessionSpeaker[]>([]);
const [contacts, setContacts] = useState<Contact[]>([]);
const [error, setError] = useState<string | null>(null);
const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null);
const [sessModal, setSessModal] = useState<{ session: Session | null; slotId: number } | null>(null);
const [deleteModal, setDeleteModal] = useState<{
eventId: string;
eventName: string;
slotsCount: number;
sessionsCount: number;
} | null>(null);
const [busy, setBusy] = useState(false);
const [deleting, setDeleting] = useState(false);
const mountedRef = useRef(false);
const loadSeqRef = useRef(0);
async function load(expectedEventId?: string, silent = false) {
const seq = ++loadSeqRef.current;
try {
const ev = await getActiveEvent();
if (!mountedRef.current || seq !== loadSeqRef.current) return;
if (expectedEventId && ev?.id !== expectedEventId) {
throw new Error('Active event changed before the schedule could refresh');
}
setEvent(ev);
if (ev) {
const [s, ss, sp, c] = await Promise.all([
getSlots(ev.id),
getSessions(ev.id),
getAllSessionSpeakers(),
getAllContacts(),
]);
if (!mountedRef.current || seq !== loadSeqRef.current) return;
setSlots(s);
setSessions(ss);
const ids = new Set(ss.map((x) => x.id));
setSpeakers(sp.filter((x) => ids.has(x.session_id)));
setContacts(c);
} else {
setSlots([]);
setSessions([]);
setSpeakers([]);
setContacts([]);
}
setLoaded(true);
} catch (e) {
if (!mountedRef.current || seq !== loadSeqRef.current) return;
// A failed background tick must not replace a good table with the error
// screen — this view renders `if (error) return <Empty/>` — so it stays quiet.
if (silent) return;
setError(e instanceof Error ? e.message : 'Failed to load');
throw e;
}
}
useEffect(() => {
mountedRef.current = true;
void load().catch(() => {});
return () => {
mountedRef.current = false;
loadSeqRef.current++;
};
}, []);
// Pull the schedule quietly in the background. Paused while a modal is open so
// the form is never re-rendered underneath whoever is typing in it. Writes here
// already `await load()`, so no refreshSoon is needed.
useSilentRefresh(() => load(event?.id, true), {
enabled: loaded && slotModal === null && sessModal === null && deleteModal === null,
});
const speakersFor = 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 nameOf = (email: string) => contacts.find((c) => c.email === email)?.full_name ?? email;
async function deleteSlot(slot: Slot) {
if (!confirm(`Delete "${slot.name}" and all its sessions?`)) return;
setBusy(true);
try {
const { error: err } = await supabase.from('slots').delete().eq('id', slot.id);
if (err) throw err;
await load();
push('success', `Deleted ${slot.name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setBusy(false);
}
}
async function deleteSession(sess: Session) {
if (!confirm(`Delete session "${sess.title}"?`)) return;
setBusy(true);
try {
const { error: err } = await supabase.from('sessions').delete().eq('id', sess.id);
if (err) throw err;
await load();
push('success', `Deleted ${sess.title}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setBusy(false);
}
}
async function deleteCurrentSchedule() {
const target = deleteModal;
if (!target || deleting) return;
setDeleting(true);
try {
const result = await deleteEventSchedule(target.eventId);
if (!mountedRef.current) return;
setDeleteModal(null);
try {
await load(target.eventId);
if (!mountedRef.current) return;
push(
'success',
`Deleted ${result.slots_deleted} slots and ${result.sessions_deleted} sessions from ${target.eventName}`,
);
} catch (refreshError) {
if (!mountedRef.current) return;
push(
'error',
`Schedule deleted for ${target.eventName}, but refresh failed: ${
refreshError instanceof Error ? refreshError.message : 'unknown error'
}`,
);
}
} catch (e) {
if (!mountedRef.current) return;
push('error', e instanceof Error ? e.message : 'Delete schedule failed');
} finally {
if (mountedRef.current) setDeleting(false);
}
}
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>Schedule</h1>
<div className="sub">Slots, sessions, speakers, and materials.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No active event. Set an event active in the Events view first." />
</div>
</div>
);
}
const hasSchedule = slots.length > 0 || sessions.length > 0;
const mutating = busy || deleting;
return (
<div>
<div className="page-head">
<div>
<h1>Schedule</h1>
<div className="sub">
{event.name} · {slots.length} slots · {sessions.length} sessions.
</div>
</div>
<div className="row-actions">
<button
className="btn danger"
disabled={mutating || !hasSchedule}
onClick={() =>
setDeleteModal({
eventId: event.id,
eventName: event.name,
slotsCount: slots.length,
sessionsCount: sessions.length,
})
}
>
Delete current schedule
</button>
<button className="btn primary" disabled={mutating} onClick={() => setSlotModal({ slot: null })}>
+ New slot
</button>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{slots.map((slot) => {
const slotSessions = sessions.filter((s) => s.slot_id === slot.id);
return (
<div key={slot.id} className="card">
<div className="row between" style={{ marginBottom: 12 }}>
<div className="row" style={{ gap: 12 }}>
<TypeBadge type={slot.type} />
<div>
<div style={{ fontWeight: 800, fontSize: 16 }}>{slot.name}</div>
<div className="muted small">
{fmtDate(slot.slot_date)} · {fmtTime(slot.start_time)}–{fmtTime(slot.end_time)}
</div>
</div>
</div>
<div className="row-actions">
<button className="btn small" disabled={mutating} onClick={() => setSessModal({ session: null, slotId: slot.id })}>
+ Session
</button>
<button className="btn small" disabled={mutating} onClick={() => setSlotModal({ slot })}>
Edit
</button>
<button className="btn small danger" disabled={mutating} onClick={() => deleteSlot(slot)}>
Delete
</button>
</div>
</div>
{slotSessions.length === 0 ? (
<div className="muted small" style={{ padding: '4px 0' }}>
No sessions in this slot.
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{slotSessions.map((s) => {
const spk = (speakersFor.get(s.id) ?? []).map(nameOf).join(', ');
return (
<div key={s.id} className="row between" style={{ padding: '10px 12px', background: 'var(--surface-2)', borderRadius: 12 }}>
<div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 700, fontSize: 14 }}>{s.title}</div>
<div className="muted small">
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null, s.level ? `📶 ${s.level}` : null, s.area ? `🗂 ${s.area}` : null].filter(Boolean).join(' · ')}
</div>
<div className="muted small" style={{ marginTop: 4 }}>
{s.average_feedback != null && <span>⭐ {s.average_feedback.toFixed(1)}</span>}
<span> · {s.material_path ? '📎 material submitted' : '⬜ material not submitted'}</span>
</div>
</div>
<div className="row-actions">
<button className="btn small" disabled={mutating} onClick={() => setSessModal({ session: s, slotId: slot.id })}>
Edit
</button>
<button className="btn small danger" disabled={mutating} onClick={() => deleteSession(s)}>
Delete
</button>
</div>
</div>
);
})}
</div>
)}
</div>
);
})}
</div>
{slotModal && (
<SlotModal
slot={slotModal.slot}
eventId={event.id}
onClose={() => setSlotModal(null)}
onSaved={async (msg) => {
setSlotModal(null);
await load();
push('success', msg);
}}
/>
)}
{deleteModal && (
<Modal
open
title="Delete current schedule"
onClose={() => {
if (!deleting) setDeleteModal(null);
}}
footer={
<>
<button className="btn" disabled={deleting} onClick={() => setDeleteModal(null)}>
Cancel
</button>
<button className="btn danger" disabled={deleting} onClick={deleteCurrentSchedule}>
{deleting ? 'Deleting…' : 'Delete schedule'}
</button>
</>
}
>
<p>
Delete the schedule for <strong>{deleteModal.eventName}</strong>?
</p>
<p className="muted">
This irreversibly deletes {deleteModal.slotsCount} slots and {deleteModal.sessionsCount} sessions, including speaker
links, preferences, check-ins and feedback. Registrations are preserved. Material file paths are removed with the
sessions, but Storage objects are not physically purged.
</p>
</Modal>
)}
{sessModal && (
<SessionModal
session={sessModal.session}
slotId={sessModal.slotId}
eventId={event.id}
contacts={contacts}
currentSpeakers={speakersFor.get(sessModal.session?.id ?? '') ?? []}
onClose={() => setSessModal(null)}
onSaved={async (msg) => {
setSessModal(null);
await load();
push('success', msg);
}}
/>
)}
</div>
);
}
function SlotModal({
slot,
eventId,
onClose,
onSaved,
}: {
slot: Slot | null;
eventId: string;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [name, setName] = useState(slot?.name ?? '');
const [type, setType] = useState<SlotType>(slot?.type ?? 'session');
const [date, setDate] = useState(slot ? slot.slot_date.slice(0, 10) : '');
const [start, setStart] = useState(slot ? slot.start_time.slice(0, 5) : '09:00');
const [end, setEnd] = useState(slot ? slot.end_time.slice(0, 5) : '10:00');
const [busy, setBusy] = useState(false);
async function save() {
if (!name.trim() || !date) return;
setBusy(true);
try {
const payload = { name: name.trim(), type, slot_date: date, start_time: start, end_time: end, event_id: eventId };
if (slot) {
const { error: err } = await supabase.from('slots').update(payload).eq('id', slot.id);
if (err) throw err;
} else {
const { error: err } = await supabase.from('slots').insert(payload);
if (err) throw err;
}
onSaved(slot ? 'Slot updated' : 'Slot created');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Save failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={slot ? 'Edit slot' : 'New slot'}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !name.trim() || !date} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="field">
<label>Name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Morning keynote" />
</div>
<div className="field">
<label>Type</label>
<select className="input" value={type} onChange={(e) => setType(e.target.value as SlotType)}>
{SLOT_TYPES.map((t) => (
<option key={t} value={t}>
{t.replace(/_/g, ' ')}
</option>
))}
</select>
</div>
<div className="field">
<label>Date</label>
<input className="input" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</div>
<div className="grid-2">
<div className="field">
<label>Start</label>
<input className="input" type="time" value={start} onChange={(e) => setStart(e.target.value)} />
</div>
<div className="field">
<label>End</label>
<input className="input" type="time" value={end} onChange={(e) => setEnd(e.target.value)} />
</div>
</div>
</Modal>
);
}
function SessionModal({
session,
slotId,
eventId,
contacts,
currentSpeakers,
onClose,
onSaved,
}: {
session: Session | null;
slotId: number;
eventId: string;
contacts: Contact[];
currentSpeakers: string[];
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [title, setTitle] = useState(session?.title ?? '');
const [room, setRoom] = useState(session?.room ?? '');
const [capacity, setCapacity] = useState(session?.capacity?.toString() ?? '');
const [description, setDescription] = useState(session?.description ?? '');
const [level, setLevel] = useState(session?.level ?? '');
const [area, setArea] = useState(session?.area ?? '');
const [speakerEmails, setSpeakerEmails] = useState<string[]>(currentSpeakers);
const [material, setMaterial] = useState<File | null>(null);
const [busy, setBusy] = useState(false);
async function save() {
if (!title.trim()) return;
setBusy(true);
try {
const payload = {
title: title.trim(),
room: room.trim() || null,
capacity: capacity ? parseInt(capacity, 10) : null,
description: description.trim() || null,
level: level.trim() || null,
area: area.trim() || null,
slot_id: slotId,
event_id: eventId,
};
let sessionId = session?.id;
if (session) {
const { error: err } = await supabase.from('sessions').update(payload).eq('id', session.id);
if (err) throw err;
} else {
const { data: ins, error: err } = await supabase.from('sessions').insert(payload).select().single();
if (err) throw err;
sessionId = (ins as Session).id;
}
// Speakers (a session must keep >= 1 speaker).
if (sessionId && speakerEmails.length > 0) {
await setSessionSpeakers(sessionId, speakerEmails);
}
// Material upload (if a new file was chosen).
if (sessionId && material) {
await uploadSessionMaterial(sessionId, material);
}
onSaved(session ? 'Session updated' : 'Session created');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Save failed');
} finally {
setBusy(false);
}
}
function toggleSpeaker(email: string) {
setSpeakerEmails((prev) =>
prev.includes(email) ? prev.filter((x) => x !== email) : [...prev, email],
);
}
return (
<Modal
open
title={session ? 'Edit session' : 'New session'}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !title.trim() || speakerEmails.length === 0} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="field">
<label>Title</label>
<input className="input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. The future of networking" />
</div>
<div className="grid-2">
<div className="field">
<label>Room</label>
<input className="input" value={room} onChange={(e) => setRoom(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Capacity</label>
<input className="input" type="number" value={capacity} onChange={(e) => setCapacity(e.target.value)} placeholder="—" />
</div>
</div>
<div className="field">
<label>Description</label>
<textarea className="input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="—" />
</div>
<div className="grid-2">
<div className="field">
<label>Level</label>
<input className="input" value={level} onChange={(e) => setLevel(e.target.value)} placeholder="e.g. 100 / Beginner" />
</div>
<div className="field">
<label>Area / Topic</label>
<input className="input" value={area} onChange={(e) => setArea(e.target.value)} placeholder="e.g. Power Apps" />
</div>
</div>
<div className="field">
<label>Speakers ({speakerEmails.length})</label>
<SpeakerMultiSelect
contacts={contacts}
selected={speakerEmails}
onToggle={toggleSpeaker}
/>
{speakerEmails.length === 0 && (
<span className="muted small">A session needs at least one speaker.</span>
)}
</div>
{session && (
<div className="field">
<label>Material</label>
{session.material_path ? (
<div className="row" style={{ gap: 10 }}>
<a className="btn small" href={sessionMaterialUrl(session.material_path)} target="_blank" rel="noreferrer">
📎 View current
</a>
<button
className="btn small danger"
disabled={busy}
onClick={async () => {
try {
await removeSessionMaterial(session.id);
onSaved('Material removed');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Remove failed');
}
}}
>
Remove
</button>
</div>
) : (
<span className="muted small">No material uploaded yet.</span>
)}
<input
className="input"
type="file"
onChange={(e) => setMaterial(e.target.files?.[0] ?? null)}
/>
{material && <span className="muted small">Will upload: {material.name}</span>}
</div>
)}
{session && session.ai_generated_feedback && (
<div className="field">
<label>AI feedback</label>
<div className="ai-box">{session.ai_generated_feedback}</div>
</div>
)}
</Modal>
);
}
/** Multi-select with a search box: type to filter, click to add/remove. */
function SpeakerMultiSelect({
contacts,
selected,
onToggle,
}: {
contacts: Contact[];
selected: string[];
onToggle: (email: string) => void;
}) {
const [query, setQuery] = useState('');
const nameOf = (email: string) => contacts.find((c) => c.email === email)?.full_name ?? email;
const q = query.trim().toLowerCase();
const matches = (q
? contacts.filter(
(c) => c.full_name.toLowerCase().includes(q) || c.email.toLowerCase().includes(q),
)
: contacts
).slice(0, 8);
return (
<div className="msel">
{selected.length > 0 && (
<div className="msel-chips">
{selected.map((email) => (
<span key={email} className="msel-chip">
{nameOf(email)}
<button className="msel-x" onClick={() => onToggle(email)} aria-label={`Remove ${nameOf(email)}`}>
✕
</button>
</span>
))}
</div>
)}
<input
className="input"
placeholder="Search speakers by name or email…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
{matches.length > 0 && (
<div className="msel-list">
{matches.map((c) => {
const on = selected.includes(c.email);
return (
<button
key={c.email}
className={`msel-item ${on ? 'on' : ''}`}
onClick={() => onToggle(c.email)}
>
<span className="msel-check">{on ? '✓' : ''}</span>
<span className="n">{c.full_name}</span>
<span className="e">{c.email}</span>
</button>
);
})}
</div>
)}
</div>
);
}
function fmtDate(d: string): string {
return new Date(d + 'T00:00:00').toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
}
function fmtTime(t: string): string {
return t.slice(0, 5);
}