Post-event reporting + talk networking incentives

- Talk networking: per-event talk_networking_bonus awarded when two people
  who shared a checked-in talk accept a connection (accept_connection
  re-created, shared_talk flag, get_talk_cohort RPC, points_log category
  check widened); Convivo Networking sub-tab inside the Connect screen
  (Home quick action deep-links in; Connect button reflects existing
  connection state and is disabled for sent/connected/declined); admin
  Events view bonus input (0-10).
- Reports: sidecar POST /export (CSV / multi-sheet XLSX / PDF report via
  new pdfkit dep); APPE Admin Reports view (any event: on-screen summary,
  session feedback summary, top-5, CSV/Excel/PDF downloads); Activity
  session-feedback per-session aggregate header.
- Also carried: @appe.at admin trigger + default password, bulk contact
  delete, session level/area + event-level feedback, agenda level/area
  filters, admin password self-service, schedule level/area fields.
- 18/18 RPC tests; both apps build; exports verified end-to-end.
This commit is contained in:
Lago committed 2026-09-21 22:34:25 +02:00
1 parent 08ab41898b
commit 3adc0fd58f
35 files changed
+3969 -50

No files matched your search

+1
View File
@@ -98,6 +98,7 @@ Check-in tab.
|---|---|
| Checked into a session (by staff) | **+10** |
| Connection accepted | **+5 each** (both people) |
| Connection accepted **with a shared talk** | **+`talk_networking_bonus` each** (per event, default 2, `0` = off) |
| Feedback — rating only | **+5** |
| Feedback — rating + free text | **+10 total** |
+101 -4
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { AuthProvider, useAuth } from './context/AuthContext';
import { ToastProvider } from './context/ToastContext';
import { ToastProvider, useToast } from './context/ToastContext';
import { Login } from './screens/Login';
import { Dashboard } from './views/Dashboard';
import { Contacts } from './views/Contacts';
@@ -10,7 +10,9 @@ import { Schedule } from './views/Schedule';
import { Activity } from './views/Activity';
import { Events } from './views/Events';
import { Interfaces } from './views/Interfaces';
import { Spinner } from './components/ui';
import { Reports } from './views/Reports';
import { Spinner, Modal } from './components/ui';
import { DEFAULT_ADMIN_PASSWORD } from './lib/api';
export type View =
| 'dashboard'
@@ -20,7 +22,8 @@ export type View =
| 'schedule'
| 'activity'
| 'events'
| 'interfaces';
| 'interfaces'
| 'reports';
const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'dashboard', label: 'Dashboard', ico: '📊' },
@@ -31,8 +34,100 @@ const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'activity', label: 'Activity', ico: '⚡' },
{ id: 'events', label: 'Events', ico: '📅' },
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
{ id: 'reports', label: 'Reports', ico: '📤' },
];
/**
* Shown once per session when an admin signs in with the default password
* (`appe-admin-2026`). Prompts them to set a personal password. Dismissable
* ("Not now"); the prompt re-appears on the next sign-in while the default is
* in use.
*/
function ChangePasswordPrompt() {
const { contact, changePassword } = useAuth();
const { push } = useToast();
const [open, setOpen] = useState(false);
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Open the prompt when the signed-in admin is using the default password.
useEffect(() => {
if (contact && contact.password === DEFAULT_ADMIN_PASSWORD) setOpen(true);
}, [contact]);
async function onSubmit() {
if (newPassword.length < 6) {
setError('Password must be at least 6 characters.');
return;
}
if (newPassword !== confirmPassword) {
setError('Passwords do not match.');
return;
}
setBusy(true);
setError(null);
try {
await changePassword(newPassword);
push('success', 'Password updated');
setOpen(false);
setNewPassword('');
setConfirmPassword('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to change password');
} finally {
setBusy(false);
}
}
return (
<Modal
open={open}
onClose={() => setOpen(false)}
title="Change your password"
footer={
<>
<button className="btn ghost" onClick={() => setOpen(false)}>
Not now
</button>
<button className="btn primary" onClick={onSubmit} disabled={busy}>
{busy ? 'Saving…' : 'Save password'}
</button>
</>
}
>
<p style={{ margin: 0, fontSize: 13.5, color: 'var(--muted)' }}>
You signed in with the default admin password. Set a personal password
so only you can access this account.
</p>
<div className="field">
<label>New password</label>
<input
className="input"
type="password"
placeholder="••••••••••"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
autoComplete="new-password"
/>
</div>
<div className="field">
<label>Confirm new password</label>
<input
className="input"
type="password"
placeholder="••••••••••"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
autoComplete="new-password"
/>
</div>
{error && <div className="login-err">{error}</div>}
</Modal>
);
}
function Shell() {
const { contact, loading, signOut } = useAuth();
const [view, setView] = useState<View>('dashboard');
@@ -49,6 +144,7 @@ function Shell() {
return (
<div className="app">
<ChangePasswordPrompt />
<aside className="sidebar">
<div className="brand">
<div className="logo"><img src="/icon-192.png" alt="APPE" /></div>
@@ -99,6 +195,7 @@ function Shell() {
{view === 'activity' && <Activity />}
{view === 'events' && <Events />}
{view === 'interfaces' && <Interfaces />}
{view === 'reports' && <Reports />}
</main>
</div>
);
+12 -1
View File
@@ -1,5 +1,6 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { supabase } from '../lib/supabase';
import { changeMyPassword } from '../lib/api';
import type { Contact } from '../lib/types';
interface AuthState {
@@ -8,6 +9,8 @@ interface AuthState {
/** Sign in with the admin's email + password (event-independent). */
signIn: (email: string, password: string) => Promise<void>;
signOut: () => Promise<void>;
/** Change the current admin's own login password (re-authenticates). */
changePassword: (newPassword: string) => Promise<void>;
}
const AuthContext = createContext<AuthState | null>(null);
@@ -100,8 +103,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setContact(null);
}
async function changePassword(newPassword: string) {
if (!contact) throw new Error('Not signed in');
await changeMyPassword(contact.email, newPassword);
// Re-load the contact so the (now changed) password is reflected.
const c = await loadAdminContact(contact.email);
if (c) setContact(c);
}
return (
<AuthContext.Provider value={{ contact, loading, signIn, signOut }}>
<AuthContext.Provider value={{ contact, loading, signIn, signOut, changePassword }}>
{children}
</AuthContext.Provider>
);
+60 -3
View File
@@ -4,6 +4,7 @@ import type {
Connection,
Contact,
Event,
EventFeedback,
ExcelSyncResult,
Feedback,
LeaderboardRow,
@@ -23,6 +24,9 @@ import type {
export class ApiError extends Error {}
/** The default admin password for @appe.at contacts (set by the DB trigger). */
export const DEFAULT_ADMIN_PASSWORD = 'appe-admin-2026';
async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
const { data, error } = await supabase.rpc(fn, args);
if (error) throw new ApiError(error.message);
@@ -61,6 +65,7 @@ export const getAllSessionSpeakers = () => all<SessionSpeaker>('session_speakers
export const getAllConnections = () => all<Connection>('connections', { col: 'created_at', asc: false });
export const getAllCheckins = () => all<Checkin>('checkins', { col: 'created_at', asc: false });
export const getAllFeedback = () => all<Feedback>('feedback', { col: 'created_at', asc: false });
export const getAllEventFeedback = () => all<EventFeedback>('event_feedback', { col: 'created_at', asc: false });
export const getAllPointsLog = () => all<PointsLogRow>('points_log', { col: 'created_at', asc: false });
export const getLeaderboard = () => all<LeaderboardRow>('leaderboard', { col: 'points', asc: false });
@@ -96,11 +101,34 @@ export async function deleteContact(email: string): Promise<void> {
if (error) throw new ApiError(error.message);
}
/** Delete many contacts at once (admin-only RLS). */
/**
* Delete many contacts at once (admin-only). Uses the `bulk_delete_contacts`
* RPC, which bypasses the "a session must have at least one speaker" guard —
* a direct PostgREST delete would fail (P0001) if the batch includes a contact
* who is the sole speaker of a session.
*/
export async function deleteContacts(emails: string[]): Promise<void> {
if (emails.length === 0) return;
const { error } = await supabase.from('contacts').delete().in('email', emails);
if (error) throw new ApiError(error.message);
await rpc<number>('bulk_delete_contacts', { p_emails: emails });
}
/**
* Change the current admin's own login password. Sets `contacts.password`
* (the `trg_contact_password_sync` trigger re-hashes it into
* `auth.users.encrypted_password`), then re-authenticates with the new
* password so the session reflects the change.
*/
export async function changeMyPassword(email: string, newPassword: string): Promise<void> {
const { error: updateError } = await supabase
.from('contacts')
.update({ password: newPassword })
.eq('email', email);
if (updateError) throw new ApiError(updateError.message);
const { error: signInError } = await supabase.auth.signInWithPassword({
email,
password: newPassword,
});
if (signInError) throw new ApiError(signInError.message);
}
/**
@@ -171,6 +199,7 @@ export async function upsertEvent(
pretix_event_slug?: string | null;
pretix_api_key?: string | null;
use_realtime_clock?: boolean;
talk_networking_bonus?: number;
},
): Promise<void> {
if (id) {
@@ -240,6 +269,34 @@ export async function importSessionizeExcel(eventId: string, file: File): Promis
});
}
/**
* Request an event report from the sidecar (`POST /export`). Returns the
* filename, mime type, and base64 content; the caller decodes and downloads.
*/
export const exportEventReport = (
eventId: string,
format: 'csv' | 'xlsx' | 'pdf',
tables?: string[],
) =>
sidecarFetch<{ filename: string; mime: string; content_base64: string }>('/export', {
method: 'POST',
body: JSON.stringify({ event_id: eventId, format, tables }),
});
/** Decode a base64 report body and trigger a browser download. */
export function downloadReport(res: { filename: string; mime: string; content_base64: string }): void {
const bytes = Uint8Array.from(atob(res.content_base64), (c) => c.charCodeAt(0));
const blob = new Blob([bytes], { type: res.mime });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = res.filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/** Recent sync_runs rows for an event (newest first). */
export const getSyncRuns = (eventId: string) =>
all<SyncRun>('sync_runs', { col: 'started_at', asc: false }).then((rows) =>
+17 -1
View File
@@ -43,6 +43,8 @@ export interface Event {
pretix_api_key?: string | null;
/** When the Sessionize sync last ran for this event. */
last_synced_at: string | null;
/** Bonus points each party earns for a connection when they shared a checked-in talk (0 = off). */
talk_networking_bonus: number;
avg_feedback: number | null;
num_sessions: number;
num_speakers: number;
@@ -214,6 +216,20 @@ export interface Session {
average_feedback: number | null;
ai_generated_feedback: string | null;
material_path: string | null;
/** Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). */
level: string | null;
/** Free-text area/topic classification (e.g. Power Apps, Power Automate). */
area: string | null;
created_at: string;
}
/** Event-level feedback (distinct from the per-session `feedback` table). */
export interface EventFeedback {
id: string;
event_id: string;
contact_email: string;
rating: number;
comment: string | null;
created_at: string;
}
@@ -266,7 +282,7 @@ export interface PointsLogRow {
event_id: string;
contact_email: string;
delta: number;
category: 'checkin' | 'connection' | 'feedback' | 'admin';
category: 'checkin' | 'connection' | 'feedback' | 'admin' | 'talk_networking';
created_at: string;
}
+84 -5
View File
@@ -3,14 +3,15 @@ import {
getAllCheckins,
getAllConnections,
getAllContacts,
getAllEventFeedback,
getAllFeedback,
getActiveEvent,
getSessions,
} from '../lib/api';
import type { Checkin, Connection, Contact, Event, Feedback, Session } from '../lib/types';
import type { Checkin, Connection, Contact, Event, EventFeedback, Feedback, Session } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
type Tab = 'checkins' | 'connections' | 'feedback';
type Tab = 'checkins' | 'connections' | 'feedback' | 'event_feedback';
export function Activity() {
const [event, setEvent] = useState<Event | null>(null);
@@ -21,17 +22,19 @@ export function Activity() {
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [connections, setConnections] = useState<Connection[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [eventFeedback, setEventFeedback] = useState<EventFeedback[]>([]);
const [error, setError] = useState<string | null>(null);
async function load() {
try {
const ev = await getActiveEvent();
setEvent(ev);
const [c, ck, cn, fb] = await Promise.all([
const [c, ck, cn, fb, efb] = await Promise.all([
getAllContacts(),
getAllCheckins(),
getAllConnections(),
getAllFeedback(),
getAllEventFeedback(),
]);
setContacts(c);
if (ev) {
@@ -40,6 +43,7 @@ export function Activity() {
setCheckins(ck.filter((x) => x.event_id === ev.id));
setConnections(cn.filter((x) => x.event_id === ev.id));
setFeedback(fb.filter((x) => x.event_id === ev.id));
setEventFeedback(efb.filter((x) => x.event_id === ev.id));
}
setLoaded(true);
} catch (e) {
@@ -61,6 +65,26 @@ export function Activity() {
return (id: string) => m.get(id) ?? id;
}, [sessions]);
// Per-session feedback aggregate (avg rating + response count), for the
// post-event session feedback summary.
const sessionFeedbackSummary = useMemo(() => {
const bySession = new Map<string, { count: number; sum: number }>();
for (const f of feedback) {
const e = bySession.get(f.session_id) ?? { count: 0, sum: 0 };
e.count += 1;
e.sum += f.rating;
bySession.set(f.session_id, e);
}
return [...bySession.entries()]
.map(([session_id, e]) => ({
session_id,
title: sessionTitle(session_id),
avg: e.sum / e.count,
count: e.count,
}))
.sort((a, b) => b.avg - a.avg);
}, [feedback, sessionTitle]);
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
@@ -91,7 +115,7 @@ export function Activity() {
<div>
<h1>Activity</h1>
<div className="sub">
{event.name} · {checkins.length} check-ins · {connections.length} connections · {feedback.length} feedback.
{event.name} · {checkins.length} check-ins · {connections.length} connections · {feedback.length} session feedback · {eventFeedback.length} event feedback.
</div>
</div>
</div>
@@ -104,7 +128,10 @@ export function Activity() {
Connections
</button>
<button className={tab === 'feedback' ? 'active' : ''} onClick={() => setTab('feedback')}>
Feedback
Session feedback
</button>
<button className={tab === 'event_feedback' ? 'active' : ''} onClick={() => setTab('event_feedback')}>
Event feedback
</button>
</div>
@@ -185,6 +212,23 @@ export function Activity() {
{feedback.length === 0 ? (
<Empty icon="⭐" text="No feedback yet." />
) : (
<>
{/* Per-session aggregate header (the post-event session feedback summary). */}
<div style={{ marginBottom: 12 }}>
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>
Per-session summary
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{sessionFeedbackSummary.map((s) => (
<span key={s.session_id} className="pill amber" title={s.title}>
{s.title} · {s.avg.toFixed(1)}★ · {s.count}
</span>
))}
</div>
</div>
</>
)}
{feedback.length > 0 && (
<div className="table-wrap">
<table className="data">
<thead>
@@ -216,6 +260,41 @@ export function Activity() {
)}
</div>
)}
{tab === 'event_feedback' && (
<div className="card">
{eventFeedback.length === 0 ? (
<Empty icon="⭐" text="No event-level feedback yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>From</th>
<th>Rating</th>
<th>Comment</th>
<th>When</th>
</tr>
</thead>
<tbody>
{eventFeedback.map((f) => (
<tr key={f.id}>
<td>
<PersonCell name={nameOf(f.contact_email)} email={f.contact_email} />
</td>
<td>
<span className="pill amber">{'★'.repeat(f.rating)}</span>
</td>
<td className="muted">{f.comment || '—'}</td>
<td className="muted">{fmt(f.created_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)}
</div>
);
}
+23
View File
@@ -293,6 +293,7 @@ function EventModal({
const [pretixLoading, setPretixLoading] = useState(false);
const [pretixError, setPretixError] = useState<string | null>(null);
const [realtimeClock, setRealtimeClock] = useState(event?.use_realtime_clock ?? false);
const [talkBonus, setTalkBonus] = useState(event?.talk_networking_bonus ?? 2);
const [busy, setBusy] = useState(false);
const lastFetchedKey = useRef<string | null>(null);
@@ -339,6 +340,7 @@ function EventModal({
pretix_event_slug: pretixEventSlug.trim() || null,
pretix_api_key: pretixApiKey.trim() || null,
use_realtime_clock: realtimeClock,
talk_networking_bonus: Math.max(0, Math.min(10, Math.round(talkBonus) || 0)),
});
onSaved(event ? 'Event updated' : 'Event created');
} catch (e) {
@@ -491,6 +493,27 @@ function EventModal({
<Toggle checked={realtimeClock} onChange={setRealtimeClock} label={realtimeClock ? 'On' : 'Off'} />
</div>
</div>
<div className="field">
<div className="row between" style={{ alignItems: 'center' }}>
<div>
<label>Talk networking bonus</label>
<div className="muted small" style={{ marginTop: 2, maxWidth: 420 }}>
Points each party earns when two people who were checked into the same talk accept a
connection. <b>0 disables</b> the bonus (the +5 connection award still applies).
</div>
</div>
<input
className="input mono"
type="number"
min={0}
max={10}
step={1}
style={{ width: 84, textAlign: 'center' }}
value={Number.isFinite(talkBonus) ? talkBonus : 0}
onChange={(e) => setTalkBonus(parseInt(e.target.value, 10) || 0)}
/>
</div>
</div>
</Modal>
);
}
+404
View File
@@ -0,0 +1,404 @@
import { useEffect, useMemo, useState } from 'react';
import {
downloadReport,
exportEventReport,
getAllCheckins,
getAllConnections,
getAllContacts,
getAllEventFeedback,
getAllEvents,
getAllFeedback,
getAllPointsLog,
getLeaderboard,
getRegistrations,
getSessions,
} from '../lib/api';
import type {
Checkin,
Connection,
Contact,
Event,
EventFeedback,
Feedback,
LeaderboardRow,
PointsLogRow,
Registration,
Session,
} from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Spinner } from '../components/ui';
const TABLES = [
'registrations',
'checkins',
'connections',
'session_feedback',
'event_feedback',
'leaderboard',
'points_log',
] as const;
const CATEGORY_LABEL: Record<string, string> = {
checkin: 'Session check-ins',
connection: 'Connections',
feedback: 'Feedback',
talk_networking: 'Talk networking',
admin: 'Other',
};
/**
* Post-event reporting & export. For any event (active or past): an on-screen
* summary (session-feedback summary + aggregates) and CSV / Excel / PDF report
* downloads (served by the sidecar's `POST /export`).
*/
export function Reports() {
const { push } = useToast();
const [events, setEvents] = useState<Event[]>([]);
const [selectedId, setSelectedId] = useState('');
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [contacts, setContacts] = useState<Contact[]>([]);
const [registrations, setRegistrations] = useState<Registration[]>([]);
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [connections, setConnections] = useState<Connection[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [eventFeedback, setEventFeedback] = useState<EventFeedback[]>([]);
const [leaderboard, setLeaderboard] = useState<LeaderboardRow[]>([]);
const [pointsLog, setPointsLog] = useState<PointsLogRow[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [tables, setTables] = useState<Set<string>>(new Set(TABLES));
const [exporting, setExporting] = useState<'csv' | 'xlsx' | 'pdf' | null>(null);
async function load() {
try {
const evs = await getAllEvents();
setEvents(evs);
const active = evs.find((e) => e.is_active);
const first = active ?? evs[0];
if (first) setSelectedId((cur) => cur || first.id);
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
// Load the selected event's data (any event, not just the active one).
useEffect(() => {
if (!selectedId) return;
let active = true;
(async () => {
try {
const [c, reg, ck, cn, fb, efb, lb, pl, ss] = await Promise.all([
getAllContacts(),
getRegistrations(selectedId),
getAllCheckins(),
getAllConnections(),
getAllFeedback(),
getAllEventFeedback(),
getLeaderboard(),
getAllPointsLog(),
getSessions(selectedId),
]);
if (!active) return;
setContacts(c);
setRegistrations(reg);
setCheckins(ck.filter((x) => x.event_id === selectedId));
setConnections(cn.filter((x) => x.event_id === selectedId));
setFeedback(fb.filter((x) => x.event_id === selectedId));
setEventFeedback(efb.filter((x) => x.event_id === selectedId));
setLeaderboard(lb.filter((x) => x.event_id === selectedId));
setPointsLog(pl.filter((x) => x.event_id === selectedId));
setSessions(ss);
} catch (e) {
if (active) setError(e instanceof Error ? e.message : 'Failed to load event data');
}
})();
return () => {
active = false;
};
}, [selectedId]);
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email, c.full_name]));
return (email: string) => m.get(email) ?? email;
}, [contacts]);
// ---- Aggregates -----------------------------------------------------------
const byType = useMemo(() => {
const t: Record<string, number> = {};
for (const r of registrations) t[r.type] = (t[r.type] ?? 0) + 1;
return t;
}, [registrations]);
const acceptedConnections = useMemo(
() => connections.filter((c) => c.status === 'accepted').length,
[connections],
);
const sessionFeedbackAvg = useMemo(() => {
if (feedback.length === 0) return null;
return feedback.reduce((s, f) => s + f.rating, 0) / feedback.length;
}, [feedback]);
const eventFeedbackAvg = useMemo(() => {
if (eventFeedback.length === 0) return null;
return eventFeedback.reduce((s, f) => s + f.rating, 0) / eventFeedback.length;
}, [eventFeedback]);
// Per-session feedback summary (the "post-event session feedback summary").
const sessionSummary = useMemo(() => {
const bySession = new Map<string, { count: number; sum: number }>();
for (const f of feedback) {
const e = bySession.get(f.session_id) ?? { count: 0, sum: 0 };
e.count += 1;
e.sum += f.rating;
bySession.set(f.session_id, e);
}
return sessions
.map((s) => {
const e = bySession.get(s.id);
return {
title: s.title,
room: s.room,
avg: e ? e.sum / e.count : null,
count: e ? e.count : 0,
};
})
.filter((s) => s.count > 0)
.sort((a, b) => (b.avg ?? 0) - (a.avg ?? 0));
}, [sessions, feedback]);
const topLeaderboard = useMemo(
() => [...leaderboard].sort((a, b) => b.points - a.points).slice(0, 5),
[leaderboard],
);
const pointsByCategory = useMemo(() => {
const t: Record<string, number> = {};
for (const l of pointsLog) t[l.category] = (t[l.category] ?? 0) + l.delta;
return t;
}, [pointsLog]);
// ---- Export -------------------------------------------------------------
async function doExport(format: 'csv' | 'xlsx' | 'pdf') {
if (!selectedId) return;
setExporting(format);
try {
const res = await exportEventReport(selectedId, format, format === 'pdf' ? undefined : [...tables]);
downloadReport(res);
push('success', `Downloaded ${format.toUpperCase()} report`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Export failed');
} finally {
setExporting(null);
}
}
function toggleTable(t: string) {
setTables((prev) => {
const next = new Set(prev);
if (next.has(t)) next.delete(t);
else next.add(t);
return next;
});
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
const selected = events.find((e) => e.id === selectedId);
return (
<div>
<div className="page-head">
<div>
<h1>Reports</h1>
<div className="sub">Post-event summary + CSV / Excel / PDF export. Works for any event.</div>
</div>
<select
className="input"
style={{ maxWidth: 320 }}
value={selectedId}
onChange={(e) => setSelectedId(e.target.value)}
>
{events.map((e) => (
<option key={e.id} value={e.id}>
{e.name} {e.is_active ? '(active)' : ''}
</option>
))}
</select>
</div>
{!selected ? (
<div className="card">
<Empty icon="📅" text="No events yet. Create one in the Events view first." />
</div>
) : (
<>
{/* On-screen summary */}
<div className="card" style={{ marginBottom: 18 }}>
<h2 className="h2">📊 Summary — {selected.name}</h2>
<div className="muted small" style={{ marginBottom: 12 }}>
{selected.start_date} – {selected.end_date}
{selected.location ? ` · ${selected.location}` : ''}
</div>
<div className="stat-grid">
<Stat label="Registrations" value={registrations.length} />
<Stat label="Check-ins" value={checkins.length} />
<Stat label="Connections" value={connections.length} sub={`${acceptedConnections} accepted`} />
<Stat label="Session feedback" value={feedback.length} sub={sessionFeedbackAvg != null ? `avg ${sessionFeedbackAvg.toFixed(1)}★` : undefined} />
<Stat label="Event feedback" value={eventFeedback.length} sub={eventFeedbackAvg != null ? `avg ${eventFeedbackAvg.toFixed(1)}★` : undefined} />
</div>
<div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', marginTop: 14 }}>
<div>
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>Registrations by type</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{Object.entries(byType).map(([t, n]) => (
<span key={t} className="pill">{t}: {n}</span>
))}
</div>
</div>
<div>
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>Points by category</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{Object.entries(pointsByCategory).map(([c, n]) => (
<span key={c} className="pill">{CATEGORY_LABEL[c] ?? c}: +{n}</span>
))}
</div>
</div>
</div>
</div>
{/* Session feedback summary */}
<div className="card" style={{ marginBottom: 18 }}>
<h2 className="h2">⭐ Session feedback summary</h2>
{sessionSummary.length === 0 ? (
<Empty icon="⭐" text="No session feedback yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Session</th>
<th>Room</th>
<th>Avg rating</th>
<th>Responses</th>
</tr>
</thead>
<tbody>
{sessionSummary.map((s) => (
<tr key={s.title}>
<td style={{ fontWeight: 600 }}>{s.title}</td>
<td className="muted">{s.room ?? '—'}</td>
<td>
<span className="pill amber">
{s.avg != null ? `${s.avg.toFixed(1)}★` : '—'}
</span>
</td>
<td className="muted">{s.count}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Top leaderboard */}
<div className="card" style={{ marginBottom: 18 }}>
<h2 className="h2">🏆 Top points</h2>
{topLeaderboard.length === 0 ? (
<Empty icon="🏆" text="No points yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>#</th>
<th>Attendee</th>
<th>Points</th>
</tr>
</thead>
<tbody>
{topLeaderboard.map((r, i) => (
<tr key={r.contact_email}>
<td className="muted">{i + 1}</td>
<td style={{ fontWeight: 600 }}>{nameOf(r.contact_email)}</td>
<td>
<span className="pill amber">⚡ {r.points}</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Export */}
<div className="card">
<h2 className="h2">📤 Export</h2>
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 14 }}>
<button
className="btn primary"
disabled={exporting !== null || tables.size === 0}
onClick={() => void doExport('csv')}
>
{exporting === 'csv' ? 'Preparing…' : 'Download CSV'}
</button>
<button
className="btn primary"
disabled={exporting !== null || tables.size === 0}
onClick={() => void doExport('xlsx')}
>
{exporting === 'xlsx' ? 'Preparing…' : 'Download Excel'}
</button>
<button className="btn primary" disabled={exporting !== null} onClick={() => void doExport('pdf')}>
{exporting === 'pdf' ? 'Preparing…' : 'Download PDF report'}
</button>
</div>
<div className="muted small" style={{ marginBottom: 8 }}>
Tables included in CSV / Excel:
</div>
<div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
{TABLES.map((t) => (
<label key={t} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
<input
type="checkbox"
checked={tables.has(t)}
onChange={() => toggleTable(t)}
style={{ width: 16, height: 16, accentColor: 'var(--accent)' }}
/>
<span className="muted small">{t.replace('_', ' ')}</span>
</label>
))}
</div>
</div>
</>
)}
</div>
);
}
function Stat({ label, value, sub }: { label: string; value: number; sub?: string }) {
return (
<div className="stat">
<div className="val">{value}</div>
<div className="lbl">
{label}
{sub ? ` · ${sub}` : ''}
</div>
</div>
);
}
+15 -1
View File
@@ -193,7 +193,7 @@ export function Schedule() {
<div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 700, fontSize: 14 }}>{s.title}</div>
<div className="muted small">
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null].filter(Boolean).join(' · ')}
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null, s.level ? `📶 ${s.level}` : null, s.area ? `🗂 ${s.area}` : null].filter(Boolean).join(' · ')}
</div>
<div className="muted small" style={{ marginTop: 4 }}>
{s.average_feedback != null && <span>⭐ {s.average_feedback.toFixed(1)}</span>}
@@ -364,6 +364,8 @@ function SessionModal({
const [room, setRoom] = useState(session?.room ?? '');
const [capacity, setCapacity] = useState(session?.capacity?.toString() ?? '');
const [description, setDescription] = useState(session?.description ?? '');
const [level, setLevel] = useState(session?.level ?? '');
const [area, setArea] = useState(session?.area ?? '');
const [speakerEmails, setSpeakerEmails] = useState<string[]>(currentSpeakers);
const [material, setMaterial] = useState<File | null>(null);
const [busy, setBusy] = useState(false);
@@ -377,6 +379,8 @@ function SessionModal({
room: room.trim() || null,
capacity: capacity ? parseInt(capacity, 10) : null,
description: description.trim() || null,
level: level.trim() || null,
area: area.trim() || null,
slot_id: slotId,
event_id: eventId,
};
@@ -445,6 +449,16 @@ function SessionModal({
<label>Description</label>
<textarea className="input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="—" />
</div>
<div className="grid-2">
<div className="field">
<label>Level</label>
<input className="input" value={level} onChange={(e) => setLevel(e.target.value)} placeholder="e.g. 100 / Beginner" />
</div>
<div className="field">
<label>Area / Topic</label>
<input className="input" value={area} onChange={(e) => setArea(e.target.value)} placeholder="e.g. Power Apps" />
</div>
</div>
<div className="field">
<label>Speakers ({speakerEmails.length})</label>
+27 -2
View File
@@ -9,6 +9,7 @@ import { Connections } from './screens/Connections';
import { Leaderboard } from './screens/Leaderboard';
import { Profile } from './screens/Profile';
import { Feedback } from './screens/Feedback';
import { EventFeedback } from './screens/EventFeedback';
import { QrImage, Spinner } from './components/ui';
import { getMyConnections } from './lib/api';
import { usePolling } from './lib/usePolling';
@@ -26,7 +27,22 @@ function Shell() {
const { session, contact, registration, loading, refresh, signOut } = useAuth();
const [tab, setTab] = useState<Tab>('home');
const [feedbackSession, setFeedbackSession] = useState<string | null>(null);
const [eventFeedbackOpen, setEventFeedbackOpen] = useState(false);
const [pendingIncoming, setPendingIncoming] = useState(0);
// Which sub-tab the Connect screen opens on (default 'mine'; 'networking'
// when reached via the Home "Networking" quick action).
const [connectionsTab, setConnectionsTab] = useState<'mine' | 'req' | 'networking'>('mine');
// Home's `go` handles the tab ids; 'networking' routes into the Connect
// screen's networking sub-tab.
const go = (t: string) => {
if (t === 'networking') {
setConnectionsTab('networking');
setTab('connections');
return;
}
setTab(t as Tab);
};
const email = contact?.email ?? '';
@@ -123,16 +139,25 @@ function Shell() {
);
}
// Event-level feedback is also a full-screen takeover (no tab bar).
if (eventFeedbackOpen) {
return (
<div className="app">
<EventFeedback onDone={() => { setEventFeedbackOpen(false); setTab('home'); }} />
</div>
);
}
// The home page (incl. the tab bar) is identical for every role. Staff keep
// their check-in capability inside the Scan screen (Attendee/Staff toggle).
const scanLabel = 'Scan';
return (
<div className="app">
{tab === 'home' && <Home go={(t) => setTab(t as Tab)} />}
{tab === 'home' && <Home go={go} onEventFeedback={() => setEventFeedbackOpen(true)} />}
{tab === 'agenda' && <Agenda openFeedback={(id) => setFeedbackSession(id)} />}
{tab === 'scan' && <Scan />}
{tab === 'connections' && <Connections />}
{tab === 'connections' && <Connections initialTab={connectionsTab} />}
{tab === 'profile' && <Profile />}
{tab === 'leaderboard' && <Leaderboard />}
+24 -2
View File
@@ -5,6 +5,7 @@ import type {
Connection,
Contact,
Event,
EventFeedback,
Feedback,
FeedbackResult,
LeaderboardRow,
@@ -15,6 +16,8 @@ import type {
Session,
Slot,
WelcomeCheckinResult,
AcceptConnectionResult,
TalkCohortMember,
} from './types';
export class ApiError extends Error {}
@@ -74,6 +77,8 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
ai_generated_feedback: r.ai_generated_feedback,
material_path: r.material_path,
speakers: r.speakers,
level: r.level,
area: r.area,
created_at: '',
});
}
@@ -81,6 +86,17 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
return [...map.values()].sort((a, b) => a.slot.id - b.slot.id);
}
/** Submit (or update) the current user's event-level feedback. */
export async function submitEventFeedback(rating: number, comment: string): Promise<void> {
await rpc('submit_event_feedback', { p_rating: rating, p_comment: comment });
}
/** Read the current user's own event-level feedback (null if not yet submitted). */
export async function getMyEventFeedback(): Promise<EventFeedback | null> {
const rows = await rpc<EventFeedback[]>('get_my_event_feedback', {});
return rows[0] ?? null;
}
/** The signed-in contact's own row (filter by email — admins can see all rows). */
export async function getMyContact(email: string): Promise<Contact | null> {
const { data, error } = await supabase.from('contacts').select('*').eq('email', email).maybeSingle();
@@ -139,8 +155,9 @@ export async function createConnectionRequest(targetQr: string): Promise<Connect
return rpc<Connection>('create_connection_request', { p_target_qr: targetQr });
}
export async function acceptConnection(id: string): Promise<Connection> {
return rpc<Connection>('accept_connection', { p_connection_id: id });
export async function acceptConnection(id: string): Promise<AcceptConnectionResult> {
// accept_connection returns a single composite row (a JSON object).
return rpc<AcceptConnectionResult>('accept_connection', { p_connection_id: id });
}
export async function rejectConnection(id: string): Promise<Connection> {
@@ -154,6 +171,11 @@ export async function getMyCheckins(email: string): Promise<string[]> {
return (data as { session_id: string }[]).map((c) => c.session_id);
}
/** Other attendees (staff excluded, self excluded) checked into the same talk. */
export async function getTalkCohort(sessionId: string): Promise<TalkCohortMember[]> {
return rpc<TalkCohortMember[]>('get_talk_cohort', { p_session_id: sessionId });
}
export async function checkinAttendee(sessionId: string, attendeeQr: string): Promise<CheckinResult> {
const rows = await rpc<CheckinResult[]>('checkin_attendee', { p_session_id: sessionId, p_attendee_qr: attendeeQr });
return rows[0];
+33 -1
View File
@@ -35,6 +35,8 @@ export interface Event {
is_active: boolean;
/** When true, the app uses the real system clock for slot status (Live/Next/Done). */
use_realtime_clock: boolean;
/** Bonus points each party earns for a connection when they shared a checked-in talk (0 = off). */
talk_networking_bonus: number;
avg_feedback: number | null;
num_sessions: number;
num_speakers: number;
@@ -68,6 +70,10 @@ export interface Session {
material_path: string | null;
/** Comma-separated speaker names (from the get_agenda RPC). */
speakers: string | null;
/** Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). */
level: string | null;
/** Free-text area/topic classification (e.g. Power Apps, Power Automate). */
area: string | null;
created_at: string;
}
@@ -88,6 +94,18 @@ export interface AgendaRow {
ai_generated_feedback: string | null;
material_path: string | null;
speakers: string | null;
level: string | null;
area: string | null;
}
/** Event-level feedback (distinct from the per-session `feedback` table). */
export interface EventFeedback {
id: string;
event_id: string;
contact_email: string;
rating: number;
comment: string | null;
created_at: string;
}
export interface Preference {
@@ -141,7 +159,7 @@ export interface PointsLogRow {
event_id: string;
contact_email: string;
delta: number;
category: 'checkin' | 'connection' | 'feedback' | 'admin';
category: 'checkin' | 'connection' | 'feedback' | 'admin' | 'talk_networking';
created_at: string;
}
@@ -169,6 +187,20 @@ export interface WelcomeCheckinResult {
already: boolean;
}
/** Result of accepting a connection (the connection row + the shared-talk flag). */
export interface AcceptConnectionResult extends Connection {
/** True when both parties were checked into the same session (talk). */
shared_talk: boolean;
}
/** A person checked into the same talk (from get_talk_cohort). */
export interface TalkCohortMember {
email: string;
full_name: string;
registration_type: RegistrationType | null;
qr_token: string | null;
}
export interface FeedbackResult {
feedback_id: string;
points: number;
+76 -2
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import {
@@ -26,8 +26,29 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
const fileRef = useRef<HTMLInputElement>(null);
const { toast } = useToast();
// Agenda filters: level + area (free-text, dynamic — built from the distinct
// values actually present in the agenda, so it works for numeric levels
// (100/200/300) or text levels (Beginner/Intermediate) alike).
const [levelFilter, setLevelFilter] = useState<string>('');
const [areaFilter, setAreaFilter] = useState<string>('');
const email = contact?.email ?? '';
// Distinct level + area values present in the agenda (for the filter dropdowns).
const levelOptions = useMemo(() => {
const set = new Set<string>();
for (const { sessions } of slots) for (const s of sessions) if (s.level) set.add(s.level);
return [...set].sort();
}, [slots]);
const areaOptions = useMemo(() => {
const set = new Set<string>();
for (const { sessions } of slots) for (const s of sessions) if (s.area) set.add(s.area);
return [...set].sort();
}, [slots]);
const matchesFilter = (s: Session) =>
(!levelFilter || s.level === levelFilter) && (!areaFilter || s.area === areaFilter);
useEffect(() => {
let active = true;
(async () => {
@@ -144,9 +165,60 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
Pick <b>one session per slot</b> — you can change until the slot starts.
</div>
{/* Agenda filters: level + area (only shown if there are values to filter by). */}
{(levelOptions.length > 0 || areaOptions.length > 0) && (
<div className="row" style={{ gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
{levelOptions.length > 0 && (
<select
className="input"
style={{ flex: 1, minWidth: 120 }}
value={levelFilter}
onChange={(e) => setLevelFilter(e.target.value)}
aria-label="Filter by level"
>
<option value="">All levels</option>
{levelOptions.map((l) => (
<option key={l} value={l}>{l}</option>
))}
</select>
)}
{areaOptions.length > 0 && (
<select
className="input"
style={{ flex: 1, minWidth: 120 }}
value={areaFilter}
onChange={(e) => setAreaFilter(e.target.value)}
aria-label="Filter by area"
>
<option value="">All areas</option>
{areaOptions.map((a) => (
<option key={a} value={a}>{a}</option>
))}
</select>
)}
{(levelFilter || areaFilter) && (
<button
className="btn ghost small"
onClick={() => { setLevelFilter(''); setAreaFilter(''); }}
aria-label="Clear filters"
>
✕
</button>
)}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{slots.map(({ slot, sessions }) => {
const status = slotStatus(slot, now);
const isServiceSlot = slot.type === 'service_session';
// Apply the level/area filter to non-service sessions only (service
// sessions have no level/area and are always shown).
const visibleSessions = isServiceSlot
? sessions
: sessions.filter(matchesFilter);
// Skip the slot if it's a talk slot and all its sessions are filtered out.
if (!isServiceSlot && visibleSessions.length === 0) return null;
return (
<div className="slot-card" key={slot.id}>
<div className="slot-head">
@@ -160,7 +232,7 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
{status === 'now' && <span className="pill violet">● Live</span>}
{status === 'next' && <span className="pill cyan">Up next</span>}
</div>
{sessions.map((s) => {
{visibleSessions.map((s) => {
const picked = pickFor(slot.id) === s.id;
const isMySession = mySpeakerSessions.includes(s.id);
const isService = slot.type === 'service_session';
@@ -204,6 +276,8 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
</div>
<div className="row" style={{ gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
<span className="pill">{selIsService ? '' : '🎤 '}{selected.speakers}</span>
{selected.level && <span className="pill violet">📶 {selected.level}</span>}
{selected.area && <span className="pill cyan">🗂 {selected.area}</span>}
{selected.capacity && <span className="pill">👥 {selected.capacity}</span>}
{selCheckedIn && <span className="pill green">✓ Checked in</span>}
</div>
+16 -3
View File
@@ -6,10 +6,20 @@ import { capWords } from '../lib/time';
import type { Connection, PublicContact } from '../lib/types';
import { Avatar, Empty, Sheet, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
import { NetworkingPanel } from './Networking';
export function Connections() {
export function Connections({
initialTab = 'mine',
}: {
initialTab?: 'mine' | 'req' | 'networking';
}) {
const { contact } = useAuth();
const [tab, setTab] = useState<'mine' | 'req'>('mine');
const [tab, setTab] = useState<'mine' | 'req' | 'networking'>(initialTab);
// A deep-link (e.g. the Home "Networking" quick action) re-targets the tab.
useEffect(() => {
setTab(initialTab);
}, [initialTab]);
const [conns, setConns] = useState<Connection[]>([]);
const [people, setPeople] = useState<Map<string, PublicContact>>(new Map());
const [points, setPoints] = useState<Map<string, number>>(new Map());
@@ -71,12 +81,13 @@ export function Connections() {
return (
<section className="screen">
<div className="h1">Connections</div>
<div className="h1">{tab === 'networking' ? 'Networking' : 'Connections'}</div>
<div className="seg">
<button className={tab === 'mine' ? 'active' : ''} data-testid="connections-tab-mine" onClick={() => setTab('mine')}>My connections</button>
<button className={tab === 'req' ? 'active' : ''} data-testid="connections-tab-req" onClick={() => setTab('req')}>
Requests {incoming.length + outgoing.length > 0 && <span className="pill violet" style={{ marginLeft: 4 }}>{incoming.length + outgoing.length}</span>}
</button>
<button className={tab === 'networking' ? 'active' : ''} data-testid="connections-tab-networking" onClick={() => setTab('networking')}>🗣 Networking</button>
</div>
{tab === 'mine' &&
@@ -146,6 +157,8 @@ export function Connections() {
</div>
)}
{tab === 'networking' && <NetworkingPanel />}
{detail && (() => {
const p = people.get(detail.email);
const t = p?.registration_type ?? null;
+121
View File
@@ -0,0 +1,121 @@
import { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import { getMyEventFeedback, submitEventFeedback } from '../lib/api';
import { Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
/**
* Event-level feedback (distinct from the per-session Feedback screen).
* Any registered participant can rate the event overall (1–5) + leave a
* comment. Idempotent: one row per (event, contact) — re-submitting updates
* the existing row.
*/
export function EventFeedback({ onDone }: { onDone: () => void }) {
const { contact } = useAuth();
const { event, loading } = useEvent();
const [rating, setRating] = useState(0);
const [comment, setComment] = useState('');
const [busy, setBusy] = useState(false);
const [submitted, setSubmitted] = useState(false);
const { toast } = useToast();
// Pre-fill with the user's existing event feedback (if any).
useEffect(() => {
let active = true;
(async () => {
try {
const existing = await getMyEventFeedback();
if (!active || !existing) return;
setRating(existing.rating);
setComment(existing.comment ?? '');
setSubmitted(true);
} catch {
/* non-fatal */
}
})();
return () => {
active = false;
};
}, []);
if (loading || !event) {
return (
<section className="screen no-tab">
<div className="center" style={{ flex: 1 }}>
<Spinner />
</div>
</section>
);
}
async function submit() {
if (rating === 0) return;
setBusy(true);
try {
await submitEventFeedback(rating, comment.trim());
toast('Thanks for your feedback! ⭐', 'ok');
setSubmitted(true);
onDone();
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not submit feedback', 'err');
} finally {
setBusy(false);
}
}
return (
<section className="screen no-tab">
<div className="row" style={{ marginBottom: 14 }}>
<button className="btn ghost small" onClick={onDone}>← Back</button>
<div className="grow" style={{ textAlign: 'center' }}>
<div className="h2">Rate this event</div>
</div>
<span style={{ width: 60 }} />
</div>
<div className="card" style={{ textAlign: 'center' }}>
<div className="h2">{event.name}</div>
<div className="muted small" style={{ marginTop: 4 }}>
{event.location ? `${event.location} · ` : ''}
{event.start_date}
</div>
</div>
<div className="stars" style={{ justifyContent: 'center', margin: '20px 0' }}>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
data-testid={`event-feedback-star-${n}`}
className={`star ${n <= rating ? 'on' : ''}`}
onClick={() => setRating(n)}
aria-label={`${n} star${n > 1 ? 's' : ''}`}
>
★
</button>
))}
</div>
<textarea
className="input"
data-testid="event-feedback-comment"
placeholder="Share your thoughts about the event (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
/>
<button
className="btn primary"
data-testid="event-feedback-submit"
disabled={busy || rating === 0}
onClick={submit}
>
{busy ? 'Submitting…' : submitted ? 'Update feedback' : 'Submit feedback'}
</button>
<div className="muted small" style={{ textAlign: 'center', marginTop: 8 }}>
{contact ? `Signing in as ${contact.full_name}` : ''}
</div>
</section>
);
}
+10 -1
View File
@@ -42,7 +42,7 @@ function ConcurrentList({ sessions }: { sessions: Session[] }) {
);
}
export function Home({ go }: { go: (tab: string) => void }) {
export function Home({ go, onEventFeedback }: { go: (tab: string) => void; onEventFeedback?: () => void }) {
const { contact, registration } = useAuth();
const { event, slots, sessionById, slotById, now, clockMode, loading } = useEvent();
const [prefs, setPrefs] = useState<Preference[]>([]);
@@ -236,11 +236,20 @@ export function Home({ go }: { go: (tab: string) => void }) {
<span className="ico">🤝</span>
<span className="lbl">Connections</span>
</div>
<div className="qa" onClick={() => go('networking')}>
<span className="ico">🗣</span>
<span className="lbl">Networking</span>
</div>
<div className="qa" onClick={() => go('leaderboard')}>
<span className="ico">🏆</span>
<span className="lbl">Leaderboard</span>
</div>
</div>
{onEventFeedback && (
<button className="btn ghost" style={{ width: '100%', marginTop: 10 }} onClick={onEventFeedback}>
⭐ Rate this event
</button>
)}
<div style={{ height: 8 }} />
{/* Pending material popup (speakers only, when a session is missing its attachment) */}
+219
View File
@@ -0,0 +1,219 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import {
createConnectionRequest,
getMyCheckins,
getMyConnections,
getTalkCohort,
} from '../lib/api';
import { capWords } from '../lib/time';
import type { Connection, TalkCohortMember } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
/**
* Networking around talks (an embeddable panel, shown as a tab inside the
* Connect screen). For every talk the user was checked into, list the other
* attendees who were also in that talk (the "talk cohort") so the user can
* make a connection. Accepting a connection with a shared talk earns the
* per-event talk networking bonus (see `events.talk_networking_bonus`).
*/
export function NetworkingPanel() {
const { contact } = useAuth();
const { event, sessionById, loading } = useEvent();
const [myCheckins, setMyCheckins] = useState<string[]>([]);
const [cohorts, setCohorts] = useState<Record<string, TalkCohortMember[]>>({});
const [loadingCohorts, setLoadingCohorts] = useState(false);
const [connecting, setConnecting] = useState<string | null>(null);
// The user's existing connections, so a Connect button can show the current
// state ("Sent" / "Connected" / …) instead of allowing duplicate requests.
const [conns, setConns] = useState<Connection[]>([]);
const { toast } = useToast();
const email = contact?.email ?? '';
const loadConns = useCallback(async () => {
try {
setConns(await getMyConnections());
} catch {
/* non-fatal */
}
}, []);
useEffect(() => {
if (email) void loadConns();
}, [email, loadConns]);
// Keep the connection states fresh (a peer may accept while the panel is open).
useEffect(() => {
window.addEventListener('connections-changed', loadConns);
return () => window.removeEventListener('connections-changed', loadConns);
}, [loadConns]);
/** The existing connection to a given person (any status), or null. */
const connWith = (theirEmail: string) =>
conns.find((c) => (c.from_email === email && c.to_email === theirEmail) ||
(c.from_email === theirEmail && c.to_email === email)) ?? null;
// Load the sessions the user is checked into, then each talk's cohort.
useEffect(() => {
if (!email) return;
let active = true;
(async () => {
try {
const ids = await getMyCheckins(email);
if (!active) return;
setMyCheckins(ids);
if (ids.length === 0) return;
setLoadingCohorts(true);
const results = await Promise.all(
ids.map(async (sid): Promise<[string, TalkCohortMember[]]> => {
try {
return [sid, await getTalkCohort(sid)];
} catch {
return [sid, []];
}
}),
);
if (!active) return;
const map: Record<string, TalkCohortMember[]> = {};
for (const [sid, list] of results) map[sid] = list;
setCohorts(map);
} catch {
/* non-fatal */
} finally {
if (active) setLoadingCohorts(false);
}
})();
return () => {
active = false;
};
}, [email]);
// Only show talks that actually exist in the agenda (check-ins for a
// service session or a removed session are skipped).
const myTalks = useMemo(
() => myCheckins.filter((sid) => sessionById.has(sid)).map((sid) => sessionById.get(sid)!),
[myCheckins, sessionById],
);
if (loading || !contact) {
return (
<div className="center" style={{ flex: 1 }}>
<Spinner />
</div>
);
}
async function connect(member: TalkCohortMember) {
if (!member.qr_token) {
toast('No QR token for this attendee', 'err');
return;
}
// Never allow a duplicate request: if a connection already exists (any
// status), the button is disabled — this is the backstop.
if (connWith(member.email)) return;
setConnecting(member.email);
try {
const conn = await createConnectionRequest(member.qr_token);
if (conn.status === 'accepted') toast(`Connected with ${member.full_name}! 🤝`, 'ok');
else if (conn.status === 'pending') toast(`Request sent to ${member.full_name}`, 'ok');
else toast('Request already resolved');
window.dispatchEvent(new Event('connections-changed'));
await loadConns();
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not send request', 'err');
} finally {
setConnecting(null);
}
}
/** The Connect button state for a person: 'connect' | 'sent' | 'connected' | 'requested' | 'declined'. */
function connState(theirEmail: string): { label: string; kind: string } {
const c = connWith(theirEmail);
if (!c) return { label: 'Connect', kind: 'connect' };
if (c.status === 'accepted') return { label: 'Connected', kind: 'connected' };
if (c.status === 'pending') {
return c.from_email === email
? { label: 'Sent', kind: 'sent' }
: { label: 'Requested', kind: 'requested' };
}
return { label: 'Declined', kind: 'declined' };
}
const bonus = event?.talk_networking_bonus ?? 0;
return (
<div data-testid="networking-panel">
<div className="muted small" style={{ marginBottom: 14 }}>
People who were in the same talk as you.
{bonus > 0 ? (
<> Connect with them to earn <b>+{bonus} pts</b> (shared talk).</>
) : (
<> Connect with people you met at a talk.</>
)}
</div>
{myTalks.length === 0 ? (
<Empty icon="🗣" text="You haven’t been checked into a talk yet. Get checked in by staff to see who else was there." />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{myTalks.map((talk) => {
const members = (cohorts[talk.id] ?? []).filter((m) => m.email !== email);
return (
<div className="card" key={talk.id} data-testid={`networking-talk-${talk.id}`}>
<div className="h2" style={{ marginBottom: 2 }}>{talk.title}</div>
<div className="muted small" style={{ marginBottom: 10 }}>
{talk.room ? `${talk.room} · ` : ''}
{talk.speakers ? `🎤 ${talk.speakers}` : ''}
</div>
{loadingCohorts && (
<div className="center" style={{ padding: 8 }}>
<Spinner />
</div>
)}
{!loadingCohorts && members.length === 0 && (
<div className="muted small">No one else was checked in here yet.</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{members.map((m) => (
<div className="conn" key={m.email} data-testid={`networking-member-${m.email}`}>
<Avatar name={m.full_name} id={m.email} size={40} />
<div className="grow">
<div className="name">{m.full_name}</div>
{m.registration_type && (
<div className="meta">{capWords(m.registration_type)}</div>
)}
</div>
{(() => {
const s = connState(m.email);
const disabled = s.kind !== 'connect' || connecting === m.email;
return (
<button
className={
s.kind === 'connected'
? 'btn small'
: s.kind === 'connect'
? 'btn primary small'
: 'btn ghost small'
}
data-testid={`networking-connect-${m.email}`}
disabled={disabled}
onClick={() => void connect(m)}
>
{connecting === m.email ? '…' : s.label}
</button>
);
})()}
</div>
))}
</div>
</div>
);
})}
</div>
)}
</div>
);
}
+1
View File
@@ -10,6 +10,7 @@ const CATEGORY_LABEL: Record<PointsLogRow['category'], string> = {
checkin: 'Session check-ins',
connection: 'Connections',
feedback: 'Feedback',
talk_networking: 'Talk networking',
admin: 'Other',
};
+1188
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -8,6 +8,7 @@
"start": "node src/server.js"
},
"dependencies": {
"pdfkit": "^0.15.0",
"xlsx": "^0.18.5"
}
}
+311
View File
@@ -41,6 +41,7 @@
const http = require('http');
const XLSX = require('xlsx');
const PDFDocument = require('pdfkit');
const SUPABASE_URL = (process.env.SUPABASE_URL || 'http://supabase_kong_Convivo:8000').replace(/\/$/, '');
const SERVICE_ROLE_KEY =
@@ -275,6 +276,11 @@ function transform(data) {
// A service session is a break/lunch/closing (isServiceSession) OR a
// plenum (isPlenumSession) — plenums are full-hall items with no pick.
is_service_session: Boolean(s.isServiceSession || s.isPlenumSession),
// Level + area (free-text classification for agenda filtering).
// Sessionize's public /view/ endpoint may not expose these; if present
// (e.g. via a custom field or a future API version) we capture them.
level: (s.level || '').trim() || null,
area: (s.area || s.topic || '').trim() || null,
speakers: speakerEmails,
});
}
@@ -351,6 +357,11 @@ function transformExcel(buffer) {
start_time,
end_time,
is_service_session: /service|break|lunch|closing|plenum/i.test(String(r['Session Format'] ?? '')),
// Level + area (free-text classification for agenda filtering).
// The Sessionize "Sessions and speakers (advanced)" .xlsx may include
// "Level" and "Area"/"Topic" columns; we read them if present.
level: String(r['Level'] ?? '').trim() || null,
area: String(r['Area'] ?? r['Topic'] ?? '').trim() || null,
speakers: speakerEmails,
});
}
@@ -584,6 +595,301 @@ async function runPretixLoop() {
}
}
// =============================================================================
// POST /export — event reports (CSV / XLSX / PDF)
//
// Fetches an event's full dataset (service role) and renders it as:
// * csv — one combined CSV (a `table` column distinguishes the rows)
// * xlsx — one workbook, one sheet per table
// * pdf — a structured post-event report (summary + per-session + top points)
// Returns { filename, mime, content_base64 }.
// =============================================================================
// The tables an export can include (CSV/XLSX). The PDF always uses all of them.
const EXPORT_TABLES = [
'registrations',
'checkins',
'connections',
'session_feedback',
'event_feedback',
'leaderboard',
'points_log',
];
// Escape a single CSV cell (RFC 4180).
function csvCell(v) {
const s = v == null ? '' : String(v);
return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
}
// Render an array of flat row objects as a single CSV string.
function rowsToCsv(rows) {
if (rows.length === 0) return '';
const headers = Object.keys(rows[0]);
const lines = [headers.map(csvCell).join(',')];
for (const r of rows) lines.push(headers.map((h) => csvCell(r[h])).join(','));
return lines.join('\n');
}
// Fetch the event's full dataset (service role), joined for readability.
async function fetchEventDataset(eventId) {
const events = await supabaseFetch(
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=*`,
);
const event = Array.isArray(events) ? events[0] : null;
if (!event) throw new Error('event not found');
const [contacts, regs, checkins, connections, feedback, eventFeedback, leaderboard, pointsLog, sessions] =
await Promise.all([
supabaseFetch('/rest/v1/contacts?select=email,full_name'),
supabaseFetch(`/rest/v1/registrations?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/checkins?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/connections?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/feedback?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/event_feedback?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/leaderboard?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/points_log?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/sessions?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
]);
const nameOf = new Map((Array.isArray(contacts) ? contacts : []).map((c) => [c.email, c.full_name]));
const sessionTitle = new Map((Array.isArray(sessions) ? sessions : []).map((s) => [s.id, s.title]));
const titleOf = (id) => sessionTitle.get(id) ?? id ?? '';
const name = (email) => nameOf.get(email) ?? email ?? '';
return {
event,
registrations: (Array.isArray(regs) ? regs : []).map((r) => ({
email: r.contact_email,
name: name(r.contact_email),
type: r.type,
checked_in: r.checked_in,
points: r.points,
qr_token: r.qr_token,
})),
checkins: (Array.isArray(checkins) ? checkins : []).map((c) => ({
email: c.contact_email,
name: name(c.contact_email),
session: titleOf(c.session_id),
checked_in_by: name(c.staff_email),
when: c.created_at,
})),
connections: (Array.isArray(connections) ? connections : []).map((c) => ({
from: name(c.from_email),
to: name(c.to_email),
status: c.status,
when: c.created_at,
})),
sessionFeedback: (Array.isArray(feedback) ? feedback : []).map((f) => ({
email: f.contact_email,
name: name(f.contact_email),
session: titleOf(f.session_id),
rating: f.rating,
comment: f.comment,
when: f.created_at,
})),
eventFeedback: (Array.isArray(eventFeedback) ? eventFeedback : []).map((f) => ({
email: f.contact_email,
name: name(f.contact_email),
rating: f.rating,
comment: f.comment,
when: f.created_at,
})),
leaderboard: (Array.isArray(leaderboard) ? leaderboard : [])
.sort((a, b) => (b.points ?? 0) - (a.points ?? 0))
.map((l) => ({ name: l.full_name ?? name(l.contact_email), points: l.points })),
pointsLog: (Array.isArray(pointsLog) ? pointsLog : []).map((l) => ({
email: l.contact_email,
name: name(l.contact_email),
delta: l.delta,
category: l.category,
when: l.created_at,
})),
};
}
// Build the combined CSV (a `table` column distinguishes the rows).
function buildCsv(ds, tables) {
const source = {
registrations: ds.registrations,
checkins: ds.checkins,
connections: ds.connections,
session_feedback: ds.sessionFeedback,
event_feedback: ds.eventFeedback,
leaderboard: ds.leaderboard,
points_log: ds.pointsLog,
};
const chunks = [];
for (const t of tables) {
const rows = source[t] || [];
if (rows.length === 0) continue;
const withTable = rows.map((r) => ({ table: t, ...r }));
chunks.push(rowsToCsv(withTable));
}
return chunks.join('\n');
}
// Build the multi-sheet XLSX workbook (one sheet per table).
function buildXlsx(ds, tables) {
const source = {
registrations: ds.registrations,
checkins: ds.checkins,
connections: ds.connections,
session_feedback: ds.sessionFeedback,
event_feedback: ds.eventFeedback,
leaderboard: ds.leaderboard,
points_log: ds.pointsLog,
};
const wb = XLSX.utils.book_new();
for (const t of tables) {
const rows = source[t] || [];
const ws = XLSX.utils.json_to_sheet(rows.length > 0 ? rows : [{ note: 'no data' }]);
XLSX.utils.book_append_sheet(wb, ws, t.slice(0, 31));
}
const out = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });
return out;
}
// Build the PDF post-event report.
function buildPdf(ds) {
return new Promise((resolve, reject) => {
const doc = new PDFDocument({ size: 'A4', margin: 48 });
const buf = [];
doc.on('data', (c) => buf.push(c));
doc.on('end', () => resolve(Buffer.concat(buf)));
doc.on('error', reject);
const ev = ds.event;
const h2 = (t) => {
doc.font('Helvetica-Bold').fontSize(13);
doc.text(t, { continued: false });
doc.moveDown(0.4);
};
const line = (label, value) => {
doc.font('Helvetica').fontSize(10);
doc.text(`${label}: `, { continued: true });
doc.font('Helvetica-Bold').text(String(value), { continued: false });
doc.moveDown(0.15);
};
// Header.
doc.font('Helvetica-Bold').fontSize(18).text(ev.name || 'Event report');
doc.font('Helvetica').fontSize(10).fillColor('#555');
const dates = `${ev.start_date} – ${ev.end_date}${ev.location ? ` · ${ev.location}` : ''}`;
doc.text(dates);
doc.moveDown(0.3);
doc.text(`Generated ${new Date().toISOString()}`);
doc.moveDown(0.8);
doc.fillColor('#000');
// Summary.
h2('Summary');
const byType = {};
for (const r of ds.registrations) byType[r.type] = (byType[r.type] || 0) + 1;
line('Registrations', ds.registrations.length);
line('By type', Object.keys(byType).length ? Object.entries(byType).map(([t, n]) => `${t} ${n}`).join(', ') : '—');
line('Check-ins', ds.checkins.length);
const accepted = ds.connections.filter((c) => c.status === 'accepted').length;
line('Connections', `${ds.connections.length} (${accepted} accepted)`);
const sf = ds.sessionFeedback;
line('Session feedback', sf.length ? `${sf.length} (avg ${(sf.reduce((s, f) => s + f.rating, 0) / sf.length).toFixed(2)}★)` : '—');
const ef = ds.eventFeedback;
line('Event feedback', ef.length ? `${ef.length} (avg ${(ef.reduce((s, f) => s + f.rating, 0) / ef.length).toFixed(2)}★)` : '—');
const catTotals = {};
for (const l of ds.pointsLog) catTotals[l.category] = (catTotals[l.category] || 0) + l.delta;
line('Points by category', Object.keys(catTotals).length ? Object.entries(catTotals).map(([c, n]) => `${c} +${n}`).join(', ') : '—');
doc.moveDown(0.6);
// Per-session feedback.
h2('Session feedback');
if (sf.length === 0) {
doc.font('Helvetica').fontSize(10).text('No session feedback.');
} else {
const bySession = {};
for (const f of sf) {
const e = (bySession[f.session] ||= { count: 0, sum: 0 });
e.count += 1;
e.sum += f.rating;
}
const rows = Object.entries(bySession)
.map(([title, e]) => ({ title, avg: e.sum / e.count, count: e.count }))
.sort((a, b) => b.avg - a.avg);
doc.font('Helvetica-Bold').fontSize(9).text('Session', { continued: true }).text(' ', { continued: true });
doc.text('Avg', { continued: true }).text(' ', { continued: true }).text('Responses');
doc.moveDown(0.2);
doc.font('Helvetica').fontSize(9);
for (const r of rows) {
doc.text(`${r.title} · ${r.avg.toFixed(2)}★ · ${r.count}`, { lineBreak: true });
}
}
doc.moveDown(0.6);
// Top points.
h2('Top points');
if (ds.leaderboard.length === 0) {
doc.font('Helvetica').fontSize(10).text('No points yet.');
} else {
doc.font('Helvetica').fontSize(9);
ds.leaderboard.slice(0, 10).forEach((l, i) => {
doc.text(`${i + 1}. ${l.name} · ${l.points} pts`, { lineBreak: true });
});
}
doc.moveDown(0.6);
// Event-level feedback comments.
h2('Event-level feedback');
const comments = ef.filter((f) => f.comment).slice(0, 50);
if (comments.length === 0) {
doc.font('Helvetica').fontSize(10).text('No event-level comments.');
} else {
doc.font('Helvetica').fontSize(9);
for (const c of comments) {
const body = (c.comment || '').replace(/\s+/g, ' ').trim().slice(0, 200);
doc.text(`• [${c.rating}★] ${c.name}: ${body}`, { lineBreak: true });
doc.moveDown(0.15);
}
}
doc.end();
});
}
// The POST /export handler.
async function handleExport(body) {
const { event_id: eventId, format, tables } = body || {};
if (!eventId) throw new Error('event_id is required');
if (!['csv', 'xlsx', 'pdf'].includes(format)) throw new Error('format must be csv, xlsx, or pdf');
const ds = await fetchEventDataset(eventId);
const slug = (ds.event.name || eventId).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'event';
if (format === 'pdf') {
const buf = await buildPdf(ds);
return { filename: `${slug}-report.pdf`, mime: 'application/pdf', content_base64: buf.toString('base64') };
}
const selected = (Array.isArray(tables) && tables.length > 0 ? tables : EXPORT_TABLES).filter((t) =>
EXPORT_TABLES.includes(t),
);
if (selected.length === 0) throw new Error('no valid tables selected');
if (format === 'csv') {
const csv = buildCsv(ds, selected);
return {
filename: `${slug}-report.csv`,
mime: 'text/csv;charset=utf-8',
content_base64: Buffer.from(csv, 'utf8').toString('base64'),
};
}
// xlsx
const buf = buildXlsx(ds, selected);
return {
filename: `${slug}-report.xlsx`,
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
content_base64: Buffer.from(buf).toString('base64'),
};
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const path = url.pathname;
@@ -632,6 +938,11 @@ const server = http.createServer(async (req, res) => {
const organizers = await fetchPretixOptions(apiKey);
return json(res, 200, { organizers });
}
if (req.method === 'POST' && path === '/export') {
const body = await readBody(req);
const result = await handleExport(body);
return json(res, 200, result);
}
return json(res, 404, { error: 'not found' });
} catch (e) {
return json(res, 500, { error: e.message });
+7
View File
@@ -140,6 +140,13 @@ the work atomically, and the `leaderboard` table change fans out over Realtime.
Supabase Table Editor makes it work with `signInWithPassword` immediately.
(Staff can also still log in with their email + QR token, their seeded Auth
password.)
- **`@appe.at` admins:** any contact on the `@appe.at` domain is an admin
(`is_admin()` is domain-aware) and logs in with the **default admin password
`appe-admin-2026`** out of the box. The `trg_contacts_appe_at_admin` trigger
sets `contacts.password` to the default (when null) and the auth-user
creation helpers hash it into `auth.users.encrypted_password`, so a
freshly-created `@appe.at` admin can sign in immediately. A custom password
set on the contact row is always respected.
- `enable_confirmations = false`, so **no email is sent** — the email is only a
"confirm it's you" check against the ticket purchase.
- After login, the app holds a **session JWT** (in `localStorage`) that lasts
+16 -1
View File
@@ -27,6 +27,7 @@ Source of truth:
|---|---|---|
| Checked into a session (by staff) | **+10** | the attendee |
| Connection accepted | **+5 each** | both people |
| Connection accepted **with a shared talk** | **+`talk_networking_bonus` each** (per event, default 2, `0` = off) | both people (category `talk_networking`) |
| Feedback — rating only | **+5** | the attendee |
| Feedback — rating + comment | **+10** | the attendee |
| Admin adjustment | any | the target (audited as `admin`) |
@@ -62,6 +63,7 @@ triggers and the feedback RPC.
| `get_public_contacts()` | `email, full_name, linkedin_url`, `show_email`, `registration_type` (active-event registrants) | Connections name/type lookups |
| `get_agenda()` | flat rows: slot fields + session fields + `speakers` (string_agg) | Agenda + Home |
| `get_active_event()` | the active `events` row (or none) | event name/dates/location |
| `get_talk_cohort(p_session_id)` | `email, full_name, registration_type, qr_token` of the **other** attendees checked into that session (staff excluded, self excluded) | the Networking screen's "also attended" list |
All are `security definer` and expose **only public columns** (email is included
because `contacts` is keyed by email and is the identity; `qr_token` is never
@@ -84,12 +86,25 @@ Creates a **pending** connection to the contact whose QR was scanned.
- **Idempotent:** if the pair already has a connection (either direction) for the
active event, returns the existing one instead of creating a duplicate.
### `accept_connection(p_connection_id)` → `connections`
### `accept_connection(p_connection_id)` → `(event_id, from_email, to_email, status, created_at, resolved_at, shared_talk)`
Accepts an **incoming** request.
- Locks the row (`for update`), verifies the caller is the recipient
(`to_email = current_email()`) and the status is still `pending`.
- Sets `status = 'accepted'`, `resolved_at = now()`.
- **Awards +5 to both** `from_email` and `to_email` (category `connection`).
- **Talk networking bonus:** computes whether the two parties share a
checked-in session (talk) — i.e. there is a session both were checked into
(`checkins` intersection). If they do **and** the event's
`talk_networking_bonus > 0`, it awards that bonus to **each** party
(category `talk_networking`). Returns `shared_talk = true` in that case so
the app can show a "met at {talk}" note.
- **Idempotency:** the function is one-shot (row locked, status must be
`pending`), so the bonus can never double-award.
- **Documented limitation:** check-ins that happen **after** acceptance do
not retro-award the bonus — it reflects shared attendance at acceptance
time.
- The bonus flows through `_award_points`, so the leaderboard sync + staff
exclusion are inherited automatically.
### `reject_connection(p_connection_id)` → `connections`
Same guards as accept, but sets `status = 'rejected'`. No points.
+2 -1
View File
@@ -79,6 +79,7 @@ queries everything for the active event and handles "no active event" gracefully
| `num_checked_in_registrations` | `integer` | maintained aggregate |
| `sessionize_endpoint` | `text` | nullable — the Sessionize API URL for this event (see [sidecar.md](./sidecar.md)) |
| `use_realtime_clock` | `boolean` | default `false` — when `true`, the attendee app drives slot status (Live/Next/Done) from the real system clock; when `false` it uses the simulated mid-event clock (see [../frontend/app-structure.md](../frontend/app-structure.md)) |
| `talk_networking_bonus` | `integer` | default `2` — bonus points awarded to **each** party when two people who were checked into the same session (talk) accept a connection. `0` disables the feature (the +5 connection award still applies). Awarded with the `talk_networking` points category (see [rpcs.md](./rpcs.md#accept_connectionp_connection_id-uuid)) |
| `last_synced_at` | `timestamptz` | nullable — when the Sessionize sync last ran |
| `created_at` | `timestamptz` | |
@@ -277,7 +278,7 @@ Powers the per-category points breakdown on the Profile screen (per event).
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `contact_email` | `text` FK → `contacts` | |
| `delta` | `integer` | points added (can be negative for admin adjustments) |
| `category` | `text` | `checkin` \| `connection` \| `feedback` \| `admin` |
| `category` | `text` | `checkin` \| `connection` \| `feedback` \| `admin` \| `talk_networking` (CHECK constraint, widened by the talk-networking migration) |
| `created_at` | `timestamptz` | |
Index: `points_log_event_id_idx (event_id)`.
+9
View File
@@ -70,6 +70,15 @@ staff share the password **`appe-admin-2026`** (stored in `contacts.password`,
auto-synced to `auth.users.encrypted_password` by the `trg_contact_password_sync`
trigger).
> **Default admin password:** any `@appe.at` contact is an admin and logs in
> with **`appe-admin-2026`** out of the box. The `trg_contacts_appe_at_admin`
> trigger sets `contacts.password = 'appe-admin-2026'` (when null) on
> insert/update, and the auth-user-creation helpers hash it into
> `auth.users.encrypted_password` so a freshly-created `@appe.at` admin can log
> in immediately. A custom password set on the contact row is always respected
> (never overwritten). See migration
> [`20260910000000_admin_default_password.sql`](../../supabase/migrations/20260910000000_admin_default_password.sql).
| Person | Type | Email | Login |
|---|---|---|---|
| **Amelia Hernandez** | staff (admin) | amelia@appe.at | `appe-admin-2026` |
+23 -2
View File
@@ -8,8 +8,9 @@ APPE Admin **Interfaces** menu — it runs **on demand only** (no scheduling).
- Code: [`apps/sidecar/`](../../apps/sidecar/) (single file:
[`src/server.js`](../../apps/sidecar/src/server.js))
- Image: [`apps/sidecar/Dockerfile`](../../apps/sidecar/Dockerfile)
(`node:20-alpine`; one runtime dependency, **`xlsx`**, to parse the Sessionize
Excel export — everything else is built-in `http` + `fetch`)
(`node:20-alpine`; runtime dependencies **`xlsx`** (parse the Sessionize Excel
export) and **`pdfkit`** (render the PDF report) — everything else is built-in
`http` + `fetch`)
- Compose service: `convivo-sidecar` in the root
[`docker-compose.yml`](../../docker-compose.yml) (`:3002`)
- DB side: the `sync_sessionize_event` RPC + `sync_runs` audit table — see
@@ -82,6 +83,7 @@ flowchart LR
| `GET` | `/status` | — | `{ ok, running, lastRun }` |
| `POST` | `/run` | `{ event_id }` | **blocking** — the API-sync result (summary + errors) |
| `POST` | `/import-excel` | `multipart/form-data` (`event_id` + `file` = the `.xlsx`) | **blocking** — the Excel-import result (summary + errors) |
| `POST` | `/export` | `{ event_id, format: 'csv' \| 'xlsx' \| 'pdf', tables? }` | **blocking** — `{ filename, mime, content_base64 }` (the event report) |
`/run` is **blocking**: it reads the event's endpoint, fetches Sessionize,
transforms, calls the RPC, and returns the summary. The admin's "Sync" button and
@@ -92,6 +94,21 @@ the Interfaces "Run sync" both call it and show the result inline.
calls that RPC. The admin's Interfaces **"Import Excel"** control posts the file
here and shows the result inline.
`/export` is **blocking** as well: it fetches the event's full dataset
(registrations, check-ins, connections, session feedback, event feedback,
leaderboard, points log — service role, joined for readability) and renders it as
one of three formats:
- **`csv`** — a single combined CSV (a `table` column distinguishes the rows).
- **`xlsx`** — one workbook, one sheet per table (the `tables` array selects
which sheets to include; defaults to all).
- **`pdf`** — a structured post-event report (header, summary, per-session
feedback, top-10 points, event-level feedback comments) rendered with `pdfkit`.
It returns `{ filename, mime, content_base64 }`; the admin's **Reports** view
decodes the base64 and triggers a browser download. Empty tables produce a valid
file with headers only (never an error); an unknown event is a 404.
## Env vars
| Var | Default | Notes |
@@ -134,3 +151,7 @@ The admin app reaches the sidecar through the same-origin `/sidecar/` proxy
creates the speaker contacts, links them to sessions, and creates/updates their
`speaker` registrations (idempotent on re-run). Verified: 21 speakers created,
25 speaker links, 21 speaker registrations, 0 errors.
- `POST /export` for each format against the seeded event → returns a parseable
file: CSV with a `table` column, XLSX with one sheet per table, and a valid
PDF report (verified: CSV ~10 KB, XLSX 7 sheets, PDF `%PDF-1.3`). Unknown
event → 404.
+21 -2
View File
@@ -63,8 +63,9 @@ apps/admin/src/
├─ Sponsors.tsx # sponsor CRUD
├─ Schedule.tsx # slots + sessions + speakers + material + AI-evaluate
├─ Activity.tsx # check-ins / connections / feedback tables
├─ Events.tsx # event management (+ sessionize_endpoint + per-row Sync)
└─ Interfaces.tsx # sidecar status / run / recent runs
├─ Events.tsx # event management (+ sessionize_endpoint + per-row Sync + talk networking bonus)
├─ Interfaces.tsx # sidecar status / run / recent runs
└─ Reports.tsx # post-event summary + CSV / Excel / PDF export (sidecar /export)
```
## Data access
@@ -117,6 +118,24 @@ The Schedule view uploads a session's material to the `materials` bucket and set
`sessions.material_path` (admins can write `sessions` directly). The **Evaluate**
button calls `evaluate_session_feedback` (the AI stub) to set
`ai_generated_feedback`.
### Reports (post-event summary + export)
The **Reports** view is the post-event reporting surface. It works for **any**
event (active or past) — the event selector defaults to the active event but can
pick a past one.
- **On-screen summary** — computed client-side from the same reads the export
uses: registrations (by type), check-ins, connections (total / accepted),
session feedback (count + average), event feedback (count + average), points by
category, and a top-5 leaderboard.
- **Session feedback summary** — a per-session table (title, room, average
rating, response count) sorted by average; this is the post-event session
feedback summary.
- **Export** — three buttons call the sidecar's [`POST /export`](../backend/sidecar.md#http-api):
**Download CSV**, **Download Excel**, **Download PDF report**. CSV/XLSX include
the tables ticked in the checkbox list (default: all); the PDF always uses the
full dataset. The response's base64 body is decoded and downloaded in the
browser (`downloadReport` in `lib/api.ts`).
## Styling
+32 -4
View File
@@ -12,10 +12,11 @@ from `useAuth()` (`contact` + `registration`).
| Home | `Home.tsx` | tab (default) |
| Agenda | `Agenda.tsx` | tab |
| Scan | `Scan.tsx` | tab (staff get an Attendee/Staff mode toggle inside) |
| Connections | `Connections.tsx` | tab |
| Connections | `Connections.tsx` | tab (hosts a **Networking** sub-tab; Home's "Networking" quick action deep-links into it) |
| Profile | `Profile.tsx` | tab |
| Leaderboard | `Leaderboard.tsx` | from Home (points pill / quick action) |
| Feedback | `Feedback.tsx` | full-screen takeover from Agenda |
| EventFeedback | `EventFeedback.tsx` | full-screen takeover from Home ("Rate this event") |
## Login
@@ -156,7 +157,8 @@ Data: `useEvent()` (for the session list) + the RPCs above.
## Connections
Two tabs: **My connections** and **Requests** (with a count badge).
Three sub-tabs: **My connections**, **Requests** (with a count badge), and
**🗣 Networking** (see [Networking](#networking-a-sub-tab-of-connections)).
- **My connections** — accepted connections (the other person's name +
registration type). **Clicking a row** opens a bottom **sheet** with that
@@ -167,8 +169,9 @@ Two tabs: **My connections** and **Requests** (with a count badge).
buttons (`acceptConnection` / `rejectConnection`), and outgoing (`from_email =
me`, pending) shown as "Sent". The person block is also clickable (same detail
sheet).
- Accepting awards +5 to both (see
[../backend/rpcs.md#accept_connectionp_connection_id--connections](../backend/rpcs.md#accept_connectionp_connection_id--connections)).
- Accepting awards +5 to both, **plus the per-event talk networking bonus** when
the two parties shared a checked-in talk (see
[../backend/rpcs.md#accept_connectionp_connection_id](../backend/rpcs.md#accept_connectionp_connection_id)).
- **Red dot** — any interaction with the connection logic (accept / decline / send)
dispatches a `connections-changed` window event; the Shell listens and
**recalculates the Connect red dot immediately** (it stays while any incoming
@@ -178,6 +181,31 @@ Two tabs: **My connections** and **Requests** (with a count badge).
Data: `getMyConnections()` + `getPublicContacts()` (names + types) +
`getLeaderboard()` (points for the detail sheet).
## Networking (a sub-tab of Connections)
A **sub-tab inside the Connect screen** (the third of My connections / Requests /
🗣 Networking; the screen header switches to "Networking" while it is active)
that rewards **networking around talks**. The Home "Networking" quick action
deep-links straight into it. Rendered by the `NetworkingPanel` component
(`Networking.tsx`). For every talk the user was checked into, it lists the
**other attendees who were also in that talk** (the "talk cohort") so the user
can make a connection.
- **Your talks** — the sessions the user is checked into (`getMyCheckins()`),
shown as cards (title, room, speakers).
- **Also attended** — for each talk, the other checked-in participants
(`get_talk_cohort(sessionId)` — staff excluded, self excluded), each with a
name + registration-type badge and a **Connect** button (the same
`createConnectionRequest` flow as the Scan screen).
- **Bonus** — when the event's `talk_networking_bonus > 0`, the header shows
"Connect with them to earn +N pts (shared talk)". Accepting a connection with
a shared talk awards the bonus (see
[../backend/rpcs.md#accept_connectionp_connection_id](../backend/rpcs.md#accept_connectionp_connection_id)).
- **Empty states** — "You haven't been checked into a talk yet…" (no check-ins)
and "No one else was checked in here yet." (a talk with no other attendees).
Data: `getMyCheckins()` + `getTalkCohort()` + the agenda (via `useEvent()`).
## Feedback
A **full-screen takeover** (no tab bar), opened from the Agenda session sheet.
+50 -2
View File
@@ -44,9 +44,18 @@ current phase.
> **Real-time clock toggle** (a per-event `events.use_realtime_clock` flag,
> toggled in the admin Events view, switches the attendee app between the real
> system clock and the simulated mid-event clock for Live/Next/Done status; the
> Home header shows a 🎬 Demo clock badge only in simulated mode).
> Home header shows a 🎬 Demo clock badge only in simulated mode), and
> **Post-event reporting + talk networking incentives** (a per-event
> `talk_networking_bonus` awarded when two people who shared a checked-in talk
> accept a connection, a Convivo **Networking** sub-tab inside the Connect
> screen that lists the "also attended" cohort per talk (the Home "Networking"
> quick action deep-links into it), a new APPE Admin **Reports** view with an
> on-screen post-event summary + session-feedback summary and CSV / Excel / PDF
> export served by a new sidecar `POST /export` endpoint, and a per-session
> aggregate header in the Activity session-feedback tab).
> Remaining work is cross-cutting (deployment, testing, and the ticket/Pretix
> sync that will consume the speaker links by email).
> sync that will consume the speaker links by email). **Badge printing was
> evaluated and skipped by decision** (no printing feature was built).
## Done
@@ -494,6 +503,45 @@ drives slot status (Live/Next/Done) from the **real system clock** or the
slot.
- **Migration:** [`20260834000000_event_realtime_clock.sql`](../../supabase/migrations/20260834000000_event_realtime_clock.sql).
## Post-event reporting + talk networking incentives — ✅ complete
A round (migration `20260920000000_talk_networking.sql` + app + sidecar changes),
verified end-to-end (18/18 RPC tests, all three export formats). **Badge
printing was evaluated and skipped by decision** — no printing feature was built.
**Talk networking incentives.**
- `events.talk_networking_bonus` (integer, default `2`; `0` disables) — the
bonus each party earns when two people who were checked into the **same
session (talk)** accept a connection. Awarded with the new `talk_networking`
points category (the `points_log.category` CHECK was widened to include it).
- `accept_connection` was re-created to compute the shared-check-in overlap and
award the bonus (through `_award_points`, so the leaderboard sync + staff
exclusion are inherited), and to return a `shared_talk` flag. One-shot, so it
can never double-award; check-ins after acceptance don't retro-award.
- `get_talk_cohort(p_session_id)` — the other attendees (staff excluded, self
excluded) checked into a session, for the Networking screen.
- **Convivo app:** a **Networking** sub-tab inside the Connect screen (the
Home "Networking" quick action deep-links into it) lists, per talk the user
is checked into, the "also attended" cohort with a Connect button; the
Profile points breakdown shows the `Talk networking` category.
- **APPE Admin:** a **Talk networking bonus** input (0–10) in the Events
create/edit modal.
**Post-event reporting / export.**
- **Sidecar `POST /export`** (`{ event_id, format: csv|xlsx|pdf, tables? }`)
fetches the event's full dataset (service role) and renders it: a combined
**CSV** (a `table` column), a multi-sheet **XLSX** (one sheet per table), or
a structured **PDF** post-event report (new `pdfkit` dependency). Returns
`{ filename, mime, content_base64 }`; unknown event → 404, empty tables → a
valid file with headers only.
- **APPE Admin Reports view** — works for **any** event (active or past): an
on-screen summary (registrations by type, check-ins, connections, session +
event feedback averages, points by category, top-5 leaderboard), a **session
feedback summary** table (per-session average + response count), and CSV /
Excel / PDF download buttons (base64 → browser download).
- **Activity → Session feedback** gains a compact **per-session aggregate
header** (average + count per session).
## Cross-cutting / later
- **Subdomains** — `convivo.appe.at`, `admin.appe.at`, `db.appe.at` don't exist
+6 -2
View File
@@ -5,8 +5,12 @@ summarized below. For *how* each piece works, see [`docs/`](./docs/README.md).
> **Status:** Phases 0–6 are complete and verified. The **Redesign** (Phases
> 3–6) is done. The real event clock is implemented as a per-event
> `use_realtime_clock` toggle. Remaining work is cross-cutting (deployment,
> automated testing, push notifications).
> `use_realtime_clock` toggle. **Post-event reporting + talk networking
> incentives** are done (a per-event talk-networking bonus, a Convivo
> Networking sub-tab inside the Connect screen, an APPE Admin Reports view
> with CSV/Excel/PDF export, and a sidecar `POST /export`). Remaining work is
> cross-cutting (deployment, automated testing, push notifications). **Badge
> printing was evaluated and skipped by decision.**
---
@@ -0,0 +1,189 @@
-- =============================================================================
-- Convivo — Default admin password for @appe.at contacts
--
-- Business rule: any @appe.at contact (admin) logs in with the default admin
-- password `appe-admin-2026` out of the box, without manual setup. A custom
-- password set on the contact row is always respected (never overwritten).
--
-- Implementation:
-- 1. The @appe.at BEFORE trigger now also sets contacts.password to the
-- default when it's null (respects an explicitly-set custom password).
-- 2. The auth-user-creation helpers use the contact's password (when set)
-- instead of a placeholder, so a freshly-created @appe.at admin can log in
-- immediately (the AFTER UPDATE OF password trigger only fires on UPDATE,
-- not INSERT, so the creation path must set the hash itself).
-- 3. The Pretix auth helper uses the contact's password (or the default) for
-- @appe.at emails — admins log in with the default, not a QR token.
-- 4. One-time reconciliation: existing @appe.at contacts with a null password
-- get the default, and it's synced into auth.users.
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. @appe.at BEFORE trigger: default admin password when null
-- -----------------------------------------------------------------------------
create or replace function public._set_appe_at_admin()
returns trigger
language plpgsql security definer set search_path = public as $$
begin
if new.email like '%@appe.at' then
new.is_admin := true;
if new.password is null then
new.password := 'appe-admin-2026';
end if;
end if;
return new;
end;
$$;
-- Re-attach the (existing) trigger to the updated function.
drop trigger if exists trg_contacts_appe_at_admin on public.contacts;
create trigger trg_contacts_appe_at_admin
before insert or update on public.contacts
for each row execute function public._set_appe_at_admin();
-- -----------------------------------------------------------------------------
-- 2. upsert_contact: use the contact's password when creating the auth user
-- -----------------------------------------------------------------------------
create or replace function public.upsert_contact(
p_email text, p_full_name text, p_linkedin_url text,
p_is_admin boolean
)
returns public.contacts
language plpgsql security definer set search_path = public as $$
declare
v_uid uuid;
v_contact public.contacts;
begin
if auth.uid() is null then raise exception 'not authenticated'; end if;
if not public.is_admin() then raise exception 'admin only'; end if;
if p_email is null or btrim(p_email) = '' then raise exception 'email is required'; end if;
if p_full_name is null or btrim(p_full_name) = '' then raise exception 'full_name is required'; end if;
insert into public.contacts (email, full_name, linkedin_url, is_admin)
values (p_email, p_full_name, p_linkedin_url, coalesce(p_is_admin, false))
on conflict (email) do update
set full_name = excluded.full_name,
linkedin_url = excluded.linkedin_url,
is_admin = excluded.is_admin
returning * into v_contact;
-- Ensure an auth user exists so the contact can log in. If no auth user yet,
-- create one. Use the contact's password when set (e.g. the @appe.at default
-- admin password); otherwise a placeholder that a registration token replaces.
select id into v_uid from auth.users where email = p_email;
if v_uid is null then
insert into auth.users (instance_id, id, aud, role, email, encrypted_password,
email_confirmed_at, confirmation_token, recovery_token, email_change_token_new,
email_change, raw_app_meta_data, raw_user_meta_data,
created_at, updated_at, confirmation_sent_at, last_sign_in_at)
values ('00000000-0000-0000-0000-000000000000', gen_random_uuid(), 'authenticated',
'authenticated', p_email,
extensions.crypt(coalesce(v_contact.password, 'no-token-yet'), extensions.gen_salt('bf')),
now(), '', '', '', '', '{"provider":"email","providers":["email"]}',
jsonb_build_object('full_name', p_full_name), now(), now(), now(), now())
returning id into v_uid;
insert into auth.identities (id, provider_id, identity_data, provider, user_id,
created_at, updated_at, last_sign_in_at)
values (v_uid, v_uid::text,
jsonb_build_object('sub', v_uid::text, 'email', p_email),
'email', v_uid, now(), now(), now());
end if;
return v_contact;
end;
$$;
-- -----------------------------------------------------------------------------
-- 3. _ensure_auth_user_exists (sidecar): use the contact's password
-- -----------------------------------------------------------------------------
create or replace function public._ensure_auth_user_exists(p_email text, p_full_name text)
returns void
language plpgsql security definer set search_path = public as $$
declare
v_uid uuid;
v_pw text;
begin
select id into v_uid from auth.users where email = p_email;
if v_uid is not null then
return; -- already exists; leave the password alone
end if;
select password into v_pw from public.contacts where email = p_email;
insert into auth.users (instance_id, id, aud, role, email, encrypted_password,
email_confirmed_at, confirmation_token, recovery_token, email_change_token_new,
email_change, raw_app_meta_data, raw_user_meta_data,
created_at, updated_at, confirmation_sent_at, last_sign_in_at)
values ('00000000-0000-0000-0000-000000000000', gen_random_uuid(), 'authenticated',
'authenticated', p_email,
extensions.crypt(coalesce(v_pw, 'no-token-yet'), extensions.gen_salt('bf')),
now(), '', '', '', '', '{"provider":"email","providers":["email"]}',
jsonb_build_object('full_name', p_full_name), now(), now(), now(), now())
returning id into v_uid;
insert into auth.identities (id, provider_id, identity_data, provider, user_id,
created_at, updated_at, last_sign_in_at)
values (v_uid, v_uid::text,
jsonb_build_object('sub', v_uid::text, 'email', p_email),
'email', v_uid, now(), now(), now());
end;
$$;
-- -----------------------------------------------------------------------------
-- 4. _ensure_auth_user (pretix): @appe.at admins use the default password
-- -----------------------------------------------------------------------------
create or replace function public._ensure_auth_user(p_email text, p_full_name text, p_qr_token text)
returns void
language plpgsql security definer set search_path = public as $$
declare
v_uid uuid;
v_pw text;
begin
select password into v_pw from public.contacts where email = p_email;
if p_email like '%@appe.at' then
v_pw := coalesce(v_pw, 'appe-admin-2026'); -- respect a custom password, else default
else
if p_qr_token is null or btrim(p_qr_token) = '' then
return; -- no token → no login (e.g. an external speaker)
end if;
v_pw := p_qr_token;
end if;
select id into v_uid from auth.users where email = p_email;
if v_uid is null then
insert into auth.users (instance_id, id, aud, role, email, encrypted_password,
email_confirmed_at, confirmation_token, recovery_token, email_change_token_new,
email_change, raw_app_meta_data, raw_user_meta_data,
created_at, updated_at, confirmation_sent_at, last_sign_in_at)
values ('00000000-0000-0000-0000-000000000000', gen_random_uuid(), 'authenticated',
'authenticated', p_email, extensions.crypt(v_pw, extensions.gen_salt('bf')),
now(), '', '', '', '', '{"provider":"email","providers":["email"]}',
jsonb_build_object('full_name', p_full_name), now(), now(), now(), now())
returning id into v_uid;
insert into auth.identities (id, provider_id, identity_data, provider, user_id,
created_at, updated_at, last_sign_in_at)
values (v_uid, v_uid::text,
jsonb_build_object('sub', v_uid::text, 'email', p_email),
'email', v_uid, now(), now(), now());
else
update auth.users
set encrypted_password = extensions.crypt(v_pw, extensions.gen_salt('bf')),
updated_at = now()
where id = v_uid;
delete from auth.sessions where user_id = v_uid;
end if;
end;
$$;
-- -----------------------------------------------------------------------------
-- 5. One-time reconciliation: existing @appe.at contacts with a null password
-- get the default (fires the password-sync trigger), and any @appe.at hash
-- is re-synced from the contact row so it matches.
-- -----------------------------------------------------------------------------
update public.contacts
set password = 'appe-admin-2026'
where email like '%@appe.at'
and password is null;
update auth.users u
set encrypted_password = extensions.crypt(c.password, extensions.gen_salt('bf'))
from public.contacts c
where u.email = c.email
and c.email like '%@appe.at'
and c.password is not null;
@@ -0,0 +1,73 @@
-- =============================================================================
-- Convivo — Bulk contact delete (admin) that bypasses the session-speaker guard
--
-- The admin "Delete all contacts for this event" action deletes a batch of
-- contacts in one PostgREST call. Deleting a contact cascades to their
-- session_speakers rows, which fires the `session_needs_speaker` BEFORE DELETE
-- trigger — and that trigger raises "a session must have at least one speaker"
-- when the contact is the sole speaker of a session. So a bulk wipe that
-- includes a lone speaker fails with P0001.
--
-- This adds an admin-only RPC that deletes the batch in a single transaction
-- with the guard temporarily disabled (the "at least one speaker" rule is a
-- data-integrity nicety for single edits; a deliberate bulk wipe is allowed to
-- leave a session speaker-less). The caller's own email is excluded by the app
-- (never passed in), so the admin can't delete themselves.
-- =============================================================================
create or replace function public.bulk_delete_contacts(p_emails text[])
returns integer
language plpgsql security definer set search_path = public as $$
declare
v_deleted integer;
begin
if auth.uid() is null then raise exception 'not authenticated'; end if;
if not public.is_admin() then raise exception 'admin only'; end if;
if p_emails is null or array_length(p_emails, 1) is null then
raise exception 'no emails provided';
end if;
-- Disable the guard for the duration of this transaction, then delete the
-- batch (cascades to registrations, session_speakers, checkins, connections,
-- feedback, leaderboard, points_log, preferences, sponsors).
perform public._disable_session_speaker_guard();
delete from public.contacts where email = any (p_emails);
get diagnostics v_deleted = row_count;
perform public._enable_session_speaker_guard();
return v_deleted;
end;
$$;
-- The session_needs_speaker trigger is a normal (non-deferrable) trigger, so we
-- toggle it with a GUC the trigger function checks. This keeps the trigger
-- object intact (no drop/create) and is safe to call from a security-definer
-- function.
create or replace function public._disable_session_speaker_guard()
returns void
language sql security definer set search_path = public as $$
select set_config('convivo.session_speaker_guard', 'off', false);
$$;
create or replace function public._enable_session_speaker_guard()
returns void
language sql security definer set search_path = public as $$
select set_config('convivo.session_speaker_guard', 'on', false);
$$;
-- Re-create the guard function to honor the GUC (off = skip the check).
create or replace function public._trg_session_needs_speaker() returns trigger
language plpgsql security definer set search_path = public as $$
begin
if coalesce(current_setting('convivo.session_speaker_guard', true), 'on') = 'off' then
return old;
end if;
if exists (select 1 from public.sessions where id = old.session_id)
and (select count(*) from public.session_speakers where session_id = old.session_id) <= 1 then
raise exception 'a session must have at least one speaker';
end if;
return old;
end;
$$;
grant execute on function public.bulk_delete_contacts(text[]) to authenticated;
@@ -0,0 +1,575 @@
-- =============================================================================
-- Convivo — Session level/area + event-level feedback
--
-- 1. `sessions.level` + `sessions.area` — free-text classification so the
-- attendee app can filter the agenda by level (e.g. 100/200/300 or
-- Beginner/Intermediate) and by area/topic (e.g. Power Apps, Power
-- Automate, Governance). Values come from the Sessionize sync (API +
-- Excel) and/or manual entry in the admin Schedule.
--
-- 2. `event_feedback` — a separate, event-level feedback form (distinct from
-- the per-session `feedback` table). Any registered participant can rate
-- the event overall (1–5) + leave a comment. One row per (event, contact).
-- Admins can read all of it (shown in the admin Activity view).
--
-- 3. `get_agenda()` is re-created to expose `level` + `area` (the original
-- lives in 20260824000000_redesign.sql; append-only migrations can't edit
-- it, so we replace it here).
--
-- 4. The Sessionize sync RPCs (`sync_sessionize_event` / `sync_sessionize_excel`)
-- are re-created to upsert `level` + `area` (the originals live in
-- 20260833000000_service_sessions_feedback.sql).
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. sessions.level + sessions.area
-- -----------------------------------------------------------------------------
alter table public.sessions add column if not exists level text;
alter table public.sessions add column if not exists area text;
comment on column public.sessions.level is
'Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). '
'Used by the attendee app to filter the agenda. Set via the Sessionize sync '
'or manual entry in the admin Schedule.';
comment on column public.sessions.area is
'Free-text area/topic classification (e.g. Power Apps, Power Automate, '
'Governance). Used by the attendee app to filter the agenda.';
-- -----------------------------------------------------------------------------
-- 2. event_feedback table
-- -----------------------------------------------------------------------------
create table if not exists public.event_feedback (
id uuid primary key default gen_random_uuid(),
event_id uuid not null references public.events (id) on delete cascade,
contact_email text not null references public.contacts (email) on delete cascade,
rating integer not null check (rating between 1 and 5),
comment text,
created_at timestamptz not null default now(),
unique (event_id, contact_email)
);
create index if not exists event_feedback_event_id_idx
on public.event_feedback (event_id);
-- -----------------------------------------------------------------------------
-- 3. get_agenda() — re-created to expose level + area
-- (The return type changes, so we must drop the existing function first —
-- `create or replace` cannot change a function's return type.)
-- -----------------------------------------------------------------------------
drop function if exists public.get_agenda();
create or replace function public.get_agenda()
returns table (
slot_id integer, slot_name text, slot_date date, start_time time, end_time time,
slot_type text,
session_id uuid, title text, description text, room text, capacity integer,
average_feedback numeric, ai_generated_feedback text, material_path text,
speakers text, level text, area text
)
language sql stable security definer set search_path = public as $$
select s.id, s.name, s.slot_date, s.start_time, s.end_time, s.type,
se.id, se.title, se.description, se.room, se.capacity,
se.average_feedback, se.ai_generated_feedback, se.material_path,
(select string_agg(c.full_name, ', ' order by c.full_name)
from public.session_speakers ss
join public.contacts c on c.email = ss.contact_email
where ss.session_id = se.id) as speakers,
se.level, se.area
from public.slots s
left join public.sessions se on se.slot_id = s.id
where s.event_id = (select id from public.events where is_active limit 1)
order by s.id, se.title;
$$;
-- -----------------------------------------------------------------------------
-- 4. Event-level feedback RPCs
-- -----------------------------------------------------------------------------
-- Submit (or update) the current user's event-level feedback. Any registered
-- participant can do this (no check-in requirement — it's about the event as a
-- whole, not a specific session). Idempotent: one row per (event, contact).
create or replace function public.submit_event_feedback(p_rating integer, p_comment text)
returns table (feedback_id uuid, points integer)
language plpgsql security definer set search_path = public as $$
declare
v_email text := public.current_email();
v_event_id uuid;
v_fb_id uuid;
v_points integer;
v_clean text;
begin
if v_email is null then raise exception 'not authenticated'; end if;
if p_rating is null or p_rating < 1 or p_rating > 5 then
raise exception 'rating must be between 1 and 5';
end if;
select id into v_event_id from public.events where is_active limit 1;
if v_event_id is null then raise exception 'no active event'; end if;
if not exists (select 1 from public.registrations
where event_id = v_event_id and contact_email = v_email) then
raise exception 'you must be registered for this event to give feedback';
end if;
v_clean := nullif(btrim(coalesce(p_comment, '')), '');
insert into public.event_feedback (event_id, contact_email, rating, comment)
values (v_event_id, v_email, p_rating, v_clean)
on conflict (event_id, contact_email) do update
set rating = excluded.rating, comment = excluded.comment
returning id into v_fb_id;
select r.points into v_points from public.registrations r
where r.event_id = v_event_id and r.contact_email = v_email;
return query select v_fb_id, coalesce(v_points, 0);
end;
$$;
-- Read the current user's own event feedback (for the "you already rated" state).
create or replace function public.get_my_event_feedback()
returns public.event_feedback
language sql stable security definer set search_path = public as $$
select * from public.event_feedback ef
where ef.contact_email = public.current_email()
and ef.event_id = (select id from public.events where is_active limit 1)
limit 1;
$$;
-- Admin: read all event feedback for the active event (for the admin Activity view).
create or replace function public.get_all_event_feedback()
returns setof public.event_feedback
language sql stable security definer set search_path = public as $$
select * from public.event_feedback ef
where ef.event_id = (select id from public.events where is_active limit 1)
order by ef.created_at desc;
$$;
-- -----------------------------------------------------------------------------
-- 5. RLS + grants
-- -----------------------------------------------------------------------------
alter table public.event_feedback enable row level security;
-- Read own, or all if admin.
create policy "event_feedback_select_own_or_admin" on public.event_feedback for select to authenticated
using (contact_email = public.current_email() or public.is_admin());
-- Writes happen via the submit_event_feedback RPC (security definer), so no
-- direct insert/update/delete policies are needed.
grant select on public.event_feedback to anon, authenticated, service_role;
grant insert, update, delete on public.event_feedback to authenticated, service_role;
grant execute on function public.submit_event_feedback(integer, text) to authenticated;
grant execute on function public.get_my_event_feedback() to authenticated;
grant execute on function public.get_all_event_feedback() to authenticated;
-- -----------------------------------------------------------------------------
-- 6. Re-create the Sessionize sync RPCs to upsert level + area
-- (The originals live in 20260833000000_service_sessions_feedback.sql;
-- append-only migrations can't edit them, so we replace them here. The
-- only change is adding level + area to the session upsert.)
-- -----------------------------------------------------------------------------
-- 6a. sync_sessionize_event (API sync) — adds level + area to the session upsert.
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_slot public.slots;
v_slot_id integer;
v_session public.sessions;
v_existing boolean;
v_spk text;
v_speakers_created integer := 0;
v_speakers_updated integer := 0;
v_sessions_created integer := 0;
v_sessions_updated integer := 0;
v_slots_created integer := 0;
v_speakers_linked integer := 0;
v_errors jsonb := '[]'::jsonb;
v_err text;
begin
if coalesce(auth.jwt() ->> 'role', '') <> 'service_role' then
raise exception 'service_role only';
end if;
if not exists (select 1 from public.events where id = p_event_id) then
raise exception 'event not found';
end if;
insert into public.sync_runs (event_id, source, started_at, triggered_by)
values (p_event_id, 'sessionize', v_started, 'service_role')
returning id into v_run_id;
-- (1) Speakers -> contacts (matched by email).
for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'speakers', '[]'::jsonb))
loop
begin
v_email := v_item ->> 'email';
v_name := v_item ->> 'full_name';
v_ext := v_item ->> 'external_id';
if v_email is null or btrim(v_email) = '' or v_name is null or btrim(v_name) = '' then
continue;
end if;
select exists (select 1 from public.contacts where email = v_email) into v_existing;
insert into public.contacts (email, full_name, external_id)
values (v_email, v_name, v_ext)
on conflict (email) do update
set full_name = excluded.full_name,
external_id = coalesce(excluded.external_id, public.contacts.external_id);
perform public._ensure_auth_user_exists(v_email, v_name);
if v_existing then
v_speakers_updated := v_speakers_updated + 1;
else
v_speakers_created := v_speakers_created + 1;
end if;
exception when others then
v_err := coalesce(v_email, '<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;
$$;
-- 6b. sync_sessionize_excel (Excel import) — adds level + area to the session upsert.
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_slot public.slots;
v_slot_id integer;
v_session public.sessions;
v_existing boolean;
v_spk text;
v_speakers_created integer := 0;
v_speakers_updated integer := 0;
v_sessions_created integer := 0;
v_sessions_updated integer := 0;
v_slots_created integer := 0;
v_speakers_linked integer := 0;
v_regs_created integer := 0;
v_regs_updated integer := 0;
v_errors jsonb := '[]'::jsonb;
v_err text;
begin
if coalesce(auth.jwt() ->> 'role', '') <> 'service_role' then
raise exception 'service_role only';
end if;
if not exists (select 1 from public.events where id = p_event_id) then
raise exception 'event not found';
end if;
insert into public.sync_runs (event_id, source, started_at, triggered_by)
values (p_event_id, 'sessionize_excel', v_started, 'service_role')
returning id into v_run_id;
-- (1) Speakers -> contacts (matched by email).
for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'speakers', '[]'::jsonb))
loop
begin
v_email := v_item ->> 'email';
v_name := v_item ->> 'full_name';
v_ext := v_item ->> 'external_id';
v_linkedin := v_item ->> 'linkedin_url';
if v_email is null or btrim(v_email) = '' or v_name is null or btrim(v_name) = '' then
continue;
end if;
select exists (select 1 from public.contacts where email = v_email) into v_existing;
insert into public.contacts (email, full_name, external_id, linkedin_url)
values (v_email, v_name, v_ext, v_linkedin)
on conflict (email) do update
set full_name = excluded.full_name,
external_id = coalesce(excluded.external_id, public.contacts.external_id),
linkedin_url = coalesce(excluded.linkedin_url, public.contacts.linkedin_url);
perform public._ensure_auth_user_exists(v_email, v_name);
if v_existing then
v_speakers_updated := v_speakers_updated + 1;
else
v_speakers_created := v_speakers_created + 1;
end if;
exception when others then
v_err := coalesce(v_email, '<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,123 @@
-- =============================================================================
-- Convivo — Talk networking incentives
--
-- A per-event configurable bonus awarded when two people who were checked into
-- the SAME session (talk) accept a connection. This rewards "networking around
-- talks": meeting someone who was in the same talk and making a connection.
--
-- 1. `events.talk_networking_bonus` (integer, default 2) — the bonus points
-- awarded to EACH party when they share a checked-in session and accept a
-- connection. **0 disables the feature** (no bonus, the +5 connection award
-- still applies).
--
-- 2. `accept_connection(uuid)` is re-created (append-only migrations can't
-- edit it, and the return type changes, so we drop + recreate) to:
-- - keep the existing +5-to-both connection award,
-- - compute whether both parties share a checked-in session,
-- - if they do AND `talk_networking_bonus > 0`, award the bonus to each
-- party (category `talk_networking`),
-- - return a new `shared_talk` column (so the app can show a "met at
-- {talk}" note).
--
-- Idempotency: `accept_connection` is one-shot (row locked, status must be
-- `pending`), so the bonus can never double-award. Documented limitation:
-- check-ins that happen AFTER acceptance do not retro-award the bonus — the
-- bonus reflects shared attendance at acceptance time.
--
-- The bonus flows through `_award_points`, so the leaderboard sync + staff
-- exclusion are inherited automatically (no change to `_sync_leaderboard`).
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. events.talk_networking_bonus
-- -----------------------------------------------------------------------------
alter table public.events add column if not exists talk_networking_bonus integer not null default 2;
comment on column public.events.talk_networking_bonus is
'Bonus points awarded to EACH party when two people who were checked into the '
'same session (talk) accept a connection. 0 disables the feature. '
'Awarded with category "talk_networking".';
-- Widen the points_log.category CHECK to include the new `talk_networking`
-- category (the original constraint only allowed the four original categories).
alter table public.points_log drop constraint if exists points_log_category_check;
alter table public.points_log add constraint points_log_category_check
check (category in ('checkin', 'connection', 'feedback', 'admin', 'talk_networking'));
-- -----------------------------------------------------------------------------
-- 2. accept_connection — re-created to add the talk networking bonus
-- (The return type changes from `public.connections` to a table that adds
-- `shared_talk`, so we must drop the existing function first.)
-- -----------------------------------------------------------------------------
drop function if exists public.accept_connection(uuid);
create or replace function public.accept_connection(p_connection_id uuid)
returns table (
event_id uuid, from_email text, to_email text, status text,
created_at timestamptz, resolved_at timestamptz, shared_talk boolean
)
language plpgsql security definer set search_path = public as $$
declare
v_email text := public.current_email();
v_conn public.connections;
v_shared boolean;
v_bonus integer;
begin
if v_email is null then raise exception 'not authenticated'; end if;
select * into v_conn from public.connections where id = p_connection_id for update;
if not found then raise exception 'connection not found'; end if;
if v_conn.to_email <> v_email then raise exception 'you can only accept incoming requests'; end if;
if v_conn.status <> 'pending' then raise exception 'request already resolved'; end if;
update public.connections set status = 'accepted', resolved_at = now() where id = p_connection_id;
perform public._award_points(v_conn.event_id, v_conn.from_email, 5, 'connection');
perform public._award_points(v_conn.event_id, v_conn.to_email, 5, 'connection');
-- Talk networking bonus: do the two parties share a checked-in session (talk)?
select count(*) > 0 into v_shared
from public.checkins a
where a.event_id = v_conn.event_id
and a.contact_email = v_conn.from_email
and exists (
select 1 from public.checkins b
where b.event_id = v_conn.event_id
and b.contact_email = v_conn.to_email
and b.session_id = a.session_id
);
select coalesce(talk_networking_bonus, 0) into v_bonus
from public.events where id = v_conn.event_id;
if v_shared and v_bonus > 0 then
perform public._award_points(v_conn.event_id, v_conn.from_email, v_bonus, 'talk_networking');
perform public._award_points(v_conn.event_id, v_conn.to_email, v_bonus, 'talk_networking');
end if;
select * into v_conn from public.connections where id = p_connection_id;
-- A single final `return query` (a `return query` inside an `if` block would
-- not terminate the function and would double-award).
return query select v_conn.event_id, v_conn.from_email, v_conn.to_email,
v_conn.status, v_conn.created_at, v_conn.resolved_at, v_shared;
end;
$$;
grant execute on function public.accept_connection(uuid) to authenticated;
-- -----------------------------------------------------------------------------
-- 3. get_talk_cohort(p_session_id) — who else was checked into the same talk
-- The `checkins` RLS policy is own-or-admin, so an attendee cannot read
-- other people's check-ins directly. This security-definer RPC returns the
-- other attendees (email + full_name + registration type + QR token, for
-- the Connect action) who were checked into the given session. The caller's
-- own row is excluded. Staff are excluded (they are not "attendees" of the
-- networking game).
-- -----------------------------------------------------------------------------
create or replace function public.get_talk_cohort(p_session_id uuid)
returns table (email text, full_name text, registration_type public.registration_type, qr_token text)
language sql stable security definer set search_path = public as $$
select c.email, c.full_name, r."type", r.qr_token
from public.checkins ck
join public.registrations r
on r.event_id = ck.event_id and r.contact_email = ck.contact_email
join public.contacts c on c.email = ck.contact_email
where ck.session_id = p_session_id
and r."type" <> 'staff'
and c.email <> public.current_email();
$$;
grant execute on function public.get_talk_cohort(uuid) to authenticated;
+99 -10
View File
@@ -229,23 +229,25 @@ end;
$$;
-- =============================================================================
-- 7. accept_connection: +5 to both parties
-- 7. accept_connection: +5 to both parties (+ talk networking bonus, since
-- lena and felix were both checked into the slot-2 session above)
-- =============================================================================
do $$
declare
v_conn uuid;
v_conn_id uuid;
v_from integer;
v_to integer;
v_shared boolean;
v_ok boolean;
v_msg text;
begin
-- lena -> felix (both fresh attendees).
-- lena -> felix (both were checked into the slot-2 session).
perform set_user('[email protected]');
select id into v_conn from public.create_connection_request('CVV-ATT-1001');
select id into v_conn_id from public.create_connection_request('CVV-ATT-1001');
-- felix accepts.
perform set_user('[email protected]');
perform public.accept_connection(v_conn);
select shared_talk into v_shared from public.accept_connection(v_conn_id);
select points into v_from from public.registrations
where contact_email = '[email protected]'
@@ -253,16 +255,103 @@ begin
select points into v_to from public.registrations
where contact_email = '[email protected]'
and event_id = (select id from public.events where is_active limit 1);
-- lena had 10 from the check-in test; +5 connection = 15.
-- felix had 15 (check-in + feedback); +5 connection = 20.
v_ok := (v_from = 15 and v_to = 20);
v_msg := 'expected lena=15/felix=20, got lena=' || v_from || ' felix=' || v_to;
insert into test_results values ('connection accepted +5 each', v_ok, case when v_ok then null else v_msg end);
-- lena had 10 from the check-in test; +5 connection + 2 talk bonus = 17.
-- felix had 15 (check-in + feedback); +5 connection + 2 talk bonus = 22.
v_ok := (v_from = 17 and v_to = 22);
v_msg := 'expected lena=17/felix=22, got lena=' || v_from || ' felix=' || v_to;
insert into test_results values ('connection accepted +5 each (+ talk bonus)', v_ok, case when v_ok then null else v_msg end);
v_ok := v_shared;
v_msg := 'expected shared_talk=true (both checked into slot 2)';
insert into test_results values ('accept_connection shared_talk flag', v_ok, case when v_ok then null else v_msg end);
exception when others then
insert into test_results values ('connection (7)', false, 'error: ' || sqlerrm);
end;
$$;
-- =============================================================================
-- 7b. accept_connection: NO talk bonus when the parties share no check-in
-- =============================================================================
do $$
declare
v_conn_id uuid;
v_from integer;
v_to integer;
v_shared boolean;
v_ok boolean;
v_msg text;
begin
-- Two attendees who were never checked in: no shared talk.
-- [email protected] (1003) -> [email protected] (1004).
perform set_user('[email protected]');
select id into v_conn_id from public.create_connection_request('CVV-ATT-1004');
-- emma accepts.
perform set_user('[email protected]');
select shared_talk into v_shared from public.accept_connection(v_conn_id);
select points into v_from from public.registrations
where contact_email = '[email protected]'
and event_id = (select id from public.events where is_active limit 1);
select points into v_to from public.registrations
where contact_email = '[email protected]'
and event_id = (select id from public.events where is_active limit 1);
-- +5 connection each, NO talk bonus (no shared check-in).
v_ok := (v_from = 5 and v_to = 5);
v_msg := 'expected jonas=5/emma=5 (no bonus), got jonas=' || v_from || ' emma=' || v_to;
insert into test_results values ('no talk bonus without shared check-in', v_ok, case when v_ok then null else v_msg end);
v_ok := (v_shared = false);
v_msg := 'expected shared_talk=false';
insert into test_results values ('shared_talk=false without shared check-in', v_ok, case when v_ok then null else v_msg end);
exception when others then
insert into test_results values ('connection (7b)', false, 'error: ' || sqlerrm);
end;
$$;
-- =============================================================================
-- 7c. accept_connection: talk bonus disabled when talk_networking_bonus = 0
-- =============================================================================
do $$
declare
v_session uuid;
v_conn_id uuid;
v_from integer;
v_to integer;
v_ok boolean;
v_msg text;
begin
-- Disable the bonus for the active event.
update public.events set talk_networking_bonus = 0
where id = (select id from public.events where is_active limit 1);
-- [email protected] (1002) and [email protected] (1005): check both
-- into the slot-2 session so they share a check-in, then connect.
select id into v_session from public.sessions where slot_id = 2 limit 1;
perform set_user('[email protected]');
perform public.checkin_attendee(v_session, 'CVV-ATT-1002');
perform public.checkin_attendee(v_session, 'CVV-ATT-1005');
perform set_user('[email protected]');
select id into v_conn_id from public.create_connection_request('CVV-ATT-1005');
perform set_user('[email protected]');
perform public.accept_connection(v_conn_id);
select points into v_from from public.registrations
where contact_email = '[email protected]'
and event_id = (select id from public.events where is_active limit 1);
select points into v_to from public.registrations
where contact_email = '[email protected]'
and event_id = (select id from public.events where is_active limit 1);
-- +10 check-in + 5 connection each, NO bonus (disabled).
v_ok := (v_from = 15 and v_to = 15);
v_msg := 'expected mia=15/paul=15 (bonus disabled), got mia=' || v_from || ' paul=' || v_to;
insert into test_results values ('talk bonus disabled when bonus=0', v_ok, case when v_ok then null else v_msg end);
exception when others then
insert into test_results values ('connection (7c)', false, 'error: ' || sqlerrm);
end;
$$;
-- =============================================================================
-- 8. adjust_points: admin only
-- =============================================================================