Files
Convivo/apps/admin/src/views/Schedule.tsx
T
5f8ded56f6 feat: add sidecar service for Sessionize sync
- Introduced a new Node HTTP service (sidecar) to sync event agendas from Sessionize into Convivo.
- Implemented two import paths: API sync and Excel import for session and speaker data.
- Added necessary database migrations for sessionize integration, including new columns and audit tables.
- Created functions for handling speaker and session imports, ensuring proper error handling and logging.
- Established row-level security and grants for new functions to restrict access to service-role only.

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-08-24 20:47:29 +02:00

575 lines
19 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 { supabase } from '../lib/supabase';
import {
evaluateSessionFeedback,
getAllContacts,
getAllSessionSpeakers,
getActiveEvent,
getSessions,
getSlots,
removeSessionMaterial,
sessionMaterialUrl,
setSessionSpeakers,
uploadSessionMaterial,
} from '../lib/api';
import type { Contact, Event, Session, SessionSpeaker, Slot, SlotType } from '../lib/types';
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 [busy, setBusy] = useState(false);
async function load() {
try {
const ev = await getActiveEvent();
setEvent(ev);
if (ev) {
const [s, ss, sp, c] = await Promise.all([
getSlots(ev.id),
getSessions(ev.id),
getAllSessionSpeakers(),
getAllContacts(),
]);
setSlots(s);
setSessions(ss);
const ids = new Set(ss.map((x) => x.id));
setSpeakers(sp.filter((x) => ids.has(x.session_id)));
setContacts(c);
}
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
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 doEvaluate(sess: Session) {
setBusy(true);
try {
await evaluateSessionFeedback(sess.id);
await load();
push('success', `AI feedback evaluated for ${sess.title}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Evaluation failed');
} finally {
setBusy(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>
);
}
return (
<div>
<div className="page-head">
<div>
<h1>Schedule</h1>
<div className="sub">
{event.name} · {slots.length} slots · {sessions.length} sessions.
</div>
</div>
<button className="btn primary" onClick={() => setSlotModal({ slot: null })}>
+ New slot
</button>
</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" onClick={() => setSessModal({ session: null, slotId: slot.id })}>
+ Session
</button>
<button className="btn small" onClick={() => setSlotModal({ slot })}>
Edit
</button>
<button className="btn small danger" disabled={busy} 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].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>
{s.ai_generated_feedback && (
<span className="ai-state"> · 🤖 {s.ai_generated_feedback}</span>
)}
</div>
</div>
<div className="row-actions">
{s.ai_generated_feedback === 'Pending AI Evaluation' && (
<button className="btn small" disabled={busy} onClick={() => doEvaluate(s)}>
Evaluate
</button>
)}
<button className="btn small" onClick={() => setSessModal({ session: s, slotId: slot.id })}>
Edit
</button>
<button className="btn small danger" disabled={busy} 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);
}}
/>
)}
{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 [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,
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="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);
}