From a5ad9795eed69cc86fd19db2e0b7931332812c3f Mon Sep 17 00:00:00 2001 From: Jose Lago Date: Tue, 25 Aug 2026 08:58:16 +0200 Subject: [PATCH] Service sessions + Home redesign + feedback loop Service sessions (new slot semantics): - Sidecar maps isServiceSession OR isPlenumSession -> service_session (Excel path also matches 'plenum' in Session Format). - checkin_attendee rejects service sessions; Scan check-in dropdown excludes them. - New _assign_service_session_speakers helper links every registered staff member as a speaker of a service session; both sync RPCs call it (and the API sync now actually types slots from is_service_session). - No material requirement + no mic emoji for service sessions. Home redesign: - Now/Next cards show all concurrent sessions as sub-sections when there's no pick (1/2/3 sessions -> 1/2/3 sub-sections), with a "Nothing scheduled" fallback for empty slots. - My picks today lists every pick (slot order) + empty state. - Demo clock EVENT_DATE fixed to 2026-02-20 (matches seed) so a slot is live at 10:20. Feedback loop: - Attendee pending-feedback pill on Home (checked into an over session, not its speaker, no feedback yet); clears on submit. - Speaker sees rating + AI summary for their own session in the Agenda sheet only after it's over. Migration 20260833000000_service_sessions_feedback.sql. Docs updated. --- apps/convivo/src/lib/api.ts | 1 + apps/convivo/src/lib/time.ts | 5 +- apps/convivo/src/lib/types.ts | 2 + apps/convivo/src/screens/Agenda.tsx | 36 +- apps/convivo/src/screens/Home.tsx | 149 +++-- apps/convivo/src/screens/Scan.tsx | 19 +- apps/convivo/src/styles.css | 23 + apps/sidecar/src/server.js | 6 +- docs/backend/rpcs.md | 28 +- docs/backend/schema.md | 2 +- docs/backend/sidecar.md | 12 +- docs/frontend/app-structure.md | 59 +- docs/frontend/screens.md | 85 ++- docs/next-steps.md | 45 +- ...260833000000_service_sessions_feedback.sql | 511 ++++++++++++++++++ 15 files changed, 878 insertions(+), 105 deletions(-) create mode 100644 supabase/migrations/20260833000000_service_sessions_feedback.sql diff --git a/apps/convivo/src/lib/api.ts b/apps/convivo/src/lib/api.ts index d4375ea..336fbfa 100644 --- a/apps/convivo/src/lib/api.ts +++ b/apps/convivo/src/lib/api.ts @@ -65,6 +65,7 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[ id: r.session_id, event_id: '', slot_id: r.slot_id, + slot_type: r.slot_type, title: r.title, description: r.description, room: r.room, diff --git a/apps/convivo/src/lib/time.ts b/apps/convivo/src/lib/time.ts index 58e9248..5ec99ae 100644 --- a/apps/convivo/src/lib/time.ts +++ b/apps/convivo/src/lib/time.ts @@ -1,9 +1,10 @@ import type { Slot } from './types'; /** The event day (from the seed). All slot times are on this date. */ -export const EVENT_DATE = '2026-10-23'; +export const EVENT_DATE = '2026-02-20'; -/** Simulated "now" used for the demo (matches the mockup: 10:20 on event day). */ +/** Simulated "now" used for the demo (10:20 on event day โ†’ Slot 2 is live, + * Slot 3 is next). Matches the mockup's "Good morning" greeting. */ export const DEFAULT_NOW = new Date(`${EVENT_DATE}T10:20:00`); export type SlotStatus = 'done' | 'now' | 'next'; diff --git a/apps/convivo/src/lib/types.ts b/apps/convivo/src/lib/types.ts index 849bc20..020723d 100644 --- a/apps/convivo/src/lib/types.ts +++ b/apps/convivo/src/lib/types.ts @@ -55,6 +55,8 @@ export interface Session { id: string; event_id: string; slot_id: number; + /** The slot's type ('session' | 'service_session') โ€” carried for convenience. */ + slot_type: SlotType; title: string; description: string | null; room: string | null; diff --git a/apps/convivo/src/screens/Agenda.tsx b/apps/convivo/src/screens/Agenda.tsx index 3f04ddd..0c30781 100644 --- a/apps/convivo/src/screens/Agenda.tsx +++ b/apps/convivo/src/screens/Agenda.tsx @@ -97,7 +97,10 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) => const selStatus = selSlot ? slotStatus(selSlot, now) : 'next'; const selCheckedIn = selected ? checkins.includes(selected.id) : false; const selISpeaker = selected ? mySpeakerSessions.includes(selected.id) : false; - const selNeedsMaterial = selISpeaker && !selected?.material_path; + const selIsService = selSlot?.type === 'service_session'; + // Service sessions have no material requirement (and no mic), so the + // pending-material notice never applies to them. + const selNeedsMaterial = selISpeaker && !selected?.material_path && !selIsService; async function handleUpload(e: React.ChangeEvent) { const file = e.target.files?.[0]; @@ -166,7 +169,9 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
{s.title} - {isMySession && ๐ŸŽค you} + {isMySession && !isService && ( + ๐ŸŽค you + )}
{s.room} ยท {s.speakers} @@ -198,7 +203,7 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) => {selected.description}
- ๐ŸŽค {selected.speakers} + {selIsService ? '' : '๐ŸŽค '}{selected.speakers} {selected.capacity && ๐Ÿ‘ฅ {selected.capacity}} {selCheckedIn && โœ“ Checked in}
@@ -214,6 +219,31 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
)} + {/* Speaker feedback: visible only after the session is over. */} + {selISpeaker && selStatus === 'done' && ( +
+
โญ Your session feedback
+ {selected.average_feedback != null ? ( +
+ + {[1, 2, 3, 4, 5].map((n) => ( + โ˜… + ))} + + {selected.average_feedback.toFixed(1)} +
+ ) : ( +
No feedback yet.
+ )} + {selected.ai_generated_feedback && ( +
+
AI summary
+
{selected.ai_generated_feedback}
+
+ )} +
+ )} +
{selStatus === 'done' && selCheckedIn && (
+ {/* Pending feedback: nudge to rate a session they attended. */} + {feedbackPending.length > 0 && ( + + )} + + {/* Now: the current slot. With a pick, show it; without, show everything running. */} {current && (
โ— Now {fmtRange(current.slot)}
- {nowSession ? ( - <> -
{nowSession.title}
-
- {nowSession.room} ยท {nowSession.speakers} -
- {checkins.includes(nowSession.id) ? ( - โœ“ Checked in - ) : ( - Show your QR to staff to check in - )} - + {nowPick ? ( + + ) : current.sessions.length > 0 ? ( + ) : ( -
- No pick yet โ€” tap a session in the Agenda to choose. -
+
Nothing scheduled right now.
)}
)} + {/* Next: the upcoming slot. */} {next && (
Next {fmtRange(next.slot)}
- {nextSession ? ( - <> -
{nextSession.title}
-
- {nextSession.room} ยท {nextSession.speakers} -
- + {nextPick ? ( + + ) : next.sessions.length > 0 ? ( + ) : ( -
- No pick yet โ€” tap a session in the Agenda to choose. -
+
Nothing scheduled next.
)}
)} + {/* My picks today */}
My picks today go('agenda')}>tap to change
-
- {[ - { label: 'Now', slot: current?.slot, session: nowSession }, - { label: 'Next', slot: next?.slot, session: nextSession }, - ] - .filter((r) => r.slot) - .map((r) => ( - ))} -
+
+ ) : ( +
+ No picks yet โ€” tap a session in the Agenda to choose. +
+ )}
diff --git a/apps/convivo/src/screens/Scan.tsx b/apps/convivo/src/screens/Scan.tsx index ecc1e54..96491a0 100644 --- a/apps/convivo/src/screens/Scan.tsx +++ b/apps/convivo/src/screens/Scan.tsx @@ -22,7 +22,8 @@ export function Scan() { useEffect(() => { if (slots.length > 0 && !sessionId) { - const first = slots[0].sessions[0]; + // Default to the first checkable (non-service) session. + const first = slots.flatMap((s) => s.sessions).find((s) => s.slot_type !== 'service_session'); if (first) setSessionId(first.id); } }, [slots, sessionId]); @@ -128,13 +129,15 @@ export function Scan() { <>
Checking in to session
)} diff --git a/apps/convivo/src/styles.css b/apps/convivo/src/styles.css index a82126e..98a9a5f 100644 --- a/apps/convivo/src/styles.css +++ b/apps/convivo/src/styles.css @@ -77,6 +77,17 @@ body { border-radius: 12px; padding: 14px; margin-bottom: 12px; display: flex; flex-direction: column; gap: 6px; } .material-notice .mn-title { font-weight: 800; font-size: 14px; } +/* speaker's post-session feedback review (rating + AI summary) */ +.feedback-review { + background: rgba(124,58,237,.07); border: 1px solid rgba(124,58,237,.35); border-left: 3px solid #7c3aed; + border-radius: 12px; padding: 14px; margin-bottom: 12px; display: flex; flex-direction: column; gap: 8px; +} +.feedback-review .fr-title { font-weight: 800; font-size: 14px; } +.feedback-review .fr-rating { display: flex; align-items: center; gap: 10px; } +.feedback-review .fr-stars { font-size: 18px; letter-spacing: 2px; color: #d6d3d1; } +.feedback-review .fr-stars .on { color: #f59e0b; } +.feedback-review .fr-num { font-weight: 800; font-size: 16px; } +.feedback-review .fr-summary { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; } .avatar { display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: 800; color: #fff; flex-shrink: 0; } .input { width: 100%; padding: 15px 16px; border-radius: 14px; border: 1px solid var(--line); @@ -168,6 +179,18 @@ textarea.input { resize: none; min-height: 96px; } color: #d50000; font-weight: 800; font-size: 14px; cursor: pointer; flex-shrink: 0; white-space: nowrap; } .now-card { background: linear-gradient(135deg, rgba(213,0,0,.1), rgba(32,178,170,.08)); border: 1px solid rgba(213,0,0,.35); } +/* Concurrent-session list inside the Now/Next card (shown when there's no pick). */ +.now-list { display: flex; flex-direction: column; gap: 10px; margin-top: 12px; } +.now-item { padding: 10px 12px; border-radius: 12px; background: var(--surface); border: 1px solid var(--line); } +.now-item .t { font-weight: 700; font-size: 14px; } +/* Pending-feedback nudge (attendees who attended a session that's now over). */ +.feedback-pill { + display: flex; align-items: center; gap: 8px; width: 100%; margin-top: 12px; + padding: 12px 14px; border-radius: 14px; cursor: pointer; font-family: inherit; + background: rgba(124,58,237,.1); border: 1px solid rgba(124,58,237,.4); + color: #6d28d9; font-weight: 800; font-size: 14px; text-align: left; +} +.feedback-pill:active { transform: scale(.99); } .qa-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } .qa { display: flex; flex-direction: column; gap: 8px; padding: 16px; border-radius: 16px; cursor: pointer; diff --git a/apps/sidecar/src/server.js b/apps/sidecar/src/server.js index d750fc0..8d3ae0a 100644 --- a/apps/sidecar/src/server.js +++ b/apps/sidecar/src/server.js @@ -127,7 +127,9 @@ function transform(data) { date: s.startsAt.slice(0, 10), start_time: s.startsAt.slice(11, 19), end_time: s.endsAt.slice(11, 19), - is_service_session: Boolean(s.isServiceSession), + // A service session is a break/lunch/closing (isServiceSession) OR a + // plenum (isPlenumSession) โ€” plenums are full-hall items with no pick. + is_service_session: Boolean(s.isServiceSession || s.isPlenumSession), speakers: speakerEmails, }); } @@ -203,7 +205,7 @@ function transformExcel(buffer) { date, start_time, end_time, - is_service_session: /service|break|lunch|closing/i.test(String(r['Session Format'] ?? '')), + is_service_session: /service|break|lunch|closing|plenum/i.test(String(r['Session Format'] ?? '')), speakers: speakerEmails, }); } diff --git a/docs/backend/rpcs.md b/docs/backend/rpcs.md index 9f7d3f3..9f0874a 100644 --- a/docs/backend/rpcs.md +++ b/docs/backend/rpcs.md @@ -99,6 +99,9 @@ Staff checks an attendee into a session. - **Role check:** `is_staff_or_admin()` (i.e. `is_admin()`) or it raises `staff or admin only`. - Resolves the attendee by `qr_token`. +- **Service-session guard:** if the session's slot is a `service_session`, it + raises `service sessions cannot be checked in` (there's nothing to check into โ€” + everyone is in the room). - `insert into checkins ... on conflict (event_id, contact_email, session_id) do nothing returning id` โ€” if no row was inserted, the attendee was **already checked in**: sets `already = true` and awards **no points**. @@ -208,13 +211,20 @@ Imports an event's Sessionize data in order: (1) speakers โ†’ contacts (matched email), (2) sessions (upserted by `external_id`), (3) the agenda (slots find-or-created by date/start/end + `session_speakers` links). `p_payload` is `{ speakers: [{email, full_name, external_id?}], sessions: [{external_id, title, -description?, room?, date, start_time, end_time, speakers: [email,...]}] }`. +description?, room?, date, start_time, end_time, is_service_session?, speakers: +[email,...]}] }`. - Guarded to the `service_role` caller (JWT role claim); granted to `service_role` only โ€” the apps cannot call it. +- **Slots are typed from `is_service_session`** (`service_session` for + breaks/lunch/closing/plenums, else `session`) with a matching name + ("Service Session" vs "Slot HH:MMโ€“HH:MM"). - **Idempotent:** re-running updates in place (contacts by email, sessions by `external_id`, slots by date/start/end). Speaker links are **diffed** (insert the new set, then delete only removed) so the `session_needs_speaker` trigger never blocks a removal. +- **Service sessions:** every registered **staff** member is linked as a speaker + (via `_assign_service_session_speakers`) โ€” a service session has no individual + speaker, so the whole staff team "owns" it. - Linking a speaker fires `session_speakers_speaker_promote`, which promotes an existing registration to `speaker`. **No registrations are created** โ€” the ticket sync does that (checking `session_speakers` by email). @@ -233,8 +243,10 @@ extra step: 1. **Speakers โ†’ contacts** (matched by email; also sets `linkedin_url`). 2. **Sessions + agenda** โ€” slots are typed from `is_service_session` - (`service_session` for breaks/lunch/closing, else `session`), sessions - upserted by `external_id`, speaker links diffed. + (`service_session` for breaks/lunch/closing/plenums, else `session`), sessions + upserted by `external_id`, speaker links diffed. **Service sessions** also get + every registered **staff** member linked as a speaker (via + `_assign_service_session_speakers`). 3. **Speaker registrations** โ€” for every speaker, creates a `speaker` registration or updates an existing `attendee` one to `speaker` (`on conflict (event_id, contact_email)`). **Never overrides `staff` / @@ -262,10 +274,16 @@ extra step: All are `security definer` so they can read `contacts` / `registrations` / `session_speakers` inside RLS checks and RPC guards. +## Internal helpers + +| Function | Returns | Meaning | +|---|---|---| +| `_assign_service_session_speakers(p_session_id, p_event_id)` | `integer` | Links **every registered staff member** of the event as a speaker of the given session (`on conflict do nothing`). Returns the number of rows affected. Called by both Sessionize sync RPCs for `service_session` sessions โ€” a service session has no individual speaker, so the whole staff team "owns" it. | + ## Error handling RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot connect with yourself`, `staff or admin only`, `you must be checked in to this -session to give feedback`, `not a speaker of this session`). The frontend -surfaces these via toasts โ€” see +session to give feedback`, `not a speaker of this session`, `service sessions +cannot be checked in`). The frontend surfaces these via toasts โ€” see [../frontend/api-client.md](../frontend/api-client.md). diff --git a/docs/backend/schema.md b/docs/backend/schema.md index b7e452e..b09bde6 100644 --- a/docs/backend/schema.md +++ b/docs/backend/schema.md @@ -136,7 +136,7 @@ Unpaid sponsors are hidden from non-admins (RLS). |---|---|---| | `id` | `integer` PK | `nextval('slots_id_seq')` default โ€” the UI/sidecar can create a slot **without** supplying an id (the seed inserts explicit ids and re-syncs the sequence) | | `event_id` | `uuid` FK โ†’ `events` | `on delete cascade` | -| `type` | `slot_type` (enum) | **`session` \| `service_session`** (default `session`) โ€” a true optionset, not freetext. `service_session` = breaks / lunch / closing (Sessionize's `isServiceSession`) | +| `type` | `slot_type` (enum) | **`session` \| `service_session`** (default `session`) โ€” a true optionset, not freetext. `service_session` = breaks / lunch / closing / plenums (Sessionize's `isServiceSession` **or** `isPlenumSession`) | | `name` | `text` | e.g. "Slot 09:00โ€“09:45" / "Service Session" | | `slot_date` | `date` | | | `start_time` / `end_time` | `time` | | diff --git a/docs/backend/sidecar.md b/docs/backend/sidecar.md index fce76c0..2e7d1b7 100644 --- a/docs/backend/sidecar.md +++ b/docs/backend/sidecar.md @@ -26,14 +26,22 @@ date/start/end + `session_speakers` links). The public `/view/` payload has no speaker emails, so this path imports sessions + agenda but **skips speakers** (unless an authenticated `/api/` endpoint + key is configured). +> **Service sessions.** A session is flagged `is_service_session` when +> Sessionize marks it `isServiceSession` **or** `isPlenumSession` (a plenum is a +> full-hall item โ€” breaks, lunch, closing, or a plenary โ€” with no individual +> speaker). The RPC then types its slot `service_session` and links every +> registered **staff** member as a speaker. + **B. Excel import** (`POST /import-excel`) โ€” the admin uploads the Sessionize **"Sessions and speakers (advanced)"** `.xlsx` export (generated on the fly by any organizer with admin access to the event). The sidecar parses it (two sheets: *Accepted sessions* + *Accepted speakers*) and calls the `sync_sessionize_excel` RPC, which imports, in order: (1) speakers as contacts (matched by **email** โ€” the Excel carries emails, so this is reliable), (2) -sessions + agenda (slots typed `session` / `service_session` from -`isServiceSession` + `session_speakers` links), and (3) **a `speaker` +sessions + agenda (slots typed `session` / `service_session` from the +**Session Format** column โ€” `service`/`break`/`lunch`/`closing`/`plenum` โ†’ +`service_session` โ€” + `session_speakers` links, with every registered **staff** +member linked as a speaker of service sessions), and (3) **a `speaker` registration for every speaker** (create, or update `attendee`โ†’`speaker`; never overrides `staff`/`sponsor`). This is the path that creates the missing speaker contacts + registrations. diff --git a/docs/frontend/app-structure.md b/docs/frontend/app-structure.md index bc8ec38..c5c4d89 100644 --- a/docs/frontend/app-structure.md +++ b/docs/frontend/app-structure.md @@ -71,27 +71,70 @@ interface EventData { ## The event clock (`lib/time.ts`) -The app uses a **simulated "now"** so the demo always looks mid-event: +The app uses a **simulated "now"** so the demo always looks mid-event โ€” it does +**not** use the real system date: ```ts -export const EVENT_DATE = '2026-10-23'; +export const EVENT_DATE = '2026-02-20'; export const DEFAULT_NOW = new Date(`${EVENT_DATE}T10:20:00`); ``` -At `10:20`, **Slot 1 (09:00โ€“09:45) is `done`** and **Slot 2 (10:00โ€“10:45) is -`now`** โ€” matching the mockup. Helpers: +`EVENT_DATE` matches the seed's event day. `DEFAULT_NOW` is frozen at **10:20 on +the event day**, so the demo shows a live session no matter what the actual +calendar date is (open it on 25 Aug 2026 and it still looks like it's 10:20 on +20 Feb). + +### How "Live" / "Up next" / "Done" is decided + +`slotStatus(slot, now)` compares the slot's start/end against `now` (the +simulated clock, **not** `new Date()`): + +```ts +export function slotStatus(slot: Slot, now: Date): SlotStatus { + if (now >= slotEnd(slot)) return 'done'; // slot ended before "now" + if (now >= slotStart(slot)) return 'now'; // "now" is inside the slot โ†’ Live + return 'next'; // slot starts after "now" โ†’ Up next +} +``` + +`useEvent()` exposes `now: DEFAULT_NOW`, and the screens derive: +- **current** (the **Now** card) = the first slot where `slotStatus === 'now'` +- **next** (the **Next** card) = the first slot where `slotStatus === 'next'` + +At the frozen `10:20`, the seed's slots resolve to: + +| Slot | Time | `slotStatus` at 10:20 | +|---|---|---| +| Slot 1 | 09:15โ€“10:00 | `done` | +| Slot 2 | 10:15โ€“11:00 | `now` โ†’ **โ— Live** | +| Slot 3 | 11:15โ€“12:00 | `next` โ†’ **Up next** | +| Slot 4+ | โ€ฆ | `next` โ†’ **Up next** | + +So the Home screen shows a live Now card, an upcoming Next card, and a done slot +that can carry a pending-feedback nudge. + +> **Why a simulated clock?** The event day (20 Feb 2026) is in the past relative +> to "today", so a real clock would mark **every** slot `done` โ€” there'd be no +> Live or Next card, just a wall of "Done". The frozen clock is what keeps the +> demo looking alive on any date. + +> **Using the real clock.** This is a **frontend-only** concern โ€” the database +> stores real slot times; the clock only decides which slot is "live" for +> display. To drive it off the real date, replace `DEFAULT_NOW` with +> `new Date()`. For a demo you'll show on arbitrary dates, a good middle ground +> is: use `new Date()` when the event day is still in the future/present, and +> fall back to the simulated mid-event clock once the event day has passed. + +Helpers: | Function | Returns | |---|---| | `slotStatus(slot, now)` | `'done'` \| `'now'` \| `'next'` | +| `slotStart(slot)` / `slotEnd(slot)` | `Date` for the slot's start / end | | `fmtTime(time)` | `"09:00"` from `"09:00:00"` | | `fmtRange(slot)` | `"09:00โ€“09:45"` | | `greeting(now)` | "Good morning" / "afternoon" / "evening" | -> This is a **frontend-only** concern. The database stores real slot times; the -> clock just decides which slot is "live" for display. To use the real clock, -> replace `DEFAULT_NOW` with `new Date()`. - ## The polling hook (`lib/usePolling.ts`) `usePolling(fn, ms, enabled)` runs `fn` every `ms` milliseconds, but **only while diff --git a/docs/frontend/screens.md b/docs/frontend/screens.md index 094a43c..bb62245 100644 --- a/docs/frontend/screens.md +++ b/docs/frontend/screens.md @@ -47,49 +47,77 @@ A 3-step flow: **splash โ†’ scan โ†’ confirm**. The landing screen. Shows: - **Greeting + pills** โ€” "Good morning, Ana ๐Ÿ‘‹" and, to the right, a **red material pill** `๐Ÿ“Ž {n}` (only for speakers who have one or more of their - sessions without material โ€” tapping it opens a popup listing the pending - sessions) and the **points pill** `โšก {points}` (tapping opens the Leaderboard). - The event name (`event.name`) is shown under the greeting. + **non-service** sessions without material โ€” tapping it opens a popup listing + the pending sessions) and the **points pill** `โšก {points}` (tapping opens the + Leaderboard). The event name (`event.name`) is shown under the greeting. +- **Pending-feedback pill** โ€” a full-width **"โญ Rate your last session"** (or + "Rate N sessions") button, shown only when the user is checked into one or more + **over** sessions, is **not** the speaker of that session, and **hasn't** + submitted feedback for it yet. It stays while feedback is pending and disappears + once submitted. Tapping goes to the Agenda (where the "Give feedback โญ" button + lives on the session sheet). - **Now card** โ€” **always shown** for the current slot. If the user has a pick, - the session title + a "โœ“ Checked in" / "Show your QR to staff to check in" - pill; otherwise a "No pick yet" placeholder (identical layout for every role). -- **Next card** โ€” **always shown** for the next slot (pick or "No pick yet"). -- **My picks today** โ€” shows only **2 rows** (the current slot's pick + the next - slot's pick). "tap to change" is a **hyperlink** to the Agenda. + the picked session's title + room + speaker + a "โœ“ Checked in" / "Show your QR + to staff to check in" pill. **If there's no pick, the card still shows what's + running** โ€” one clean sub-section per concurrent session (title + room + + speaker), so a slot with 1, 2, or 3 sessions renders 1, 2, or 3 sub-sections. + If the slot has no sessions at all, a "Nothing scheduled right now." line. +- **Next card** โ€” **always shown** for the next slot (same pick / concurrent-list + logic as the Now card, without the check-in pill). +- **My picks today** โ€” one row per pick the user has made **today** (in slot + order), each showing the slot time + session title + room. "tap to change" is a + **hyperlink** to the Agenda. With no picks, a "No picks yet" line. - **Quick actions** โ€” Scan & connect, Agenda, Connections, Leaderboard. - **No active event** โ€” a graceful empty state ("No active event right now. Check back soon!"). > **Identical for every role.** The Home screen (and the tab bar) is the same for > attendees and staff โ€” no role badge, no "Check-in" relabel. The Now/Next cards -> always render (with a "No pick yet" placeholder when there's no pick), so the -> layout is identical whether or not the user has picks. Staff keep their check-in -> capability inside the **Scan** screen (Attendee/Staff mode toggle). +> always render (with a concurrent-session list or "Nothing scheduled" when there's +> no pick), so the layout is identical whether or not the user has picks. Staff +> keep their check-in capability inside the **Scan** screen (Attendee/Staff mode +> toggle). Data: `useEvent()` (event + agenda + clock) + `getMyPreferences()` + `getMyCheckins(email)` + `getMySpeakerSessions(email)` (for the pending-material -pill). Slot status comes from `slotStatus(slot, now)` +pill) + `getMyFeedback(email)` (for the pending-feedback pill). Slot status comes +from `slotStatus(slot, now)` ([app-structure.md#the-event-clock](./app-structure.md#the-event-clock)). ## Agenda -Lists all slots, each with its sessions, a **slot-type badge** (keynote / session -/ lunch break / coffee break / close up), and a status pill (**Done / โ— Live / -Up next**). The user's pick per slot is highlighted (filled check). A session the -user speaks shows a **"๐ŸŽค you"** tag; a session with material shows a **๐Ÿ“Ž**. +Lists all slots, each with its sessions, a **slot-type badge** (**Session** / +**Service Session** โ€” the `slot_type` enum, capitalized), and a status pill +(**Done / โ— Live / Up next**). The user's pick per slot is highlighted (filled +check). A session the user speaks shows a **"๐ŸŽค you"** tag; a session with +material shows a **๐Ÿ“Ž**. + +**Service sessions** (breaks / lunch / closing / plenums) are treated +differently: +- the **pick circle (โœ“) is hidden** โ€” they can't be picked (the sheet shows + "No pick needed for this slot." instead of the pick button); +- the **๐ŸŽค mic emoji is never shown** (neither the "๐ŸŽค you" tag nor the mic in + the speaker pill) โ€” service sessions have no individual speaker; +- they have **no material requirement** (the pending-material notice never + applies to them). - **Tap a session** โ†’ opens a bottom **sheet** with details (description, speakers, room, capacity, checked-in state) and actions: - **Give feedback โญ** โ€” only when the session is *done* **and** the user is checked in. Opens the Feedback takeover (`openFeedback(sessionId)`). + - **Speaker feedback review** โ€” when the user is a **speaker** of the session + **and** the session is *done*, a **"โญ Your session feedback"** block shows the + session's **average rating** (stars + number) and the **AI-generated summary** + (`ai_generated_feedback`). It is **never shown while the session is still + running** โ€” only after it's over. - **Pick / Remove my pick** โ€” `setPreference(sessionId)` / `clearPreference(slotId)`. - - **Speaker material** โ€” if the user is a speaker of the session and no material - is uploaded yet, a **non-dismissible** "๐Ÿ“Ž Upload your session material" notice - with a file input. Uploading stores the file in the `materials` bucket and - calls `set_session_material` (via `uploadSessionMaterial`). Once uploaded, the - notice is gone and a **๐Ÿ“Ž Download material** button appears (visible to **all** - attendees), pinned to the **bottom** of the sheet's button stack (below - "Pick this session"). + - **Speaker material** โ€” if the user is a speaker of a **non-service** session + and no material is uploaded yet, a **non-dismissible** "๐Ÿ“Ž Upload your session + material" notice with a file input. Uploading stores the file in the + `materials` bucket and calls `set_session_material` (via + `uploadSessionMaterial`). Once uploaded, the notice is gone and a **๐Ÿ“Ž + Download material** button appears (visible to **all** attendees), pinned to + the **bottom** of the sheet's button stack (below "Pick this session"). - **Remove material** โ€” a speaker of the session can also **๐Ÿ—‘ Remove material** (to re-upload). This deletes the storage object and clears `material_path` via `set_session_material` (null) โ€” `removeSessionMaterial`. @@ -112,10 +140,13 @@ is role-aware โ€” staff (`contact.is_admin`) default to **Staff** mode, attendee yourself. Result toast reflects the connection status (sent / already connected). - **Staff mode (check-in):** a **check-in type toggle** (uiverse switch) switches between two sub-modes: - - **Session check-in** (default) โ€” pick a session (dropdown grouped by slot), - then scan an attendee's lanyard โ†’ `checkinAttendee(sessionId, qr)`. Shows a - result sheet: "โœ“ {name} โ€” Checked in โ€” +10 pts ยท now {total}" or "โš ๏ธ Already - checked in โ€” no extra points" (the `already` flag from the RPC). + - **Session check-in** (default) โ€” pick a session (dropdown grouped by slot, + **service sessions excluded** โ€” they can't be checked into), then scan an + attendee's lanyard โ†’ `checkinAttendee(sessionId, qr)`. Shows a result sheet: + "โœ“ {name} โ€” Checked in โ€” +10 pts ยท now {total}" or "โš ๏ธ Already checked in โ€” + no extra points" (the `already` flag from the RPC). The `checkin_attendee` + RPC also rejects a service session server-side ("service sessions cannot be + checked in"). - **Welcome check-in** โ€” no session dropdown; scanning an attendee's lanyard โ†’ `welcomeCheckin(qr)` marks them present at the **event** (`registrations.checked_in = true`, no points). Result sheet: "๐Ÿ‘‹ {name} โ€” diff --git a/docs/next-steps.md b/docs/next-steps.md index 3df264b..1475e8c 100644 --- a/docs/next-steps.md +++ b/docs/next-steps.md @@ -31,7 +31,16 @@ current phase. > speaker contacts, session links, and `speaker` registrations by email; `slots.type` > is now a `session`/`service_session` enum; the seed uses the real Global Power > Platform Bootcamp (Austria) agenda + 50 attendees + 4 staff, with the event's -> endpoint set and speakers added via the Excel import). +> endpoint set and speakers added via the Excel import), and +> **Service sessions + Home redesign + feedback loop** (a session is a +> `service_session` when Sessionize marks it `isServiceSession` **or** +> `isPlenumSession`; service sessions can't be checked in, have every registered +> staff member as their speaker, no material requirement, and no mic emoji; the +> Home Now/Next cards show **all concurrent sessions** as sub-sections when there's +> no pick; attendees who attended an over session (and aren't its speaker) get a +> pending-feedback pill on Home that clears once they rate it; and a session's +> speaker can see the rating + AI summary for their own session only after it's +> over). > Remaining work is cross-cutting (real event clock, deployment, testing, and the > ticket/Pretix sync that will consume the speaker links by email). @@ -429,6 +438,40 @@ Migration `20260829000000_registration_type_optionset_speaker_promote_welcome_ch - Bruno and Rita now have `contacts.password = 'appe-admin-2026'` so the Convivo **staff QR login** (QR + staff password) works out of the box after a reset. +## Service sessions + Home redesign + feedback loop โ€” โœ… complete + +**Service sessions (new slot semantics).** A session is a `service_session` when +Sessionize marks it `isServiceSession` **or** `isPlenumSession` (the sidecar maps +both; the Excel path matches `service`/`break`/`lunch`/`closing`/`plenum` in the +Session Format column). Service sessions: +- **can't be checked in** โ€” `checkin_attendee` raises `service sessions cannot be + checked in`, and the Scan check-in dropdown excludes them. +- **have every registered staff member as their speaker** โ€” both sync RPCs call + the new `_assign_service_session_speakers` helper for service sessions. +- **have no material requirement** โ€” excluded from the pending-material pill and + the Agenda upload notice. +- **never show the mic emoji** โ€” no "๐ŸŽค you" tag and no mic in the speaker pill. + +**Home redesign.** The **Now** and **Next** cards now show **all concurrent +sessions** as clean sub-sections (title + room + speaker) when the user has no +pick โ€” so a slot with 1, 2, or 3 sessions renders 1, 2, or 3 sub-sections โ€” and +fall back to "Nothing scheduled" when the slot is empty. **My picks today** lists +every pick the user has made (in slot order) with a "No picks yet" empty state. +The demo clock (`EVENT_DATE`) now matches the seed's event day (2026-02-20) so a +slot is live. + +**Feedback loop.** +- **Attendee:** anyone checked into an **over** session (any registration type, + **except** the session's own speaker) sees a **"โญ Rate your last session"** pill + on Home while feedback is pending; it disappears once they submit. +- **Speaker:** a session's speaker can see the **rating + AI summary** for their + own session in the Agenda sheet โ€” **only after the session is over**, never + during. + +**Migration:** [`20260833000000_service_sessions_feedback.sql`](../../supabase/migrations/20260833000000_service_sessions_feedback.sql) +adds `_assign_service_session_speakers`, re-creates `checkin_attendee` (service +guard) and both sync RPCs (service-session typing + staff speakers). + ## Cross-cutting / later - **Real event clock** โ€” replace the simulated `DEFAULT_NOW` diff --git a/supabase/migrations/20260833000000_service_sessions_feedback.sql b/supabase/migrations/20260833000000_service_sessions_feedback.sql new file mode 100644 index 0000000..0c4dd75 --- /dev/null +++ b/supabase/migrations/20260833000000_service_sessions_feedback.sql @@ -0,0 +1,511 @@ +-- ============================================================================= +-- Convivo โ€” Service sessions + feedback semantics +-- +-- A "service session" (slot_type = 'service_session') is a full-hall agenda +-- item: a break, lunch, closing, or a plenum (Sessionize's isPlenumSession). +-- The sidecar now maps isServiceSession OR isPlenumSession to it. This +-- migration gives service sessions their distinct semantics: +-- +-- 1. No check-in. `checkin_attendee` rejects a service session outright +-- (there is nothing to check into โ€” everyone is in the room). +-- 2. All registered staff are automatically the speakers. A helper +-- `_assign_service_session_speakers` links every 'staff' registration to +-- the session; both sync RPCs call it for service sessions. +-- 3. No material requirement. (Handled in the UI: service sessions are +-- excluded from the pending-material list and the mic/material affordances.) +-- +-- The two Sessionize sync RPCs are re-created (append-only migrations can't +-- edit the originals): +-- * sync_sessionize_event โ€” now reads is_service_session so API-synced slots +-- get the correct type/name (previously always 'session'), and assigns +-- staff speakers to service sessions. +-- * sync_sessionize_excel โ€” already typed slots from is_service_session; now +-- also assigns staff speakers to service sessions. +-- ============================================================================= + +-- ----------------------------------------------------------------------------- +-- 1. HELPER: link every registered staff member to a service session. +-- Idempotent (on conflict do nothing). Returns the number of rows affected. +-- ----------------------------------------------------------------------------- +create or replace function public._assign_service_session_speakers(p_session_id uuid, p_event_id uuid) +returns integer +language plpgsql security definer set search_path = public as $$ +declare + v_count integer := 0; +begin + insert into public.session_speakers (session_id, contact_email) + select p_session_id, r.contact_email + from public.registrations r + where r.event_id = p_event_id and r.type = 'staff' + on conflict (session_id, contact_email) do nothing; + get diagnostics v_count = row_count; + return v_count; +end; +$$; + +-- ----------------------------------------------------------------------------- +-- 2. CHECK-IN: block service sessions. +-- Re-creates checkin_attendee (the 20260826 version) with a guard: a +-- service session cannot be checked into. +-- ----------------------------------------------------------------------------- +create or replace function public.checkin_attendee(p_session_id uuid, p_attendee_qr text) +returns table (checkin_id uuid, attendee_email text, attendee_name text, + points integer, already boolean) +language plpgsql security definer set search_path = public as $$ +declare + v_staff text := public.current_email(); + v_attendee text; + v_name text; + v_event_id uuid; + v_slot_type public.slot_type; + v_new_id uuid; + v_points integer; + v_already boolean := false; +begin + if v_staff is null then raise exception 'not authenticated'; end if; + if not public.is_staff_or_admin() then raise exception 'staff or admin only'; end if; + select r.contact_email, c.full_name into v_attendee, v_name + from public.registrations r + join public.contacts c on c.email = r.contact_email + where r.qr_token = p_attendee_qr + and r.event_id = (select id from public.events where is_active limit 1); + if v_attendee is null then raise exception 'no attendee found for that QR code'; end if; + select se.event_id, s.type into v_event_id, v_slot_type + from public.sessions se + join public.slots s on s.id = se.slot_id + where se.id = p_session_id; + if v_event_id is null then raise exception 'session not found'; end if; + if v_slot_type = 'service_session' then + raise exception 'service sessions cannot be checked in'; + end if; + insert into public.checkins (event_id, contact_email, session_id, staff_email) + values (v_event_id, v_attendee, p_session_id, v_staff) + on conflict (event_id, contact_email, session_id) do nothing + returning id into v_new_id; + if v_new_id is null then + v_already := true; + select id into v_new_id from public.checkins + where event_id = v_event_id and contact_email = v_attendee and session_id = p_session_id; + else + perform public._award_points(v_event_id, v_attendee, 10, 'checkin'); + update public.registrations set checked_in = true + where event_id = v_event_id and contact_email = v_attendee; + end if; + select r.points into v_points from public.registrations r + where r.event_id = v_event_id and r.contact_email = v_attendee; + return query select v_new_id, v_attendee, v_name, coalesce(v_points, 0), v_already; +end; +$$; + +-- ----------------------------------------------------------------------------- +-- 3. API SYNC: type slots from is_service_session + assign staff speakers. +-- Re-creates sync_sessionize_event (the 20260831 version). The only changes: +-- * reads is_service_session from the payload, +-- * creates the slot with the correct type + name, +-- * calls _assign_service_session_speakers for service sessions. +-- ----------------------------------------------------------------------------- +create or replace function public.sync_sessionize_event(p_event_id uuid, p_payload jsonb) +returns jsonb +language plpgsql security definer set search_path = public as $$ +declare + v_run_id uuid; + v_started timestamptz := now(); + v_item jsonb; + v_email text; + v_name text; + v_ext text; + v_title text; + v_desc text; + v_room text; + v_date date; + v_start time; + v_end time; + v_service boolean; + v_slot public.slots; + v_slot_id integer; + v_session public.sessions; + v_existing boolean; + v_spk text; + v_speakers_created integer := 0; + v_speakers_updated integer := 0; + v_sessions_created integer := 0; + v_sessions_updated integer := 0; + v_slots_created integer := 0; + v_speakers_linked integer := 0; + v_errors jsonb := '[]'::jsonb; + v_err text; +begin + if coalesce(auth.jwt() ->> 'role', '') <> 'service_role' then + raise exception 'service_role only'; + end if; + if not exists (select 1 from public.events where id = p_event_id) then + raise exception 'event not found'; + end if; + insert into public.sync_runs (event_id, source, started_at, triggered_by) + values (p_event_id, 'sessionize', v_started, 'service_role') + returning id into v_run_id; + + -- (1) Speakers -> contacts (matched by email). + for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'speakers', '[]'::jsonb)) + loop + begin + v_email := v_item ->> 'email'; + v_name := v_item ->> 'full_name'; + v_ext := v_item ->> 'external_id'; + if v_email is null or btrim(v_email) = '' or v_name is null or btrim(v_name) = '' then + continue; + end if; + select exists (select 1 from public.contacts where email = v_email) into v_existing; + insert into public.contacts (email, full_name, external_id) + values (v_email, v_name, v_ext) + on conflict (email) do update + set full_name = excluded.full_name, + external_id = coalesce(excluded.external_id, public.contacts.external_id); + perform public._ensure_auth_user_exists(v_email, v_name); + if v_existing then + v_speakers_updated := v_speakers_updated + 1; + else + v_speakers_created := v_speakers_created + 1; + end if; + exception when others then + v_err := coalesce(v_email, '') || ': ' || sqlerrm; + v_errors := v_errors || to_jsonb(v_err); + end; + end loop; + + -- (2) Sessions + (3) agenda (slots + speaker links). + for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'sessions', '[]'::jsonb)) + loop + begin + v_ext := v_item ->> 'external_id'; + v_title := v_item ->> 'title'; + v_desc := v_item ->> 'description'; + v_room := v_item ->> 'room'; + v_date := (v_item ->> 'date')::date; + v_start := (v_item ->> 'start_time')::time; + v_end := (v_item ->> 'end_time')::time; + v_service := coalesce((v_item ->> 'is_service_session')::boolean, false); + + if v_ext is null or v_title is null or v_date is null or v_start is null or v_end is null then + v_errors := v_errors || to_jsonb(coalesce(v_title, '') || ': missing required field'); + continue; + end if; + + -- Find or create the slot by (event, date, start, end). + select * into v_slot from public.slots + where event_id = p_event_id and slot_date = v_date + and start_time = v_start and end_time = v_end + limit 1; + if not found then + select greatest(nextval('public.slots_id_seq'), + (select coalesce(max(id), 0) from public.slots) + 1) + into v_slot_id; + perform setval('public.slots_id_seq', v_slot_id, true); + insert into public.slots (id, event_id, type, name, slot_date, start_time, end_time) + values (v_slot_id, p_event_id, + case when v_service then 'service_session'::public.slot_type + else 'session'::public.slot_type end, + case when v_service then 'Service Session' + else 'Slot ' || to_char(v_start, 'HH24:MI') || 'โ€“' || to_char(v_end, 'HH24:MI') end, + v_date, v_start, v_end) + returning * into v_slot; + v_slots_created := v_slots_created + 1; + end if; + + -- Upsert the session by external_id. + select exists (select 1 from public.sessions + where event_id = p_event_id and external_id = v_ext) into v_existing; + insert into public.sessions (event_id, slot_id, title, description, room, external_id) + values (p_event_id, v_slot.id, v_title, v_desc, v_room, v_ext) + on conflict (external_id) where external_id is not null do update + set slot_id = excluded.slot_id, + title = excluded.title, + description = coalesce(excluded.description, public.sessions.description), + room = coalesce(excluded.room, public.sessions.room) + returning * into v_session; + if v_existing then + v_sessions_updated := v_sessions_updated + 1; + else + v_sessions_created := v_sessions_created + 1; + end if; + + -- (3) Speaker links: DIFF (insert the new set, then delete only removed). + for v_spk in select * from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb)) + loop + if v_spk is null or btrim(v_spk) = '' then + continue; + end if; + insert into public.session_speakers (session_id, contact_email) + values (v_session.id, v_spk) + on conflict (session_id, contact_email) do nothing; + v_speakers_linked := v_speakers_linked + 1; + end loop; + if (select count(*) from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb))) > 0 then + delete from public.session_speakers ss + where ss.session_id = v_session.id + and not exists ( + select 1 from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb)) as e + where e = ss.contact_email + ); + end if; + + -- Service sessions: every registered staff member is a speaker. + if v_service then + perform public._assign_service_session_speakers(v_session.id, p_event_id); + end if; + exception when others then + v_err := coalesce(v_title, '') || ': ' || sqlerrm; + v_errors := v_errors || to_jsonb(v_err); + end; + end loop; + + update public.sync_runs + set finished_at = now(), + created = v_speakers_created + v_sessions_created + v_slots_created, + updated = v_speakers_updated + v_sessions_updated, + skipped = 0, + error = case when jsonb_array_length(v_errors) > 0 then v_errors::text else null end + where id = v_run_id; + + update public.events set last_synced_at = now() where id = p_event_id; + + return jsonb_build_object( + 'speakers_created', v_speakers_created, + 'speakers_updated', v_speakers_updated, + 'sessions_created', v_sessions_created, + 'sessions_updated', v_sessions_updated, + 'slots_created', v_slots_created, + 'speakers_linked', v_speakers_linked, + 'errors', v_errors + ); +end; +$$; + +-- ----------------------------------------------------------------------------- +-- 4. EXCEL SYNC: assign staff speakers to service sessions. +-- Re-creates sync_sessionize_excel (the 20260832 version). The only change: +-- after linking the provided speakers, service sessions also get every +-- registered staff member as a speaker. +-- ----------------------------------------------------------------------------- +create or replace function public.sync_sessionize_excel(p_event_id uuid, p_payload jsonb) +returns jsonb +language plpgsql security definer set search_path = public as $$ +declare + v_run_id uuid; + v_started timestamptz := now(); + v_item jsonb; + v_email text; + v_name text; + v_ext text; + v_linkedin text; + v_title text; + v_desc text; + v_room text; + v_date date; + v_start time; + v_end time; + v_service boolean; + v_slot public.slots; + v_slot_id integer; + v_session public.sessions; + v_existing boolean; + v_spk text; + v_speakers_created integer := 0; + v_speakers_updated integer := 0; + v_sessions_created integer := 0; + v_sessions_updated integer := 0; + v_slots_created integer := 0; + v_speakers_linked integer := 0; + v_regs_created integer := 0; + v_regs_updated integer := 0; + v_errors jsonb := '[]'::jsonb; + v_err text; +begin + if coalesce(auth.jwt() ->> 'role', '') <> 'service_role' then + raise exception 'service_role only'; + end if; + if not exists (select 1 from public.events where id = p_event_id) then + raise exception 'event not found'; + end if; + insert into public.sync_runs (event_id, source, started_at, triggered_by) + values (p_event_id, 'sessionize_excel', v_started, 'service_role') + returning id into v_run_id; + + -- (1) Speakers -> contacts (matched by email). + for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'speakers', '[]'::jsonb)) + loop + begin + v_email := v_item ->> 'email'; + v_name := v_item ->> 'full_name'; + v_ext := v_item ->> 'external_id'; + v_linkedin := v_item ->> 'linkedin_url'; + if v_email is null or btrim(v_email) = '' or v_name is null or btrim(v_name) = '' then + continue; + end if; + select exists (select 1 from public.contacts where email = v_email) into v_existing; + insert into public.contacts (email, full_name, external_id, linkedin_url) + values (v_email, v_name, v_ext, v_linkedin) + on conflict (email) do update + set full_name = excluded.full_name, + external_id = coalesce(excluded.external_id, public.contacts.external_id), + linkedin_url = coalesce(excluded.linkedin_url, public.contacts.linkedin_url); + perform public._ensure_auth_user_exists(v_email, v_name); + if v_existing then + v_speakers_updated := v_speakers_updated + 1; + else + v_speakers_created := v_speakers_created + 1; + end if; + exception when others then + v_err := coalesce(v_email, '') || ': ' || sqlerrm; + v_errors := v_errors || to_jsonb(v_err); + end; + end loop; + + -- (2) Sessions + agenda (slots + speaker links). + for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'sessions', '[]'::jsonb)) + loop + begin + v_ext := v_item ->> 'external_id'; + v_title := v_item ->> 'title'; + v_desc := v_item ->> 'description'; + v_room := v_item ->> 'room'; + v_date := (v_item ->> 'date')::date; + v_start := (v_item ->> 'start_time')::time; + v_end := (v_item ->> 'end_time')::time; + v_service := coalesce((v_item ->> 'is_service_session')::boolean, false); + + if v_ext is null or v_title is null or v_date is null or v_start is null or v_end is null then + v_errors := v_errors || to_jsonb(coalesce(v_title, '') || ': missing required field'); + continue; + end if; + + -- Find or create the slot by (event, date, start, end). + select * into v_slot from public.slots + where event_id = p_event_id and slot_date = v_date + and start_time = v_start and end_time = v_end + limit 1; + if not found then + select greatest(nextval('public.slots_id_seq'), + (select coalesce(max(id), 0) from public.slots) + 1) + into v_slot_id; + perform setval('public.slots_id_seq', v_slot_id, true); + insert into public.slots (id, event_id, type, name, slot_date, start_time, end_time) + values (v_slot_id, p_event_id, + case when v_service then 'service_session'::public.slot_type + else 'session'::public.slot_type end, + case when v_service then 'Service Session' + else 'Slot ' || to_char(v_start, 'HH24:MI') || 'โ€“' || to_char(v_end, 'HH24:MI') end, + v_date, v_start, v_end) + returning * into v_slot; + v_slots_created := v_slots_created + 1; + end if; + + -- Upsert the session by external_id. + select exists (select 1 from public.sessions + where event_id = p_event_id and external_id = v_ext) into v_existing; + insert into public.sessions (event_id, slot_id, title, description, room, external_id) + values (p_event_id, v_slot.id, v_title, v_desc, v_room, v_ext) + on conflict (external_id) where external_id is not null do update + set slot_id = excluded.slot_id, + title = excluded.title, + description = coalesce(excluded.description, public.sessions.description), + room = coalesce(excluded.room, public.sessions.room) + returning * into v_session; + if v_existing then + v_sessions_updated := v_sessions_updated + 1; + else + v_sessions_created := v_sessions_created + 1; + end if; + + -- Speaker links: DIFF (insert the new set, then delete only removed). + for v_spk in select * from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb)) + loop + if v_spk is null or btrim(v_spk) = '' then + continue; + end if; + insert into public.session_speakers (session_id, contact_email) + values (v_session.id, v_spk) + on conflict (session_id, contact_email) do nothing; + v_speakers_linked := v_speakers_linked + 1; + end loop; + if (select count(*) from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb))) > 0 then + delete from public.session_speakers ss + where ss.session_id = v_session.id + and not exists ( + select 1 from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb)) as e + where e = ss.contact_email + ); + end if; + + -- Service sessions: every registered staff member is a speaker. + if v_service then + perform public._assign_service_session_speakers(v_session.id, p_event_id); + end if; + exception when others then + v_err := coalesce(v_title, '') || ': ' || sqlerrm; + v_errors := v_errors || to_jsonb(v_err); + end; + end loop; + + -- (3) Speaker registrations: create/update to 'speaker' for every speaker. + for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'speakers', '[]'::jsonb)) + loop + begin + v_email := v_item ->> 'email'; + if v_email is null or btrim(v_email) = '' then + continue; + end if; + if not exists (select 1 from public.contacts where email = v_email) then + continue; + end if; + select exists (select 1 from public.registrations + where event_id = p_event_id and contact_email = v_email) into v_existing; + insert into public.registrations (event_id, contact_email, type) + values (p_event_id, v_email, 'speaker'::public.registration_type) + on conflict (event_id, contact_email) do update + set type = case when public.registrations.type in ('staff', 'sponsor') + then public.registrations.type + else 'speaker'::public.registration_type end + where public.registrations.type not in ('staff', 'sponsor'); + if v_existing then + v_regs_updated := v_regs_updated + 1; + else + v_regs_created := v_regs_created + 1; + end if; + exception when others then + v_err := coalesce(v_email, '') || ': ' || sqlerrm; + v_errors := v_errors || to_jsonb(v_err); + end; + end loop; + + update public.sync_runs + set finished_at = now(), + created = v_speakers_created + v_sessions_created + v_slots_created + v_regs_created, + updated = v_speakers_updated + v_sessions_updated + v_regs_updated, + skipped = 0, + error = case when jsonb_array_length(v_errors) > 0 then v_errors::text else null end + where id = v_run_id; + + update public.events set last_synced_at = now() where id = p_event_id; + + return jsonb_build_object( + 'speakers_created', v_speakers_created, + 'speakers_updated', v_speakers_updated, + 'sessions_created', v_sessions_created, + 'sessions_updated', v_sessions_updated, + 'slots_created', v_slots_created, + 'speakers_linked', v_speakers_linked, + 'registrations_created', v_regs_created, + 'registrations_updated', v_regs_updated, + 'errors', v_errors + ); +end; +$$; + +-- ----------------------------------------------------------------------------- +-- 5. GRANTS +-- ----------------------------------------------------------------------------- +grant execute on function public._assign_service_session_speakers(uuid, uuid) to service_role; +grant execute on function public.checkin_attendee(uuid, text) to authenticated; +grant execute on function public.sync_sessionize_event(uuid, jsonb) to service_role; +grant execute on function public.sync_sessionize_excel(uuid, jsonb) to service_role;