feat(admin): full session material management in the session editor

See the attached file (clean name), Open (signed-URL preview), Download
(authenticated blob under the original filename), Delete (confirm, storage
object + path, errors surface), and Upload/Replace with previous-object
cleanup and upload rollback on DB failure. Admins already passed every
storage RLS gate for material writes, so no migration; this also documents
and smoke-verifies insert/read/update/delete as an impersonated admin.
Also fixes the stale e2e expectation that the speaker-portal download is an
<a href> (it became an authenticated blob button with the private bucket).
This commit is contained in:
Lago committed 2026-10-21 21:17:02 +02:00
1 parent 246be7d787
commit ca88c0e564
5 files changed
+129 -22

No files matched your search

+46 -6
View File
@@ -518,13 +518,34 @@ export async function setSessionSpeakers(sessionId: string, emails: string[]): P
} }
} }
/** Upload a session material file to the `materials` bucket and store the path. */ /** Human filename of a material object path (`sessions/<id>/<ts>-<name>`). */
export async function uploadSessionMaterial(sessionId: string, file: File): Promise<string> { export function sessionMaterialName(path: string): string {
const base = path.slice(path.lastIndexOf('/') + 1);
return base.replace(/^\d+-/, '');
}
/** Upload a session material file to the `materials` bucket and store the
* path. Admin passes the storage write gate (`can_write_session_material`
* allows `is_admin()`), so uploads on behalf of speakers work. When replacing
* an existing file, the old object is removed best-effort after the new one
* is in place; a failed DB update rolls the fresh upload back so the session
* never points at a nonexistent path. */
export async function uploadSessionMaterial(
sessionId: string,
file: File,
previousPath?: string | null,
): Promise<string> {
const path = `sessions/${sessionId}/${Date.now()}-${file.name}`; const path = `sessions/${sessionId}/${Date.now()}-${file.name}`;
const { error } = await supabase.storage.from('materials').upload(path, file, { upsert: true }); const { error } = await supabase.storage.from('materials').upload(path, file, { upsert: true });
if (error) throw new ApiError(error.message); if (error) throw new ApiError(error.message);
const { error: upErr } = await supabase.from('sessions').update({ material_path: path }).eq('id', sessionId); const { error: upErr } = await supabase.from('sessions').update({ material_path: path }).eq('id', sessionId);
if (upErr) throw new ApiError(upErr.message); if (upErr) {
await supabase.storage.from('materials').remove([path]);
throw new ApiError(upErr.message);
}
if (previousPath && previousPath !== path) {
await supabase.storage.from('materials').remove([previousPath]);
}
return path; return path;
} }
@@ -532,20 +553,39 @@ export async function removeSessionMaterial(sessionId: string): Promise<void> {
const { data } = await supabase.from('sessions').select('material_path').eq('id', sessionId).maybeSingle(); const { data } = await supabase.from('sessions').select('material_path').eq('id', sessionId).maybeSingle();
const path = (data as Session | null)?.material_path; const path = (data as Session | null)?.material_path;
if (path) { if (path) {
await supabase.storage.from('materials').remove([path]); // Surface storage failures instead of nulling the path and orphaning the file.
const { error: rmErr } = await supabase.storage.from('materials').remove([path]);
if (rmErr) throw new ApiError(rmErr.message);
} }
const { error } = await supabase.from('sessions').update({ material_path: null }).eq('id', sessionId); const { error } = await supabase.from('sessions').update({ material_path: null }).eq('id', sessionId);
if (error) throw new ApiError(error.message); if (error) throw new ApiError(error.message);
} }
/** Open a session material in a new tab via a short-lived signed URL. The /** Open a session material in a new tab via a short-lived signed URL (previews
* materials bucket is private; storage RLS always allows admins. */ * inline for browser-renderable types like PDF). The materials bucket is
* private; storage RLS always allows admins, bypassing the attendee time-lock. */
export async function openSessionMaterial(path: string): Promise<void> { export async function openSessionMaterial(path: string): Promise<void> {
const { data, error } = await supabase.storage.from('materials').createSignedUrl(path, 600); const { data, error } = await supabase.storage.from('materials').createSignedUrl(path, 600);
if (error) throw new ApiError(error.message); if (error) throw new ApiError(error.message);
window.open(data.signedUrl, '_blank'); window.open(data.signedUrl, '_blank');
} }
/** Save a session material to disk through authenticated storage download —
* same mechanism the attendee app uses after a session ends, always allowed
* for admins. Saves under the clean original filename. */
export async function downloadSessionMaterial(path: string): Promise<void> {
const { data, error } = await supabase.storage.from('materials').download(path);
if (error) throw new ApiError(error.message);
const url = URL.createObjectURL(data);
const a = document.createElement('a');
a.href = url;
a.download = sessionMaterialName(path);
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
async function feedbackSidecarFetch<T>(path: string, init?: RequestInit): Promise<T> { async function feedbackSidecarFetch<T>(path: string, init?: RequestInit): Promise<T> {
const { data, error } = await supabase.auth.getSession(); const { data, error } = await supabase.auth.getSession();
if (error || !data.session) throw new ApiError('Sign in as an administrator'); if (error || !data.session) throw new ApiError('Sign in as an administrator');
+59 -11
View File
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { supabase } from '../lib/supabase'; import { supabase } from '../lib/supabase';
import { import {
deleteEventSchedule, deleteEventSchedule,
downloadSessionMaterial,
getAllContacts, getAllContacts,
getAllSessionSpeakers, getAllSessionSpeakers,
getActiveEvent, getActiveEvent,
@@ -9,6 +10,7 @@ import {
getSlots, getSlots,
removeSessionMaterial, removeSessionMaterial,
openSessionMaterial, openSessionMaterial,
sessionMaterialName,
setSessionSpeakers, setSessionSpeakers,
uploadSessionMaterial, uploadSessionMaterial,
} from '../lib/api'; } from '../lib/api';
@@ -338,6 +340,7 @@ export function Schedule() {
<SessionModal <SessionModal
session={sessModal.session} session={sessModal.session}
slotId={sessModal.slotId} slotId={sessModal.slotId}
slot={slots.find((s) => s.id === sessModal.slotId)}
eventId={event.id} eventId={event.id}
contacts={contacts} contacts={contacts}
currentSpeakers={speakersFor.get(sessModal.session?.id ?? '') ?? []} currentSpeakers={speakersFor.get(sessModal.session?.id ?? '') ?? []}
@@ -442,6 +445,7 @@ function SlotModal({
function SessionModal({ function SessionModal({
session, session,
slotId, slotId,
slot,
eventId, eventId,
contacts, contacts,
currentSpeakers, currentSpeakers,
@@ -450,6 +454,8 @@ function SessionModal({
}: { }: {
session: Session | null; session: Session | null;
slotId: number; slotId: number;
/** Slot this session belongs to; used to show when material unlocks for attendees. */
slot?: Slot;
eventId: string; eventId: string;
contacts: Contact[]; contacts: Contact[];
currentSpeakers: string[]; currentSpeakers: string[];
@@ -464,6 +470,8 @@ function SessionModal({
const [area, setArea] = useState(session?.area ?? ''); const [area, setArea] = useState(session?.area ?? '');
const [speakerEmails, setSpeakerEmails] = useState<string[]>(currentSpeakers); const [speakerEmails, setSpeakerEmails] = useState<string[]>(currentSpeakers);
const [material, setMaterial] = useState<File | null>(null); const [material, setMaterial] = useState<File | null>(null);
const [matBusy, setMatBusy] = useState(false);
const [matError, setMatError] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
async function save() { async function save() {
@@ -493,9 +501,10 @@ function SessionModal({
if (sessionId && speakerEmails.length > 0) { if (sessionId && speakerEmails.length > 0) {
await setSessionSpeakers(sessionId, speakerEmails); await setSessionSpeakers(sessionId, speakerEmails);
} }
// Material upload (if a new file was chosen). // Material upload (if a new file was chosen). Passes the old path so a
// replacement removes the previous object instead of orphaning it.
if (sessionId && material) { if (sessionId && material) {
await uploadSessionMaterial(sessionId, material); await uploadSessionMaterial(sessionId, material, session?.material_path);
} }
onSaved(session ? 'Session updated' : 'Session created'); onSaved(session ? 'Session updated' : 'Session created');
} catch (e) { } catch (e) {
@@ -569,38 +578,65 @@ function SessionModal({
</div> </div>
{session && ( {session && (
<div className="field"> <div className="field" data-testid="session-material">
<label>Material</label> <label>Material</label>
{session.material_path ? ( {session.material_path ? (
<div className="row" style={{ gap: 10 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<div className="muted small">📎 {sessionMaterialName(session.material_path)}</div>
<div className="row" style={{ gap: 10, flexWrap: 'wrap' }}>
<button <button
className="btn small" className="btn small"
disabled={busy} disabled={busy || matBusy}
onClick={async () => { onClick={async () => {
setMatBusy(true);
setMatError(null);
try { try {
await openSessionMaterial(session.material_path!); await openSessionMaterial(session.material_path!);
} catch (e) { } catch (e) {
onSaved(e instanceof Error ? e.message : 'Could not open material'); setMatError(e instanceof Error ? e.message : 'Could not open material');
} finally {
setMatBusy(false);
} }
}} }}
> >
📎 View current Open
</button>
<button
className="btn small"
disabled={busy || matBusy}
onClick={async () => {
setMatBusy(true);
setMatError(null);
try {
await downloadSessionMaterial(session.material_path!);
} catch (e) {
setMatError(e instanceof Error ? e.message : 'Download failed');
} finally {
setMatBusy(false);
}
}}
>
⬇ Download
</button> </button>
<button <button
className="btn small danger" className="btn small danger"
disabled={busy} disabled={busy || matBusy}
onClick={async () => { onClick={async () => {
if (!confirm(`Delete material "${sessionMaterialName(session.material_path!)}"? Attendees and speakers lose access immediately.`)) return;
setMatBusy(true);
try { try {
await removeSessionMaterial(session.id); await removeSessionMaterial(session.id);
onSaved('Material removed'); onSaved('Material removed');
} catch (e) { } catch (e) {
onSaved(e instanceof Error ? e.message : 'Remove failed'); setMatBusy(false);
setMatError(e instanceof Error ? e.message : 'Delete failed');
} }
}} }}
> >
Remove Delete
</button> </button>
</div> </div>
</div>
) : ( ) : (
<span className="muted small">No material uploaded yet.</span> <span className="muted small">No material uploaded yet.</span>
)} )}
@@ -609,7 +645,19 @@ function SessionModal({
type="file" type="file"
onChange={(e) => setMaterial(e.target.files?.[0] ?? null)} onChange={(e) => setMaterial(e.target.files?.[0] ?? null)}
/> />
{material && <span className="muted small">Will upload: {material.name}</span>} {material && (
<span className="muted small">
{session.material_path ? 'Replaces current file on Save' : 'Uploads on Save'}: {material.name}
</span>
)}
{slot && (
<span className="muted small">
{session.material_path
? `Attendees can download it once the session ends (${fmtDate(slot.slot_date)}, ${fmtTime(slot.end_time)}).`
: `Once uploaded, attendees can download it when the session ends (${fmtDate(slot.slot_date)}, ${fmtTime(slot.end_time)}).`}
</span>
)}
{matError && <span className="feedback-error small">{matError}</span>}
</div> </div>
)} )}
+3 -1
View File
@@ -149,7 +149,9 @@ timezone('Europe/Amsterdam', now())`). Anything malformed or in another bucket
is denied by this policy (other buckets keep their own policies). is denied by this policy (other buckets keep their own policies).
Registered speakers can write only their own non-service session paths; admins Registered speakers can write only their own non-service session paths; admins
retain material management access. Any authenticated attendee can read (download). retain material management access (the admin session editor uses these same
policies for its open/download/delete/upload-on-behalf-of-speaker actions).
Any authenticated attendee can read (download).
Because the `sessions` table is admin-write only, a speaker attaches their Because the `sessions` table is admin-write only, a speaker attaches their
uploaded file via the `set_session_material` RPC (see uploaded file via the `set_session_material` RPC (see
[rpcs.md](./rpcs.md#set_session_materialp_session_id-p_material_path--sessions)). [rpcs.md](./rpcs.md#set_session_materialp_session_id-p_material_path--sessions)).
+18 -2
View File
@@ -284,8 +284,24 @@ event uses, but the `category` is `admin` so manual adjustments are auditable in
### Session material ### Session material
The Schedule view uploads a session's material to the `materials` bucket and sets The session editor in the Schedule view manages a session's material in the
`sessions.material_path` (admins can write `sessions` directly). private `materials` bucket — admins can act **on behalf of a speaker** at any
time (storage RLS lets `is_admin()` read, insert, update and delete, bypassing
the attendee time-lock):
- **See** — the current file is shown with its clean name (the
`sessions/<id>/<ts>-<name>` timestamp prefix stripped) plus a hint of when
attendees unlock it (slot date + end time).
- **Open** — short-lived signed URL (600 s) in a new tab; previews inline for
browser-renderable types (PDF).
- **Download** — authenticated storage download saved as a blob under the
clean filename.
- **Delete** — confirm dialog, then the storage object is removed (errors
surface rather than orphaning) and `material_path` is nulled.
- **Upload / replace** — file input; on Save the new object uploads
(`upsert`), `sessions.material_path` is updated (admins write `sessions`
directly), the previous object is deleted, and a failed DB update rolls the
fresh upload back. New sessions upload right after creation.
### Feedback AI Summaries ### Feedback AI Summaries
+3 -2
View File
@@ -88,14 +88,15 @@ test.describe('Speaker portal', () => {
await expect(page.getByText('Future talk', { exact: true })).toBeVisible(); await expect(page.getByText('Future talk', { exact: true })).toBeVisible();
await expect(page.getByTestId('checkin-required-gate')).toHaveCount(0); await expect(page.getByTestId('checkin-required-gate')).toHaveCount(0);
await article.getByLabel(`Upload material for ${title}`).setInputFiles({ name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('First slides') }); await article.getByLabel(`Upload material for ${title}`).setInputFiles({ name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('First slides') });
await expect(article.getByRole('link', { name: 'Download material' })).toBeVisible(); await expect(article.getByRole('button', { name: 'Download material' })).toBeVisible();
const firstPath = materialPath; const firstPath = materialPath;
await article.getByLabel(`Replace material for ${title}`).setInputFiles({ name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('Replacement slides') }); await article.getByLabel(`Replace material for ${title}`).setInputFiles({ name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('Replacement slides') });
await expect.poll(() => uploaded.length).toBe(2); await expect.poll(() => uploaded.length).toBe(2);
await expect(article.getByRole('button', { name: 'Remove material' })).toBeEnabled(); await expect(article.getByRole('button', { name: 'Remove material' })).toBeEnabled();
expect(materialPath).not.toBe(firstPath); expect(materialPath).not.toBe(firstPath);
expect(removed).toEqual([firstPath]); expect(removed).toEqual([firstPath]);
await expect(article.getByRole('link', { name: 'Download material' })).toHaveAttribute('href', new RegExp(`${materialPath}$`)); // Authenticated blob download (private bucket) — a button, no href anymore.
await expect(article.getByRole('button', { name: 'Download material' })).toBeEnabled();
await page.screenshot({ path: `/tmp/convivo-speaker-${width}-${title.split(' ')[0]}.png`, fullPage: true }); await page.screenshot({ path: `/tmp/convivo-speaker-${width}-${title.split(' ')[0]}.png`, fullPage: true });
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
page.once('dialog', (dialog) => dialog.accept()); page.once('dialog', (dialog) => dialog.accept());