feat: add event-scoped schedule deletion and import date guard

This commit is contained in:
Lago committed 2026-10-10 01:44:40 +02:00
1 parent ef0121a3e4
commit 5c93d4a0cb
12 files changed
+2032 -12

No files matched your search

+5
View File
@@ -3,6 +3,7 @@ import type {
Checkin, Checkin,
Connection, Connection,
Contact, Contact,
DeleteEventScheduleResult,
Event, Event,
EventFeedback, EventFeedback,
ExcelSyncResult, ExcelSyncResult,
@@ -319,6 +320,10 @@ export async function deactivateEvent(id: string): Promise<void> {
if (error) throw new ApiError(error.message); if (error) throw new ApiError(error.message);
} }
export async function deleteEventSchedule(eventId: string): Promise<DeleteEventScheduleResult> {
return await rpc<DeleteEventScheduleResult>('delete_event_schedule', { p_event_id: eventId });
}
// ---- Points ------------------------------------------------------------------ // ---- Points ------------------------------------------------------------------
/** Admin manual points adjustment for the active event (audited as 'admin'). */ /** Admin manual points adjustment for the active event (audited as 'admin'). */
+12
View File
@@ -238,6 +238,18 @@ export interface SessionSpeaker {
contact_email: string; contact_email: string;
} }
export interface DeleteEventScheduleResult {
event_id: string;
event_name: string;
slots_deleted: number;
sessions_deleted: number;
session_speakers_deleted: number;
preferences_deleted: number;
checkins_deleted: number;
feedback_deleted: number;
material_paths_unpurged: number;
}
export type ConnectionStatus = 'pending' | 'accepted' | 'rejected'; export type ConnectionStatus = 'pending' | 'accepted' | 'rejected';
export interface Connection { export interface Connection {
+117 -10
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { supabase } from '../lib/supabase'; import { supabase } from '../lib/supabase';
import { import {
deleteEventSchedule,
evaluateSessionFeedback, evaluateSessionFeedback,
getAllContacts, getAllContacts,
getAllSessionSpeakers, getAllSessionSpeakers,
@@ -30,11 +31,25 @@ export function Schedule() {
const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null); const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null);
const [sessModal, setSessModal] = useState<{ session: Session | null; slotId: number } | null>(null); const [sessModal, setSessModal] = useState<{ session: Session | null; slotId: number } | null>(null);
const [deleteModal, setDeleteModal] = useState<{
eventId: string;
eventName: string;
slotsCount: number;
sessionsCount: number;
} | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [deleting, setDeleting] = useState(false);
const mountedRef = useRef(false);
const loadSeqRef = useRef(0);
async function load() { async function load(expectedEventId?: string) {
const seq = ++loadSeqRef.current;
try { try {
const ev = await getActiveEvent(); const ev = await getActiveEvent();
if (!mountedRef.current || seq !== loadSeqRef.current) return;
if (expectedEventId && ev?.id !== expectedEventId) {
throw new Error('Active event changed before the schedule could refresh');
}
setEvent(ev); setEvent(ev);
if (ev) { if (ev) {
const [s, ss, sp, c] = await Promise.all([ const [s, ss, sp, c] = await Promise.all([
@@ -43,20 +58,33 @@ export function Schedule() {
getAllSessionSpeakers(), getAllSessionSpeakers(),
getAllContacts(), getAllContacts(),
]); ]);
if (!mountedRef.current || seq !== loadSeqRef.current) return;
setSlots(s); setSlots(s);
setSessions(ss); setSessions(ss);
const ids = new Set(ss.map((x) => x.id)); const ids = new Set(ss.map((x) => x.id));
setSpeakers(sp.filter((x) => ids.has(x.session_id))); setSpeakers(sp.filter((x) => ids.has(x.session_id)));
setContacts(c); setContacts(c);
} else {
setSlots([]);
setSessions([]);
setSpeakers([]);
setContacts([]);
} }
setLoaded(true); setLoaded(true);
} catch (e) { } catch (e) {
if (!mountedRef.current || seq !== loadSeqRef.current) return;
setError(e instanceof Error ? e.message : 'Failed to load'); setError(e instanceof Error ? e.message : 'Failed to load');
throw e;
} }
} }
useEffect(() => { useEffect(() => {
load(); mountedRef.current = true;
void load().catch(() => {});
return () => {
mountedRef.current = false;
loadSeqRef.current++;
};
}, []); }, []);
const speakersFor = useMemo(() => { const speakersFor = useMemo(() => {
@@ -114,6 +142,38 @@ export function Schedule() {
} }
} }
async function deleteCurrentSchedule() {
const target = deleteModal;
if (!target || deleting) return;
setDeleting(true);
try {
const result = await deleteEventSchedule(target.eventId);
if (!mountedRef.current) return;
setDeleteModal(null);
try {
await load(target.eventId);
if (!mountedRef.current) return;
push(
'success',
`Deleted ${result.slots_deleted} slots and ${result.sessions_deleted} sessions from ${target.eventName}`,
);
} catch (refreshError) {
if (!mountedRef.current) return;
push(
'error',
`Schedule deleted for ${target.eventName}, but refresh failed: ${
refreshError instanceof Error ? refreshError.message : 'unknown error'
}`,
);
}
} catch (e) {
if (!mountedRef.current) return;
push('error', e instanceof Error ? e.message : 'Delete schedule failed');
} finally {
if (mountedRef.current) setDeleting(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />; if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded) if (!loaded)
return ( return (
@@ -138,6 +198,9 @@ export function Schedule() {
); );
} }
const hasSchedule = slots.length > 0 || sessions.length > 0;
const mutating = busy || deleting;
return ( return (
<div> <div>
<div className="page-head"> <div className="page-head">
@@ -147,10 +210,26 @@ export function Schedule() {
{event.name} · {slots.length} slots · {sessions.length} sessions. {event.name} · {slots.length} slots · {sessions.length} sessions.
</div> </div>
</div> </div>
<button className="btn primary" onClick={() => setSlotModal({ slot: null })}> <div className="row-actions">
<button
className="btn danger"
disabled={mutating || !hasSchedule}
onClick={() =>
setDeleteModal({
eventId: event.id,
eventName: event.name,
slotsCount: slots.length,
sessionsCount: sessions.length,
})
}
>
Delete current schedule
</button>
<button className="btn primary" disabled={mutating} onClick={() => setSlotModal({ slot: null })}>
+ New slot + New slot
</button> </button>
</div> </div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{slots.map((slot) => { {slots.map((slot) => {
@@ -168,13 +247,13 @@ export function Schedule() {
</div> </div>
</div> </div>
<div className="row-actions"> <div className="row-actions">
<button className="btn small" onClick={() => setSessModal({ session: null, slotId: slot.id })}> <button className="btn small" disabled={mutating} onClick={() => setSessModal({ session: null, slotId: slot.id })}>
+ Session + Session
</button> </button>
<button className="btn small" onClick={() => setSlotModal({ slot })}> <button className="btn small" disabled={mutating} onClick={() => setSlotModal({ slot })}>
Edit Edit
</button> </button>
<button className="btn small danger" disabled={busy} onClick={() => deleteSlot(slot)}> <button className="btn small danger" disabled={mutating} onClick={() => deleteSlot(slot)}>
Delete Delete
</button> </button>
</div> </div>
@@ -205,14 +284,14 @@ export function Schedule() {
</div> </div>
<div className="row-actions"> <div className="row-actions">
{s.ai_generated_feedback === 'Pending AI Evaluation' && ( {s.ai_generated_feedback === 'Pending AI Evaluation' && (
<button className="btn small" disabled={busy} onClick={() => doEvaluate(s)}> <button className="btn small" disabled={mutating} onClick={() => doEvaluate(s)}>
Evaluate Evaluate
</button> </button>
)} )}
<button className="btn small" onClick={() => setSessModal({ session: s, slotId: slot.id })}> <button className="btn small" disabled={mutating} onClick={() => setSessModal({ session: s, slotId: slot.id })}>
Edit Edit
</button> </button>
<button className="btn small danger" disabled={busy} onClick={() => deleteSession(s)}> <button className="btn small danger" disabled={mutating} onClick={() => deleteSession(s)}>
Delete Delete
</button> </button>
</div> </div>
@@ -238,6 +317,34 @@ export function Schedule() {
}} }}
/> />
)} )}
{deleteModal && (
<Modal
open
title="Delete current schedule"
onClose={() => {
if (!deleting) setDeleteModal(null);
}}
footer={
<>
<button className="btn" disabled={deleting} onClick={() => setDeleteModal(null)}>
Cancel
</button>
<button className="btn danger" disabled={deleting} onClick={deleteCurrentSchedule}>
{deleting ? 'Deleting…' : 'Delete schedule'}
</button>
</>
}
>
<p>
Delete the schedule for <strong>{deleteModal.eventName}</strong>?
</p>
<p className="muted">
This irreversibly deletes {deleteModal.slotsCount} slots and {deleteModal.sessionsCount} sessions, including speaker
links, preferences, check-ins and feedback. Registrations are preserved. Material file paths are removed with the
sessions, but Storage objects are not physically purged.
</p>
</Modal>
)}
{sessModal && ( {sessModal && (
<SessionModal <SessionModal
session={sessModal.session} session={sessModal.session}
+19
View File
@@ -210,6 +210,25 @@ existing uploaded `materials` object under `sessions/<this session UUID>/<filena
There is no active-event, date, check-in or points condition. Shared by Agenda and There is no active-event, date, check-in or points condition. Shared by Agenda and
the [speaker portal](../frontend/screens.md#speaker-portal). the [speaker portal](../frontend/screens.md#speaker-portal).
### `delete_event_schedule(p_event_id)` → `jsonb`
**Admin-only.** Deletes the slots and sessions for exactly one event in a single
transaction. It locks the event plus that event's schedule rows, validates that
sessions and dependent `preferences` / `checkins` / `feedback` rows do not cross
event boundaries, then deletes `sessions` and `slots` for `p_event_id`.
FK cascades remove `session_speakers`, `preferences`, `checkins` and
`feedback`. The event row, contacts, registrations, sponsors, connections,
points, leaderboard rows and other events are preserved. Session
`material_path` values disappear with the deleted session rows, but Storage
objects in the `materials` bucket are not physically purged.
The function is `security definer` with an empty `search_path`, requires both
`auth.uid()` and `public.is_admin()`, revokes execution from `PUBLIC` / `anon` /
`authenticated`, then grants execution back only to `authenticated`. It returns
counts for deleted slots, sessions and dependent rows plus the number of
material paths left unpurged. It does not coordinate with Sessionize/Pretix
sync; a concurrent or later import can repopulate the event schedule.
## Speaker Portal RPCs ## Speaker Portal RPCs
Source: [20261006175631_speaker_portal.sql](../../supabase/migrations/20261006175631_speaker_portal.sql), Source: [20261006175631_speaker_portal.sql](../../supabase/migrations/20261006175631_speaker_portal.sql),
+14
View File
@@ -50,6 +50,20 @@ contacts + registrations.
Linking a speaker to a session fires the `session_speakers_speaker_promote` Linking a speaker to a session fires the `session_speakers_speaker_promote`
trigger, which promotes an existing registration to `speaker`. trigger, which promotes an existing registration to `speaker`.
Both import paths are guarded by the event's configured `start_date` /
`end_date`: any Sessionize session dated outside that inclusive range aborts the
RPC before speakers, sessions, slots, links, registrations, audit rows, or event
sync timestamps are changed. The exception includes the bad date, the configured
range, and the actionable check to verify the Sessionize endpoint, Excel export,
or event dates. Existing historical rows outside the range are retained by later
successful imports; deleting or reconciling them is a separate, explicitly
approved data-repair task.
The date guard lives in
[`20261009225632_guard_sessionize_dates.sql`](../../supabase/migrations/20261009225632_guard_sessionize_dates.sql).
It is not automatically deployed by being present in the repository; apply it
through the normal reviewed migration path for each environment.
## How it reaches things ## How it reaches things
```mermaid ```mermaid
+43
View File
@@ -88,6 +88,49 @@ authorization separately. See [screen contract](../frontend/screens.md#speaker-p
[API client](../frontend/api-client.md#speaker-portal), [RLS](./rls.md#speaker-portal-authorization) [API client](../frontend/api-client.md#speaker-portal), [RLS](./rls.md#speaker-portal-authorization)
and [RPCs](./rpcs.md#speaker-portal-rpcs). and [RPCs](./rpcs.md#speaker-portal-rpcs).
## Sessionize Date Guard
[sessionize_date_guard_tests.sql](../../supabase/tests/sessionize_date_guard_tests.sql)
is an independent fail-fast rollback-only suite for the Sessionize API and Excel
RPC date guard. It creates generated event/contact/auth fixtures, precreates
explicit negative slot IDs so successful imports do not allocate sequence values,
and ends with `ROLLBACK`.
To verify the migration and suite together on the local database without
persisting either change:
```bash
{ printf 'BEGIN;\n'; cat supabase/migrations/20261009225632_guard_sessionize_dates.sql supabase/tests/sessionize_date_guard_tests.sql; printf '\nROLLBACK;\n'; } | docker exec -i supabase_db_Convivo psql -U postgres -d postgres -v ON_ERROR_STOP=1
```
The nested `BEGIN` warning from the suite is harmless in this rollback-only
check. This command is local validation only; it does not write CLI migration
history and is not a production deployment. Historical rows outside the newly
configured event range are retained by successful imports and need a separately
approved reconciliation if they should be removed or changed.
## Delete Event Schedule
[delete_event_schedule_tests.sql](../../supabase/tests/delete_event_schedule_tests.sql)
is an independent fail-fast rollback-only suite for the admin schedule-clear RPC.
It creates generated contacts/events/auth fixtures, uses explicit negative slot
IDs so fixture setup does not advance `slots_id_seq`, and ends with `ROLLBACK`.
To verify the migration and suite together on the local database without
persisting either change:
```bash
{ printf 'BEGIN;\n'; cat supabase/migrations/20261009231817_delete_event_schedule.sql supabase/tests/delete_event_schedule_tests.sql; printf '\nROLLBACK;\n'; } | docker exec -i supabase_db_Convivo psql -U postgres -d postgres -v ON_ERROR_STOP=1
```
The suite checks authenticated admin execution, non-admin rejection, anon
execute denial, missing-event rejection, exact delete counts, unchanged event
selection, registrations, contacts, auth users, sponsors, connections, points,
event feedback, leaderboard and other-event schedule rows. It also proves
cross-event slot/dependent mismatches fail atomically instead of cascading
foreign-event rows. This is local validation only; it does not write migration
history or deploy anything.
## Files ## Files
- [`supabase/tests/rpc_tests.sql`](../../supabase/tests/rpc_tests.sql) — the test - [`supabase/tests/rpc_tests.sql`](../../supabase/tests/rpc_tests.sql) — the test
+20 -2
View File
@@ -18,7 +18,7 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) | | **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) |
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset). | | **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset). |
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). | | **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). |
| **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state, `average_feedback`, `ai_generated_feedback` + an **Evaluate** stub button). | | **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state, `average_feedback`, `ai_generated_feedback` + an **Evaluate** stub button), plus an admin-only **Delete current schedule** action for the active event. |
| **Activity** | Tables of check-ins, connections, and feedback (per active event). | | **Activity** | Tables of check-ins, connections, and feedback (per active event). |
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. | | **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
| **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). | | **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). |
@@ -128,7 +128,8 @@ key. Everything it can do is allowed by RLS:
(admin-only policies). (admin-only policies).
- **RPCs** — `adjust_points` (manual, audited as `admin`), `upsert_contact`, - **RPCs** — `adjust_points` (manual, audited as `admin`), `upsert_contact`,
`create_registration`, `set_registration_type`, `evaluate_session_feedback` `create_registration`, `set_registration_type`, `evaluate_session_feedback`
(AI stub), and `set_session_material` (attach uploaded material). The (AI stub), `set_session_material` (attach uploaded material), and
`delete_event_schedule` (clear the active event's slots/sessions). The
`reset_registration_qr_token` RPC still exists but the admin UI no longer `reset_registration_qr_token` RPC still exists but the admin UI no longer
exposes a token reset. See exposes a token reset. See
[../backend/rpcs.md](../backend/rpcs.md). [../backend/rpcs.md](../backend/rpcs.md).
@@ -164,6 +165,23 @@ The Schedule view uploads a session's material to the `materials` bucket and set
`sessions.material_path` (admins can write `sessions` directly). The **Evaluate** `sessions.material_path` (admins can write `sessions` directly). The **Evaluate**
button calls `evaluate_session_feedback` (the AI stub) to set button calls `evaluate_session_feedback` (the AI stub) to set
`ai_generated_feedback`. `ai_generated_feedback`.
### Delete current schedule
The Schedule view keeps the existing active-event selection pattern: it loads
`getActiveEvent()`, then reads slots/sessions for that event. **Delete current
schedule** captures the active event ID/name when the confirmation modal opens
and calls `delete_event_schedule(p_event_id)`. Success refreshes only that same
event view and reports deleted slot/session counts; if the admin navigates away
or changes the active event while the RPC is pending, the stale completion does
not clear the newly selected event's UI.
The confirmation spells out the irreversible data loss: slots, sessions,
speaker links, preferences, check-ins and feedback are deleted; registrations
are preserved; material paths are removed with session rows, but Storage objects
are not physically purged. The UI disables schedule mutation controls while the
delete is pending. A later or concurrent Sessionize/Pretix sync can recreate
schedule rows because the admin delete does not lock the import sidecar.
### Reports (post-event summary + export) ### Reports (post-event summary + export)
The **Reports** view is the post-event reporting surface. It works for **any** The **Reports** view is the post-event reporting surface. It works for **any**
+410
View File
@@ -0,0 +1,410 @@
import { test, expect, type Page, type Route } from '@playwright/test';
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
type MockEvent = {
id: string;
name: string;
start_date: string;
end_date: string;
location: string | null;
is_active: boolean;
use_realtime_clock: boolean;
sessionize_endpoint: string | null;
last_synced_at: string | null;
talk_networking_bonus: number;
avg_feedback: number | null;
num_sessions: number;
num_speakers: number;
num_registrations: number;
num_checked_in_registrations: number;
created_at: string;
};
type MockSlot = {
id: number;
event_id: string;
type: 'session' | 'service_session';
name: string;
slot_date: string;
start_time: string;
end_time: string;
};
type MockSession = {
id: string;
event_id: string;
slot_id: number;
title: string;
description: string | null;
room: string | null;
capacity: number | null;
average_feedback: number | null;
ai_generated_feedback: string | null;
material_path: string | null;
level: string | null;
area: string | null;
created_at: string;
};
type MockState = {
activeEventId: string | null;
events: MockEvent[];
slots: MockSlot[];
sessions: MockSession[];
contacts: Array<{ email: string; full_name: string; is_admin: boolean; password: string | null }>;
speakers: Array<{ session_id: string; contact_email: string }>;
};
const eventA = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const eventB = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
function makeEvent(id: string, name: string, active = false): MockEvent {
return {
id,
name,
start_date: '2026-11-01',
end_date: '2026-11-02',
location: 'Vienna',
is_active: active,
use_realtime_clock: false,
sessionize_endpoint: 'https://sessionize.example/api',
last_synced_at: null,
talk_networking_bonus: 2,
avg_feedback: null,
num_sessions: 1,
num_speakers: 1,
num_registrations: 2,
num_checked_in_registrations: 1,
created_at: '2026-01-01T00:00:00Z',
};
}
function makeState(activeEventId: string | null = eventA): MockState {
return {
activeEventId,
events: [
makeEvent(eventA, 'Admin Conf A', activeEventId === eventA),
makeEvent(eventB, 'Admin Conf B', activeEventId === eventB),
],
slots: [
{ id: 101, event_id: eventA, type: 'session', name: 'A Morning', slot_date: '2026-11-01', start_time: '09:00:00', end_time: '10:00:00' },
{ id: 201, event_id: eventB, type: 'session', name: 'B Morning', slot_date: '2026-11-01', start_time: '11:00:00', end_time: '12:00:00' },
],
sessions: [
{
id: '11111111-1111-4111-8111-111111111111',
event_id: eventA,
slot_id: 101,
title: 'A Talk',
description: null,
room: 'A1',
capacity: null,
average_feedback: null,
ai_generated_feedback: 'Pending AI Evaluation',
material_path: 'sessions/a/slides.pdf',
level: null,
area: null,
created_at: '2026-01-01T00:00:00Z',
},
{
id: '22222222-2222-4222-8222-222222222222',
event_id: eventB,
slot_id: 201,
title: 'B Talk',
description: null,
room: 'B1',
capacity: null,
average_feedback: null,
ai_generated_feedback: null,
material_path: null,
level: null,
area: null,
created_at: '2026-01-01T00:00:00Z',
},
],
contacts: [
{ email: '[email protected]', full_name: 'Test Admin', is_admin: true, password: null },
{ email: '[email protected]', full_name: 'Schedule Speaker', is_admin: false, password: null },
],
speakers: [
{ session_id: '11111111-1111-4111-8111-111111111111', contact_email: '[email protected]' },
{ session_id: '22222222-2222-4222-8222-222222222222', contact_email: '[email protected]' },
],
};
}
function mockSession() {
const user = {
id: '99999999-9999-4999-8999-999999999999',
aud: 'authenticated',
role: 'authenticated',
email: '[email protected]',
app_metadata: {},
user_metadata: {},
created_at: '2026-01-01T00:00:00Z',
};
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
return { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test-signature`, refresh_token: 'mock-refresh-token', token_type: 'bearer', expires_in: 3600 };
}
async function mockAdminApi(
page: Page,
state: MockState,
onRpc?: (route: Route) => Promise<void>,
delayActiveEvent?: Promise<void>,
) {
const session = mockSession();
await page.route('**/auth/v1/**', async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith('/user')) {
await route.fulfill({ json: session.user });
} else if (url.pathname.endsWith('/token')) {
await route.fulfill({ json: session });
} else if (url.pathname.endsWith('/logout')) {
await route.fulfill({ status: 204 });
} else {
await route.fulfill({ json: {} });
}
});
await page.route('**/rest/v1/**', async (route) => {
const url = new URL(route.request().url());
const path = url.pathname.split('/').pop();
if (path === 'rpc' || url.pathname.includes('/rpc/')) {
if (onRpc) return onRpc(route);
await route.fulfill({ json: {} });
return;
}
if (url.pathname.endsWith('/rpc/delete_event_schedule')) {
if (onRpc) return onRpc(route);
await route.fulfill({ json: {} });
return;
}
if (path === 'contacts') {
if (url.searchParams.has('email')) {
await route.fulfill({ json: state.contacts[0] });
} else {
await route.fulfill({ json: state.contacts });
}
return;
}
if (path === 'events') {
if (route.request().method() === 'PATCH') {
const id = (url.searchParams.get('id') ?? '').replace(/^eq\./, '');
const body = route.request().postDataJSON() as Partial<MockEvent>;
if (body.is_active) {
state.activeEventId = id;
state.events = state.events.map((event) => ({ ...event, is_active: event.id === id }));
} else if (id === state.activeEventId) {
state.activeEventId = null;
state.events = state.events.map((event) => ({ ...event, is_active: false }));
}
await route.fulfill({ status: 204 });
return;
}
if (url.searchParams.get('is_active') === 'eq.true') {
if (delayActiveEvent) await delayActiveEvent;
await route.fulfill({ json: state.events.find((event) => event.id === state.activeEventId) ?? null });
} else {
await route.fulfill({ json: state.events });
}
return;
}
if (path === 'slots') {
await route.fulfill({ json: state.slots });
return;
}
if (path === 'sessions') {
await route.fulfill({ json: state.sessions });
return;
}
if (path === 'session_speakers') {
await route.fulfill({ json: state.speakers });
return;
}
await route.fulfill({ json: [] });
});
return session;
}
async function openAdmin(page: Page, state: MockState, onRpc?: (route: Route) => Promise<void>, delayActiveEvent?: Promise<void>) {
const session = await mockAdminApi(page, state, onRpc, delayActiveEvent);
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
}
async function gotoSchedule(page: Page) {
await page.locator('.nav').getByRole('button', { name: /Schedule/ }).click();
}
function navButton(page: Page, name: RegExp) {
return page.locator('.nav').getByRole('button', { name });
}
test.describe('Admin schedule delete', () => {
test('cancel skips RPC; confirm deletes captured active event and reloads empty schedule', async ({ page }) => {
const state = makeState(eventA);
let rpcCalls = 0;
let releaseRpc!: () => void;
const pendingRpc = new Promise<void>((resolve) => { releaseRpc = resolve; });
await openAdmin(page, state, async (route) => {
if (!route.request().url().endsWith('/rpc/delete_event_schedule')) return route.fulfill({ json: {} });
rpcCalls++;
expect(route.request().postDataJSON()).toEqual({ p_event_id: eventA });
await pendingRpc;
state.slots = state.slots.filter((slot) => slot.event_id !== eventA);
state.sessions = state.sessions.filter((session) => session.event_id !== eventA);
await route.fulfill({
json: {
event_id: eventA,
event_name: 'Admin Conf A',
slots_deleted: 1,
sessions_deleted: 1,
session_speakers_deleted: 1,
preferences_deleted: 1,
checkins_deleted: 1,
feedback_deleted: 1,
material_paths_unpurged: 1,
},
});
});
await gotoSchedule(page);
await expect(page.getByText('Admin Conf A · 1 slots · 1 sessions.')).toBeVisible();
await page.getByRole('button', { name: 'Delete current schedule', exact: true }).click();
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
expect(rpcCalls).toBe(0);
await page.getByRole('button', { name: 'Delete current schedule', exact: true }).click();
await expect(page.getByRole('dialog', { name: 'Delete current schedule' })).toContainText('Registrations are preserved');
await expect(page.getByRole('dialog', { name: 'Delete current schedule' })).toContainText('Storage objects are not physically purged');
await page.getByRole('button', { name: 'Delete schedule', exact: true }).click();
await expect(page.getByRole('button', { name: /Deleting/ })).toBeDisabled();
await expect(page.getByRole('button', { name: '+ New slot', exact: true })).toBeDisabled();
await expect(page.getByRole('button', { name: 'Evaluate', exact: true })).toBeDisabled();
releaseRpc();
await expect(page.getByText('Admin Conf A · 0 slots · 0 sessions.')).toBeVisible();
await expect(page.getByText('Deleted 1 slots and 1 sessions from Admin Conf A')).toBeVisible();
await expect(page.getByRole('button', { name: 'Delete current schedule', exact: true })).toBeDisabled();
await navButton(page, /Events/).click();
await expect(page.locator('tr', { hasText: 'Admin Conf A' }).getByText('active', { exact: true })).toBeVisible();
expect(rpcCalls).toBe(1);
});
test('permission and network failures keep the visible schedule intact', async ({ page }) => {
const state = makeState(eventA);
let rpcCalls = 0;
await openAdmin(page, state, async (route) => {
rpcCalls++;
if (rpcCalls === 1) {
await route.fulfill({ status: 403, json: { message: 'admin only', code: '42501' } });
} else {
await route.abort('failed');
}
});
await gotoSchedule(page);
for (const expected of [/admin only/, /Failed to fetch|Delete schedule failed|NetworkError/]) {
await page.getByRole('button', { name: 'Delete current schedule', exact: true }).click();
await page.getByRole('button', { name: 'Delete schedule', exact: true }).click();
await expect(page.getByText(expected)).toBeVisible();
await expect(page.getByText('Admin Conf A · 1 slots · 1 sessions.')).toBeVisible();
await expect(page.getByText('A Talk')).toBeVisible();
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
}
expect(rpcCalls).toBe(2);
});
test('initial schedule load failure shows an error without page errors', async ({ page }) => {
const state = makeState(eventA);
const pageErrors: Error[] = [];
page.on('pageerror', (error) => pageErrors.push(error));
await openAdmin(page, state);
await expect(navButton(page, /Schedule/)).toBeVisible();
await page.route('**/rest/v1/events?*', async (route) => {
const url = new URL(route.request().url());
if (route.request().method() === 'GET' && url.searchParams.get('is_active') === 'eq.true') {
await route.fulfill({ status: 500, json: { message: 'active event load failed' } });
return;
}
await route.fallback();
});
await gotoSchedule(page);
await expect(page.getByText('active event load failed')).toBeVisible();
await expect(page.getByRole('button', { name: 'Delete current schedule', exact: true })).toHaveCount(0);
expect(pageErrors).toHaveLength(0);
});
test('empty, no-event and loading states disable or hide deletion safely', async ({ page }) => {
const emptyState = makeState(eventA);
emptyState.slots = emptyState.slots.filter((slot) => slot.event_id !== eventA);
emptyState.sessions = emptyState.sessions.filter((session) => session.event_id !== eventA);
await openAdmin(page, emptyState);
await gotoSchedule(page);
await expect(page.getByText('Admin Conf A · 0 slots · 0 sessions.')).toBeVisible();
await expect(page.getByRole('button', { name: 'Delete current schedule', exact: true })).toBeDisabled();
const noEventPage = await page.context().newPage();
await openAdmin(noEventPage, makeState(null));
await gotoSchedule(noEventPage);
await expect(noEventPage.getByText('No active event. Set an event active in the Events view first.')).toBeVisible();
await expect(noEventPage.getByRole('button', { name: 'Delete current schedule', exact: true })).toHaveCount(0);
const loadingPage = await page.context().newPage();
let releaseLoad!: () => void;
const pendingLoad = new Promise<void>((resolve) => { releaseLoad = resolve; });
await openAdmin(loadingPage, makeState(eventA), undefined, pendingLoad);
await navButton(loadingPage, /Schedule/).click();
await expect(loadingPage.locator('.loading-screen .spinner')).toBeVisible();
releaseLoad();
await expect(loadingPage.getByText('Admin Conf A · 1 slots · 1 sessions.')).toBeVisible();
});
test('stale completion after navigating and activating another event does not clear the new view', async ({ page }) => {
const state = makeState(eventA);
let releaseRpc!: () => void;
const pendingRpc = new Promise<void>((resolve) => { releaseRpc = resolve; });
let capturedId: string | null = null;
await openAdmin(page, state, async (route) => {
if (!route.request().url().endsWith('/rpc/delete_event_schedule')) return route.fulfill({ json: {} });
capturedId = route.request().postDataJSON().p_event_id;
await pendingRpc;
state.slots = state.slots.filter((slot) => slot.event_id !== eventA);
state.sessions = state.sessions.filter((session) => session.event_id !== eventA);
await route.fulfill({
json: {
event_id: eventA,
event_name: 'Admin Conf A',
slots_deleted: 1,
sessions_deleted: 1,
session_speakers_deleted: 1,
preferences_deleted: 0,
checkins_deleted: 0,
feedback_deleted: 0,
material_paths_unpurged: 1,
},
});
});
page.on('dialog', (dialog) => dialog.accept());
await gotoSchedule(page);
await page.getByRole('button', { name: 'Delete current schedule', exact: true }).click();
await page.getByRole('button', { name: 'Delete schedule', exact: true }).click();
const eventsNav = navButton(page, /Events/);
await eventsNav.focus();
await eventsNav.press('Enter');
const eventBRow = page.locator('tr', { hasText: 'Admin Conf B' });
const eventBCheckbox = eventBRow.getByRole('checkbox');
await eventBRow.locator('label.toggle').click();
await expect(eventBCheckbox).toBeChecked();
await expect(eventBRow.getByText('active', { exact: true })).toBeVisible();
await navButton(page, /Schedule/).click();
await expect(page.getByText('Admin Conf B · 1 slots · 1 sessions.')).toBeVisible();
const deleteCompletion = page.waitForResponse((response) => response.url().endsWith('/rpc/delete_event_schedule'));
releaseRpc();
await deleteCompletion;
await expect(page.getByText('B Talk')).toBeVisible();
await expect(page.getByText('Admin Conf B · 1 slots · 1 sessions.')).toBeVisible();
await expect(page.getByText('Admin Conf B · 0 slots · 0 sessions.')).toHaveCount(0);
expect(capturedId).toBe(eventA);
});
});
@@ -0,0 +1,448 @@
-- Guard Sessionize imports against session dates outside the configured event range.
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_level text;
v_area text;
v_event_start date;
v_event_end date;
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;
select start_date, end_date into v_event_start, v_event_end
from public.events
where id = p_event_id;
if not found then
raise exception 'event not found';
end if;
for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'sessions', '[]'::jsonb))
loop
begin
v_date := (v_item ->> 'date')::date;
exception when others then
continue;
end;
if v_date is not null and (v_date < v_event_start or v_date > v_event_end) then
raise exception
'session date % is outside event date range % to %. Check Sessionize endpoint/Excel/event dates.',
v_date, v_event_start, v_event_end;
end if;
end loop;
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, '<no 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);
v_level := nullif(btrim(coalesce(v_item ->> 'level', '')), '');
v_area := nullif(btrim(coalesce(v_item ->> 'area', '')), '');
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, '<no 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 (now including level + area).
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, level, area)
values (p_event_id, v_slot.id, v_title, v_desc, v_room, v_ext, v_level, v_area)
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),
level = coalesce(excluded.level, public.sessions.level),
area = coalesce(excluded.area, public.sessions.area)
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, '<no 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;
$$;
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_level text;
v_area text;
v_event_start date;
v_event_end date;
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;
select start_date, end_date into v_event_start, v_event_end
from public.events
where id = p_event_id;
if not found then
raise exception 'event not found';
end if;
for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'sessions', '[]'::jsonb))
loop
begin
v_date := (v_item ->> 'date')::date;
exception when others then
continue;
end;
if v_date is not null and (v_date < v_event_start or v_date > v_event_end) then
raise exception
'session date % is outside event date range % to %. Check Sessionize endpoint/Excel/event dates.',
v_date, v_event_start, v_event_end;
end if;
end loop;
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, '<no 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);
v_level := nullif(btrim(coalesce(v_item ->> 'level', '')), '');
v_area := nullif(btrim(coalesce(v_item ->> 'area', '')), '');
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, '<no 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 (now including level + area).
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, level, area)
values (p_event_id, v_slot.id, v_title, v_desc, v_room, v_ext, v_level, v_area)
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),
level = coalesce(excluded.level, public.sessions.level),
area = coalesce(excluded.area, public.sessions.area)
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, '<no 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, '<no 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;
$$;
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;
@@ -0,0 +1,157 @@
-- Admin-only schedule wipe for one event. This removes slots and sessions for
-- the requested event; FK cascades remove dependent session rows, but event
-- registrations, contacts, sponsors, connections, points and the event itself
-- are intentionally left intact.
create or replace function public.delete_event_schedule(p_event_id uuid)
returns jsonb
language plpgsql security definer set search_path = '' as $$
declare
v_event public.events;
v_slots_deleted integer := 0;
v_sessions_deleted integer := 0;
v_session_speakers_deleted integer := 0;
v_preferences_deleted integer := 0;
v_checkins_deleted integer := 0;
v_feedback_deleted integer := 0;
v_material_paths_unpurged integer := 0;
begin
if auth.uid() is null then
raise exception 'not authenticated' using errcode = '42501';
end if;
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
if p_event_id is null then
raise exception 'event id is required';
end if;
select * into v_event
from public.events
where id = p_event_id
for update;
if not found then
raise exception 'event not found';
end if;
perform 1 from public.slots where event_id = p_event_id order by id for update;
perform 1 from public.sessions where event_id = p_event_id order by id for update;
perform 1
from public.preferences preference
join public.sessions talk on talk.id = preference.session_id
where talk.event_id = p_event_id
order by preference.id
for update of preference;
perform 1
from public.checkins checkin_row
join public.sessions talk on talk.id = checkin_row.session_id
where talk.event_id = p_event_id
order by checkin_row.id
for update of checkin_row;
perform 1
from public.feedback feedback_row
join public.sessions talk on talk.id = feedback_row.session_id
where talk.event_id = p_event_id
order by feedback_row.id
for update of feedback_row;
if exists (
select 1
from public.sessions talk
join public.slots slot on slot.id = talk.slot_id
where talk.event_id = p_event_id
and slot.event_id <> p_event_id
) then
raise exception 'cannot delete schedule: session references a slot from another event';
end if;
if exists (
select 1
from public.sessions talk
join public.slots slot on slot.id = talk.slot_id
where slot.event_id = p_event_id
and talk.event_id <> p_event_id
) then
raise exception 'cannot delete schedule: another event has a session in this event slot';
end if;
if exists (
select 1
from public.preferences preference
join public.sessions talk on talk.id = preference.session_id
where talk.event_id = p_event_id
and preference.event_id <> p_event_id
) then
raise exception 'cannot delete schedule: preference event mismatch';
end if;
if exists (
select 1
from public.checkins checkin_row
join public.sessions talk on talk.id = checkin_row.session_id
where talk.event_id = p_event_id
and checkin_row.event_id <> p_event_id
) then
raise exception 'cannot delete schedule: check-in event mismatch';
end if;
if exists (
select 1
from public.feedback feedback_row
join public.sessions talk on talk.id = feedback_row.session_id
where talk.event_id = p_event_id
and feedback_row.event_id <> p_event_id
) then
raise exception 'cannot delete schedule: feedback event mismatch';
end if;
select count(*) into v_slots_deleted
from public.slots
where event_id = p_event_id;
select count(*) into v_sessions_deleted
from public.sessions
where event_id = p_event_id;
select count(*) into v_session_speakers_deleted
from public.session_speakers speaker
join public.sessions talk on talk.id = speaker.session_id
where talk.event_id = p_event_id;
select count(*) into v_preferences_deleted
from public.preferences preference
join public.sessions talk on talk.id = preference.session_id
where talk.event_id = p_event_id;
select count(*) into v_checkins_deleted
from public.checkins checkin_row
join public.sessions talk on talk.id = checkin_row.session_id
where talk.event_id = p_event_id;
select count(*) into v_feedback_deleted
from public.feedback feedback_row
join public.sessions talk on talk.id = feedback_row.session_id
where talk.event_id = p_event_id;
select count(*) into v_material_paths_unpurged
from public.sessions
where event_id = p_event_id
and material_path is not null;
delete from public.sessions
where event_id = p_event_id;
delete from public.slots
where event_id = p_event_id;
return jsonb_build_object(
'event_id', p_event_id,
'event_name', v_event.name,
'slots_deleted', v_slots_deleted,
'sessions_deleted', v_sessions_deleted,
'session_speakers_deleted', v_session_speakers_deleted,
'preferences_deleted', v_preferences_deleted,
'checkins_deleted', v_checkins_deleted,
'feedback_deleted', v_feedback_deleted,
'material_paths_unpurged', v_material_paths_unpurged
);
end;
$$;
revoke all on function public.delete_event_schedule(uuid) from public, anon, authenticated;
grant execute on function public.delete_event_schedule(uuid) to authenticated;
notify pgrst, 'reload schema';
@@ -0,0 +1,332 @@
\set ON_ERROR_STOP on
begin;
create function pg_temp.assert_delete_schedule(p_condition boolean, p_name text)
returns void language plpgsql as $$
begin
if p_condition is distinct from true then
raise exception 'FAIL: %', p_name;
end if;
raise notice 'PASS: %', p_name;
end;
$$;
create function pg_temp.set_delete_schedule_user(p_user_id uuid, p_email text)
returns void language plpgsql as $$
begin
perform set_config(
'request.jwt.claims',
json_build_object('sub', p_user_id, 'email', p_email, 'role', 'authenticated')::text,
true
);
end;
$$;
create function pg_temp.expect_delete_schedule_reject(p_statement text, p_expected text, p_name text)
returns void language plpgsql as $$
declare
v_message text;
begin
begin
execute p_statement;
exception when others then
v_message := sqlerrm;
perform pg_temp.assert_delete_schedule(v_message like p_expected, p_name || ' rejected: ' || v_message);
return;
end;
raise exception 'FAIL: % was allowed', p_name;
end;
$$;
create temporary table delete_schedule_fixture as
select
gen_random_uuid() as admin_id,
gen_random_uuid() as nonadmin_id,
gen_random_uuid() as event_a,
gen_random_uuid() as event_b,
gen_random_uuid() as slot_mismatch_target_event,
gen_random_uuid() as slot_mismatch_other_event,
gen_random_uuid() as slot_owned_other_event,
gen_random_uuid() as dependent_mismatch_target_event,
gen_random_uuid() as dependent_mismatch_other_event,
gen_random_uuid() as session_a_one,
gen_random_uuid() as session_a_two,
gen_random_uuid() as session_b,
gen_random_uuid() as session_slot_mismatch,
gen_random_uuid() as session_slot_owned_other,
gen_random_uuid() as session_dependent_mismatch,
(select least(coalesce(min(id), 0), 0) from public.slots) - 700 as slot_a_one,
(select least(coalesce(min(id), 0), 0) from public.slots) - 701 as slot_a_two,
(select least(coalesce(min(id), 0), 0) from public.slots) - 702 as slot_b,
(select least(coalesce(min(id), 0), 0) from public.slots) - 703 as slot_mismatch_target,
(select least(coalesce(min(id), 0), 0) from public.slots) - 704 as slot_mismatch_other,
(select least(coalesce(min(id), 0), 0) from public.slots) - 705 as slot_owned_other_target,
(select least(coalesce(min(id), 0), 0) from public.slots) - 706 as slot_dependent_mismatch,
'delete-schedule-admin-' || gen_random_uuid() || '@example.invalid' as admin_email,
'delete-schedule-nonadmin-' || gen_random_uuid() || '@example.invalid' as nonadmin_email,
'delete-schedule-speaker-' || gen_random_uuid() || '@example.invalid' as speaker_email,
'delete-schedule-attendee-' || gen_random_uuid() || '@example.invalid' as attendee_email,
'delete-schedule-staff-' || gen_random_uuid() || '@example.invalid' as staff_email;
grant select on delete_schedule_fixture to authenticated, anon;
create temporary table delete_schedule_sequence_before as
select last_value, is_called from public.slots_id_seq;
insert into public.contacts(email, full_name, is_admin)
select admin_email, 'Delete Schedule Admin', true from delete_schedule_fixture
union all select nonadmin_email, 'Delete Schedule Nonadmin', false from delete_schedule_fixture
union all select speaker_email, 'Delete Schedule Speaker', false from delete_schedule_fixture
union all select attendee_email, 'Delete Schedule Attendee', false from delete_schedule_fixture
union all select staff_email, 'Delete Schedule Staff', false from delete_schedule_fixture;
select public._ensure_auth_user_exists(admin_email, 'Delete Schedule Admin') from delete_schedule_fixture;
select public._ensure_auth_user_exists(attendee_email, 'Delete Schedule Attendee') from delete_schedule_fixture;
update public.events set is_active = false where is_active;
insert into public.events(id, name, start_date, end_date, is_active)
select event_a, 'Delete Schedule A', date '2026-11-01', date '2026-11-02', true from delete_schedule_fixture
union all select event_b, 'Delete Schedule B', '2026-12-01', '2026-12-02', false from delete_schedule_fixture
union all select slot_mismatch_target_event, 'Delete Schedule Slot Mismatch Target', '2027-01-01', '2027-01-01', false from delete_schedule_fixture
union all select slot_mismatch_other_event, 'Delete Schedule Slot Mismatch Other', '2027-01-02', '2027-01-02', false from delete_schedule_fixture
union all select slot_owned_other_event, 'Delete Schedule Slot Owned Other', '2027-01-03', '2027-01-03', false from delete_schedule_fixture
union all select dependent_mismatch_target_event, 'Delete Schedule Dep Mismatch Target', '2027-01-04', '2027-01-04', false from delete_schedule_fixture
union all select dependent_mismatch_other_event, 'Delete Schedule Dep Mismatch Other', '2027-01-05', '2027-01-05', false from delete_schedule_fixture;
insert into public.slots(id, event_id, type, name, slot_date, start_time, end_time)
select slot_a_one, event_a, 'session'::public.slot_type, 'A morning', date '2026-11-01', time '09:00', time '10:00' from delete_schedule_fixture
union all select slot_a_two, event_a, 'session', 'A afternoon', '2026-11-01', '14:00', '15:00' from delete_schedule_fixture
union all select slot_b, event_b, 'session', 'B morning', '2026-12-01', '09:00', '10:00' from delete_schedule_fixture
union all select slot_mismatch_target, slot_mismatch_target_event, 'session', 'Target slot', '2027-01-01', '09:00', '10:00' from delete_schedule_fixture
union all select slot_mismatch_other, slot_mismatch_other_event, 'session', 'Other slot', '2027-01-02', '09:00', '10:00' from delete_schedule_fixture
union all select slot_owned_other_target, slot_mismatch_target_event, 'session', 'Target-owned slot', '2027-01-01', '11:00', '12:00' from delete_schedule_fixture
union all select slot_dependent_mismatch, dependent_mismatch_target_event, 'session', 'Dependent slot', '2027-01-04', '09:00', '10:00' from delete_schedule_fixture;
insert into public.sessions(id, event_id, slot_id, title, material_path)
select session_a_one, event_a, slot_a_one, 'A session one', 'sessions/a-one/slides.pdf' from delete_schedule_fixture
union all select session_a_two, event_a, slot_a_two, 'A session two', 'sessions/a-two/slides.pdf' from delete_schedule_fixture
union all select session_b, event_b, slot_b, 'B session', 'sessions/b/slides.pdf' from delete_schedule_fixture
union all select session_slot_mismatch, slot_mismatch_target_event, slot_mismatch_other, 'Wrong slot event', null from delete_schedule_fixture
union all select session_slot_owned_other, slot_mismatch_other_event, slot_owned_other_target, 'Other session in target slot', null from delete_schedule_fixture
union all select session_dependent_mismatch, dependent_mismatch_target_event, slot_dependent_mismatch, 'Dependent mismatch session', null from delete_schedule_fixture;
insert into public.registrations(event_id, contact_email, type, points, checked_in)
select event_a, speaker_email, 'speaker'::public.registration_type, 10, true from delete_schedule_fixture
union all select event_a, attendee_email, 'attendee', 20, true from delete_schedule_fixture
union all select event_b, speaker_email, 'speaker', 30, false from delete_schedule_fixture
union all select event_b, attendee_email, 'attendee', 40, false from delete_schedule_fixture
union all select dependent_mismatch_other_event, attendee_email, 'attendee', 50, false from delete_schedule_fixture;
insert into public.session_speakers(session_id, contact_email)
select session_a_one, speaker_email from delete_schedule_fixture
union all select session_a_two, speaker_email from delete_schedule_fixture
union all select session_b, speaker_email from delete_schedule_fixture
union all select session_slot_mismatch, speaker_email from delete_schedule_fixture
union all select session_slot_owned_other, speaker_email from delete_schedule_fixture
union all select session_dependent_mismatch, speaker_email from delete_schedule_fixture;
insert into public.preferences(event_id, contact_email, session_id, slot_id)
select event_a, attendee_email, session_a_one, slot_a_one from delete_schedule_fixture
union all select dependent_mismatch_other_event, attendee_email, session_dependent_mismatch, slot_dependent_mismatch from delete_schedule_fixture;
insert into public.checkins(event_id, contact_email, session_id, staff_email)
select event_a, attendee_email, session_a_one, admin_email from delete_schedule_fixture
union all select dependent_mismatch_other_event, attendee_email, session_dependent_mismatch, admin_email from delete_schedule_fixture;
insert into public.feedback(event_id, contact_email, session_id, rating, comment)
select event_a, attendee_email, session_a_one, 5, 'Useful' from delete_schedule_fixture
union all select dependent_mismatch_other_event, attendee_email, session_dependent_mismatch, 4, 'Wrong event' from delete_schedule_fixture;
insert into public.event_feedback(event_id, contact_email, rating, comment)
select event_a, attendee_email, 5, 'Event feedback stays' from delete_schedule_fixture;
insert into public.sponsors(event_id, type, name, contact_email)
select event_a, 'community', 'Schedule Sponsor', speaker_email from delete_schedule_fixture;
insert into public.connections(event_id, from_email, to_email, status)
select event_a, speaker_email, attendee_email, 'accepted' from delete_schedule_fixture;
insert into public.points_log(event_id, contact_email, delta, category)
select event_a, attendee_email, 9, 'admin' from delete_schedule_fixture;
insert into public.leaderboard(event_id, contact_email, full_name, points)
select event_a, attendee_email, 'Delete Schedule Attendee', 20 from delete_schedule_fixture;
create temporary table delete_schedule_before as
select
(select count(*) from auth.users u join delete_schedule_fixture f on u.email in (f.admin_email, f.attendee_email)) as auth_users,
(select count(*) from public.contacts c cross join delete_schedule_fixture f where c.email in (f.admin_email, f.nonadmin_email, f.speaker_email, f.attendee_email, f.staff_email)) as contacts,
(select count(*) from public.registrations r join delete_schedule_fixture f on r.event_id in (f.event_a, f.event_b)) as registrations,
(select count(*) from public.sponsors s join delete_schedule_fixture f on s.event_id = f.event_a) as sponsors,
(select count(*) from public.connections c join delete_schedule_fixture f on c.event_id = f.event_a) as connections,
(select count(*) from public.points_log p join delete_schedule_fixture f on p.event_id = f.event_a) as points_log,
(select count(*) from public.event_feedback ef join delete_schedule_fixture f on ef.event_id = f.event_a) as event_feedback,
(select count(*) from public.leaderboard l join delete_schedule_fixture f on l.event_id = f.event_a) as leaderboard,
(select count(*) from public.slots s join delete_schedule_fixture f on s.event_id = f.event_b) as b_slots,
(select count(*) from public.sessions s join delete_schedule_fixture f on s.event_id = f.event_b) as b_sessions;
select pg_temp.assert_delete_schedule(
not has_function_privilege('anon', 'public.delete_event_schedule(uuid)', 'execute'),
'anonymous execute privilege revoked');
select pg_temp.assert_delete_schedule(
has_function_privilege('authenticated', 'public.delete_event_schedule(uuid)', 'execute'),
'authenticated execute privilege granted');
select pg_temp.set_delete_schedule_user(admin_id, admin_email) from delete_schedule_fixture;
set local role authenticated;
select pg_temp.assert_delete_schedule(public.is_admin(), 'authenticated admin passes is_admin check');
create temporary table delete_schedule_result as
select public.delete_event_schedule(event_a) as result
from delete_schedule_fixture;
reset role;
select pg_temp.assert_delete_schedule(
(select result->>'event_name' = 'Delete Schedule A' from delete_schedule_result),
'result includes event name');
select pg_temp.assert_delete_schedule(
(select (result->>'slots_deleted')::integer = 2 and (result->>'sessions_deleted')::integer = 2
and (result->>'session_speakers_deleted')::integer = 2 and (result->>'preferences_deleted')::integer = 1
and (result->>'checkins_deleted')::integer = 1 and (result->>'feedback_deleted')::integer = 1
and (result->>'material_paths_unpurged')::integer = 2 from delete_schedule_result),
'result includes exact deleted counts');
select pg_temp.assert_delete_schedule(
not exists (select 1 from public.slots s join delete_schedule_fixture f on s.event_id = f.event_a),
'event A slots deleted');
select pg_temp.assert_delete_schedule(
not exists (select 1 from public.sessions s join delete_schedule_fixture f on s.event_id = f.event_a),
'event A sessions deleted');
select pg_temp.assert_delete_schedule(
not exists (
select 1 from public.session_speakers ss
join delete_schedule_fixture f on ss.session_id in (f.session_a_one, f.session_a_two)
),
'event A speaker links cascaded');
select pg_temp.assert_delete_schedule(
not exists (
select 1 from public.preferences p
join delete_schedule_fixture f on p.session_id in (f.session_a_one, f.session_a_two)
),
'event A preferences cascaded');
select pg_temp.assert_delete_schedule(
not exists (
select 1 from public.checkins c
join delete_schedule_fixture f on c.session_id in (f.session_a_one, f.session_a_two)
),
'event A check-ins cascaded');
select pg_temp.assert_delete_schedule(
not exists (
select 1 from public.feedback fb
join delete_schedule_fixture f on fb.session_id in (f.session_a_one, f.session_a_two)
),
'event A feedback cascaded');
select pg_temp.assert_delete_schedule(
(select is_active from public.events e join delete_schedule_fixture f on e.id = f.event_a),
'active event selection retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.registrations r join delete_schedule_fixture f on r.event_id in (f.event_a, f.event_b))
= (select registrations from delete_schedule_before),
'registrations retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.contacts c cross join delete_schedule_fixture f where c.email in (f.admin_email, f.nonadmin_email, f.speaker_email, f.attendee_email, f.staff_email))
= (select contacts from delete_schedule_before),
'contacts retained');
select pg_temp.assert_delete_schedule(
(select count(*) from auth.users u join delete_schedule_fixture f on u.email in (f.admin_email, f.attendee_email))
= (select auth_users from delete_schedule_before),
'auth users retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.sponsors s join delete_schedule_fixture f on s.event_id = f.event_a)
= (select sponsors from delete_schedule_before),
'sponsors retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.connections c join delete_schedule_fixture f on c.event_id = f.event_a)
= (select connections from delete_schedule_before),
'connections retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.points_log p join delete_schedule_fixture f on p.event_id = f.event_a)
= (select points_log from delete_schedule_before),
'points log retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.event_feedback ef join delete_schedule_fixture f on ef.event_id = f.event_a)
= (select event_feedback from delete_schedule_before),
'event feedback retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.leaderboard l join delete_schedule_fixture f on l.event_id = f.event_a)
= (select leaderboard from delete_schedule_before),
'leaderboard retained');
select pg_temp.assert_delete_schedule(
(select count(*) from public.slots s join delete_schedule_fixture f on s.event_id = f.event_b)
= (select b_slots from delete_schedule_before),
'event B slots unchanged');
select pg_temp.assert_delete_schedule(
(select count(*) from public.sessions s join delete_schedule_fixture f on s.event_id = f.event_b)
= (select b_sessions from delete_schedule_before),
'event B sessions unchanged');
select pg_temp.set_delete_schedule_user(nonadmin_id, nonadmin_email) from delete_schedule_fixture;
set local role authenticated;
select pg_temp.assert_delete_schedule(not public.is_admin(), 'authenticated non-admin fails is_admin check');
select pg_temp.expect_delete_schedule_reject(
format('select public.delete_event_schedule(%L::uuid)', (select event_b from delete_schedule_fixture)),
'%admin only%',
'non-admin delete');
reset role;
set local role anon;
select pg_temp.expect_delete_schedule_reject(
format('select public.delete_event_schedule(%L::uuid)', (select event_b from delete_schedule_fixture)),
'%permission denied%delete_event_schedule%',
'anon execute');
reset role;
select pg_temp.set_delete_schedule_user(admin_id, admin_email) from delete_schedule_fixture;
set local role authenticated;
select pg_temp.expect_delete_schedule_reject(
format('select public.delete_event_schedule(%L::uuid)', gen_random_uuid()),
'%event not found%',
'missing event');
reset role;
create temporary table delete_schedule_mismatch_before as
select
(select count(*) from public.slots s join delete_schedule_fixture f on s.event_id = f.slot_mismatch_target_event) as slot_mismatch_slots,
(select count(*) from public.sessions s join delete_schedule_fixture f on s.event_id = f.slot_mismatch_target_event) as slot_mismatch_sessions,
(select count(*) from public.sessions s join delete_schedule_fixture f on s.event_id = f.slot_mismatch_other_event) as slot_owned_other_sessions,
(select count(*) from public.preferences p join delete_schedule_fixture f on p.session_id = f.session_dependent_mismatch) as dep_preferences,
(select count(*) from public.checkins c join delete_schedule_fixture f on c.session_id = f.session_dependent_mismatch) as dep_checkins,
(select count(*) from public.feedback fb join delete_schedule_fixture f on fb.session_id = f.session_dependent_mismatch) as dep_feedback;
select pg_temp.set_delete_schedule_user(admin_id, admin_email) from delete_schedule_fixture;
set local role authenticated;
select pg_temp.expect_delete_schedule_reject(
format('select public.delete_event_schedule(%L::uuid)', (select slot_mismatch_target_event from delete_schedule_fixture)),
'%session references a slot from another event%',
'target session with foreign slot');
select pg_temp.expect_delete_schedule_reject(
format('select public.delete_event_schedule(%L::uuid)', (select dependent_mismatch_target_event from delete_schedule_fixture)),
'%preference event mismatch%',
'cross-event dependent reference');
reset role;
select pg_temp.assert_delete_schedule(
(select count(*) from public.slots s join delete_schedule_fixture f on s.event_id = f.slot_mismatch_target_event)
= (select slot_mismatch_slots from delete_schedule_mismatch_before),
'slot mismatch failure kept target slots');
select pg_temp.assert_delete_schedule(
(select count(*) from public.sessions s join delete_schedule_fixture f on s.event_id = f.slot_mismatch_target_event)
= (select slot_mismatch_sessions from delete_schedule_mismatch_before),
'slot mismatch failure kept target sessions');
select pg_temp.assert_delete_schedule(
(select count(*) from public.sessions s join delete_schedule_fixture f on s.event_id = f.slot_mismatch_other_event)
= (select slot_owned_other_sessions from delete_schedule_mismatch_before),
'slot mismatch failure kept other-event session in target slot');
select pg_temp.assert_delete_schedule(
(select count(*) from public.preferences p join delete_schedule_fixture f on p.session_id = f.session_dependent_mismatch)
= (select dep_preferences from delete_schedule_mismatch_before),
'dependent mismatch failure kept preferences');
select pg_temp.assert_delete_schedule(
(select count(*) from public.checkins c join delete_schedule_fixture f on c.session_id = f.session_dependent_mismatch)
= (select dep_checkins from delete_schedule_mismatch_before),
'dependent mismatch failure kept check-ins');
select pg_temp.assert_delete_schedule(
(select count(*) from public.feedback fb join delete_schedule_fixture f on fb.session_id = f.session_dependent_mismatch)
= (select dep_feedback from delete_schedule_mismatch_before),
'dependent mismatch failure kept feedback');
select pg_temp.assert_delete_schedule(
(select (last_value, is_called) from public.slots_id_seq)
= (select (last_value, is_called) from delete_schedule_sequence_before),
'explicit negative slot ids did not advance slots sequence');
rollback;
@@ -0,0 +1,455 @@
\set ON_ERROR_STOP on
begin;
create function pg_temp.assert_sessionize_guard(p_condition boolean, p_name text)
returns void language plpgsql as $$
begin
if p_condition is distinct from true then
raise exception 'FAIL: %', p_name;
end if;
raise notice 'PASS: %', p_name;
end;
$$;
create function pg_temp.expect_sessionize_reject(p_statement text, p_name text,
p_imported_date date default date '2026-02-20',
p_start_date date default date '2026-10-23', p_end_date date default date '2026-10-24')
returns void language plpgsql as $$
declare
v_message text;
begin
begin
execute p_statement;
exception when others then
v_message := sqlerrm;
perform pg_temp.assert_sessionize_guard(
position(p_imported_date::text in v_message) > 0
and position(p_start_date::text in v_message) > 0 and position(p_end_date::text in v_message) > 0
and v_message like '%Check Sessionize endpoint/Excel/event dates%',
p_name || ' includes actual date, event range and actionable check');
return;
end;
raise exception 'FAIL: % was allowed', p_name;
end;
$$;
create temporary table sessionize_guard_fixture as
select
gen_random_uuid() as event_id,
gen_random_uuid() as existing_session_id,
gen_random_uuid() as stale_session_id,
(select least(coalesce(min(id), 0), 0) from public.slots) - 100 as slot_day_one_id,
(select least(coalesce(min(id), 0), 0) from public.slots) - 101 as slot_day_two_id,
(select least(coalesce(min(id), 0), 0) from public.slots) - 102 as slot_stale_id,
'guard-existing-' || gen_random_uuid() || '@example.invalid' as existing_email,
'guard-replacement-' || gen_random_uuid() || '@example.invalid' as replacement_email,
'guard-new-' || gen_random_uuid() || '@example.invalid' as new_email,
'guard-staff-' || gen_random_uuid() || '@example.invalid' as staff_email,
'guard-sponsor-' || gen_random_uuid() || '@example.invalid' as sponsor_email,
'guard-existing-' || gen_random_uuid() as existing_external_id,
'guard-new-' || gen_random_uuid() as new_external_id,
'guard-bad-' || gen_random_uuid() as bad_external_id,
'guard-stale-' || gen_random_uuid() as stale_external_id;
insert into public.contacts(email, full_name, external_id)
select existing_email, 'Guard Existing Speaker', 'contact-existing' from sessionize_guard_fixture
union all select replacement_email, 'Guard Replacement Speaker', 'contact-replacement' from sessionize_guard_fixture
union all select staff_email, 'Guard Staff', 'contact-staff' from sessionize_guard_fixture
union all select sponsor_email, 'Guard Sponsor', 'contact-sponsor' from sessionize_guard_fixture;
insert into public.events(id, name, start_date, end_date, is_active)
select event_id, 'Sessionize guard regression', '2026-10-23', '2026-10-24', false
from sessionize_guard_fixture;
insert into public.slots(id, event_id, type, name, slot_date, start_time, end_time)
select slot_day_one_id, event_id, 'session'::public.slot_type, 'Guard day one', date '2026-10-23', time '09:00', time '10:00'
from sessionize_guard_fixture
union all
select slot_day_two_id, event_id, 'session', 'Guard day two', '2026-10-24', '16:00', '17:00'
from sessionize_guard_fixture
union all
select slot_stale_id, event_id, 'session', 'Guard stale outside range', '2026-02-20', '12:00', '13:00'
from sessionize_guard_fixture;
insert into public.sessions(id, event_id, slot_id, title, description, room, capacity, average_feedback,
ai_generated_feedback, material_path, external_id, level, area)
select existing_session_id, event_id, slot_day_one_id, 'Guard old title', 'local description',
'Local room', 42, 4.5, 'local feedback', 'sessions/local/slides.pdf', existing_external_id,
'Intermediate', 'Backend'
from sessionize_guard_fixture
union all
select stale_session_id, event_id, slot_stale_id, 'Guard retained stale title', 'stale description',
'Stale room', 7, null, null, null, stale_external_id, null, null
from sessionize_guard_fixture;
insert into public.registrations(event_id, contact_email, type, points, checked_in)
select event_id, existing_email, 'speaker'::public.registration_type, 11, false from sessionize_guard_fixture
union all select event_id, staff_email, 'staff', 22, true from sessionize_guard_fixture
union all select event_id, sponsor_email, 'sponsor', 33, true from sessionize_guard_fixture;
insert into public.session_speakers(session_id, contact_email)
select existing_session_id, existing_email from sessionize_guard_fixture;
select public._ensure_auth_user_exists(existing_email, 'Guard Existing Speaker') from sessionize_guard_fixture;
create temporary table sessionize_guard_before as
select
(select last_value from public.slots_id_seq) as slots_last_value,
(select is_called from public.slots_id_seq) as slots_is_called,
(select count(*) from public.contacts) as contacts_count,
(select count(*) from auth.users) as auth_users_count,
(select count(*) from auth.identities) as identities_count,
(select count(*) from public.registrations) as registrations_count,
(select count(*) from public.sessions) as sessions_count,
(select count(*) from public.slots) as slots_count,
(select count(*) from public.session_speakers) as links_count,
(select count(*) from public.sync_runs) as sync_runs_count,
(select jsonb_agg(to_jsonb(c) order by c.email) from public.contacts c
cross join sessionize_guard_fixture f
where c.email in (f.existing_email, f.replacement_email, f.new_email, f.staff_email, f.sponsor_email)) as contact_rows,
(select jsonb_agg(to_jsonb(u) order by u.id) from auth.users u
cross join sessionize_guard_fixture f
where u.email in (f.existing_email, f.replacement_email, f.new_email, f.staff_email, f.sponsor_email)) as auth_rows,
(select jsonb_agg(to_jsonb(i) order by i.id) from auth.identities i
join auth.users u on u.id = i.user_id cross join sessionize_guard_fixture f
where u.email in (f.existing_email, f.replacement_email, f.new_email, f.staff_email, f.sponsor_email)) as identity_rows,
(select to_jsonb(e) from public.events e join sessionize_guard_fixture f on f.event_id = e.id) as event_row,
(select to_jsonb(s) from public.sessions s join sessionize_guard_fixture f on f.existing_session_id = s.id) as existing_session_row,
(select to_jsonb(s) from public.sessions s join sessionize_guard_fixture f on f.stale_session_id = s.id) as stale_session_row,
(select jsonb_agg(to_jsonb(r) order by r.contact_email)
from public.registrations r join sessionize_guard_fixture f on f.event_id = r.event_id) as fixture_registrations,
(select jsonb_agg(to_jsonb(ss) order by ss.session_id, ss.contact_email)
from public.session_speakers ss
join public.sessions s on s.id = ss.session_id
join sessionize_guard_fixture f on f.event_id = s.event_id) as fixture_links;
do $$
begin
perform public.sync_sessionize_event(event_id, jsonb_build_object('sessions', '[]'::jsonb))
from sessionize_guard_fixture;
raise exception 'FAIL: anonymous API sync was allowed';
exception when others then
perform pg_temp.assert_sessionize_guard(sqlerrm = 'service_role only', 'anonymous API sync rejected before event/date lookup');
end;
$$;
select set_config('request.jwt.claims', '{"role":"authenticated","email":"[email protected]"}', true);
do $$
begin
perform public.sync_sessionize_excel(event_id, jsonb_build_object('sessions', '[]'::jsonb))
from sessionize_guard_fixture;
raise exception 'FAIL: authenticated Excel sync was allowed';
exception when others then
perform pg_temp.assert_sessionize_guard(sqlerrm = 'service_role only', 'authenticated Excel sync rejected before event/date lookup');
end;
$$;
select set_config('request.jwt.claims', '{"role":"service_role"}', true);
do $$
begin
perform public.sync_sessionize_event(gen_random_uuid(), jsonb_build_object('sessions', '[]'::jsonb));
raise exception 'FAIL: missing event was allowed';
exception when others then
perform pg_temp.assert_sessionize_guard(sqlerrm = 'event not found', 'missing event behavior unchanged');
end;
$$;
select pg_temp.expect_sessionize_reject(
format($sql$
select public.sync_sessionize_event(%L::uuid, %L::jsonb)
$sql$, event_id, jsonb_build_object(
'speakers', jsonb_build_array(
jsonb_build_object('email', replacement_email, 'full_name', 'Guard Replacement Updated'),
jsonb_build_object('email', new_email, 'full_name', 'Guard New Created')
),
'sessions', jsonb_build_array(
jsonb_build_object('external_id', existing_external_id, 'title', 'Guard updated title',
'date', '2026-10-23', 'start_time', '09:00', 'end_time', '10:00', 'room', 'Updated room',
'speakers', jsonb_build_array(replacement_email)),
jsonb_build_object('external_id', new_external_id, 'title', 'Guard new title',
'date', '2026-10-24', 'start_time', '16:00', 'end_time', '17:00', 'room', 'New room',
'speakers', jsonb_build_array(new_email)),
jsonb_build_object('external_id', bad_external_id, 'title', 'Guard outside title',
'date', '2026-02-20', 'start_time', '11:00', 'end_time', '12:00', 'room', 'Bad room',
'speakers', jsonb_build_array(new_email))
)
)::text),
'API sync rejects wrong date after valid updates in payload')
from sessionize_guard_fixture;
select pg_temp.expect_sessionize_reject(
format($sql$
select public.sync_sessionize_excel(%L::uuid, %L::jsonb)
$sql$, event_id, jsonb_build_object(
'speakers', jsonb_build_array(
jsonb_build_object('email', replacement_email, 'full_name', 'Guard Replacement Updated'),
jsonb_build_object('email', new_email, 'full_name', 'Guard New Created')
),
'sessions', jsonb_build_array(
jsonb_build_object('external_id', existing_external_id, 'title', 'Guard Excel updated title',
'date', '2026-10-23', 'start_time', '09:00', 'end_time', '10:00',
'speakers', jsonb_build_array(replacement_email)),
jsonb_build_object('external_id', new_external_id, 'title', 'Guard Excel new title',
'date', '2026-10-24', 'start_time', '16:00', 'end_time', '17:00',
'speakers', jsonb_build_array(new_email)),
jsonb_build_object('external_id', bad_external_id, 'title', 'Guard Excel outside title',
'date', '2026-02-20', 'start_time', '11:00', 'end_time', '12:00',
'speakers', jsonb_build_array(new_email))
)
)::text),
'Excel sync rejects wrong date after valid speaker/session payload')
from sessionize_guard_fixture;
do $$
declare
v_rpc text;
v_fixture record;
begin
select * into v_fixture from sessionize_guard_fixture;
foreach v_rpc in array array['sync_sessionize_event', 'sync_sessionize_excel'] loop
perform pg_temp.expect_sessionize_reject(
format('select public.%I(%L::uuid, %L::jsonb)', v_rpc, v_fixture.event_id,
jsonb_build_object('sessions', jsonb_build_array(jsonb_build_object(
'external_id', v_fixture.bad_external_id, 'title', 'Single outside session',
'date', '2026-02-20', 'start_time', '09:00', 'end_time', '10:00')))::text),
v_rpc || ' rejects a single outside session');
end loop;
end;
$$;
select pg_temp.assert_sessionize_guard(
(select jsonb_agg(to_jsonb(c) order by c.email) from public.contacts c
cross join sessionize_guard_fixture f
where c.email in (f.existing_email, f.replacement_email, f.new_email, f.staff_email, f.sponsor_email))
is not distinct from (select contact_rows from sessionize_guard_before)
and (select jsonb_agg(to_jsonb(u) order by u.id) from auth.users u
cross join sessionize_guard_fixture f
where u.email in (f.existing_email, f.replacement_email, f.new_email, f.staff_email, f.sponsor_email))
is not distinct from (select auth_rows from sessionize_guard_before)
and (select jsonb_agg(to_jsonb(i) order by i.id) from auth.identities i
join auth.users u on u.id = i.user_id cross join sessionize_guard_fixture f
where u.email in (f.existing_email, f.replacement_email, f.new_email, f.staff_email, f.sponsor_email))
is not distinct from (select identity_rows from sessionize_guard_before),
'rejected imports do not insert or update contacts, auth users or identities');
select pg_temp.assert_sessionize_guard(
(select (last_value, is_called) from public.slots_id_seq)
= (select (slots_last_value, slots_is_called) from sessionize_guard_before),
'rejected imports do not advance slots_id_seq');
select pg_temp.assert_sessionize_guard(
(select count(*) from public.contacts) = (select contacts_count from sessionize_guard_before)
and (select count(*) from auth.users) = (select auth_users_count from sessionize_guard_before)
and (select count(*) from auth.identities) = (select identities_count from sessionize_guard_before)
and (select count(*) from public.registrations) = (select registrations_count from sessionize_guard_before)
and (select count(*) from public.sessions) = (select sessions_count from sessionize_guard_before)
and (select count(*) from public.slots) = (select slots_count from sessionize_guard_before)
and (select count(*) from public.session_speakers) = (select links_count from sessionize_guard_before)
and (select count(*) from public.sync_runs) = (select sync_runs_count from sessionize_guard_before),
'rejected imports leave table counts unchanged');
select pg_temp.assert_sessionize_guard(
(select to_jsonb(e) from public.events e join sessionize_guard_fixture f on f.event_id = e.id)
= (select event_row from sessionize_guard_before)
and (select to_jsonb(s) from public.sessions s join sessionize_guard_fixture f on f.existing_session_id = s.id)
= (select existing_session_row from sessionize_guard_before)
and (select to_jsonb(s) from public.sessions s join sessionize_guard_fixture f on f.stale_session_id = s.id)
= (select stale_session_row from sessionize_guard_before)
and (select jsonb_agg(to_jsonb(r) order by r.contact_email)
from public.registrations r join sessionize_guard_fixture f on f.event_id = r.event_id)
= (select fixture_registrations from sessionize_guard_before)
and (select jsonb_agg(to_jsonb(ss) order by ss.session_id, ss.contact_email)
from public.session_speakers ss
join public.sessions s on s.id = ss.session_id
join sessionize_guard_fixture f on f.event_id = s.event_id)
= (select fixture_links from sessionize_guard_before),
'rejected imports leave event, sessions, registrations and links unchanged');
do $$
declare
v_result jsonb;
begin
select public.sync_sessionize_event(event_id, jsonb_build_object(
'sessions', jsonb_build_array(
jsonb_build_object('external_id', 'malformed-date-first', 'title', 'Malformed first',
'date', 'not-a-date', 'start_time', '09:00', 'end_time', '10:00'),
jsonb_build_object('external_id', bad_external_id, 'title', 'Outside after malformed',
'date', '2026-02-20', 'start_time', '11:00', 'end_time', '12:00')
)
)) into v_result
from sessionize_guard_fixture;
raise exception 'FAIL: malformed first plus outside date was allowed';
exception when others then
perform pg_temp.assert_sessionize_guard(
sqlerrm like '%2026-02-20%' and sqlerrm like '%2026-10-23%' and sqlerrm like '%2026-10-24%',
'preflight continues after malformed date and rejects later outside date');
end;
$$;
do $$
declare
v_result jsonb;
begin
select public.sync_sessionize_event(event_id, jsonb_build_object(
'sessions', jsonb_build_array(
jsonb_build_object('external_id', 'malformed-date-only', 'title', 'Malformed date only',
'date', 'not-a-date', 'start_time', '09:00', 'end_time', '10:00'),
jsonb_build_object('external_id', 'malformed-time-only', 'title', 'Malformed time only',
'date', '2026-10-23', 'start_time', 'nope', 'end_time', '10:00'),
jsonb_build_object('external_id', 'missing-field-only', 'title', 'Missing field only',
'date', '2026-10-23', 'start_time', '11:00')
)
)) into v_result
from sessionize_guard_fixture;
perform pg_temp.assert_sessionize_guard(
jsonb_array_length(v_result -> 'errors') = 3
and (v_result -> 'errors')::text like '%Malformed date only%'
and (v_result -> 'errors')::text like '%Malformed time only%'
and (v_result -> 'errors')::text like '%Missing field only%missing required field%',
'inside/malformed dates keep per-row malformed date/time/missing-field errors');
end;
$$;
do $$
declare
v_result jsonb;
begin
select public.sync_sessionize_excel(event_id, jsonb_build_object(
'speakers', jsonb_build_array(
jsonb_build_object('email', existing_email, 'full_name', 'Guard Existing Updated'),
jsonb_build_object('email', replacement_email, 'full_name', 'Guard Replacement Speaker'),
jsonb_build_object('email', new_email, 'full_name', 'Guard New Speaker')
),
'sessions', jsonb_build_array(
jsonb_build_object('external_id', existing_external_id, 'title', 'Guard final title',
'description', null, 'date', '2026-10-23', 'start_time', '09:00', 'end_time', '10:00',
'room', null, 'level', 'Advanced', 'area', 'Data', 'speakers', jsonb_build_array(replacement_email)),
jsonb_build_object('external_id', new_external_id, 'title', 'Guard inclusive end title',
'description', 'new description', 'date', '2026-10-24', 'start_time', '16:00', 'end_time', '17:00',
'room', 'New room', 'level', 'Beginner', 'area', 'Frontend', 'speakers', jsonb_build_array(new_email))
)
)) into v_result
from sessionize_guard_fixture;
perform pg_temp.assert_sessionize_guard(
v_result @> '{"sessions_created":1,"sessions_updated":1,"slots_created":0,"errors":[]}'::jsonb,
'Excel success accepts same-day start and multiday inclusive end using existing slots');
end;
$$;
select pg_temp.assert_sessionize_guard(
exists (select 1 from public.sessions s join sessionize_guard_fixture f on f.existing_session_id = s.id
where s.title = 'Guard final title' and s.description = 'local description' and s.room = 'Local room'
and s.capacity = 42 and s.average_feedback = 4.5 and s.ai_generated_feedback = 'local feedback'
and s.material_path = 'sessions/local/slides.pdf' and s.level = 'Advanced' and s.area = 'Data'),
'local material, capacity, feedback, description and room are preserved on update');
select pg_temp.assert_sessionize_guard(
exists (select 1 from public.session_speakers ss join sessionize_guard_fixture f on f.existing_session_id = ss.session_id
where ss.contact_email = replacement_email)
and not exists (select 1 from public.session_speakers ss join sessionize_guard_fixture f on f.existing_session_id = ss.session_id
where ss.contact_email = existing_email),
'speaker links keep DIFF behavior on successful import');
select pg_temp.assert_sessionize_guard(
exists (select 1 from public.sessions s join sessionize_guard_fixture f on f.stale_session_id = s.id
where s.title = 'Guard retained stale title')
and exists (select 1 from public.slots sl join sessionize_guard_fixture f on f.slot_stale_id = sl.id
where sl.slot_date = '2026-02-20'),
'stale slot/session outside range are retained after successful imports');
select pg_temp.assert_sessionize_guard(
exists (select 1 from public.registrations r join sessionize_guard_fixture f on f.event_id = r.event_id
where r.contact_email = staff_email and r.type = 'staff' and r.points = 22 and r.checked_in)
and exists (select 1 from public.registrations r join sessionize_guard_fixture f on f.event_id = r.event_id
where r.contact_email = sponsor_email and r.type = 'sponsor' and r.points = 33 and r.checked_in)
and exists (select 1 from public.registrations r join sessionize_guard_fixture f on f.event_id = r.event_id
where r.contact_email = new_email and r.type = 'speaker'),
'Excel speaker registrations preserve staff/sponsor and create speaker registration');
select pg_temp.assert_sessionize_guard(
(select (last_value, is_called) from public.slots_id_seq)
= (select (slots_last_value, slots_is_called) from sessionize_guard_before),
'successful fixture imports do not advance slots_id_seq when slots already exist');
do $$
declare
v_first jsonb;
v_second jsonb;
begin
select public.sync_sessionize_event(event_id, jsonb_build_object(
'sessions', jsonb_build_array(
jsonb_build_object('external_id', existing_external_id, 'title', 'Guard final title',
'date', '2026-10-23', 'start_time', '09:00', 'end_time', '10:00',
'speakers', jsonb_build_array(replacement_email)),
jsonb_build_object('external_id', new_external_id, 'title', 'Guard inclusive end title',
'date', '2026-10-24', 'start_time', '16:00', 'end_time', '17:00',
'speakers', jsonb_build_array(new_email))
)
)) into v_first
from sessionize_guard_fixture;
select public.sync_sessionize_event(event_id, jsonb_build_object(
'sessions', jsonb_build_array(
jsonb_build_object('external_id', existing_external_id, 'title', 'Guard final title',
'date', '2026-10-23', 'start_time', '09:00', 'end_time', '10:00',
'speakers', jsonb_build_array(replacement_email)),
jsonb_build_object('external_id', new_external_id, 'title', 'Guard inclusive end title',
'date', '2026-10-24', 'start_time', '16:00', 'end_time', '17:00',
'speakers', jsonb_build_array(new_email))
)
)) into v_second
from sessionize_guard_fixture;
perform pg_temp.assert_sessionize_guard(
v_first @> '{"sessions_created":0,"sessions_updated":2,"slots_created":0,"errors":[]}'::jsonb
and v_second @> '{"sessions_created":0,"sessions_updated":2,"slots_created":0,"errors":[]}'::jsonb,
'API replay is idempotent across same-day and inclusive-end sessions');
end;
$$;
do $$
declare
v_before timestamptz;
v_after timestamptz;
begin
select last_synced_at into v_before from public.events e join sessionize_guard_fixture f on f.event_id = e.id;
perform public.sync_sessionize_event(event_id, '{"sessions":[]}'::jsonb) from sessionize_guard_fixture;
select last_synced_at into v_after from public.events e join sessionize_guard_fixture f on f.event_id = e.id;
perform pg_temp.assert_sessionize_guard(v_after >= coalesce(v_before, '-infinity'::timestamptz), 'empty sessions import is preserved and updates audit timestamp');
end;
$$;
update public.events set end_date = start_date
where id = (select event_id from sessionize_guard_fixture);
do $$
declare
v_rpc text;
v_fixture record;
v_payload jsonb;
v_result jsonb;
begin
select * into v_fixture from sessionize_guard_fixture;
foreach v_rpc in array array['sync_sessionize_event', 'sync_sessionize_excel'] loop
v_payload := jsonb_build_object('sessions', jsonb_build_array(jsonb_build_object(
'external_id', v_fixture.existing_external_id, 'title', 'Guard single-day title',
'date', '2026-10-23', 'start_time', '09:00', 'end_time', '10:00')));
execute format('select public.%I($1, $2)', v_rpc) into v_result
using v_fixture.event_id, v_payload;
perform pg_temp.assert_sessionize_guard(
v_result @> '{"sessions_created":0,"sessions_updated":1,"slots_created":0,"errors":[]}'::jsonb,
v_rpc || ' accepts an event whose start and end dates are identical');
perform pg_temp.expect_sessionize_reject(
format('select public.%I(%L::uuid, %L::jsonb)', v_rpc, v_fixture.event_id,
jsonb_set(v_payload, '{sessions,0,date}', '"2026-10-24"'::jsonb)::text),
v_rpc || ' rejects the day after a single-day event',
date '2026-10-24', date '2026-10-23', date '2026-10-23');
execute format('select public.%I($1, $2)', v_rpc) into v_result
using v_fixture.event_id, '{"sessions":[]}'::jsonb;
perform pg_temp.assert_sessionize_guard(
v_result @> '{"sessions_created":0,"sessions_updated":0,"slots_created":0,"errors":[]}'::jsonb,
v_rpc || ' preserves empty-session payload behavior');
end loop;
end;
$$;
select pg_temp.assert_sessionize_guard(
(select (last_value, is_called) from public.slots_id_seq)
= (select (slots_last_value, slots_is_called) from sessionize_guard_before),
'complete suite leaves the slot sequence unchanged');
rollback;