diff --git a/apps/admin/src/components/events/EventExtras.tsx b/apps/admin/src/components/events/EventExtras.tsx index b0028c1..cd3d0d4 100644 --- a/apps/admin/src/components/events/EventExtras.tsx +++ b/apps/admin/src/components/events/EventExtras.tsx @@ -3,6 +3,7 @@ * last time. Each panel saves by itself, so it is only shown once the event exists. */ import type { Event } from '../../types/event'; +import { EventHostsPanel } from './EventHostsPanel'; import { EventLastTimePanel } from './EventLastTimePanel'; import { EventPartnersPanel } from './EventPartnersPanel'; import { EventResourcesPanel } from './EventResourcesPanel'; @@ -14,6 +15,7 @@ export function EventExtras({ event }: { event: Event }) {

On the event's page

+ diff --git a/apps/admin/src/components/events/EventHostsPanel.tsx b/apps/admin/src/components/events/EventHostsPanel.tsx new file mode 100644 index 0000000..18f17fc --- /dev/null +++ b/apps/admin/src/components/events/EventHostsPanel.tsx @@ -0,0 +1,401 @@ +/** "Speakers and hosts" for an event, held locally until the exec saves. */ +import { ArrowDown, ArrowUp, X } from 'lucide-react'; +import { useState } from 'react'; +import { Link } from 'react-router'; +import { type Choices, choicesFrom } from '../../hooks/choices'; +import { useCompanies } from '../../hooks/useCompanies'; +import { useEventHosts, useSaveHosts } from '../../hooks/useEventHosts'; +import { useGuests } from '../../hooks/useGuests'; +import { useTeam } from '../../hooks/useTeam'; +import { PATHS } from '../../paths'; +import type { Company } from '../../types/company'; +import type { Guest } from '../../types/guest'; +import type { HostCard, HostFields } from '../../types/event-host'; +import type { TeamMember } from '../../types/team'; +import { CompanyMark } from '../guests/CompanyMark'; +import { FIELD_INPUT } from '../ui/field-styles'; +import { SearchField } from '../ui/SearchField'; +import { Tag } from '../ui/Tag'; +import { ExtraPanel } from './ExtraPanel'; +import { PanelSaveBar } from './PanelSaveBar'; + +const ACTION_BUTTON = + 'grid size-10 place-items-center rounded-full transition-colors hover:bg-slate disabled:opacity-40'; + +/** Loads an event's hosts and the people who can be added to it. */ +export function EventHostsPanel({ eventId }: { eventId: string }) { + const hosts = useEventHosts(eventId); + const save = useSaveHosts(eventId); + const guests = choicesFrom(useGuests()); + const team = choicesFrom(useTeam()); + const companies = choicesFrom(useCompanies()); + + return ( + + {(saved) => ( + + )} + + ); +} + +type HostsEditorProps = { + saved: readonly HostCard[]; + save: ReturnType; + guests: Choices; + team: Choices; + companies: Choices; +}; + +function HostsEditor({ + saved, + save, + guests, + team, + companies, +}: HostsEditorProps) { + const [rows, setRows] = useState(saved); + const [changed, setChanged] = useState(false); + const [query, setQuery] = useState(''); + const companyById = new Map( + (typeof companies === 'string' ? [] : companies).map((company) => [ + company.id, + company, + ]), + ); + + function change(next: readonly HostCard[]) { + setRows(next); + setChanged(true); + } + function move(index: number, by: -1 | 1) { + const next = [...rows]; + const [row] = next.splice(index, 1); + if (row) next.splice(index + by, 0, row); + change(next); + } + function addGuest(guest: Guest) { + change([ + ...rows, + guestHostCard(guest, companyById.get(guest.companyId ?? ''), rows.length), + ]); + setQuery(''); + } + function addTeamMember(member: TeamMember) { + change([...rows, teamHostCard(member, rows.length)]); + setQuery(''); + } + + return ( + <> + change(rows.filter((row) => row.id !== id))} + /> + + + save.mutate(rows.map(toHostFields), { + onSuccess: () => setChanged(false), + }) + } + /> + + ); +} + +function HostList({ + rows, + onMove, + onRemove, +}: { + rows: readonly HostCard[]; + onMove: (index: number, by: -1 | 1) => void; + onRemove: (id: string) => void; +}) { + if (rows.length === 0) + return ( +

+ No speakers or hosts yet. Add guests here, or from their guest page. +

+ ); + return ( +
    + {rows.map((host, index) => ( + onRemove(host.id)} + /> + ))} +
+ ); +} + +function HostPicker({ + query, + guests, + team, + rows, + onQueryChange, + onPickGuest, + onPickTeam, +}: { + query: string; + guests: Choices; + team: Choices; + rows: readonly HostCard[]; + onQueryChange: (query: string) => void; + onPickGuest: (guest: Guest) => void; + onPickTeam: (member: TeamMember) => void; +}) { + const added = new Set(rows.map((row) => `${row.kind}:${row.personId}`)); + return ( +
+ + + +

+ + Add a new guest + +

+
+ ); +} + +function PickerGroup({ + title, + query, + choices, + onPick, +}: { + title: string; + query: string; + choices: Choices; + onPick: (person: T) => void; +}) { + const message = pickerMessage(title, query, choices); + const people = typeof choices === 'string' ? null : choices; + return ( +
+

{title}

+ {message ? ( +

{message}

+ ) : ( +
    + {people?.map((person) => ( +
  • + +
  • + ))} +
+ )} +
+ ); +} + +function HostRow({ + host, + index, + total, + onMove, + onRemove, +}: { + host: HostCard; + index: number; + total: number; + onMove: (index: number, by: -1 | 1) => void; + onRemove: () => void; +}) { + return ( +
  • + +
    +

    {host.name}

    + {host.subtitle && ( +

    {host.subtitle}

    + )} + {host.kind === 'team' && ( +

    + Not shown on the site yet + {!host.isPublic && '; hidden from the site'}. +

    + )} +
    + {host.kind === 'guest' && } + {host.kind === 'team' ? 'Team' : 'Guest'} +
    + + + +
    +
  • + ); +} + +/** Their photo, or one initial so a missing photo does not leave a blank gap. */ +function HostFace({ host }: { host: HostCard }) { + return host.pictureUrl ? ( + + ) : ( + + ); +} + +/** Removes saved people from a searched list, without presenting a full directory first. */ +function choicesToAdd( + choices: Choices, + kind: 'guest' | 'team', + added: ReadonlySet, + query: string, +): Choices { + if (typeof choices === 'string' || !query.trim()) return choices; + const term = query.trim().toLocaleLowerCase(); + return choices.filter( + (person) => + !added.has(`${kind}:${person.id}`) && + person.name.toLocaleLowerCase().includes(term), + ); +} + +/** Explains the current picker state. */ +function pickerMessage( + title: string, + query: string, + choices: Choices, +): string | null { + if (!query.trim()) return 'Start typing to search.'; + if (choices === 'loading') return `Loading ${title.toLocaleLowerCase()}…`; + if (choices === 'failed') return `${title} couldn't be loaded.`; + return choices.length === 0 ? `No ${title.toLocaleLowerCase()} found.` : null; +} + +/** Builds a draft guest row with the company details it will have after the joined read reloads. */ +function guestHostCard( + guest: Guest, + company: Company | undefined, + sortOrder: number, +): HostCard { + return { + id: crypto.randomUUID(), + eventId: '', + sortOrder, + kind: 'guest', + personId: guest.id, + name: guest.name, + subtitle: guest.title, + pictureUrl: guest.pictureUrl, + company: company + ? { name: company.name, colour: company.colour, logoUrl: company.logoUrl } + : null, + isPublic: true, + }; +} + +/** Builds a draft team row. Team members are recorded for now, not rendered on the site. */ +function teamHostCard(member: TeamMember, sortOrder: number): HostCard { + return { + id: crypto.randomUUID(), + eventId: '', + sortOrder, + kind: 'team', + personId: member.id, + name: member.name, + subtitle: member.role, + pictureUrl: member.pictureUrl, + company: null, + isPublic: member.isPublic, + }; +} + +/** Turns display rows back into the small list the save function stores. */ +function toHostFields(host: HostCard): HostFields { + return host.kind === 'team' + ? { kind: 'team', teamId: host.personId } + : { kind: 'guest', guestId: host.personId }; +} diff --git a/apps/admin/src/components/guests/CompanyMark.tsx b/apps/admin/src/components/guests/CompanyMark.tsx index 219e986..70aeb0b 100644 --- a/apps/admin/src/components/guests/CompanyMark.tsx +++ b/apps/admin/src/components/guests/CompanyMark.tsx @@ -4,7 +4,10 @@ */ import type { CompanyBadge } from '../../types/company'; -export function CompanyMark({ company }: { company: CompanyBadge | null }) { +/** The company fields this small mark needs, whether it comes from the guest book or another list. */ +type MarkCompany = Pick; + +export function CompanyMark({ company }: { company: MarkCompany | null }) { if (!company) return No company; return ( diff --git a/apps/admin/src/hooks/useEventHosts.ts b/apps/admin/src/hooks/useEventHosts.ts index 6ccab58..ff389b9 100644 --- a/apps/admin/src/hooks/useEventHosts.ts +++ b/apps/admin/src/hooks/useEventHosts.ts @@ -1,56 +1,25 @@ -/** Event hosts loaded and cached by TanStack Query, and the changes that refresh them. */ +/** Event hosts loaded and saved as an ordered list. */ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { addGuestHost, addTeamHost, deleteHost, getHost, listHosts, reorderHosts, updateHost } from '../lib/data/event-hosts'; -import type { EventHost, HostFields } from '../types/event-host'; +import { listHosts, saveHosts } from '../lib/data/event-hosts'; +import type { HostFields } from '../types/event-host'; +import { GUESTS_KEY } from './useGuests'; -// Every hosts query for an event starts with this key. const makeHostsKey = (eventId: string) => ['hosts', eventId] as const; +/** Loads display-ready hosts for one event. */ export function useEventHosts(eventId: string) { return useQuery({ queryKey: makeHostsKey(eventId), queryFn: () => listHosts(eventId) }); } -/** One host for editing; `data` is null when there is no such host. */ -export function useEventHost(id: string) { - return useQuery({ queryKey: ['host', id], queryFn: () => getHost(id) }); -} - -/** Refreshes hosts for an event once a change has been saved. */ -function useRefreshHosts(eventId: string) { +/** Saves hosts and refreshes guest event links, which power both the guest page and photo tagging. */ +export function useSaveHosts(eventId: string) { const queryClient = useQueryClient(); - return () => queryClient.invalidateQueries({ queryKey: makeHostsKey(eventId) }); -} - -export function useAddTeamHost(eventId: string) { - const refresh = useRefreshHosts(eventId); - return useMutation({ - mutationFn: (teamId: string) => addTeamHost(eventId, teamId), - onSuccess: refresh, - }); -} - -export function useAddGuestHost(eventId: string) { - const refresh = useRefreshHosts(eventId); return useMutation({ - mutationFn: (guestId: string) => addGuestHost(eventId, guestId), - onSuccess: refresh, + mutationFn: (people: readonly HostFields[]) => saveHosts(eventId, people), + onSuccess: () => + Promise.all([ + queryClient.invalidateQueries({ queryKey: makeHostsKey(eventId) }), + queryClient.invalidateQueries({ queryKey: GUESTS_KEY }), + ]), }); } - -export function useUpdateHost(host: EventHost) { - const refresh = useRefreshHosts(host.eventId); - return useMutation({ - mutationFn: (fields: HostFields) => updateHost(host, fields), - onSuccess: refresh, - }); -} - -export function useDeleteHost(host: EventHost) { - const refresh = useRefreshHosts(host.eventId); - return useMutation({ mutationFn: () => deleteHost(host), onSuccess: refresh }); -} - -export function useReorderHosts(eventId: string) { - const refresh = useRefreshHosts(eventId); - return useMutation({ mutationFn: (hosts: readonly EventHost[]) => reorderHosts(hosts), onSuccess: refresh }); -} diff --git a/apps/admin/src/lib/data/event-hosts.ts b/apps/admin/src/lib/data/event-hosts.ts index cd13eed..10e203d 100644 --- a/apps/admin/src/lib/data/event-hosts.ts +++ b/apps/admin/src/lib/data/event-hosts.ts @@ -1,188 +1,160 @@ -/** - * Reading, adding, changing, and deleting event hosts in Supabase v2. Rows are checked and turned into - * `EventHost`s here, once, so pages get typed data. Each host is either a team member or a guest, never both. - */ +/** Reading and saving event hosts in Supabase v2. */ import { z } from 'zod'; import type { Database } from '../../types/database.types'; -import { type EventHost, type HostFields, EventHostSchema, type SpeakerLink } from '../../types/event-host'; +import { type HostCard, HostCardSchema, type HostFields, type SpeakerLink } from '../../types/event-host'; import { UnavailableError } from '../server/errors'; +import { BUCKETS, publicUrl } from '../server/storage'; import { getSupabase } from '../server/supabase'; -type HostRow = Database['v2']['Tables']['event_hosts']['Row']; type HostInsert = Database['v2']['Tables']['event_hosts']['Insert']; -type HostUpdate = Database['v2']['Tables']['event_hosts']['Update']; -const COLUMNS = 'id, event_id, team_id, guest_id, sort_order'; +const HOST_COLUMNS = ` + id, event_id, team_id, guest_id, sort_order, + team(id, name, role, picture_path, is_public), + guests(id, name, title, picture_path, companies(name, colour, logo_path)) +`; + +const HostRowSchema = z.object({ + id: z.uuid(), + event_id: z.uuid(), + team_id: z.uuid().nullable(), + guest_id: z.uuid().nullable(), + sort_order: z.number().int().nonnegative(), + team: z + .object({ id: z.uuid(), name: z.string(), role: z.string().nullable(), picture_path: z.string().nullable(), is_public: z.boolean() }) + .nullable(), + guests: z + .object({ + id: z.uuid(), + name: z.string(), + title: z.string().nullable(), + picture_path: z.string().nullable(), + companies: z.object({ name: z.string(), colour: z.string(), logo_path: z.string().nullable() }).nullable(), + }) + .nullable(), +}); +const SpeakerLinkRowSchema = z.object({ event_id: z.uuid(), guest_id: z.uuid() }); const v2 = () => getSupabase().schema('v2'); -/** - * All hosts for an event, in sort order. Empty when there are none. A row that doesn't fit `EventHost` is left out - * and logged, so one bad row can't hide every other host. - * @throws UnavailableError when Supabase cannot be reached or refuses the read. - */ -export async function listHosts(eventId: string): Promise { +/** Lists display-ready hosts for an event, in their saved order. */ +export async function listHosts(eventId: string): Promise { if (!z.uuid().safeParse(eventId).success) return []; - const { data, error } = await v2().from('event_hosts').select(COLUMNS).eq('event_id', eventId).order('sort_order') as any; + + const { data, error } = await v2().from('event_hosts').select(HOST_COLUMNS).eq('event_id', eventId).order('sort_order'); if (error) throw new UnavailableError('Hosts could not be loaded.', { cause: error }); - return data.flatMap((row: any) => toEventHost(row) ?? []); -} -/** - * One host by id, or null when there is no such host (including an id that isn't a valid id at all). - * @throws UnavailableError when Supabase cannot be reached, or the saved host has data the admin can't read. - */ -export async function getHost(id: string): Promise { - if (!z.uuid().safeParse(id).success) return null; - const { data, error } = await v2().from('event_hosts').select(COLUMNS).eq('id', id).maybeSingle() as any; - if (error) throw new UnavailableError('This host could not be loaded.', { cause: error }); - if (!data) return null; - const host = toEventHost(data); - if (!host) throw new UnavailableError("This host has saved data the admin can't read. It needs fixing in Supabase."); - return host; + return data.flatMap(toHostCard); } /** - * Adds a host (team member or guest) to an event. - * @throws UnavailableError when the row could not be saved. + * Saves the complete ordered host list. Removing absent people first makes a replacement safe when it would + * otherwise temporarily violate either unique `(event_id, person_id)` constraint. */ -export async function addHost(eventId: string, fields: HostFields): Promise { +export async function saveHosts(eventId: string, people: readonly HostFields[]): Promise { if (!z.uuid().safeParse(eventId).success) throw new UnavailableError('Invalid event id.'); - const insert: HostInsert = { - event_id: eventId, - team_id: fields.kind === 'team' ? fields.teamId : null, - guest_id: fields.kind === 'guest' ? fields.guestId : null, - sort_order: 0, // Will be adjusted if needed - }; - - const { data, error } = await v2() - .from('event_hosts') - .select(COLUMNS) - .eq('event_id', eventId) - .order('sort_order', { ascending: false }) - .limit(1) as any; - if (error) throw new UnavailableError("The host couldn't be added.", { cause: error }); - - const nextSortOrder = data.length > 0 ? (data[0]?.sort_order ?? -1) + 1 : 0; - insert.sort_order = nextSortOrder; - - const { error: insertError } = await v2().from('event_hosts').insert(insert); - if (insertError) throw new UnavailableError("The host couldn't be added.", { cause: insertError }); -} - -/** - * Adds a team member as a host to an event. - * @throws UnavailableError when the row could not be saved. - */ -export async function addTeamHost(eventId: string, teamId: string): Promise { - return addHost(eventId, { kind: 'team', teamId }); -} - -/** - * Adds a guest as a host to an event. - * @throws UnavailableError when the row could not be saved. - */ -export async function addGuestHost(eventId: string, guestId: string): Promise { - return addHost(eventId, { kind: 'guest', guestId }); -} + const failure = "The event's hosts couldn't be saved."; + const { data: current, error: readError } = await v2().from('event_hosts').select('team_id, guest_id').eq('event_id', eventId); + if (readError) throw new UnavailableError(failure, { cause: readError }); -/** - * Updates a host (changing which team member or guest it refers to). - * @throws UnavailableError when it could not be saved (Supabase down, the host is gone, or the update was refused). - */ -export async function updateHost(host: EventHost, fields: HostFields): Promise { - const update: HostUpdate = { - team_id: fields.kind === 'team' ? fields.teamId : null, - guest_id: fields.kind === 'guest' ? fields.guestId : null, - }; - - const { data, error } = await v2().from('event_hosts').update(update).eq('id', host.id).select('id'); - if (error || data.length === 0) throw new UnavailableError("Your changes couldn't be saved.", { cause: error }); -} + const wanted = new Set(people.map(hostKey)); + for (const row of current) { + const currentHost = row.team_id ? { kind: 'team' as const, personId: row.team_id } : { kind: 'guest' as const, personId: row.guest_id }; + if (!currentHost.personId || wanted.has(`${currentHost.kind}:${currentHost.personId}`)) continue; -/** - * Deletes a host from an event. - * @throws UnavailableError when the host could not be deleted (Supabase down, or the delete was refused). - */ -export async function deleteHost(host: EventHost): Promise { - const { data, error } = await v2().from('event_hosts').delete().eq('id', host.id).select('id'); - if (error || data.length === 0) throw new UnavailableError("The host couldn't be deleted.", { cause: error }); -} - -/** - * Reorders hosts by sort_order. All sort orders must be valid, contiguous, and start from 0. - * @throws UnavailableError when the reorder could not be saved. - */ -export async function reorderHosts(hosts: readonly EventHost[]): Promise { - if (hosts.length === 0) return; - - for (let i = 0; i < hosts.length; i++) { - const { error } = await v2() - .from('event_hosts') - .update({ sort_order: i }) - .eq('id', hosts[i]!.id); - if (error) throw new UnavailableError("The hosts couldn't be reordered.", { cause: error }); + const removal = v2().from('event_hosts').delete().eq('event_id', eventId); + const { error } = currentHost.kind === 'team' + ? await removal.eq('team_id', currentHost.personId) + : await removal.eq('guest_id', currentHost.personId); + if (error) throw new UnavailableError(failure, { cause: error }); } -} -const SpeakerLinkRowSchema = z.object({ event_id: z.uuid(), guest_id: z.uuid() }); + await upsertHosts(eventId, people, 'team', failure); + await upsertHosts(eventId, people, 'guest', failure); +} -/** - * Which guest speaks at which event, for every guest host. Empty when no event has a guest yet. - * @throws UnavailableError when Supabase cannot be reached or refuses the read. - */ +/** Lists every guest-event speaker link for photo tagging. */ export async function listSpeakerLinks(): Promise { const { data, error } = await v2().from('event_hosts').select('event_id, guest_id').not('guest_id', 'is', null); if (error) throw new UnavailableError("Who speaks at which event couldn't be loaded.", { cause: error }); + return data.flatMap((row) => { const parsed = SpeakerLinkRowSchema.safeParse(row); return parsed.success ? [{ eventId: parsed.data.event_id, guestId: parsed.data.guest_id }] : []; }); } -/** - * Sets the events a guest speaks at to `wanted`: adds them to the ones they aren't at yet and takes them off the - * rest. It reads where they speak now first, so running it again after a failure picks up where it stopped. - * @throws UnavailableError when any of it could not be saved. - */ +/** Adds and removes a guest's event links, appending new events after their existing hosts. */ export async function setGuestEvents(guestId: string, wanted: readonly string[]): Promise { const { data, error } = await v2().from('event_hosts').select('event_id').eq('guest_id', guestId); if (error) throw new UnavailableError("Their events couldn't be saved.", { cause: error }); + const current = data.map((row) => row.event_id); - // One at a time: adding a host reads the event's last place in the running order to put them after it. for (const eventId of wanted.filter((id) => !current.includes(id))) await addGuestHost(eventId, guestId); + const leaving = current.filter((id) => !wanted.includes(id)); if (leaving.length === 0) return; + const removed = await v2().from('event_hosts').delete().eq('guest_id', guestId).in('event_id', leaving); if (removed.error) throw new UnavailableError("Their events couldn't all be saved.", { cause: removed.error }); } -function toEventHost(row: HostRow): EventHost | null { - const baseData = { - id: row.id, - eventId: row.event_id, - sortOrder: row.sort_order, - }; - - if (row.team_id && !row.guest_id) { - const parsed = EventHostSchema.safeParse({ - ...baseData, - kind: 'team' as const, - teamId: row.team_id, - guestId: null, - }); - if (parsed.success) return parsed.data; - } else if (row.guest_id && !row.team_id) { - const parsed = EventHostSchema.safeParse({ - ...baseData, - kind: 'guest' as const, - teamId: null, - guestId: row.guest_id, - }); - if (parsed.success) return parsed.data; +async function upsertHosts(eventId: string, people: readonly HostFields[], kind: HostFields['kind'], failure: string): Promise { + const rows = kind === 'team' ? teamRows(eventId, people) : guestRows(eventId, people); + if (rows.length === 0) return; + + const conflict = kind === 'team' ? 'event_id,team_id' : 'event_id,guest_id'; + const { error } = await v2().from('event_hosts').upsert(rows, { onConflict: conflict }); + if (error) throw new UnavailableError(failure, { cause: error }); +} + +function teamRows(eventId: string, people: readonly HostFields[]): HostInsert[] { + return people.flatMap((person, sortOrder): HostInsert[] => + person.kind === 'team' ? [{ event_id: eventId, team_id: person.teamId, guest_id: null, sort_order: sortOrder }] : [], + ); +} + +function guestRows(eventId: string, people: readonly HostFields[]): HostInsert[] { + return people.flatMap((person, sortOrder): HostInsert[] => + person.kind === 'guest' ? [{ event_id: eventId, team_id: null, guest_id: person.guestId, sort_order: sortOrder }] : [], + ); +} + +async function addGuestHost(eventId: string, guestId: string): Promise { + const { data, error } = await v2().from('event_hosts').select('sort_order').eq('event_id', eventId).order('sort_order', { ascending: false }).limit(1); + if (error) throw new UnavailableError("The host couldn't be added.", { cause: error }); + + const result = await v2().from('event_hosts').insert({ event_id: eventId, guest_id: guestId, team_id: null, sort_order: (data[0]?.sort_order ?? -1) + 1 }); + if (result.error) throw new UnavailableError("The host couldn't be added.", { cause: result.error }); +} + +function hostKey(person: HostFields): string { + return person.kind === 'team' ? `team:${person.teamId}` : `guest:${person.guestId}`; +} + +function toHostCard(row: unknown): HostCard[] { + const parsed = HostRowSchema.safeParse(row); + if (!parsed.success) { + console.warn('event_hosts.row_skipped', { problems: parsed.error.issues.map((issue) => issue.path.join('.')) }); + return []; + } + + const host = parsed.data; + const base = { id: host.id, eventId: host.event_id, sortOrder: host.sort_order }; + if (host.team_id && !host.guest_id && host.team?.id === host.team_id) { + return parseHostCard({ ...base, kind: 'team', personId: host.team.id, name: host.team.name, subtitle: host.team.role, pictureUrl: host.team.picture_path ? publicUrl(BUCKETS.team, host.team.picture_path) : null, company: null, isPublic: host.team.is_public }); } + if (host.guest_id && !host.team_id && host.guests?.id === host.guest_id) { + const company = host.guests.companies; + return parseHostCard({ ...base, kind: 'guest', personId: host.guests.id, name: host.guests.name, subtitle: host.guests.title, pictureUrl: host.guests.picture_path ? publicUrl(BUCKETS.guests, host.guests.picture_path) : null, company: company ? { name: company.name, colour: company.colour, logoUrl: company.logo_path ? publicUrl(BUCKETS.logos, company.logo_path) : null } : null, isPublic: true }); + } + + console.warn('event_hosts.row_skipped', { id: host.id, reason: 'missing joined host' }); + return []; +} - console.warn('event_hosts.row_skipped', { id: row.id, reason: 'invalid discriminator (must have exactly one of team_id or guest_id)' }); - return null; +function parseHostCard(value: unknown): HostCard[] { + const parsed = HostCardSchema.safeParse(value); + return parsed.success ? [parsed.data] : []; } diff --git a/apps/admin/src/types/event-host.ts b/apps/admin/src/types/event-host.ts index e5c8db0..0ada8ca 100644 --- a/apps/admin/src/types/event-host.ts +++ b/apps/admin/src/types/event-host.ts @@ -1,37 +1,30 @@ -/** - * An event host as the admin works with it, matching the v2 `event_hosts` table. - * A discriminated union: either a team member (team_id set) or a guest (guest_id set), never both. - */ +/** The person and company details needed to draw a saved event host. */ import { z } from 'zod'; -const TeamHostSchema = z.object({ - id: z.uuid(), - eventId: z.uuid(), - kind: z.literal('team'), - teamId: z.uuid(), - guestId: z.null(), - sortOrder: z.number().int().nonnegative(), +const HostCompanySchema = z.object({ + name: z.string().trim().min(1), + colour: z.string(), + logoUrl: z.url().nullable(), }); -export type TeamHost = Readonly>; -const GuestHostSchema = z.object({ +export const HostCardSchema = z.object({ id: z.uuid(), eventId: z.uuid(), - kind: z.literal('guest'), - teamId: z.null(), - guestId: z.uuid(), sortOrder: z.number().int().nonnegative(), + kind: z.enum(['team', 'guest']), + personId: z.uuid(), + name: z.string().trim().min(1), + subtitle: z.string().nullable(), + pictureUrl: z.url().nullable(), + company: HostCompanySchema.nullable(), + isPublic: z.boolean(), }); -export type GuestHost = Readonly>; -export const EventHostSchema = z.union([TeamHostSchema, GuestHostSchema]); -export type EventHost = Readonly>; +/** A host ready to show in the event editor. */ +export type HostCard = Readonly>; -/** What an exec fills in when adding a host. */ -export type HostFields = Readonly< - | { kind: 'team'; teamId: string } - | { kind: 'guest'; guestId: string } ->; +/** One person in the order the editor wants to save. */ +export type HostFields = Readonly<{ kind: 'team'; teamId: string } | { kind: 'guest'; guestId: string }>; -/** A guest speaking at an event: one guest host row, without its place in the running order. */ +/** A guest speaking at an event, without their display details. */ export type SpeakerLink = Readonly<{ eventId: string; guestId: string }>; diff --git a/apps/admin/tests/lib/data/event-hosts.test.ts b/apps/admin/tests/lib/data/event-hosts.test.ts index d4824e0..04ccece 100644 --- a/apps/admin/tests/lib/data/event-hosts.test.ts +++ b/apps/admin/tests/lib/data/event-hosts.test.ts @@ -1,217 +1,88 @@ import { UnavailableError } from '../../../src/lib/server/errors'; -import { - addGuestHost, - addTeamHost, - deleteHost, - getHost, - listHosts, - listSpeakerLinks, - reorderHosts, - setGuestEvents, - updateHost, -} from '../../../src/lib/data/event-hosts'; -import type { EventHost } from '../../../src/types/event-host'; -import { installV2Supabase } from '../server/supabase-v2-mock'; +import { listHosts, listSpeakerLinks, saveHosts, setGuestEvents } from '../../../src/lib/data/event-hosts'; +import { STORAGE_BASE, installV2Supabase } from '../server/supabase-v2-mock'; vi.mock('../../../src/lib/server/supabase'); - const EVENT_ID = '0b6f9c2e-7a41-4d5b-8e3c-2f1a9b8c7d6e'; -const HOST_ID = '1c7a0d3f-8b52-4e6c-9f4d-3a2b1c0d9e8f'; const TEAM_ID = '2d8b1e4f-9c6a-4f7d-8e5b-0c1d2e3f4e5f'; const GUEST_ID = '3e9c2f5d-0d7b-4e8c-9f6d-1a2b3c4d5e6f'; - -const TEAM_HOST_ROW = { id: HOST_ID, event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null, sort_order: 0 }; -const GUEST_HOST_ROW = { id: HOST_ID, event_id: EVENT_ID, team_id: null, guest_id: GUEST_ID, sort_order: 0 }; - -const TEAM_HOST: EventHost = { - id: HOST_ID, - eventId: EVENT_ID, - kind: 'team' as const, - teamId: TEAM_ID, - guestId: null, - sortOrder: 0, -}; - -const GUEST_HOST: EventHost = { - id: HOST_ID, - eventId: EVENT_ID, - kind: 'guest' as const, - teamId: null, - guestId: GUEST_ID, - sortOrder: 0, -}; - -const SAVED = { data: [{ id: HOST_ID }], error: null }; -const FAILED = { data: null, error: { message: 'boom' } }; +const HOST_ID = '1c7a0d3f-8b52-4e6c-9f4d-3a2b1c0d9e8f'; describe('listHosts', () => { - it('returns all hosts for an event', async () => { - const order = vi.fn().mockResolvedValue({ data: [TEAM_HOST_ROW], error: null }); - installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order })) })) } }); - + it('maps joined team and guest rows to display cards', async () => { + const rows = [ + { id: HOST_ID, event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null, sort_order: 0, team: { id: TEAM_ID, name: 'Ada', role: 'President', picture_path: 'ada.png', is_public: false }, guests: null }, + { id: '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70', event_id: EVENT_ID, team_id: null, guest_id: GUEST_ID, sort_order: 1, team: null, guests: { id: GUEST_ID, name: 'Grace', title: 'Engineer', picture_path: 'grace.png', companies: { name: 'LCS', colour: '#111111', logo_path: 'logo.png' } } }, + ]; + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn().mockResolvedValue({ data: rows, error: null }) })) })) } }); const hosts = await listHosts(EVENT_ID); - expect(hosts).toHaveLength(1); - expect(hosts[0]?.kind).toBe('team'); + expect(hosts).toMatchObject([{ kind: 'team', name: 'Ada', isPublic: false, pictureUrl: `${STORAGE_BASE}/team-images/ada.png` }, { kind: 'guest', name: 'Grace', company: { logoUrl: `${STORAGE_BASE}/company-logos/logo.png` } }]); }); - - it('returns empty list for invalid event id', async () => { - expect(await listHosts('not-a-uuid')).toEqual([]); + it('lists team-only and guest-only rows', async () => { + const team = { id: HOST_ID, event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null, sort_order: 0, team: { id: TEAM_ID, name: 'Ada', role: 'President', picture_path: null, is_public: true }, guests: null }; + const guest = { id: HOST_ID, event_id: EVENT_ID, team_id: null, guest_id: GUEST_ID, sort_order: 0, team: null, guests: { id: GUEST_ID, name: 'Grace', title: null, picture_path: null, companies: null } }; + const order = vi.fn().mockResolvedValueOnce({ data: [team], error: null }).mockResolvedValueOnce({ data: [guest], error: null }); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order })) })) } }); + await expect(listHosts(EVENT_ID)).resolves.toMatchObject([{ kind: 'team' }]); + await expect(listHosts(EVENT_ID)).resolves.toMatchObject([{ kind: 'guest' }]); }); -}); - -describe('getHost', () => { - it('returns a team host by id', async () => { - installV2Supabase({ - event_hosts: { - select: vi.fn(() => ({ - eq: vi.fn(() => ({ maybeSingle: vi.fn().mockResolvedValue({ data: TEAM_HOST_ROW, error: null }) })), - })), - }, - }); - - const host = await getHost(HOST_ID); - expect(host?.kind).toBe('team'); - expect(host?.teamId).toBe(TEAM_ID); + it('skips a row with no joined team member or guest', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const row = { id: HOST_ID, event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null, sort_order: 0, team: null, guests: null }; + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn().mockResolvedValue({ data: [row], error: null }) })) })) } }); + await expect(listHosts(EVENT_ID)).resolves.toEqual([]); expect(warn).toHaveBeenCalled(); warn.mockRestore(); }); - it('returns a guest host by id', async () => { - installV2Supabase({ - event_hosts: { - select: vi.fn(() => ({ - eq: vi.fn(() => ({ maybeSingle: vi.fn().mockResolvedValue({ data: GUEST_HOST_ROW, error: null }) })), - })), - }, - }); - - const host = await getHost(HOST_ID); - expect(host?.kind).toBe('guest'); - expect(host?.guestId).toBe(GUEST_ID); + it('skips an invalid joined row', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn().mockResolvedValue({ data: [{ id: HOST_ID }], error: null }) })) })) } }); + expect(await listHosts(EVENT_ID)).toEqual([]); expect(warn).toHaveBeenCalled(); warn.mockRestore(); }); }); -describe('addTeamHost', () => { - it('adds a team member as a host', async () => { - const insert = vi.fn().mockResolvedValue({ error: null }); - const select = vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) })); - installV2Supabase({ event_hosts: { insert, select } }); - - await addTeamHost(EVENT_ID, TEAM_ID); - - expect(insert).toHaveBeenCalledWith(expect.objectContaining({ event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null })); +describe('saveHosts', () => { + it('deletes missing rows before upserting ordered team and guest rows', async () => { + const remove = vi.fn().mockResolvedValue({ error: null }); const upsert = vi.fn().mockResolvedValue({ error: null }); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [{ team_id: '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70', guest_id: null }], error: null }) })), delete: vi.fn(() => ({ eq: vi.fn(() => ({ eq: remove })) })), upsert } }); + await saveHosts(EVENT_ID, [{ kind: 'guest', guestId: GUEST_ID }, { kind: 'team', teamId: TEAM_ID }]); + expect(remove).toHaveBeenCalledBefore(upsert); expect(upsert).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ guest_id: GUEST_ID, sort_order: 0 })]), { onConflict: 'event_id,guest_id' }); expect(upsert).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ team_id: TEAM_ID, sort_order: 1 })]), { onConflict: 'event_id,team_id' }); }); -}); - -describe('addGuestHost', () => { - it('adds a guest as a host', async () => { - const insert = vi.fn().mockResolvedValue({ error: null }); - const select = vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) })); - installV2Supabase({ event_hosts: { insert, select } }); - - await addGuestHost(EVENT_ID, GUEST_ID); - - expect(insert).toHaveBeenCalledWith(expect.objectContaining({ event_id: EVENT_ID, guest_id: GUEST_ID, team_id: null })); + it('uses list indexes when reordered across both kinds', async () => { + const upsert = vi.fn().mockResolvedValue({ error: null }); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [], error: null }) })), upsert } }); + await saveHosts(EVENT_ID, [{ kind: 'guest', guestId: GUEST_ID }, { kind: 'team', teamId: TEAM_ID }]); + expect(upsert).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ guest_id: GUEST_ID, sort_order: 0 })]), { onConflict: 'event_id,guest_id' }); + expect(upsert).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ team_id: TEAM_ID, sort_order: 1 })]), { onConflict: 'event_id,team_id' }); }); -}); - -describe('updateHost', () => { - it('changes a team host to a guest host', async () => { - const update = vi.fn(() => ({ eq: vi.fn(() => ({ select: vi.fn().mockResolvedValue(SAVED) })) })); - installV2Supabase({ event_hosts: { update } }); - - await updateHost(TEAM_HOST, { kind: 'guest', guestId: GUEST_ID }); - - expect(update).toHaveBeenCalledWith(expect.objectContaining({ guest_id: GUEST_ID, team_id: null })); + it('throws UnavailableError on delete failure', async () => { + const remove = vi.fn().mockResolvedValue({ error: { message: 'no' } }); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [{ team_id: TEAM_ID, guest_id: null }], error: null }) })), delete: vi.fn(() => ({ eq: vi.fn(() => ({ eq: remove })) })) } }); + await expect(saveHosts(EVENT_ID, [])).rejects.toBeInstanceOf(UnavailableError); }); -}); - -describe('deleteHost', () => { - it('deletes a host', async () => { - const eq = vi.fn(() => ({ select: vi.fn().mockResolvedValue(SAVED) })); - installV2Supabase({ event_hosts: { delete: vi.fn(() => ({ eq })) } }); - - await deleteHost(TEAM_HOST); - - expect(eq).toHaveBeenCalledWith('id', HOST_ID); + it('throws UnavailableError on upsert failure', async () => { + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [], error: null }) })), upsert: vi.fn().mockResolvedValue({ error: { message: 'no' } }) } }); + await expect(saveHosts(EVENT_ID, [{ kind: 'guest', guestId: GUEST_ID }])).rejects.toBeInstanceOf(UnavailableError); }); - it('fails when delete fails', async () => { - installV2Supabase({ event_hosts: { delete: vi.fn(() => ({ eq: vi.fn(() => ({ select: vi.fn().mockResolvedValue(FAILED) })) })) } }); - - await expect(deleteHost(TEAM_HOST)).rejects.toBeInstanceOf(UnavailableError); + it('deletes every row for an empty list', async () => { + const remove = vi.fn().mockResolvedValue({ error: null }); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [{ team_id: TEAM_ID, guest_id: null }], error: null }) })), delete: vi.fn(() => ({ eq: vi.fn(() => ({ eq: remove })) })) } }); + await saveHosts(EVENT_ID, []); expect(remove).toHaveBeenCalled(); }); -}); - -describe('reorderHosts', () => { - it('updates sort orders', async () => { - const hosts: EventHost[] = [ - { ...TEAM_HOST, sortOrder: 0 }, - { ...GUEST_HOST, id: '4f0d3g6h-1e8c-5f9d-0g7e-2b3c4d5e6f7g', sortOrder: 1 }, - ]; - const update = vi.fn(() => ({ eq: vi.fn(() => ({}) ) })); - installV2Supabase({ event_hosts: { update } }); - - await reorderHosts(hosts); - - expect(update).toHaveBeenCalledTimes(2); + it('reports failed saves as unavailable', async () => { + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [], error: null }) })), upsert: vi.fn().mockResolvedValue({ error: { message: 'no' } }) } }); + await expect(saveHosts(EVENT_ID, [{ kind: 'team', teamId: TEAM_ID }])).rejects.toBeInstanceOf(UnavailableError); }); }); -describe('listSpeakerLinks', () => { - it('lists which guest speaks at which event', async () => { - const not = vi.fn().mockResolvedValue({ data: [{ event_id: EVENT_ID, guest_id: GUEST_ID }], error: null }); - installV2Supabase({ event_hosts: { select: vi.fn(() => ({ not })) } }); - +describe('speaker links and guest events', () => { + it('lists guest speaker links', async () => { + const not = vi.fn().mockResolvedValue({ data: [{ event_id: EVENT_ID, guest_id: GUEST_ID }], error: null }); installV2Supabase({ event_hosts: { select: vi.fn(() => ({ not })) } }); expect(await listSpeakerLinks()).toEqual([{ eventId: EVENT_ID, guestId: GUEST_ID }]); - expect(not).toHaveBeenCalledWith('guest_id', 'is', null); - }); - - it('reports a failed read as unavailable', async () => { - const not = vi.fn().mockResolvedValue({ data: null, error: { message: 'down' } }); - installV2Supabase({ event_hosts: { select: vi.fn(() => ({ not })) } }); - - await expect(listSpeakerLinks()).rejects.toBeInstanceOf(UnavailableError); }); -}); - -describe('setGuestEvents', () => { - const OTHER_EVENT = '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70'; - const NEW_EVENT = '5a1e4b7f-2f9d-4a0e-9b8f-3c4d5e6f7a81'; - - /** An `event_hosts` table where the guest speaks at `current`, recording what is added and taken off. */ - function hostsTable(current: readonly string[], removeError: unknown = null) { - const insert = vi.fn().mockResolvedValue({ error: null }); - const takeOff = vi.fn().mockResolvedValue({ error: removeError }); - const select = vi.fn((columns: string) => - columns === 'event_id' - ? { eq: vi.fn().mockResolvedValue({ data: current.map((id) => ({ event_id: id })), error: null }) } - : { eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) }, - ); - installV2Supabase({ event_hosts: { select, insert, delete: vi.fn(() => ({ eq: vi.fn(() => ({ in: takeOff })) })) } }); - return { insert, takeOff }; - } - - it('adds the guest to new events and takes them off the ones no longer wanted', async () => { - const { insert, takeOff } = hostsTable([EVENT_ID, OTHER_EVENT]); - - await setGuestEvents(GUEST_ID, [EVENT_ID, NEW_EVENT]); - - expect(insert).toHaveBeenCalledTimes(1); - expect(insert).toHaveBeenCalledWith(expect.objectContaining({ event_id: NEW_EVENT, guest_id: GUEST_ID })); - expect(takeOff).toHaveBeenCalledWith('event_id', [OTHER_EVENT]); - }); - - it('changes nothing when the events are the same', async () => { - const { insert, takeOff } = hostsTable([EVENT_ID]); - - await setGuestEvents(GUEST_ID, [EVENT_ID]); - - expect(insert).not.toHaveBeenCalled(); - expect(takeOff).not.toHaveBeenCalled(); - }); - - it('reports a failed removal as unavailable', async () => { - hostsTable([EVENT_ID], { message: 'refused' }); - - await expect(setGuestEvents(GUEST_ID, [])).rejects.toThrow("Their events couldn't all be saved."); + it('adds and removes guest event links', async () => { + const OTHER = '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70'; const NEW = '5a1e4b7f-2f9d-4a0e-9b8f-3c4d5e6f7a81'; const insert = vi.fn().mockResolvedValue({ error: null }); const takeOff = vi.fn().mockResolvedValue({ error: null }); + const select = vi.fn((columns: string) => columns === 'event_id' ? { eq: vi.fn().mockResolvedValue({ data: [{ event_id: OTHER }], error: null }) } : { eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) }); + installV2Supabase({ event_hosts: { select, insert, delete: vi.fn(() => ({ eq: vi.fn(() => ({ in: takeOff })) })) } }); await setGuestEvents(GUEST_ID, [NEW]); expect(insert).toHaveBeenCalled(); expect(takeOff).toHaveBeenCalledWith('event_id', [OTHER]); }); }); diff --git a/apps/admin/tests/pages/EventExtras.test.tsx b/apps/admin/tests/pages/EventExtras.test.tsx index 54f0ec7..7e16694 100644 --- a/apps/admin/tests/pages/EventExtras.test.tsx +++ b/apps/admin/tests/pages/EventExtras.test.tsx @@ -6,6 +6,9 @@ import { addLinkDocument, listDocuments } from '../../src/lib/data/event-documen import { listPartners, savePartners } from '../../src/lib/data/event-partners'; import { listRelated, saveRelated } from '../../src/lib/data/event-related'; import { listTopics, saveTopics } from '../../src/lib/data/event-topics'; +import { listHosts, saveHosts } from '../../src/lib/data/event-hosts'; +import { listGuests } from '../../src/lib/data/guests'; +import { listTeam } from '../../src/lib/data/team'; import { getEvent, listEvents } from '../../src/lib/data/events'; import { UnavailableError } from '../../src/lib/server/errors'; import { sampleEvent } from '../fixtures/events'; @@ -20,11 +23,16 @@ vi.mock('../../src/lib/data/event-partners'); vi.mock('../../src/lib/data/companies'); vi.mock('../../src/lib/data/event-documents'); vi.mock('../../src/lib/data/event-related'); +vi.mock('../../src/lib/data/event-hosts'); +vi.mock('../../src/lib/data/guests'); +vi.mock('../../src/lib/data/team'); const FINAL_REVIEW = sampleEvent({ id: '0b6f9c2e-7a41-4d5b-8e3c-2f1a9b8c7d6e', title: 'CP312 Final Review', date: '2026-12-05', category: 'review' }); const MIDTERM_REVIEW = sampleEvent({ id: '1c7a0d3f-8b52-4e6c-9f4d-3a2b1c0d9e8f', title: 'CP312 Midterm Review', date: '2026-10-15', category: 'review' }); const LWICS = { id: '2d8b1e4f-9c6a-4f7d-8e5b-0c1d2e3f4a5b', name: 'LWICS', colour: '#ff9fc4', logoPath: null, logoUrl: null, cardLogoPath: null, cardLogoUrl: null }; const TOPIC_ID = '3e9c2f5a-0d7b-4a8e-9f6c-1d2e3f4a5b6c'; +const GUEST = { id: '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70', name: 'Grace Hopper', title: 'Engineer', companyId: LWICS.id, picturePath: null, pictureUrl: null, linkUrl: null }; +const MEMBER = { id: '5a1e4b7f-2f9d-4a0e-9b8f-3c4d5e6f7a81', name: 'Ada Lovelace', role: 'President', department: 'Engineering' as const, isPublic: false, photoPath: null, pictureUrl: null, githubUrl: null, linkedinUrl: null }; beforeEach(() => { mockAccess(SAM_ADMIN); @@ -40,6 +48,10 @@ beforeEach(() => { vi.mocked(savePartners).mockResolvedValue(); vi.mocked(saveRelated).mockResolvedValue(); vi.mocked(addLinkDocument).mockResolvedValue(); + vi.mocked(listHosts).mockResolvedValue([]); + vi.mocked(saveHosts).mockResolvedValue(); + vi.mocked(listGuests).mockResolvedValue([GUEST]); + vi.mocked(listTeam).mockResolvedValue([MEMBER]); }); /** One of the panels under the form, once its list has loaded. */ @@ -105,6 +117,64 @@ describe('in collaboration with', () => { }); }); +describe('speakers and hosts', () => { + it('searches guests and team members, adds them in order, and saves them', async () => { + vi.mocked(listHosts).mockResolvedValue([]); + renderApp(`/events/${FINAL_REVIEW.id}`); + const hosts = await panel('Speakers and hosts'); + expect(hosts.getAllByText('Start typing to search.')).toHaveLength(2); + + const search = hosts.getByLabelText('Add a speaker or host'); + await userEvent.type(search, 'grace'); + await userEvent.click(await hosts.findByRole('button', { name: 'Grace Hopper' })); + expect(hosts.getByText('LWICS')).toBeInTheDocument(); + await userEvent.type(search, 'ada'); + await userEvent.click(await hosts.findByRole('button', { name: 'Ada Lovelace' })); + expect(hosts.getByText(/hidden from the site/)).toBeInTheDocument(); + await userEvent.click(hosts.getByRole('button', { name: 'Save speakers and hosts' })); + + expect(saveHosts).toHaveBeenCalledWith(FINAL_REVIEW.id, [{ kind: 'guest', guestId: GUEST.id }, { kind: 'team', teamId: MEMBER.id }]); + }); + + it('shows loading, failed and empty guest choices', async () => { + vi.mocked(listHosts).mockResolvedValue([]); + vi.mocked(listGuests).mockReturnValue(new Promise(() => {})); + renderApp(`/events/${FINAL_REVIEW.id}`); + const hosts = await panel('Speakers and hosts'); + await userEvent.type(hosts.getByLabelText('Add a speaker or host'), 'grace'); + expect(await hosts.findByText('Loading guests…')).toBeInTheDocument(); + }); + + it('shows a failed message when guests cannot be loaded', async () => { + vi.mocked(listHosts).mockResolvedValue([]); + vi.mocked(listGuests).mockRejectedValue(new UnavailableError('Guests could not be loaded.')); + renderApp(`/events/${FINAL_REVIEW.id}`); + const hosts = await panel('Speakers and hosts'); + await userEvent.type(hosts.getByLabelText('Add a speaker or host'), 'grace'); + expect(await hosts.findByText("Guests couldn't be loaded.")).toBeInTheDocument(); + }); + + it('shows when there are no matching guests', async () => { + vi.mocked(listHosts).mockResolvedValue([]); + vi.mocked(listGuests).mockResolvedValue([]); + renderApp(`/events/${FINAL_REVIEW.id}`); + const hosts = await panel('Speakers and hosts'); + await userEvent.type(hosts.getByLabelText('Add a speaker or host'), 'grace'); + expect(await hosts.findByText('No guests found.')).toBeInTheDocument(); + }); + + it('saves a reordered guest host', async () => { + vi.mocked(listHosts).mockResolvedValue([{ id: '6b2f5c8a-3d1e-4f0a-9b7c-2d3e4f5a6b7c', eventId: FINAL_REVIEW.id, sortOrder: 0, kind: 'team', personId: MEMBER.id, name: MEMBER.name, subtitle: MEMBER.role, pictureUrl: null, company: null, isPublic: false }, { id: '7c3e6d9b-4f2a-4b1c-8d9e-3f4a5b6c7d8e', eventId: FINAL_REVIEW.id, sortOrder: 1, kind: 'guest', personId: GUEST.id, name: GUEST.name, subtitle: GUEST.title, pictureUrl: null, company: { name: LWICS.name, colour: LWICS.colour, logoUrl: null }, isPublic: true }]); + renderApp(`/events/${FINAL_REVIEW.id}`); + const hosts = await panel('Speakers and hosts'); + await userEvent.click(hosts.getByRole('button', { name: 'Move Grace Hopper up' })); + expect(hosts.getByText(/hidden from the site/)).toBeInTheDocument(); + await userEvent.click(hosts.getByRole('button', { name: 'Remove Ada Lovelace' })); + await userEvent.click(hosts.getByRole('button', { name: 'Save speakers and hosts' })); + expect(saveHosts).toHaveBeenCalledWith(FINAL_REVIEW.id, [{ kind: 'guest', guestId: GUEST.id }]); + }); +}); + describe('resources', () => { it('adds a link with its kind', async () => { renderApp(`/events/${FINAL_REVIEW.id}`); diff --git a/docs/admin-guide.md b/docs/admin-guide.md index c23bada..2096a2b 100644 --- a/docs/admin-guide.md +++ b/docs/admin-guide.md @@ -32,6 +32,10 @@ Notion) and sign in again; nothing you saved is lost. ## Events +### Speakers and hosts + +On an existing event, use **Speakers and hosts** to add guests or team members, put them in order, and save the whole list. Guests can also be linked to events from their guest page's **Speaks at** field. Only guest speakers appear on the public event page for now; team hosts are saved but marked as not shown there. + ### Post an event 1. On **Events**, press **New event**. diff --git a/docs/plans/300-event-hosts.md b/docs/plans/300-event-hosts.md new file mode 100644 index 0000000..04e60ed --- /dev/null +++ b/docs/plans/300-event-hosts.md @@ -0,0 +1,25 @@ +# Event hosts panel + +## Remaining work + +Issues #299 and #300 already have resources, related events, topics, partners, and guest-side event links. This change completes the joined host read and the event-side speakers and hosts editor. + +## Design + +- Read `event_hosts` with its team or guest relation and map each valid row to a display-ready host card. +- Save the desired host list as one ordered operation: remove rows that are no longer wanted, then upsert the remaining rows with their current positions. +- Add the first event-extra panel for speakers and hosts. It supports an accessible grouped picker, draft-only add/remove/reorder controls, and a single save action. +- Keep guest links in sync after saves; team hosts remain visibly marked as not yet published on the site. + +## Files and tests + +- Update the host types, data functions, query hooks, event extras, guide, and add `EventHostsPanel`. +- Extend data tests for joined mapping and whole-list saves; extend event extras tests for keyboard reordering, picker choices, saving, and host visibility notes. +- Verify the admin lint, test, and build commands, plus the site build. Resource reordering will be checked but is outside this change if unsupported. + +## Review fixes + +- Match the other extras panels' formatting, helper comments, and picker-state handling. +- Reuse the guest company mark and show a newly picked guest's company before saving. +- Only show picker results after a search, with distinct loading, failed, and empty states. +- Add event-page and data-layer coverage for host editing, ordering, failures, and incomplete joined rows.