Files
Convivo/apps/convivo/src/screens/SpeakerPortal.tsx
T
Lago d4e4637e7c feat(sessions): material downloads unlock when the session ends
Private materials bucket + RLS read gate (admins/own speakers anytime, all
attendees after the scheduled slot end, event-local Amsterdam time); always
visible uploaded-state, locked download panel, authenticated client downloads,
admin signed URLs. 12 new assertions in material_time_lock_tests.sql.
2026-10-21 18:57:15 +02:00

134 lines
7.0 KiB
TypeScript

import { useEffect, useState, type FormEvent } from 'react';
import type { Session } from '@supabase/supabase-js';
import { LoaderCircle, Paperclip } from 'lucide-react';
import { supabase } from '../lib/supabase';
import { getSpeakerPortalSessions, speakerPortalSession, type SpeakerSession } from '../lib/speakerPortal';
import { downloadSessionMaterial, removeSessionMaterial, uploadSessionMaterial } from '../lib/api';
const MAX_FILE_SIZE = 50 * 1024 * 1024;
const FILE_TYPES = '.pdf,.ppt,.pptx,.odp,.zip,.txt';
function messageOf(error: unknown) {
return error instanceof Error ? error.message : 'Something went wrong. Please try again.';
}
export function SpeakerPortal() {
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
const [email, setEmail] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [notice, setNotice] = useState('');
const [talks, setTalks] = useState<SpeakerSession[]>([]);
const [talksLoading, setTalksLoading] = useState(false);
const [talksError, setTalksError] = useState('');
const [reload, setReload] = useState(0);
const [workingTalk, setWorkingTalk] = useState<string | null>(null);
useEffect(() => {
let active = true;
setTalks([]);
setTalksError('');
if (!session) return;
setTalksLoading(true);
void getSpeakerPortalSessions().then((rows) => {
if (active) setTalks(rows);
}).catch((failure: unknown) => {
if (active) setTalksError(messageOf(failure));
}).finally(() => { if (active) setTalksLoading(false); });
return () => { active = false; };
}, [session?.user.id, reload]);
useEffect(() => {
let active = true;
void speakerPortalSession.then((result) => {
if (!active) return;
setSession(result.session);
setError(result.error?.message || '');
setLoading(false);
});
const { data } = supabase.auth.onAuthStateChange((_event, next) => {
if (active) setSession(next);
});
return () => { active = false; data.subscription.unsubscribe(); };
}, []);
async function sendLink(event: FormEvent) {
event.preventDefault();
setBusy(true);
setError('');
setNotice('');
try {
const { error: authError } = await supabase.auth.signInWithOtp({
email: email.trim().toLowerCase(),
options: { shouldCreateUser: false, emailRedirectTo: `${window.location.origin}/speaker/secret` },
});
if (authError) throw authError;
setNotice('Sign-in link requested. Check your email.');
} catch {
setError('Unable to send a sign-in link. Check your registered email or try again later.');
} finally { setBusy(false); }
}
async function logout() {
setBusy(true);
const { error: authError } = await supabase.auth.signOut({ scope: 'local' });
if (authError) setError(authError.message);
else { setSession(null); setNotice(''); }
setBusy(false);
}
async function changeMaterial(talk: SpeakerSession, file?: File) {
setError('');
setNotice('');
if (file && (!file.size || file.size > MAX_FILE_SIZE || !/\.(pdf|ppt|pptx|odp|zip|txt)$/i.test(file.name))) {
setError('Choose a non-empty PDF, PowerPoint, ODP, ZIP or TXT file, up to 50 MB.');
return;
}
if (!file && !window.confirm(`Remove materials for "${talk.title}"?`)) return;
setWorkingTalk(talk.session_id);
try {
if (file) await uploadSessionMaterial(talk.session_id, file);
else await removeSessionMaterial(talk.session_id);
setNotice(file ? 'Material saved.' : 'Material removed.');
} catch (failure) { setError(messageOf(failure)); }
finally { setWorkingTalk(null); setReload((value) => value + 1); }
}
return <div className="app speaker-app"><main className="screen no-tab speaker-portal" data-testid="speaker-portal">
<header className="row between"><h1 className="h1">Speaker Portal</h1>
{session && <button className="btn small ghost" onClick={() => void logout()} disabled={busy || !!workingTalk}>Sign out</button>}
</header>
{error && <p role="alert">{error}</p>}
{notice && <p role="status">{notice}</p>}
{loading ? <p role="status">Signing in...</p> : session ? <>
<p className="small muted">{session.user.email}</p>
<h2 className="h2">My Talk Materials</h2>
{talksLoading ? <p role="status">Loading talks...</p> : talksError ? <>
<p role="alert">{talksError}</p><button className="btn" onClick={() => setReload((value) => value + 1)}>Retry</button>
</> : !talks.length ? <p role="status">No assigned talks for your speaker or staff registrations.</p> : talks.map((talk) => <article className="speaker-talk" key={talk.session_id} data-testid={`speaker-talk-${talk.session_id}`}>
<p className="small muted">{talk.event_name} · {talk.is_active ? 'Active event' : 'Inactive event'}</p>
<h3 className="h2">{talk.title}</h3>
<p className="small">{talk.slot_date} · {talk.start_time.slice(0, 5)} - {talk.end_time.slice(0, 5)}{talk.room && ` · ${talk.room}`}</p>
{talk.material_path ? <button className="speaker-download" onClick={async () => { try { await downloadSessionMaterial(talk.material_path!); } catch (failure) { setError(messageOf(failure)); } }}>Download material</button> : <p className="small muted">No material uploaded</p>}
<label className="speaker-upload" htmlFor={`material-${talk.session_id}`}>
{workingTalk === talk.session_id ? <LoaderCircle aria-hidden="true" className="speaker-upload-spinner" /> : <Paperclip aria-hidden="true" />}
<span>{workingTalk === talk.session_id ? 'Saving material...' : talk.material_path ? 'Replace material' : 'Upload material'}</span>
<input className="input" id={`material-${talk.session_id}`} aria-label={`${talk.material_path ? 'Replace' : 'Upload'} material for ${talk.title}`} aria-describedby={`material-help-${talk.session_id}`} type="file" accept={FILE_TYPES} disabled={!!workingTalk || busy} onChange={(event) => {
const file = event.target.files?.[0];
event.target.value = '';
if (file) void changeMaterial(talk, file);
}} />
</label>
<p id={`material-help-${talk.session_id}`} className="small muted">PDF, PowerPoint, ODP, ZIP, TXT · Max 50 MB</p>
{workingTalk === talk.session_id && <><progress aria-label="Saving material" /><p role="status">Saving material...</p></>}
{talk.material_path && <button className="btn small danger" disabled={!!workingTalk || busy} onClick={() => void changeMaterial(talk)}>Remove material</button>}
</article>)}
</> : <form onSubmit={(event) => void sendLink(event)}>
<label htmlFor="speaker-email">Email</label>
<input className="input" id="speaker-email" type="email" autoComplete="email" required value={email} onChange={(event) => setEmail(event.target.value)} />
<button className="btn primary" type="submit" disabled={busy}>{busy ? 'Sending...' : 'Send sign-in link'}</button>
</form>}
</main></div>;
}