Redesign Phases 3-6: multi-event model, APPE Admin, Convivo App behaviors, APPE branding

- Phase 3: new migration 20260824000000_redesign.sql (contacts/events/registrations/sponsors, slot types, session speakers + feedback/material), seed rewrite
- Phase 4: APPE Admin rebrand + Contacts/Registrations/Sponsors/Schedule/Activity/Events views
- Phase 5: Convivo App (24h login, 5s polling, QR type badge, red dot, speaker material)
- Phase 6: APPE favicon + PWA icons for both apps
- Docs: schema/rpcs/rls/seed/screens/api-client/admin-app/architecture/next-steps/README/roadmap updated
This commit is contained in:
Lago committed 2026-08-23 02:53:16 +02:00
1 parent 5adb5785aa
commit 22f5f1d317
64 files changed
+4494 -1272

No files matched your search

+42 -28
View File
@@ -2,16 +2,20 @@
**Turn a conference into a game.** Convivo is a mobile-first web app (PWA) that gets attendees out of their seats: mark the sessions you want, scan lanyards to make connections, get checked in by staff, and climb the live leaderboard. The whole thing runs on a **Dockerized Supabase core** — no custom backend.
> **Status:** Phases 0–2 complete. Now in the **Redesign** (Phases 3–6) — a new
> multi-event data model (contacts / events / registrations / sponsors), the
> admin app rebranded to **APPE Admin**, and new Convivo App behaviors.
> **Status:** Phases 0–6 complete and verified, including the full **Redesign**
> (Phases 3–6) — a new multi-event data model (contacts / events / registrations /
> sponsors), the admin app rebranded to **APPE Admin**, and new Convivo App
> behaviors.
>
> - **Phase 0** — Dockerized Supabase core (Postgres + GoTrue + PostgREST + Realtime + Kong + Studio) with the full schema, RLS, and transactional points RPCs.
> - **Phase 1** — Attendee web PWA: login (QR + email), Home, Agenda, Scan/Connect, staff Check-in, Feedback, live Leaderboard, Profile.
> - **Phase 2** — Admin console (desktop-first, admin-role only): Dashboard, Attendees (edit / reset QR / adjust points), Schedule (slots + sessions), Activity.
> - **Phase 3** — Redesign data model: contacts / events / registrations / sponsors, slot types, session speakers + feedback/material.
> - **Phase 4** — APPE Admin: rebrand + Contacts / Registrations / Sponsors / Schedule / Activity / event mgmt.
> - **Phase 5** — Convivo App: 24h login, 5s polling, QR type badge, red dot, speaker material.
> - **Phase 6** — Branding: APPE favicon + icons for both apps.
>
> **Next:** Phase 3 (data model) → 4 (APPE Admin) → 5 (Convivo App) → 6
> (branding) → 7 (Pretix) → 8 (Sessionize). See [`roadmap.md`](./roadmap.md).
> **Next:** Phase 7 (Pretix) → 8 (Sessionize). See [`roadmap.md`](./roadmap.md).
---
@@ -50,7 +54,9 @@ The schedule is **data-driven** (stored in Postgres), so times and sessions can
| **Staff** | Everything an attendee can do, **plus** a Check-in mode: pick a session, scan attendee lanyards to check them in |
| **Admin** | Staff powers **plus** full read/write on all event data (used by the Admin console) |
Staff and attendees use the **same app** — the role is an attribute on the profile and changes the Scan tab into a Check-in tab.
Staff and attendees use the **same app** — the role is the contact's
**registration type** for the active event and changes the Scan tab into a
Check-in tab.
## 4. Features
@@ -95,7 +101,7 @@ Staff and attendees use the **same app** — the role is an attribute on the pro
| Feedback — rating only | **+5** |
| Feedback — rating + free text | **+10 total** |
Points are updated **transactionally** by Postgres RPCs (`security definer`): each RPC updates `profiles.points`, inserts the related row, and re-syncs the `leaderboard` mirror **in a single transaction**. This guarantees the leaderboard is always consistent and that duplicate actions (re-check-in, re-feedback) never double-award.
Points are updated **transactionally** by Postgres RPCs (`security definer`): each RPC updates `registrations.points`, inserts the related row, and re-syncs the `leaderboard` mirror **in a single transaction**. This guarantees the leaderboard is always consistent and that duplicate actions (re-check-in, re-feedback) never double-award.
## 6. Architecture
@@ -137,21 +143,28 @@ The app talks to Supabase through **same-origin paths** (`/auth`, `/rest`, `/rea
## 7. Data model (Postgres)
The model is **multi-event**: people (`contacts`) register for `events` via
`registrations`, and all activity is scoped to `event_id` + `contact_email`.
| Table | Key fields | Notes |
|---|---|---|
| `profiles` | id (= auth uid), email (unique), full_name, company, role (attendee/staff/admin), qr_token (unique), points | One row per attendee; id is the Supabase Auth user id |
| `slots` | id, name, start, end | 6 rows for 23 Oct |
| `sessions` | id, title, description, slot_id, room, speakers, capacity | 18 rows (3 per slot) |
| `preferences` | profile_id, session_id, slot_id | Unique per (profile, slot) — one pick per slot |
| `connections` | from_id, to_id, status (pending/accepted/rejected), created_at, resolved_at | Unique per unordered pair (via `least`/`greatest` index) |
| `checkins` | profile_id, session_id, staff_id, created_at | Unique per (profile, session) |
| `feedback` | profile_id, session_id, rating (1–5), comment, created_at | Unique per (profile, session); only after session end |
| `leaderboard` | profile_id, full_name, company, points, updated_at | Realtime mirror, kept in sync by the RPCs |
| `points_log` | profile_id, delta, category, created_at | Audit trail powering the per-category breakdown |
| `contacts` | email (PK), full_name, linkedin_url, show_email, show_linkedin, is_admin, qr_token (unique) | One row per person; mirrors `auth.users` (email + bcrypt(qr_token)) |
| `events` | id, name, start_date, end_date, location, is_active, + aggregates | Partial unique index → at most one active event |
| `registrations` | id, event_id, contact_email, type (attendee/speaker/staff/sponsor), checked_in, points | Unique (event_id, contact_email); points live here |
| `sponsors` | id, event_id, type, name, email, phone, paid, amount_eur, contact_email | `paid` gates visibility to non-admins |
| `slots` | id, event_id, type (session/lunch_break/coffee_break/keynote/close_up), name, slot_date, start_time, end_time | 6 rows for 23 Oct |
| `sessions` | id, event_id, slot_id, title, description, room, capacity, average_feedback, ai_generated_feedback, material_path | 18 rows (3 per session slot) |
| `session_speakers` | session_id, contact_email | Join; a session must have ≥1 speaker |
| `preferences` | event_id, contact_email, session_id, slot_id | Unique per (event, contact, slot) — one pick per slot |
| `connections` | event_id, from_email, to_email, status, created_at, resolved_at | Unique per unordered pair (via `least`/`greatest` index) |
| `checkins` | event_id, contact_email, session_id, staff_email, created_at | Unique per (event, contact, session) |
| `feedback` | event_id, contact_email, session_id, rating (1–5), comment, created_at | Unique per (event, contact, session); only after session end |
| `leaderboard` | event_id, contact_email, full_name, points, updated_at | Realtime mirror, kept in sync by the RPCs |
| `points_log` | event_id, contact_email, delta, category, created_at | Audit trail powering the per-category breakdown |
**Key RPCs** (all `security definer`, transactional): `lanyard_lookup`, `set_preference`, `clear_preference`, `create_connection_request`, `accept_connection`, `reject_connection`, `checkin_attendee`, `submit_feedback`, `adjust_points`, `get_agenda`, `get_public_profiles`.
**Key RPCs** (all `security definer`, transactional): `lanyard_lookup`, `get_active_event`, `get_agenda`, `get_public_contacts`, `get_leaderboard`, `set_preference`, `clear_preference`, `create_connection_request`, `accept_connection`, `reject_connection`, `checkin_attendee`, `submit_feedback`, `adjust_points`, `reset_qr_token`, `upsert_contact`, `create_registration`, `set_registration_type`, `evaluate_session_feedback`, `set_session_material`.
**RLS:** every table has policies. Profiles are self-or-admin; event tables are scoped to `auth.uid()`; slots/sessions are readable by any authenticated user and writable by admin; the leaderboard is readable by any authenticated user.
**RLS:** every table has policies. Contacts are self-or-admin; sponsors are visible only when `paid` (or to admins); schedule/registrations are readable per active event and writable by admin; the leaderboard is readable by any authenticated user. A `materials` storage bucket holds session materials (read for attendees, write for speakers/admins).
## 8. Tech stack
@@ -181,9 +194,10 @@ Convivo/
│ └─ src/ # screens, components, lib, context
├─ supabase/
│ ├─ config.toml # Local stack config (ports, auth, RLS defaults)
│ ├─ migrations/ # 20260822000000_init.sql — schema, RLS, RPCs
│ └─ seed.sql # Slots, sessions, 13 demo users, Ana's demo state
├─ docker-compose.yml # Runs the app sidecar on the Supabase network
│ ├─ migrations/ # 20260824000000_redesign.sql — current schema, RLS, RPCs
│ └─ seed.sql # 1 event, 6 slots, 18 sessions, 14 contacts, demo state
├─ apps/admin/ # APPE Admin console (React + Vite + TS)
├─ docker-compose.yml # Runs the app sidecars on the Supabase network
└─ mockup/index.html # Original interactive mockup (design reference)
```
@@ -243,7 +257,7 @@ Login = **QR code** (typed or scanned) + **email**. The QR token is the password
| **Ana Silva** | attendee | `CVV-ANA-4821` | ana.silva@nubank.com |
| **Bruno Costa** | staff | `CVV-BRU-1177` | bruno.costa@acme.com |
| **Rita Lopes** | staff | `CVV-RIT-9034` | rita.lopes@globant.com |
| **Convivo Admin** | admin | `CVV-ADM-0001` | admin@appe.at |
| **APPE Admin** | admin | `CVV-ADM-0001` | admin@appe.at |
| Tomás Ribeiro | attendee | `CVV-TOM-5566` | tomas.ribeiro@dataprev.com |
| Sofia Almeida | attendee | `CVV-SOF-2299` | sofia.almeida@loop.com |
| Marco Chen | attendee | `CVV-MRC-7712` | marco.chen@deepmind.com |
@@ -259,7 +273,7 @@ Login = **QR code** (typed or scanned) + **email**. The QR token is the password
2. Scan **Marco** (`CVV-MRC-7712`) → send a connection request.
3. Log in as **Bruno** (staff) → the Scan tab becomes **Check-in** → pick a session → scan **Carla** (`CVV-CAR-6623`) → she gets +10.
4. Watch the **Leaderboard** update live.
5. Open the **admin console** on **:3001** → log in as **Convivo Admin** (`CVV-ADM-0001` / admin@appe.at) → see the Dashboard, reset an attendee's QR, adjust points, and edit the schedule.
5. Open the **APPE Admin** console on **:3001** → log in as **APPE Admin** (`CVV-ADM-0001` / admin@appe.at) → see the Dashboard, reset a contact's QR, adjust points, and edit the schedule.
## 13. Roadmap
@@ -270,11 +284,11 @@ Full detail in [`roadmap.md`](./roadmap.md).
| **0** | Dockerized Supabase core: schema, RLS, transactional points RPCs, seed | ✅ |
| **1** | Attendee web PWA: login, Home, Agenda, Scan/Connect, Check-in, Feedback, Leaderboard, Profile | ✅ |
| **2** | Admin console (Convivo Admin): Dashboard, Attendees, Schedule, Activity | ✅ |
| **3** | **Redesign — data model**: contacts / events / registrations / sponsors, slot types, session speakers + feedback/material | 🔨 next |
| **4** | **Redesign — APPE Admin**: rebrand + Contacts / Registrations / Sponsors / Schedule / Activity / event mgmt | ⬜ |
| **5** | **Redesign — Convivo App**: 24h login, 5s polling, QR type badge, red dot, speaker material | ⬜ |
| **6** | **Redesign — branding**: APPE favicon + icons for both apps | ⬜ |
| **7** | **Pretix** interface — sync tickets → contacts + registrations | ⬜ |
| **3** | **Redesign — data model**: contacts / events / registrations / sponsors, slot types, session speakers + feedback/material | ✅ |
| **4** | **Redesign — APPE Admin**: rebrand + Contacts / Registrations / Sponsors / Schedule / Activity / event mgmt | ✅ |
| **5** | **Redesign — Convivo App**: 24h login, 5s polling, QR type badge, red dot, speaker material | ✅ |
| **6** | **Redesign — branding**: APPE favicon + icons for both apps | ✅ |
| **7** | **Pretix** interface — sync tickets → contacts + registrations | ⬜ next |
| **8** | **Sessionize** interface — sync the real agenda (slots, sessions, speakers) | ⬜ |
> **Subdomains** (`convivo.appe.at`, `admin.appe.at`, `db.appe.at`, `pretix.eu`, `sessionize.com`) do not exist yet — everything runs on **localhost** for now.
+4 -3
View File
@@ -2,15 +2,16 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#1f1b1b" />
<meta name="description" content="Convivo Admin — manage attendees, schedule, and points." />
<meta name="description" content="APPE Admin — manage contacts, registrations, sponsors, schedule, and points." />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800;900&display=swap" rel="stylesheet" />
<title>Convivo Admin</title>
<title>APPE Admin</title>
</head>
<body>
<div id="root"></div>
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

-10
View File
@@ -1,10 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#d50000"/>
<stop offset="1" stop-color="#ff5a4e"/>
</linearGradient>
</defs>
<rect width="100" height="100" rx="24" fill="url(#g)"/>
<text x="50" y="68" font-family="Poppins, Arial, sans-serif" font-size="52" font-weight="900" fill="#fff" text-anchor="middle">C</text>
</svg>

Before

Width:  |  Height:  |  Size: 455 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

After

Width:  |  Height:  |  Size: 28 KiB

+5 -4
View File
@@ -1,13 +1,14 @@
{
"name": "Convivo Admin",
"short_name": "Convivo Admin",
"description": "Manage attendees, schedule, and points for the Convivo event.",
"name": "APPE Admin",
"short_name": "APPE Admin",
"description": "Manage contacts, registrations, sponsors, schedule, and points for APPE.",
"start_url": "/",
"display": "standalone",
"background_color": "#f0f2f6",
"theme_color": "#1f1b1b",
"icons": [
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/apple-touch-icon.png", "sizes": "180x180", "type": "image/png", "purpose": "any" }
]
}
+21 -12
View File
@@ -3,22 +3,28 @@ import { AuthProvider, useAuth } from './context/AuthContext';
import { ToastProvider } from './context/ToastContext';
import { Login } from './screens/Login';
import { Dashboard } from './views/Dashboard';
import { Attendees } from './views/Attendees';
import { Contacts } from './views/Contacts';
import { Registrations } from './views/Registrations';
import { Sponsors } from './views/Sponsors';
import { Schedule } from './views/Schedule';
import { Activity } from './views/Activity';
import { Events } from './views/Events';
import { Spinner } from './components/ui';
type View = 'dashboard' | 'attendees' | 'schedule' | 'activity';
export type View = 'dashboard' | 'contacts' | 'registrations' | 'sponsors' | 'schedule' | 'activity' | 'events';
const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'dashboard', label: 'Dashboard', ico: '📊' },
{ id: 'attendees', label: 'Attendees', ico: '👥' },
{ id: 'contacts', label: 'Contacts', ico: '👥' },
{ id: 'registrations', label: 'Registrations', ico: '🎟️' },
{ id: 'sponsors', label: 'Sponsors', ico: '🤝' },
{ id: 'schedule', label: 'Schedule', ico: '🗓️' },
{ id: 'activity', label: 'Activity', ico: '⚡' },
{ id: 'events', label: 'Events', ico: '📅' },
];
function Shell() {
const { profile, loading, signOut } = useAuth();
const { contact, loading, signOut } = useAuth();
const [view, setView] = useState<View>('dashboard');
if (loading) {
@@ -29,16 +35,16 @@ function Shell() {
);
}
if (!profile) return <Login />;
if (!contact) return <Login />;
return (
<div className="app">
<aside className="sidebar">
<div className="brand">
<div className="logo">C</div>
<div className="logo">A</div>
<div>
<div className="name">Convivo</div>
<div className="sub">Admin Console</div>
<div className="name">APPE</div>
<div className="sub">Admin</div>
</div>
</div>
<nav className="nav">
@@ -56,7 +62,7 @@ function Shell() {
<div className="sidebar-foot">
<div className="admin-card">
<span className="avatar" style={{ width: 36, height: 36, fontSize: 13, background: '#d50000' }}>
{profile.full_name
{contact.full_name
.split(' ')
.map((w) => w[0])
.slice(0, 2)
@@ -64,8 +70,8 @@ function Shell() {
.toUpperCase()}
</span>
<div className="who">
<div className="n">{profile.full_name}</div>
<div className="e">{profile.email}</div>
<div className="n">{contact.full_name}</div>
<div className="e">{contact.email}</div>
</div>
</div>
<button className="signout" onClick={signOut}>
@@ -76,9 +82,12 @@ function Shell() {
<main className="content">
{view === 'dashboard' && <Dashboard onNavigate={setView} />}
{view === 'attendees' && <Attendees />}
{view === 'contacts' && <Contacts />}
{view === 'registrations' && <Registrations />}
{view === 'sponsors' && <Sponsors />}
{view === 'schedule' && <Schedule />}
{view === 'activity' && <Activity />}
{view === 'events' && <Events />}
</main>
</div>
);
+24 -3
View File
@@ -79,7 +79,28 @@ export function QrImage({ value, size = 180 }: { value: string; size?: number })
);
}
/** Small colored badge for a role. */
export function RoleBadge({ role }: { role: string }) {
return <span className={`pill pill-${role}`}>{role}</span>;
/** Small colored badge for a registration / sponsor type. */
export function TypeBadge({ type }: { type: string }) {
return <span className={`pill pill-${type}`}>{type.replace('_', ' ')}</span>;
}
/** A small on/off toggle switch. */
export function Toggle({
checked,
onChange,
label,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label?: string;
}) {
return (
<label className="toggle" title={label}>
<input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
<span className="track">
<span className="knob" />
</span>
{label && <span className="toggle-lbl">{label}</span>}
</label>
);
}
+29 -30
View File
@@ -1,9 +1,9 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { supabase } from '../lib/supabase';
import type { Profile } from '../lib/types';
import type { Contact } from '../lib/types';
interface AuthState {
profile: Profile | null;
contact: Contact | null;
loading: boolean;
signIn: (email: string, qrToken: string) => Promise<void>;
signOut: () => Promise<void>;
@@ -11,11 +11,23 @@ interface AuthState {
const AuthContext = createContext<AuthState | null>(null);
// Load the current user's contact row. Returns null if it doesn't exist or the
// contact is not an admin (this is an admin-only app).
async function loadAdminContact(email: string): Promise<Contact | null> {
const { data } = await supabase
.from('contacts')
.select('*')
.eq('email', email)
.maybeSingle();
const c = data as Contact | null;
return c && c.is_admin ? c : null;
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [profile, setProfile] = useState<Profile | null>(null);
const [contact, setContact] = useState<Contact | null>(null);
const [loading, setLoading] = useState(true);
// On mount: restore any existing session and load the profile. If the
// On mount: restore any existing session and load the contact. If the
// session belongs to a non-admin, sign out immediately (admin-only app).
useEffect(() => {
let cancelled = false;
@@ -27,14 +39,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
if (!cancelled) setLoading(false);
return;
}
const { data: prof } = await supabase
.from('profiles')
.select('*')
.eq('id', session.user.id)
.maybeSingle();
const c = session.user.email ? await loadAdminContact(session.user.email) : null;
if (cancelled) return;
if (prof && prof.role === 'admin') {
setProfile(prof as Profile);
if (c) {
setContact(c);
} else {
// Not an admin — clear the session.
await supabase.auth.signOut();
@@ -46,19 +54,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const { data: sub } = supabase.auth.onAuthStateChange(async (_event, session) => {
if (!session) {
setProfile(null);
setContact(null);
return;
}
const { data: prof } = await supabase
.from('profiles')
.select('*')
.eq('id', session.user.id)
.maybeSingle();
if (prof && prof.role === 'admin') {
setProfile(prof as Profile);
const c = session.user.email ? await loadAdminContact(session.user.email) : null;
if (c) {
setContact(c);
} else {
await supabase.auth.signOut();
setProfile(null);
setContact(null);
}
});
@@ -75,27 +79,22 @@ export function AuthProvider({ children }: { children: ReactNode }) {
});
if (error) throw new Error(error.message);
const { data: prof } = await supabase
.from('profiles')
.select('*')
.eq('id', data.user.id)
.maybeSingle();
if (!prof || prof.role !== 'admin') {
const c = data.user.email ? await loadAdminContact(data.user.email) : null;
if (!c) {
// Signed in, but not an admin — reject and sign out.
await supabase.auth.signOut();
throw new Error('This account is not an admin.');
}
setProfile(prof as Profile);
setContact(c);
}
async function signOut() {
await supabase.auth.signOut();
setProfile(null);
setContact(null);
}
return (
<AuthContext.Provider value={{ profile, loading, signIn, signOut }}>
<AuthContext.Provider value={{ contact, loading, signIn, signOut }}>
{children}
</AuthContext.Provider>
);
+165 -18
View File
@@ -2,13 +2,17 @@ import { supabase } from './supabase';
import type {
Checkin,
Connection,
Contact,
Event,
Feedback,
LeaderboardRow,
PointsLogRow,
Profile,
Registration,
ResetQrResult,
Session,
SessionSpeaker,
Slot,
Sponsor,
} from './types';
export class ApiError extends Error {}
@@ -29,33 +33,176 @@ async function all<T>(table: string, order?: { col: string; asc?: boolean }): Pr
// ---- Reads (admin can read all rows via RLS) --------------------------------
export const getAllProfiles = () => all<Profile>('profiles', { col: 'points', asc: false });
export const getAllSlots = () => all<Slot>('slots', { col: 'id' });
export const getAllSessions = () => all<Session>('sessions', { col: 'slot_id' });
export const getAllContacts = () => all<Contact>('contacts', { col: 'full_name' });
export const getAllEvents = () => all<Event>('events', { col: 'start_date', asc: false });
export const getActiveEvent = async (): Promise<Event | null> => {
const { data, error } = await supabase.from('events').select('*').eq('is_active', true).maybeSingle();
if (error) throw new ApiError(error.message);
return (data as Event) ?? null;
};
export const getRegistrations = (eventId: string) =>
all<Registration>('registrations', { col: 'points', asc: false }).then((rows) =>
rows.filter((r) => r.event_id === eventId),
);
export const getSponsors = (eventId: string) =>
all<Sponsor>('sponsors', { col: 'name' }).then((rows) => rows.filter((s) => s.event_id === eventId));
export const getSlots = (eventId: string) =>
all<Slot>('slots', { col: 'id' }).then((rows) => rows.filter((s) => s.event_id === eventId));
export const getSessions = (eventId: string) =>
all<Session>('sessions', { col: 'slot_id' }).then((rows) => rows.filter((s) => s.event_id === eventId));
// session_speakers has no event_id; callers filter by the event's session ids.
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 getAllPointsLog = () => all<PointsLogRow>('points_log', { col: 'created_at', asc: false });
export const getLeaderboard = () => all<LeaderboardRow>('leaderboard', { col: 'points', asc: false });
// ---- Writes (admin only) ----------------------------------------------------
// ---- Contacts ----------------------------------------------------------------
/** Update an attendee's editable fields (name, company, role). */
export async function updateProfile(
id: string,
patch: { full_name?: string; company?: string | null; role?: Profile['role'] },
export async function upsertContact(input: {
email: string;
full_name: string;
linkedin_url?: string | null;
is_admin?: boolean;
qr_token?: string | null;
}): Promise<Contact> {
// upsert_contact returns a single composite row (a JSON object, not an array).
return await rpc<Contact>('upsert_contact', {
p_email: input.email,
p_full_name: input.full_name,
p_linkedin_url: input.linkedin_url ?? null,
p_is_admin: input.is_admin ?? false,
p_qr_token: input.qr_token ?? null,
});
}
export async function updateContact(
email: string,
patch: Partial<Pick<Contact, 'full_name' | 'linkedin_url' | 'show_email' | 'show_linkedin' | 'is_admin'>>,
): Promise<void> {
const { error } = await supabase.from('profiles').update(patch).eq('id', id);
const { error } = await supabase.from('contacts').update(patch).eq('email', email);
if (error) throw new ApiError(error.message);
}
/** Admin manual points adjustment (audited as 'admin'). */
export async function adjustPoints(profileId: string, delta: number, reason: string): Promise<void> {
await rpc('adjust_points', { p_profile_id: profileId, p_delta: delta, p_reason: reason });
}
/** Regenerate an attendee's QR token (syncs the auth password, forces re-login). */
export async function resetQrToken(profileId: string): Promise<ResetQrResult> {
const rows = await rpc<ResetQrResult[]>('reset_qr_token', { p_profile_id: profileId });
/** Regenerate a contact's QR token (syncs the auth password, forces re-login). */
export async function resetQrToken(email: string): Promise<ResetQrResult> {
const rows = await rpc<ResetQrResult[]>('reset_qr_token', { p_contact_email: email });
return rows[0];
}
// ---- Registrations -----------------------------------------------------------
export async function createRegistration(contactEmail: string, type: Registration['type']): Promise<void> {
await rpc('create_registration', { p_contact_email: contactEmail, p_type: type });
}
export async function setRegistrationType(contactEmail: string, type: Registration['type']): Promise<void> {
await rpc('set_registration_type', { p_contact_email: contactEmail, p_type: type });
}
export async function setCheckedIn(registrationId: string, checkedIn: boolean): Promise<void> {
const { error } = await supabase.from('registrations').update({ checked_in: checkedIn }).eq('id', registrationId);
if (error) throw new ApiError(error.message);
}
// ---- Sponsors ----------------------------------------------------------------
export async function upsertSponsor(
id: string | null,
input: {
event_id: string;
type: Sponsor['type'];
name: string;
email?: string | null;
phone?: string | null;
paid?: boolean;
amount_eur?: number | null;
contact_email?: string | null;
},
): Promise<void> {
if (id) {
const { error } = await supabase.from('sponsors').update(input).eq('id', id);
if (error) throw new ApiError(error.message);
} else {
const { error } = await supabase.from('sponsors').insert(input);
if (error) throw new ApiError(error.message);
}
}
export async function deleteSponsor(id: string): Promise<void> {
const { error } = await supabase.from('sponsors').delete().eq('id', id);
if (error) throw new ApiError(error.message);
}
// ---- Events ------------------------------------------------------------------
export async function upsertEvent(
id: string | null,
input: { name: string; start_date: string; end_date: string; location?: string | null },
): Promise<void> {
if (id) {
const { error } = await supabase.from('events').update(input).eq('id', id);
if (error) throw new ApiError(error.message);
} else {
const { error } = await supabase.from('events').insert(input);
if (error) throw new ApiError(error.message);
}
}
/** Set an event active (deactivates all others via trigger). */
export async function activateEvent(id: string): Promise<void> {
const { error } = await supabase.from('events').update({ is_active: true }).eq('id', id);
if (error) throw new ApiError(error.message);
}
// ---- Points ------------------------------------------------------------------
/** Admin manual points adjustment for the active event (audited as 'admin'). */
export async function adjustPoints(contactEmail: string, delta: number, reason: string): Promise<void> {
await rpc('adjust_points', { p_contact_email: contactEmail, p_delta: delta, p_reason: reason });
}
// ---- Sessions: speakers, material, AI feedback -------------------------------
export async function setSessionSpeakers(sessionId: string, emails: string[]): Promise<void> {
// Replace the speaker set: delete all, then insert the new set.
const { error: delErr } = await supabase.from('session_speakers').delete().eq('session_id', sessionId);
if (delErr) throw new ApiError(delErr.message);
if (emails.length > 0) {
const rows = emails.map((contact_email) => ({ session_id: sessionId, contact_email }));
const { error: insErr } = await supabase.from('session_speakers').insert(rows);
if (insErr) throw new ApiError(insErr.message);
}
}
/** Upload a session material file to the `materials` bucket and store the path. */
export async function uploadSessionMaterial(sessionId: string, file: File): Promise<string> {
const path = `sessions/${sessionId}/${Date.now()}-${file.name}`;
const { error } = await supabase.storage.from('materials').upload(path, file, { upsert: true });
if (error) throw new ApiError(error.message);
const { error: upErr } = await supabase.from('sessions').update({ material_path: path }).eq('id', sessionId);
if (upErr) throw new ApiError(upErr.message);
return path;
}
export async function removeSessionMaterial(sessionId: string): Promise<void> {
const { data } = await supabase.from('sessions').select('material_path').eq('id', sessionId).maybeSingle();
const path = (data as Session | null)?.material_path;
if (path) {
await supabase.storage.from('materials').remove([path]);
}
const { error } = await supabase.from('sessions').update({ material_path: null }).eq('id', sessionId);
if (error) throw new ApiError(error.message);
}
export function sessionMaterialUrl(path: string): string {
const { data } = supabase.storage.from('materials').getPublicUrl(path);
return data.publicUrl;
}
/** Trigger the (stub) AI feedback evaluation for a session. */
export async function evaluateSessionFeedback(sessionId: string): Promise<Session> {
// evaluate_session_feedback returns a single composite row (a JSON object, not an array).
return await rpc<Session>('evaluate_session_feedback', { p_session_id: sessionId });
}
+80 -16
View File
@@ -1,18 +1,70 @@
export type Role = 'attendee' | 'staff' | 'admin';
export type RegistrationType = 'attendee' | 'speaker' | 'staff' | 'sponsor';
export interface Profile {
id: string;
export type SponsorType =
| 'headline'
| 'platinum'
| 'gold'
| 'silver'
| 'community'
| 'swag'
| 'catering'
| 'diversity';
export type SlotType = 'session' | 'lunch_break' | 'coffee_break' | 'keynote' | 'close_up';
export interface Contact {
email: string;
full_name: string;
company: string | null;
role: Role;
linkedin_url: string | null;
show_email: boolean;
show_linkedin: boolean;
is_admin: boolean;
qr_token: string | null;
created_at: string;
}
export interface Event {
id: string;
name: string;
start_date: string;
end_date: string;
location: string | null;
is_active: boolean;
avg_feedback: number | null;
num_sessions: number;
num_speakers: number;
num_registrations: number;
num_checked_in_registrations: number;
created_at: string;
}
export interface Registration {
id: string;
event_id: string;
contact_email: string;
type: RegistrationType;
checked_in: boolean;
points: number;
created_at: string;
}
export interface Sponsor {
id: string;
event_id: string;
type: SponsorType;
name: string;
email: string | null;
phone: string | null;
paid: boolean;
amount_eur: number | null;
contact_email: string | null;
created_at: string;
}
export interface Slot {
id: number;
event_id: string;
type: SlotType;
name: string;
slot_date: string;
start_time: string;
@@ -21,21 +73,30 @@ export interface Slot {
export interface Session {
id: string;
event_id: string;
slot_id: number;
title: string;
description: string | null;
slot_id: number;
room: string | null;
capacity: number | null;
speakers: string | null;
average_feedback: number | null;
ai_generated_feedback: string | null;
material_path: string | null;
created_at: string;
}
export interface SessionSpeaker {
session_id: string;
contact_email: string;
}
export type ConnectionStatus = 'pending' | 'accepted' | 'rejected';
export interface Connection {
id: string;
from_id: string;
to_id: string;
event_id: string;
from_email: string;
to_email: string;
status: ConnectionStatus;
created_at: string;
resolved_at: string | null;
@@ -43,15 +104,17 @@ export interface Connection {
export interface Checkin {
id: string;
profile_id: string;
event_id: string;
contact_email: string;
session_id: string;
staff_id: string;
staff_email: string;
created_at: string;
}
export interface Feedback {
id: string;
profile_id: string;
event_id: string;
contact_email: string;
session_id: string;
rating: number;
comment: string | null;
@@ -59,22 +122,23 @@ export interface Feedback {
}
export interface LeaderboardRow {
profile_id: string;
event_id: string;
contact_email: string;
full_name: string;
company: string | null;
points: number;
updated_at: string;
}
export interface PointsLogRow {
id: string;
profile_id: string;
event_id: string;
contact_email: string;
delta: number;
category: 'checkin' | 'connection' | 'feedback' | 'admin';
created_at: string;
}
export interface ResetQrResult {
profile_id: string;
email: string;
qr_token: string;
}
+2 -2
View File
@@ -31,9 +31,9 @@ export function Login() {
<div className="login-wrap">
<div className="login-card">
<div className="login-brand">
<div className="logo">C</div>
<div className="logo">A</div>
<div>
<h1>Convivo Admin</h1>
<h1>APPE Admin</h1>
<p>Sign in with your admin QR token and email.</p>
</div>
</div>
+58
View File
@@ -94,6 +94,25 @@ body {
.pill.green { background: rgba(5,150,105,.12); border-color: rgba(5,150,105,.35); color: var(--green); }
.pill.violet { background: var(--accent-soft); border-color: rgba(213,0,0,.35); color: var(--accent); }
.pill.cyan { background: rgba(32,178,170,.13); border-color: rgba(32,178,170,.4); color: #0f766e; }
.pill.red { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); }
/* registration types */
.pill.speaker { background: rgba(124,58,237,.12); border-color: rgba(124,58,237,.4); color: #6d28d9; }
.pill.sponsor { background: rgba(234,88,12,.13); border-color: rgba(234,88,12,.4); color: #c2410c; }
/* slot types */
.pill.session { background: rgba(14,165,233,.12); border-color: rgba(14,165,233,.4); color: #0369a1; }
.pill.lunch_break { background: rgba(245,158,11,.14); border-color: rgba(245,158,11,.4); color: #b45309; }
.pill.coffee_break { background: rgba(120,113,108,.14); border-color: rgba(120,113,108,.4); color: #57534e; }
.pill.keynote { background: var(--accent-soft); border-color: rgba(213,0,0,.35); color: var(--accent); }
.pill.close_up { background: rgba(5,150,105,.12); border-color: rgba(5,150,105,.35); color: var(--green); }
/* sponsor tiers */
.pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); }
.pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; }
.pill.gold { background: rgba(245,158,11,.14); border-color: rgba(245,158,11,.4); color: #b45309; }
.pill.silver { background: rgba(148,163,184,.14); border-color: rgba(148,163,184,.4); color: #64748b; }
.pill.community { background: rgba(5,150,105,.12); border-color: rgba(5,150,105,.35); color: var(--green); }
.pill.swag { background: rgba(219,39,119,.12); border-color: rgba(219,39,119,.4); color: #be185d; }
.pill.catering { background: rgba(234,88,12,.13); border-color: rgba(234,88,12,.4); color: #c2410c; }
.pill.diversity { background: rgba(124,58,237,.12); border-color: rgba(124,58,237,.4); color: #6d28d9; }
.avatar { display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: 800; color: #fff; flex-shrink: 0; }
.input, select.input {
width: 100%; padding: 12px 14px; border-radius: 12px; border: 1px solid var(--line);
@@ -194,6 +213,45 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
@media (max-width: 900px) { .grid-2 { grid-template-columns: 1fr; } }
/* ---------- Toggle switch ---------- */
.toggle { display: inline-flex; align-items: center; gap: 9px; cursor: pointer; user-select: none; }
.toggle input { position: absolute; opacity: 0; width: 0; height: 0; }
.toggle .track {
width: 40px; height: 23px; border-radius: 999px; background: #d5d8e2; position: relative;
transition: background .15s; flex-shrink: 0;
}
.toggle .knob {
position: absolute; top: 2.5px; left: 2.5px; width: 18px; height: 18px; border-radius: 50%;
background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.25); transition: transform .15s;
}
.toggle input:checked + .track { background: var(--accent); }
.toggle input:checked + .track .knob { transform: translateX(17px); }
.toggle-lbl { font-size: 13px; font-weight: 600; color: var(--text); }
/* ---------- Event card (dashboard) ---------- */
.event-card {
background: linear-gradient(135deg, rgba(213,0,0,.1), rgba(32,178,170,.08));
border: 1px solid rgba(213,0,0,.25); border-radius: 16px; padding: 20px; margin-bottom: 22px;
}
.event-name { font-size: 22px; font-weight: 900; letter-spacing: -.5px; }
/* ---------- Speaker picker (schedule) ---------- */
.speaker-pick { display: flex; flex-wrap: wrap; gap: 8px; max-height: 220px; overflow-y: auto; padding: 4px; }
.speaker-opt {
display: inline-flex; align-items: center; gap: 7px; padding: 7px 12px; border-radius: 999px;
border: 1px solid var(--line); background: var(--surface-2); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .12s;
}
.speaker-opt input { accent-color: var(--accent); }
.speaker-opt.on { background: var(--accent-soft); border-color: rgba(213,0,0,.4); color: var(--accent); }
/* ---------- AI feedback box (schedule) ---------- */
.ai-box {
background: var(--surface-2); border: 1px solid var(--line); border-left: 3px solid var(--accent-2);
border-radius: 10px; padding: 12px 14px; font-size: 13.5px; line-height: 1.5; color: var(--text);
}
.ai-state { color: var(--accent-2); font-weight: 600; }
/* ---------- Toast ---------- */
.toast-stack { position: fixed; right: 20px; bottom: 20px; z-index: 90; display: flex; flex-direction: column; gap: 10px; }
.toast {
+103 -52
View File
@@ -1,56 +1,75 @@
import { useEffect, useMemo, useState } from 'react';
import { getAllCheckins, getAllConnections, getAllFeedback, getAllProfiles, getAllSessions } from '../lib/api';
import type { Checkin, Connection, Feedback, Profile, Session } from '../lib/types';
import {
getAllCheckins,
getAllConnections,
getAllContacts,
getAllFeedback,
getActiveEvent,
getSessions,
} from '../lib/api';
import type { Checkin, Connection, Contact, Event, Feedback, Session } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
type Tab = 'checkins' | 'connections' | 'feedback';
export function Activity() {
const [profiles, setProfiles] = useState<Profile[] | null>(null);
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [tab, setTab] = useState<Tab>('checkins');
const [contacts, setContacts] = useState<Contact[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [connections, setConnections] = useState<Connection[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [error, setError] = useState<string | null>(null);
const [tab, setTab] = useState<Tab>('checkins');
useEffect(() => {
let cancelled = false;
(async () => {
async function load() {
try {
const [p, s, c, conn, f] = await Promise.all([
getAllProfiles(),
getAllSessions(),
const ev = await getActiveEvent();
setEvent(ev);
const [c, ck, cn, fb] = await Promise.all([
getAllContacts(),
getAllCheckins(),
getAllConnections(),
getAllFeedback(),
]);
if (cancelled) return;
setProfiles(p);
setSessions(s);
setCheckins(c);
setConnections(conn);
setFeedback(f);
} catch (e) {
if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
setContacts(c);
if (ev) {
const ss = await getSessions(ev.id);
setSessions(ss);
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));
}
})();
return () => {
cancelled = true;
};
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
const byId = useMemo(() => new Map((profiles ?? []).map((p) => [p.id, p])), [profiles]);
const sessById = useMemo(() => new Map(sessions.map((s) => [s.id, s])), [sessions]);
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email, c.full_name]));
return (email: string) => m.get(email) ?? email;
}, [contacts]);
const sessionTitle = useMemo(() => {
const m = new Map(sessions.map((s) => [s.id, s.title]));
return (id: string) => m.get(id) ?? id;
}, [sessions]);
if (error) return <Empty icon="⚠️" text={error} />;
if (!profiles)
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
if (!event) {
return (
<div>
<div className="page-head">
@@ -59,20 +78,41 @@ export function Activity() {
<div className="sub">Check-ins, connections, and feedback.</div>
</div>
</div>
<div className="card">
<Empty icon="📊" text="No active event. Set an event active in the Events view first." />
</div>
</div>
);
}
<div className="seg" style={{ maxWidth: 420, marginBottom: 18 }}>
return (
<div>
<div className="page-head">
<div>
<h1>Activity</h1>
<div className="sub">
{event.name} · {checkins.length} check-ins · {connections.length} connections · {feedback.length} feedback.
</div>
</div>
</div>
<div className="seg" style={{ marginBottom: 16 }}>
<button className={tab === 'checkins' ? 'active' : ''} onClick={() => setTab('checkins')}>
Check-ins ({checkins.length})
Check-ins
</button>
<button className={tab === 'connections' ? 'active' : ''} onClick={() => setTab('connections')}>
Connections ({connections.length})
Connections
</button>
<button className={tab === 'feedback' ? 'active' : ''} onClick={() => setTab('feedback')}>
Feedback ({feedback.length})
Feedback
</button>
</div>
{tab === 'checkins' && (
<div className="card">
{checkins.length === 0 ? (
<Empty icon="📍" text="No check-ins yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
@@ -87,20 +127,25 @@ export function Activity() {
{checkins.map((c) => (
<tr key={c.id}>
<td>
<PersonCell p={byId.get(c.profile_id)} />
<PersonCell name={nameOf(c.contact_email)} email={c.contact_email} />
</td>
<td>{sessById.get(c.session_id)?.title ?? '—'}</td>
<td className="muted small">{byId.get(c.staff_id)?.full_name ?? '—'}</td>
<td className="muted small">{fmt(c.created_at)}</td>
<td>{sessionTitle(c.session_id)}</td>
<td className="muted">{nameOf(c.staff_email)}</td>
<td className="muted">{fmt(c.created_at)}</td>
</tr>
))}
</tbody>
</table>
{checkins.length === 0 && <div style={{ padding: 16 }}><Empty icon="✅" text="No check-ins yet" /></div>}
</div>
)}
</div>
)}
{tab === 'connections' && (
<div className="card">
{connections.length === 0 ? (
<Empty icon="🤝" text="No connections yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
@@ -115,31 +160,36 @@ export function Activity() {
{connections.map((c) => (
<tr key={c.id}>
<td>
<PersonCell p={byId.get(c.from_id)} />
<PersonCell name={nameOf(c.from_email)} email={c.from_email} />
</td>
<td>
<PersonCell p={byId.get(c.to_id)} />
<PersonCell name={nameOf(c.to_email)} email={c.to_email} />
</td>
<td>
<span className={`pill ${c.status === 'accepted' ? 'green' : c.status === 'rejected' ? 'violet' : 'amber'}`}>
<span className={`pill ${c.status === 'accepted' ? 'green' : c.status === 'rejected' ? 'red' : 'amber'}`}>
{c.status}
</span>
</td>
<td className="muted small">{fmt(c.resolved_at ?? c.created_at)}</td>
<td className="muted">{fmt(c.created_at)}</td>
</tr>
))}
</tbody>
</table>
{connections.length === 0 && <div style={{ padding: 16 }}><Empty icon="🤝" text="No connections yet" /></div>}
</div>
)}
</div>
)}
{tab === 'feedback' && (
<div className="card">
{feedback.length === 0 ? (
<Empty icon="⭐" text="No feedback yet." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Attendee</th>
<th>From</th>
<th>Session</th>
<th>Rating</th>
<th>Comment</th>
@@ -150,33 +200,34 @@ export function Activity() {
{feedback.map((f) => (
<tr key={f.id}>
<td>
<PersonCell p={byId.get(f.profile_id)} />
<PersonCell name={nameOf(f.contact_email)} email={f.contact_email} />
</td>
<td>{sessById.get(f.session_id)?.title ?? '—'}</td>
<td>{sessionTitle(f.session_id)}</td>
<td>
<span className="pill amber">{'★'.repeat(f.rating)}</span>
</td>
<td className="muted small" style={{ maxWidth: 260 }}>
{f.comment ?? '—'}
</td>
<td className="muted small">{fmt(f.created_at)}</td>
<td className="muted">{f.comment || '—'}</td>
<td className="muted">{fmt(f.created_at)}</td>
</tr>
))}
</tbody>
</table>
{feedback.length === 0 && <div style={{ padding: 16 }}><Empty icon="⭐" text="No feedback yet" /></div>}
</div>
)}
</div>
)}
</div>
);
}
function PersonCell({ p }: { p: Profile | undefined }) {
if (!p) return <span className="muted small">—</span>;
function PersonCell({ name, email }: { name: string; email: string }) {
return (
<div className="cell-person">
<Avatar name={p.full_name} id={p.id} size={32} fs={12} />
<div className="n">{p.full_name}</div>
<div className="row" style={{ gap: 10 }}>
<Avatar name={name} id={email} size={38} fs={13} />
<div>
<div style={{ fontWeight: 600, fontSize: 13 }}>{name}</div>
<div className="muted small">{email}</div>
</div>
</div>
);
}
-332
View File
@@ -1,332 +0,0 @@
import { useEffect, useMemo, useState } from 'react';
import { adjustPoints, getAllProfiles, resetQrToken, updateProfile } from '../lib/api';
import type { Profile, Role } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Avatar, Empty, Modal, QrImage, RoleBadge, Spinner } from '../components/ui';
export function Attendees() {
const { push } = useToast();
const [profiles, setProfiles] = useState<Profile[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
// Modal state
const [editing, setEditing] = useState<Profile | null>(null);
const [qrFor, setQrFor] = useState<Profile | null>(null);
const [newToken, setNewToken] = useState<string | null>(null);
const [pointsFor, setPointsFor] = useState<Profile | null>(null);
const [busy, setBusy] = useState(false);
async function load() {
try {
setProfiles(await getAllProfiles());
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
const filtered = useMemo(() => {
if (!profiles) return [];
const q = query.trim().toLowerCase();
if (!q) return profiles;
return profiles.filter(
(p) =>
p.full_name.toLowerCase().includes(q) ||
(p.company ?? '').toLowerCase().includes(q) ||
p.email.toLowerCase().includes(q) ||
(p.qr_token ?? '').toLowerCase().includes(q),
);
}, [profiles, query]);
async function doResetQr(p: Profile) {
setBusy(true);
try {
const res = await resetQrToken(p.id);
setNewToken(res.qr_token);
setQrFor(p);
// refresh the list so the token column updates
await load();
push('success', `New QR token issued for ${p.full_name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Reset failed');
} finally {
setBusy(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!profiles)
return (
<div className="loading-screen">
<Spinner />
</div>
);
return (
<div>
<div className="page-head">
<div>
<h1>Attendees</h1>
<div className="sub">{profiles.length} people · manage profiles, QR tokens, and points.</div>
</div>
<input
className="input"
style={{ maxWidth: 280 }}
placeholder="Search name, company, email, token…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Name</th>
<th>Role</th>
<th>QR token</th>
<th style={{ textAlign: 'right' }}>Points</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{filtered.map((p) => (
<tr key={p.id}>
<td>
<div className="cell-person">
<Avatar name={p.full_name} id={p.id} size={38} fs={13} />
<div>
<div className="n">{p.full_name}</div>
<div className="e">{p.email}</div>
</div>
</div>
</td>
<td>
<RoleBadge role={p.role} />
</td>
<td>
<span className="mono small">{p.qr_token ?? '—'}</span>
</td>
<td style={{ textAlign: 'right' }}>
<span className="pts">{p.points}</span>
</td>
<td>
<div className="row-actions">
<button className="btn small" onClick={() => setEditing(p)}>
Edit
</button>
<button className="btn small" onClick={() => { setNewToken(null); setQrFor(p); }}>
QR
</button>
<button className="btn small" onClick={() => setPointsFor(p)}>
Points
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{filtered.length === 0 && <div style={{ padding: 16 }}><Empty icon="🔍" text="No matches" /></div>}
</div>
{editing && (
<EditProfileModal
profile={editing}
onClose={() => setEditing(null)}
onSaved={async (msg) => {
setEditing(null);
await load();
push('success', msg);
}}
/>
)}
{qrFor && (
<Modal
open
title={`QR — ${qrFor.full_name}`}
onClose={() => setQrFor(null)}
footer={
<>
<button
className="btn danger"
disabled={busy}
onClick={() => doResetQr(qrFor)}
>
{busy ? 'Resetting…' : 'Reset token'}
</button>
<button className="btn primary" onClick={() => setQrFor(null)}>
Done
</button>
</>
}
>
<div className="qr-wrap">
{newToken ? (
<>
<QrImage value={newToken} size={190} />
<div className="token-big">{newToken}</div>
<p className="muted small">
New token issued. The old token no longer works — the attendee must re-scan.
</p>
</>
) : (
<>
<QrImage value={qrFor.qr_token ?? ''} size={190} />
<div className="token-big">{qrFor.qr_token ?? '—'}</div>
<p className="muted small">Current token. Reset to issue a new one.</p>
</>
)}
</div>
</Modal>
)}
{pointsFor && (
<AdjustPointsModal
profile={pointsFor}
onClose={() => setPointsFor(null)}
onSaved={async (msg) => {
setPointsFor(null);
await load();
push('success', msg);
}}
/>
)}
</div>
);
}
function EditProfileModal({
profile,
onClose,
onSaved,
}: {
profile: Profile;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [name, setName] = useState(profile.full_name);
const [company, setCompany] = useState(profile.company ?? '');
const [role, setRole] = useState<Role>(profile.role);
const [busy, setBusy] = useState(false);
async function save() {
setBusy(true);
try {
await updateProfile(profile.id, {
full_name: name.trim(),
company: company.trim() || null,
role,
});
onSaved(`Updated ${name.trim()}`);
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Update failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Edit — ${profile.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !name.trim()} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="field">
<label>Full name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="field">
<label>Company</label>
<input className="input" value={company} onChange={(e) => setCompany(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Role</label>
<select className="input" value={role} onChange={(e) => setRole(e.target.value as Role)}>
<option value="attendee">attendee</option>
<option value="staff">staff</option>
<option value="admin">admin</option>
</select>
</div>
</Modal>
);
}
function AdjustPointsModal({
profile,
onClose,
onSaved,
}: {
profile: Profile;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [delta, setDelta] = useState('10');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
async function save() {
const d = parseInt(delta, 10);
if (Number.isNaN(d) || d === 0) return;
setBusy(true);
try {
await adjustPoints(profile.id, d, reason.trim() || 'manual adjustment');
onSaved(`${d > 0 ? '+' : ''}${d} points for ${profile.full_name}`);
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Adjustment failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Points — ${profile.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy} onClick={save}>
{busy ? 'Applying…' : 'Apply'}
</button>
</>
}
>
<div className="row" style={{ justifyContent: 'center', gap: 16 }}>
<Avatar name={profile.full_name} id={profile.id} size={52} fs={18} />
<div>
<div style={{ fontWeight: 700 }}>{profile.full_name}</div>
<div className="muted small">
Current: <span className="pts">{profile.points}</span>
</div>
</div>
</div>
<div className="field">
<label>Adjustment (use a negative number to subtract)</label>
<input className="input mono" type="number" value={delta} onChange={(e) => setDelta(e.target.value)} />
</div>
<div className="field">
<label>Reason (optional)</label>
<input className="input" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. prize, correction" />
</div>
</Modal>
);
}
+430
View File
@@ -0,0 +1,430 @@
import { useEffect, useMemo, useState } from 'react';
import { adjustPoints, getAllContacts, resetQrToken, updateContact, upsertContact } from '../lib/api';
import type { Contact } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Avatar, Empty, Modal, QrImage, Spinner, Toggle } from '../components/ui';
export function Contacts() {
const { push } = useToast();
const [contacts, setContacts] = useState<Contact[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [editing, setEditing] = useState<Contact | null>(null);
const [creating, setCreating] = useState(false);
const [qrFor, setQrFor] = useState<Contact | null>(null);
const [newToken, setNewToken] = useState<string | null>(null);
const [pointsFor, setPointsFor] = useState<Contact | null>(null);
const [busy, setBusy] = useState(false);
async function load() {
try {
setContacts(await getAllContacts());
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
const filtered = useMemo(() => {
if (!contacts) return [];
const q = query.trim().toLowerCase();
if (!q) return contacts;
return contacts.filter(
(c) =>
c.full_name.toLowerCase().includes(q) ||
c.email.toLowerCase().includes(q) ||
(c.linkedin_url ?? '').toLowerCase().includes(q) ||
(c.qr_token ?? '').toLowerCase().includes(q),
);
}, [contacts, query]);
async function doResetQr(c: Contact) {
setBusy(true);
try {
const res = await resetQrToken(c.email);
setNewToken(res.qr_token);
setQrFor(c);
await load();
push('success', `New QR token issued for ${c.full_name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Reset failed');
} finally {
setBusy(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!contacts)
return (
<div className="loading-screen">
<Spinner />
</div>
);
return (
<div>
<div className="page-head">
<div>
<h1>Contacts</h1>
<div className="sub">{contacts.length} people · manage contacts, QR tokens, and points.</div>
</div>
<div className="row" style={{ gap: 10 }}>
<input
className="input"
style={{ maxWidth: 260 }}
placeholder="Search name, email, token…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button className="btn primary" onClick={() => setCreating(true)}>
+ New contact
</button>
</div>
</div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Name</th>
<th>LinkedIn</th>
<th>Visibility</th>
<th>Admin</th>
<th>QR token</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{filtered.map((c) => (
<tr key={c.email}>
<td>
<div className="cell-person">
<Avatar name={c.full_name} id={c.email} size={38} fs={13} />
<div>
<div className="n">{c.full_name}</div>
<div className="e">{c.email}</div>
</div>
</div>
</td>
<td>
{c.linkedin_url ? (
<a className="muted small" href={c.linkedin_url} target="_blank" rel="noreferrer">
linkedin
</a>
) : (
<span className="muted small">—</span>
)}
</td>
<td>
<div className="row" style={{ gap: 10 }}>
<span className="muted small" title="Show email">
{c.show_email ? '📧' : '🙈'}
</span>
<span className="muted small" title="Show LinkedIn">
{c.show_linkedin ? '💼' : '🙈'}
</span>
</div>
</td>
<td>
{c.is_admin ? <span className="pill admin">admin</span> : <span className="muted small">—</span>}
</td>
<td>
<span className="mono small">{c.qr_token ?? '—'}</span>
</td>
<td>
<div className="row-actions">
<button className="btn small" onClick={() => setEditing(c)}>
Edit
</button>
<button className="btn small" onClick={() => { setNewToken(null); setQrFor(c); }}>
QR
</button>
<button className="btn small" onClick={() => setPointsFor(c)}>
Points
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{filtered.length === 0 && <div style={{ padding: 16 }}><Empty icon="🔍" text="No matches" /></div>}
</div>
{editing && (
<EditContactModal
contact={editing}
onClose={() => setEditing(null)}
onSaved={async (msg) => {
setEditing(null);
await load();
push('success', msg);
}}
/>
)}
{creating && (
<CreateContactModal
onClose={() => setCreating(false)}
onSaved={async (msg) => {
setCreating(false);
await load();
push('success', msg);
}}
/>
)}
{qrFor && (
<Modal
open
title={`QR — ${qrFor.full_name}`}
onClose={() => setQrFor(null)}
footer={
<>
<button className="btn danger" disabled={busy} onClick={() => doResetQr(qrFor)}>
{busy ? 'Resetting…' : 'Reset token'}
</button>
<button className="btn primary" onClick={() => setQrFor(null)}>
Done
</button>
</>
}
>
<div className="qr-wrap">
{newToken ? (
<>
<QrImage value={newToken} size={190} />
<div className="token-big">{newToken}</div>
<p className="muted small">
New token issued. The old token no longer works — the person must re-scan.
</p>
</>
) : (
<>
<QrImage value={qrFor.qr_token ?? ''} size={190} />
<div className="token-big">{qrFor.qr_token ?? '—'}</div>
<p className="muted small">Current token. Reset to issue a new one.</p>
</>
)}
</div>
</Modal>
)}
{pointsFor && (
<AdjustPointsModal
contact={pointsFor}
onClose={() => setPointsFor(null)}
onSaved={async (msg) => {
setPointsFor(null);
push('success', msg);
}}
/>
)}
</div>
);
}
function EditContactModal({
contact,
onClose,
onSaved,
}: {
contact: Contact;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [name, setName] = useState(contact.full_name);
const [linkedin, setLinkedin] = useState(contact.linkedin_url ?? '');
const [showEmail, setShowEmail] = useState(contact.show_email);
const [showLinkedin, setShowLinkedin] = useState(contact.show_linkedin);
const [isAdmin, setIsAdmin] = useState(contact.is_admin);
const [busy, setBusy] = useState(false);
async function save() {
setBusy(true);
try {
await updateContact(contact.email, {
full_name: name.trim(),
linkedin_url: linkedin.trim() || null,
show_email: showEmail,
show_linkedin: showLinkedin,
is_admin: isAdmin,
});
onSaved(`Updated ${name.trim()}`);
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Update failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Edit — ${contact.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !name.trim()} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="field">
<label>Full name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="field">
<label>Email</label>
<input className="input" value={contact.email} disabled />
</div>
<div className="field">
<label>LinkedIn URL</label>
<input className="input" value={linkedin} onChange={(e) => setLinkedin(e.target.value)} placeholder="—" />
</div>
<div className="row" style={{ gap: 20, flexWrap: 'wrap' }}>
<Toggle checked={showEmail} onChange={setShowEmail} label="Show email" />
<Toggle checked={showLinkedin} onChange={setShowLinkedin} label="Show LinkedIn" />
<Toggle checked={isAdmin} onChange={setIsAdmin} label="Admin / staff" />
</div>
</Modal>
);
}
function CreateContactModal({
onClose,
onSaved,
}: {
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [linkedin, setLinkedin] = useState('');
const [isAdmin, setIsAdmin] = useState(false);
const [busy, setBusy] = useState(false);
async function save() {
if (!email.trim() || !name.trim()) return;
setBusy(true);
try {
await upsertContact({
email: email.trim(),
full_name: name.trim(),
linkedin_url: linkedin.trim() || null,
is_admin: isAdmin,
});
onSaved(`Created ${name.trim()}`);
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Create failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title="New contact"
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !email.trim() || !name.trim()} onClick={save}>
{busy ? 'Creating…' : 'Create'}
</button>
</>
}
>
<div className="field">
<label>Full name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Ana Silva" />
</div>
<div className="field">
<label>Email</label>
<input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" />
</div>
<div className="field">
<label>LinkedIn URL</label>
<input className="input" value={linkedin} onChange={(e) => setLinkedin(e.target.value)} placeholder="—" />
</div>
<div className="row">
<Toggle checked={isAdmin} onChange={setIsAdmin} label="Admin / staff" />
</div>
<p className="muted small">A QR token is generated automatically and becomes the login password.</p>
</Modal>
);
}
function AdjustPointsModal({
contact,
onClose,
onSaved,
}: {
contact: Contact;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [delta, setDelta] = useState('10');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
async function save() {
const d = parseInt(delta, 10);
if (Number.isNaN(d) || d === 0) return;
setBusy(true);
try {
await adjustPoints(contact.email, d, reason.trim() || 'manual adjustment');
onSaved(`${d > 0 ? '+' : ''}${d} points for ${contact.full_name}`);
onClose();
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Adjustment failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Points — ${contact.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy} onClick={save}>
{busy ? 'Applying…' : 'Apply'}
</button>
</>
}
>
<div className="row" style={{ justifyContent: 'center', gap: 16 }}>
<Avatar name={contact.full_name} id={contact.email} size={52} fs={18} />
<div>
<div style={{ fontWeight: 700 }}>{contact.full_name}</div>
<div className="muted small">{contact.email}</div>
</div>
</div>
<div className="field">
<label>Adjustment for the active event (use a negative number to subtract)</label>
<input className="input mono" type="number" value={delta} onChange={(e) => setDelta(e.target.value)} />
</div>
<div className="field">
<label>Reason (optional)</label>
<input className="input" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. prize, correction" />
</div>
</Modal>
);
}
+95 -50
View File
@@ -1,23 +1,23 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import {
getAllCheckins,
getAllConnections,
getAllContacts,
getAllFeedback,
getAllProfiles,
getAllSessions,
getActiveEvent,
getLeaderboard,
} from '../lib/api';
import type { Checkin, Connection, Feedback, LeaderboardRow, Profile, Session } from '../lib/types';
import type { Checkin, Connection, Contact, Event, Feedback, LeaderboardRow } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
type View = 'dashboard' | 'attendees' | 'schedule' | 'activity';
import type { View } from '../App';
export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
const [profiles, setProfiles] = useState<Profile[] | null>(null);
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [contacts, setContacts] = useState<Contact[]>([]);
const [checkins, setCheckins] = useState<Checkin[]>([]);
const [connections, setConnections] = useState<Connection[]>([]);
const [feedback, setFeedback] = useState<Feedback[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [lb, setLb] = useState<LeaderboardRow[]>([]);
const [error, setError] = useState<string | null>(null);
@@ -25,21 +25,27 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
let cancelled = false;
(async () => {
try {
const [p, c, conn, f, s, l] = await Promise.all([
getAllProfiles(),
const ev = await getActiveEvent();
if (cancelled) return;
setEvent(ev);
if (!ev) {
setLoaded(true);
return;
}
const [c, ck, conn, f, l] = await Promise.all([
getAllContacts(),
getAllCheckins(),
getAllConnections(),
getAllFeedback(),
getAllSessions(),
getLeaderboard(),
]);
if (cancelled) return;
setProfiles(p);
setCheckins(c);
setConnections(conn);
setFeedback(f);
setSessions(s);
setLb(l);
setContacts(c);
setCheckins(ck.filter((x) => x.event_id === ev.id));
setConnections(conn.filter((x) => x.event_id === ev.id));
setFeedback(f.filter((x) => x.event_id === ev.id));
setLb(l.filter((x) => x.event_id === ev.id));
setLoaded(true);
} catch (e) {
if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
}
@@ -49,21 +55,20 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
};
}, []);
const nameOf = useMemo(() => {
const m = new Map(contacts.map((c) => [c.email, c.full_name]));
return (email: string) => m.get(email) ?? email;
}, [contacts]);
if (error) return <Empty icon="⚠️" text={error} />;
if (!profiles)
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
const attendees = profiles.filter((p) => p.role === 'attendee');
const accepted = connections.filter((c) => c.status === 'accepted').length;
const avgRating = feedback.length
? (feedback.reduce((s, f) => s + f.rating, 0) / feedback.length).toFixed(1)
: '—';
const top = lb.slice(0, 5);
if (!event) {
return (
<div>
<div className="page-head">
@@ -72,32 +77,68 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
<div className="sub">Live overview of the event.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No active event. Create one and set it active in the Events view." />
<div style={{ textAlign: 'center', marginTop: 12 }}>
<button className="btn primary" onClick={() => onNavigate('events')}>
Go to Events →
</button>
</div>
</div>
</div>
);
}
const top = lb.slice(0, 5);
return (
<div>
<div className="page-head">
<div>
<h1>Dashboard</h1>
<div className="sub">Live overview of the active event.</div>
</div>
</div>
<div className="card event-card">
<div className="row between" style={{ flexWrap: 'wrap', gap: 12 }}>
<div>
<div className="event-name">{event.name}</div>
<div className="muted small">
{fmtDate(event.start_date)}
{event.end_date !== event.start_date ? ` – ${fmtDate(event.end_date)}` : ''}
{event.location ? ` · ${event.location}` : ''}
</div>
</div>
<span className="pill green">● Active</span>
</div>
</div>
<div className="stat-grid">
<div className="stat">
<span className="ico">👥</span>
<span className="val">{attendees.length}</span>
<span className="lbl">Attendees</span>
<span className="ico">🎟️</span>
<span className="val">{event.num_registrations}</span>
<span className="lbl">Registrations</span>
</div>
<div className="stat">
<span className="ico">✅</span>
<span className="val">{checkins.length}</span>
<span className="lbl">Check-ins</span>
<span className="val">{event.num_checked_in_registrations}</span>
<span className="lbl">Checked in</span>
</div>
<div className="stat">
<span className="ico">🤝</span>
<span className="val">{accepted}</span>
<span className="lbl">Connections accepted</span>
<span className="ico">🗓️</span>
<span className="val">{event.num_sessions}</span>
<span className="lbl">Sessions</span>
</div>
<div className="stat">
<span className="ico">⭐</span>
<span className="val">{avgRating}</span>
<span className="lbl">Avg. session rating</span>
<span className="ico">🎤</span>
<span className="val">{event.num_speakers}</span>
<span className="lbl">Speakers</span>
</div>
<div className="stat accent">
<span className="ico">🏆</span>
<span className="val">{sessions.length}</span>
<span className="lbl">Sessions scheduled</span>
<span className="ico">⭐</span>
<span className="val">{event.avg_feedback != null ? event.avg_feedback.toFixed(1) : '—'}</span>
<span className="lbl">Avg. feedback</span>
</div>
</div>
@@ -105,7 +146,7 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
<div className="card">
<div className="row between" style={{ marginBottom: 14 }}>
<h2 className="h2">🏆 Top points</h2>
<button className="btn small ghost" onClick={() => onNavigate('attendees')}>
<button className="btn small ghost" onClick={() => onNavigate('registrations')}>
View all →
</button>
</div>
@@ -114,12 +155,12 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{top.map((r, i) => (
<div key={r.profile_id} className="row" style={{ gap: 12 }}>
<div key={r.contact_email} className="row" style={{ gap: 12 }}>
<span style={{ width: 22, fontWeight: 900, color: 'var(--muted)' }}>{i + 1}</span>
<Avatar name={r.full_name} id={r.profile_id} size={36} fs={13} />
<Avatar name={r.full_name} id={r.contact_email} size={36} fs={13} />
<div className="grow">
<div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name}</div>
{r.company && <div className="muted small">{r.company}</div>}
<div className="muted small">{r.contact_email}</div>
</div>
<span className="pts">{r.points}</span>
</div>
@@ -135,7 +176,7 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
View all →
</button>
</div>
<ActivityFeed checkins={checkins} connections={connections} feedback={feedback} profiles={profiles} limit={6} />
<ActivityFeed checkins={checkins} connections={connections} feedback={feedback} nameOf={nameOf} limit={6} />
</div>
</div>
</div>
@@ -146,34 +187,34 @@ function ActivityFeed({
checkins,
connections,
feedback,
profiles,
nameOf,
limit,
}: {
checkins: Checkin[];
connections: Connection[];
feedback: Feedback[];
profiles: Profile[];
nameOf: (email: string) => string;
limit: number;
}) {
const byId = new Map(profiles.map((p) => [p.id, p]));
type Item = { at: string; icon: string; text: string };
const name = (email: string) => nameOf(email);
const items: Item[] = [
...checkins.map((c) => ({
at: c.created_at,
icon: '✅',
text: `${byId.get(c.profile_id)?.full_name ?? 'Someone'} checked in`,
text: `${name(c.contact_email)} checked in`,
})),
...connections
.filter((c) => c.status === 'accepted')
.map((c) => ({
at: c.resolved_at ?? c.created_at,
icon: '🤝',
text: `${byId.get(c.from_id)?.full_name ?? 'Someone'} connected with ${byId.get(c.to_id)?.full_name ?? 'someone'}`,
text: `${name(c.from_email)} connected with ${name(c.to_email)}`,
})),
...feedback.map((f) => ({
at: f.created_at,
icon: '⭐',
text: `${byId.get(f.profile_id)?.full_name ?? 'Someone'} rated a session ${f.rating}★`,
text: `${name(f.contact_email)} rated a session ${f.rating}★`,
})),
]
.sort((a, b) => (a.at < b.at ? 1 : -1))
@@ -194,3 +235,7 @@ function ActivityFeed({
</div>
);
}
function fmtDate(d: string): string {
return new Date(d + 'T00:00:00').toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
}
+205
View File
@@ -0,0 +1,205 @@
import { useEffect, useState } from 'react';
import { activateEvent, getAllEvents, upsertEvent } from '../lib/api';
import type { Event } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner } from '../components/ui';
export function Events() {
const { push } = useToast();
const [events, setEvents] = useState<Event[]>([]);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [modal, setModal] = useState<{ event: Event | null } | null>(null);
const [busy, setBusy] = useState(false);
async function load() {
try {
setEvents(await getAllEvents());
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
async function doActivate(ev: Event) {
if (!confirm(`Set "${ev.name}" as the active event? All other events will be deactivated.`)) return;
setBusy(true);
try {
await activateEvent(ev.id);
await load();
push('success', `${ev.name} is now active`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Failed to activate');
} finally {
setBusy(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
return (
<div>
<div className="page-head">
<div>
<h1>Events</h1>
<div className="sub">
{events.length} event{events.length === 1 ? '' : 's'} · only one can be active at a time.
</div>
</div>
<button className="btn primary" onClick={() => setModal({ event: null })}>
+ New event
</button>
</div>
<div className="card">
{events.length === 0 ? (
<Empty icon="📅" text="No events yet. Create one to get started." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Event</th>
<th>Dates</th>
<th>Location</th>
<th>Stats</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{events.map((ev) => (
<tr key={ev.id}>
<td>
<div style={{ fontWeight: 700 }}>{ev.name}</div>
{ev.is_active && <span className="pill green">active</span>}
</td>
<td className="muted">
{fmtDate(ev.start_date)} – {fmtDate(ev.end_date)}
</td>
<td className="muted">{ev.location || '—'}</td>
<td className="muted small">
{ev.num_registrations} reg · {ev.num_sessions} sessions · {ev.num_speakers} speakers
{ev.avg_feedback != null && ` · ⭐ ${ev.avg_feedback.toFixed(1)}`}
</td>
<td>
{ev.is_active ? (
<span className="pill green">Active</span>
) : (
<button className="btn small" disabled={busy} onClick={() => doActivate(ev)}>
Set active
</button>
)}
</td>
<td>
<button className="btn small" onClick={() => setModal({ event: ev })}>
Edit
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{modal && (
<EventModal
event={modal.event}
onClose={() => setModal(null)}
onSaved={async (msg) => {
setModal(null);
await load();
push('success', msg);
}}
/>
)}
</div>
);
}
function EventModal({
event,
onClose,
onSaved,
}: {
event: Event | null;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [name, setName] = useState(event?.name ?? '');
const [startDate, setStartDate] = useState(event ? event.start_date.slice(0, 10) : '');
const [endDate, setEndDate] = useState(event ? event.end_date.slice(0, 10) : '');
const [location, setLocation] = useState(event?.location ?? '');
const [busy, setBusy] = useState(false);
async function save() {
if (!name.trim() || !startDate || !endDate) return;
setBusy(true);
try {
await upsertEvent(event?.id ?? null, {
name: name.trim(),
start_date: startDate,
end_date: endDate,
location: location.trim() || null,
});
onSaved(event ? 'Event updated' : 'Event created');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Save failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={event ? 'Edit event' : 'New event'}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !name.trim() || !startDate || !endDate} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="field">
<label>Name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. APPE 2027" />
</div>
<div className="grid-2">
<div className="field">
<label>Start date</label>
<input className="input" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
</div>
<div className="field">
<label>End date</label>
<input className="input" type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
</div>
</div>
<div className="field">
<label>Location</label>
<input className="input" value={location} onChange={(e) => setLocation(e.target.value)} placeholder="—" />
</div>
</Modal>
);
}
function fmtDate(d: string): string {
return new Date(d + 'T00:00:00').toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' });
}
+279
View File
@@ -0,0 +1,279 @@
import { useEffect, useMemo, useState } from 'react';
import {
createRegistration,
getAllContacts,
getActiveEvent,
getRegistrations,
setCheckedIn,
setRegistrationType,
} from '../lib/api';
import type { Contact, Event, Registration, RegistrationType } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Avatar, Empty, Modal, Spinner, Toggle, TypeBadge } from '../components/ui';
const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor'];
export function Registrations() {
const { push } = useToast();
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [contacts, setContacts] = useState<Contact[]>([]);
const [registrations, setRegistrations] = useState<Registration[]>([]);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [adding, setAdding] = useState(false);
const [busy, setBusy] = useState(false);
async function load() {
try {
const ev = await getActiveEvent();
setEvent(ev);
if (ev) {
const [c, r] = await Promise.all([getAllContacts(), getRegistrations(ev.id)]);
setContacts(c);
setRegistrations(r);
}
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
const byEmail = useMemo(() => new Map(contacts.map((c) => [c.email, c])), [contacts]);
const filtered = useMemo(() => {
if (!registrations) return [];
const q = query.trim().toLowerCase();
if (!q) return registrations;
return registrations.filter((r) => {
const c = byEmail.get(r.contact_email);
return (
(c?.full_name ?? '').toLowerCase().includes(q) ||
r.contact_email.toLowerCase().includes(q) ||
r.type.toLowerCase().includes(q)
);
});
}, [registrations, query, byEmail]);
async function changeType(r: Registration, type: RegistrationType) {
setBusy(true);
try {
await setRegistrationType(r.contact_email, type);
await load();
push('success', `${byEmail.get(r.contact_email)?.full_name ?? r.contact_email} → ${type}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Update failed');
} finally {
setBusy(false);
}
}
async function toggleCheckedIn(r: Registration, v: boolean) {
setBusy(true);
try {
await setCheckedIn(r.id, v);
await load();
} catch (e) {
push('error', e instanceof Error ? e.message : 'Update failed');
} finally {
setBusy(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
if (!event) {
return (
<div>
<div className="page-head">
<div>
<h1>Registrations</h1>
<div className="sub">Ticket types and check-ins for the active event.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No active event. Set an event active in the Events view first." />
</div>
</div>
);
}
return (
<div>
<div className="page-head">
<div>
<h1>Registrations</h1>
<div className="sub">
{event.name} · {registrations.length} registrations · {registrations.filter((r) => r.checked_in).length} checked in.
</div>
</div>
<div className="row" style={{ gap: 10 }}>
<input
className="input"
style={{ maxWidth: 240 }}
placeholder="Search name, email, type…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button className="btn primary" onClick={() => setAdding(true)}>
+ Register
</button>
</div>
</div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Contact</th>
<th>Type</th>
<th>Checked in</th>
<th style={{ textAlign: 'right' }}>Points</th>
</tr>
</thead>
<tbody>
{filtered.map((r) => {
const c = byEmail.get(r.contact_email);
return (
<tr key={r.id}>
<td>
<div className="cell-person">
<Avatar name={c?.full_name ?? r.contact_email} id={r.contact_email} size={38} fs={13} />
<div>
<div className="n">{c?.full_name ?? r.contact_email}</div>
<div className="e">{r.contact_email}</div>
</div>
</div>
</td>
<td>
<div className="row" style={{ gap: 8 }}>
<TypeBadge type={r.type} />
<select
className="input"
style={{ width: 130, padding: '6px 10px', fontSize: 12.5 }}
value={r.type}
disabled={busy}
onChange={(e) => changeType(r, e.target.value as RegistrationType)}
>
{TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
</div>
</td>
<td>
<Toggle checked={r.checked_in} onChange={(v) => toggleCheckedIn(r, v)} />
</td>
<td style={{ textAlign: 'right' }}>
<span className="pts">{r.points}</span>
</td>
</tr>
);
})}
</tbody>
</table>
{filtered.length === 0 && <div style={{ padding: 16 }}><Empty icon="🎟️" text="No registrations yet" /></div>}
</div>
{adding && (
<AddRegistrationModal
contacts={contacts}
existing={new Set(registrations.map((r) => r.contact_email))}
onClose={() => setAdding(false)}
onSaved={async (msg) => {
setAdding(false);
await load();
push('success', msg);
}}
/>
)}
</div>
);
}
function AddRegistrationModal({
contacts,
existing,
onClose,
onSaved,
}: {
contacts: Contact[];
existing: Set<string>;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const available = contacts.filter((c) => !existing.has(c.email));
const [email, setEmail] = useState(available[0]?.email ?? '');
const [type, setType] = useState<RegistrationType>('attendee');
const [busy, setBusy] = useState(false);
async function save() {
if (!email) return;
setBusy(true);
try {
await createRegistration(email, type);
onSaved(`Registered ${email} as ${type}`);
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Registration failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title="Register contact"
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !email} onClick={save}>
{busy ? 'Registering…' : 'Register'}
</button>
</>
}
>
<div className="field">
<label>Contact</label>
<select className="input" value={email} onChange={(e) => setEmail(e.target.value)}>
{available.length === 0 && <option value="">All contacts already registered</option>}
{available.map((c) => (
<option key={c.email} value={c.email}>
{c.full_name} — {c.email}
</option>
))}
</select>
</div>
<div className="field">
<label>Type</label>
<select className="input" value={type} onChange={(e) => setType(e.target.value as RegistrationType)}>
{TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
</div>
{type === 'sponsor' && (
<p className="muted small">
A sponsor registration requires a sponsor lookup — add the sponsor in the Sponsors view first.
</p>
)}
</Modal>
);
}
+206 -20
View File
@@ -1,14 +1,31 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { supabase } from '../lib/supabase';
import { getAllSessions, getAllSlots } from '../lib/api';
import type { Session, Slot } from '../lib/types';
import {
evaluateSessionFeedback,
getAllContacts,
getAllSessionSpeakers,
getActiveEvent,
getSessions,
getSlots,
removeSessionMaterial,
sessionMaterialUrl,
setSessionSpeakers,
uploadSessionMaterial,
} from '../lib/api';
import type { Contact, Event, Session, SessionSpeaker, Slot, SlotType } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner } from '../components/ui';
import { Empty, Modal, Spinner, TypeBadge } from '../components/ui';
const SLOT_TYPES: SlotType[] = ['session', 'lunch_break', 'coffee_break', 'keynote', 'close_up'];
export function Schedule() {
const { push } = useToast();
const [slots, setSlots] = useState<Slot[] | null>(null);
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [slots, setSlots] = useState<Slot[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [speakers, setSpeakers] = useState<SessionSpeaker[]>([]);
const [contacts, setContacts] = useState<Contact[]>([]);
const [error, setError] = useState<string | null>(null);
const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null);
@@ -17,9 +34,22 @@ export function Schedule() {
async function load() {
try {
const [s, ss] = await Promise.all([getAllSlots(), getAllSessions()]);
const ev = await getActiveEvent();
setEvent(ev);
if (ev) {
const [s, ss, sp, c] = await Promise.all([
getSlots(ev.id),
getSessions(ev.id),
getAllSessionSpeakers(),
getAllContacts(),
]);
setSlots(s);
setSessions(ss);
const ids = new Set(ss.map((x) => x.id));
setSpeakers(sp.filter((x) => ids.has(x.session_id)));
setContacts(c);
}
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
@@ -29,6 +59,18 @@ export function Schedule() {
load();
}, []);
const speakersFor = useMemo(() => {
const m = new Map<string, string[]>();
for (const sp of speakers) {
const arr = m.get(sp.session_id) ?? [];
arr.push(sp.contact_email);
m.set(sp.session_id, arr);
}
return m;
}, [speakers]);
const nameOf = (email: string) => contacts.find((c) => c.email === email)?.full_name ?? email;
async function deleteSlot(slot: Slot) {
if (!confirm(`Delete "${slot.name}" and all its sessions?`)) return;
setBusy(true);
@@ -59,20 +101,51 @@ export function Schedule() {
}
}
async function doEvaluate(sess: Session) {
setBusy(true);
try {
await evaluateSessionFeedback(sess.id);
await load();
push('success', `AI feedback evaluated for ${sess.title}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Evaluation failed');
} finally {
setBusy(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!slots)
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
if (!event) {
return (
<div>
<div className="page-head">
<div>
<h1>Schedule</h1>
<div className="sub">{slots.length} slots · {sessions.length} sessions.</div>
<div className="sub">Slots, sessions, speakers, and materials.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No active event. Set an event active in the Events view first." />
</div>
</div>
);
}
return (
<div>
<div className="page-head">
<div>
<h1>Schedule</h1>
<div className="sub">
{event.name} · {slots.length} slots · {sessions.length} sessions.
</div>
</div>
<button className="btn primary" onClick={() => setSlotModal({ slot: null })}>
+ New slot
@@ -86,6 +159,7 @@ export function Schedule() {
<div key={slot.id} className="card">
<div className="row between" style={{ marginBottom: 12 }}>
<div className="row" style={{ gap: 12 }}>
<TypeBadge type={slot.type} />
<div>
<div style={{ fontWeight: 800, fontSize: 16 }}>{slot.name}</div>
<div className="muted small">
@@ -112,15 +186,29 @@ export function Schedule() {
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{slotSessions.map((s) => (
{slotSessions.map((s) => {
const spk = (speakersFor.get(s.id) ?? []).map(nameOf).join(', ');
return (
<div key={s.id} className="row between" style={{ padding: '10px 12px', background: 'var(--surface-2)', borderRadius: 12 }}>
<div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 700, fontSize: 14 }}>{s.title}</div>
<div className="muted small">
{[s.room, s.speakers, s.capacity ? `cap ${s.capacity}` : null].filter(Boolean).join(' · ') || '—'}
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null].filter(Boolean).join(' · ')}
</div>
<div className="muted small" style={{ marginTop: 4 }}>
{s.average_feedback != null && <span>⭐ {s.average_feedback.toFixed(1)}</span>}
{s.material_path && <span> · 📎 material</span>}
{s.ai_generated_feedback && (
<span className="ai-state"> · 🤖 {s.ai_generated_feedback}</span>
)}
</div>
</div>
<div className="row-actions">
{s.ai_generated_feedback === 'Pending AI Evaluation' && (
<button className="btn small" disabled={busy} onClick={() => doEvaluate(s)}>
Evaluate
</button>
)}
<button className="btn small" onClick={() => setSessModal({ session: s, slotId: slot.id })}>
Edit
</button>
@@ -129,7 +217,8 @@ export function Schedule() {
</button>
</div>
</div>
))}
);
})}
</div>
)}
</div>
@@ -140,6 +229,7 @@ export function Schedule() {
{slotModal && (
<SlotModal
slot={slotModal.slot}
eventId={event.id}
onClose={() => setSlotModal(null)}
onSaved={async (msg) => {
setSlotModal(null);
@@ -152,6 +242,9 @@ export function Schedule() {
<SessionModal
session={sessModal.session}
slotId={sessModal.slotId}
eventId={event.id}
contacts={contacts}
currentSpeakers={speakersFor.get(sessModal.session?.id ?? '') ?? []}
onClose={() => setSessModal(null)}
onSaved={async (msg) => {
setSessModal(null);
@@ -166,14 +259,17 @@ export function Schedule() {
function SlotModal({
slot,
eventId,
onClose,
onSaved,
}: {
slot: Slot | null;
eventId: string;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [name, setName] = useState(slot?.name ?? '');
const [type, setType] = useState<SlotType>(slot?.type ?? 'session');
const [date, setDate] = useState(slot ? slot.slot_date.slice(0, 10) : '');
const [start, setStart] = useState(slot ? slot.start_time.slice(0, 5) : '09:00');
const [end, setEnd] = useState(slot ? slot.end_time.slice(0, 5) : '10:00');
@@ -183,7 +279,7 @@ function SlotModal({
if (!name.trim() || !date) return;
setBusy(true);
try {
const payload = { name: name.trim(), slot_date: date, start_time: start, end_time: end };
const payload = { name: name.trim(), type, slot_date: date, start_time: start, end_time: end, event_id: eventId };
if (slot) {
const { error: err } = await supabase.from('slots').update(payload).eq('id', slot.id);
if (err) throw err;
@@ -219,6 +315,16 @@ function SlotModal({
<label>Name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Morning keynote" />
</div>
<div className="field">
<label>Type</label>
<select className="input" value={type} onChange={(e) => setType(e.target.value as SlotType)}>
{SLOT_TYPES.map((t) => (
<option key={t} value={t}>
{t.replace('_', ' ')}
</option>
))}
</select>
</div>
<div className="field">
<label>Date</label>
<input className="input" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
@@ -240,19 +346,26 @@ function SlotModal({
function SessionModal({
session,
slotId,
eventId,
contacts,
currentSpeakers,
onClose,
onSaved,
}: {
session: Session | null;
slotId: number;
eventId: string;
contacts: Contact[];
currentSpeakers: string[];
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [title, setTitle] = useState(session?.title ?? '');
const [room, setRoom] = useState(session?.room ?? '');
const [speakers, setSpeakers] = useState(session?.speakers ?? '');
const [capacity, setCapacity] = useState(session?.capacity?.toString() ?? '');
const [description, setDescription] = useState(session?.description ?? '');
const [speakerEmails, setSpeakerEmails] = useState<string[]>(currentSpeakers);
const [material, setMaterial] = useState<File | null>(null);
const [busy, setBusy] = useState(false);
async function save() {
@@ -262,17 +375,27 @@ function SessionModal({
const payload = {
title: title.trim(),
room: room.trim() || null,
speakers: speakers.trim() || null,
capacity: capacity ? parseInt(capacity, 10) : null,
description: description.trim() || null,
slot_id: slotId,
event_id: eventId,
};
let sessionId = session?.id;
if (session) {
const { error: err } = await supabase.from('sessions').update(payload).eq('id', session.id);
if (err) throw err;
} else {
const { error: err } = await supabase.from('sessions').insert(payload);
const { data: ins, error: err } = await supabase.from('sessions').insert(payload).select().single();
if (err) throw err;
sessionId = (ins as Session).id;
}
// Speakers (a session must keep >= 1 speaker).
if (sessionId && speakerEmails.length > 0) {
await setSessionSpeakers(sessionId, speakerEmails);
}
// Material upload (if a new file was chosen).
if (sessionId && material) {
await uploadSessionMaterial(sessionId, material);
}
onSaved(session ? 'Session updated' : 'Session created');
} catch (e) {
@@ -282,6 +405,12 @@ function SessionModal({
}
}
function toggleSpeaker(email: string) {
setSpeakerEmails((prev) =>
prev.includes(email) ? prev.filter((x) => x !== email) : [...prev, email],
);
}
return (
<Modal
open
@@ -292,7 +421,7 @@ function SessionModal({
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !title.trim()} onClick={save}>
<button className="btn primary" disabled={busy || !title.trim() || speakerEmails.length === 0} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
@@ -312,14 +441,71 @@ function SessionModal({
<input className="input" type="number" value={capacity} onChange={(e) => setCapacity(e.target.value)} placeholder="—" />
</div>
</div>
<div className="field">
<label>Speakers</label>
<input className="input" value={speakers} onChange={(e) => setSpeakers(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Description</label>
<textarea className="input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Speakers ({speakerEmails.length})</label>
<div className="speaker-pick">
{contacts.map((c) => (
<label key={c.email} className={`speaker-opt ${speakerEmails.includes(c.email) ? 'on' : ''}`}>
<input
type="checkbox"
checked={speakerEmails.includes(c.email)}
onChange={() => toggleSpeaker(c.email)}
/>
{c.full_name}
</label>
))}
</div>
{speakerEmails.length === 0 && (
<span className="muted small">A session needs at least one speaker.</span>
)}
</div>
{session && (
<div className="field">
<label>Material</label>
{session.material_path ? (
<div className="row" style={{ gap: 10 }}>
<a className="btn small" href={sessionMaterialUrl(session.material_path)} target="_blank" rel="noreferrer">
📎 View current
</a>
<button
className="btn small danger"
disabled={busy}
onClick={async () => {
try {
await removeSessionMaterial(session.id);
onSaved('Material removed');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Remove failed');
}
}}
>
Remove
</button>
</div>
) : (
<span className="muted small">No material uploaded yet.</span>
)}
<input
className="input"
type="file"
onChange={(e) => setMaterial(e.target.files?.[0] ?? null)}
/>
{material && <span className="muted small">Will upload: {material.name}</span>}
</div>
)}
{session && session.ai_generated_feedback && (
<div className="field">
<label>AI feedback</label>
<div className="ai-box">{session.ai_generated_feedback}</div>
</div>
)}
</Modal>
);
}
+277
View File
@@ -0,0 +1,277 @@
import { useEffect, useState } from 'react';
import { deleteSponsor, getAllContacts, getActiveEvent, getSponsors, upsertSponsor } from '../lib/api';
import type { Contact, Event, Sponsor, SponsorType } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner, Toggle, TypeBadge } from '../components/ui';
const SPONSOR_TYPES: SponsorType[] = [
'headline',
'platinum',
'gold',
'silver',
'community',
'swag',
'catering',
'diversity',
];
export function Sponsors() {
const { push } = useToast();
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [contacts, setContacts] = useState<Contact[]>([]);
const [sponsors, setSponsors] = useState<Sponsor[]>([]);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<Sponsor | null>(null);
const [creating, setCreating] = useState(false);
const [busy, setBusy] = useState(false);
async function load() {
try {
const ev = await getActiveEvent();
setEvent(ev);
if (ev) {
const [c, s] = await Promise.all([getAllContacts(), getSponsors(ev.id)]);
setContacts(c);
setSponsors(s);
}
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
async function doDelete(s: Sponsor) {
if (!confirm(`Delete sponsor "${s.name}"?`)) return;
setBusy(true);
try {
await deleteSponsor(s.id);
await load();
push('success', `Deleted ${s.name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setBusy(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
if (!event) {
return (
<div>
<div className="page-head">
<div>
<h1>Sponsors</h1>
<div className="sub">Sponsors for the active event.</div>
</div>
</div>
<div className="card">
<Empty icon="📅" text="No active event. Set an event active in the Events view first." />
</div>
</div>
);
}
const paid = sponsors.filter((s) => s.paid).length;
return (
<div>
<div className="page-head">
<div>
<h1>Sponsors</h1>
<div className="sub">
{event.name} · {sponsors.length} sponsors · {paid} paid. Unpaid sponsors are hidden from attendees.
</div>
</div>
<button className="btn primary" onClick={() => setCreating(true)}>
+ New sponsor
</button>
</div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Contact</th>
<th>Paid</th>
<th style={{ textAlign: 'right' }}>Amount</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{sponsors.map((s) => (
<tr key={s.id}>
<td>
<div className="n">{s.name}</div>
{s.email && <div className="e">{s.email}</div>}
</td>
<td>
<TypeBadge type={s.type} />
</td>
<td className="muted small">{s.contact_email ?? '—'}</td>
<td>
<span className={`pill ${s.paid ? 'green' : 'amber'}`}>{s.paid ? 'paid' : 'unpaid'}</span>
</td>
<td style={{ textAlign: 'right' }} className="mono small">
{s.amount_eur != null ? `€${s.amount_eur.toLocaleString()}` : '—'}
</td>
<td>
<div className="row-actions">
<button className="btn small" onClick={() => setEditing(s)}>
Edit
</button>
<button className="btn small danger" disabled={busy} onClick={() => doDelete(s)}>
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{sponsors.length === 0 && <div style={{ padding: 16 }}><Empty icon="🤝" text="No sponsors yet" /></div>}
</div>
{(editing || creating) && (
<SponsorModal
sponsor={editing}
eventId={event.id}
contacts={contacts}
onClose={() => {
setEditing(null);
setCreating(false);
}}
onSaved={async (msg) => {
setEditing(null);
setCreating(false);
await load();
push('success', msg);
}}
/>
)}
</div>
);
}
function SponsorModal({
sponsor,
eventId,
contacts,
onClose,
onSaved,
}: {
sponsor: Sponsor | null;
eventId: string;
contacts: Contact[];
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [type, setType] = useState<SponsorType>(sponsor?.type ?? 'gold');
const [name, setName] = useState(sponsor?.name ?? '');
const [email, setEmail] = useState(sponsor?.email ?? '');
const [phone, setPhone] = useState(sponsor?.phone ?? '');
const [paid, setPaid] = useState(sponsor?.paid ?? false);
const [amount, setAmount] = useState(sponsor?.amount_eur != null ? String(sponsor.amount_eur) : '');
const [contactEmail, setContactEmail] = useState(sponsor?.contact_email ?? '');
const [busy, setBusy] = useState(false);
async function save() {
if (!name.trim()) return;
setBusy(true);
try {
await upsertSponsor(sponsor?.id ?? null, {
event_id: eventId,
type,
name: name.trim(),
email: email.trim() || null,
phone: phone.trim() || null,
paid,
amount_eur: amount ? parseFloat(amount) : null,
contact_email: contactEmail || null,
});
onSaved(sponsor ? 'Sponsor updated' : 'Sponsor created');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Save failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={sponsor ? `Edit — ${sponsor.name}` : 'New sponsor'}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !name.trim()} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="grid-2">
<div className="field">
<label>Type</label>
<select className="input" value={type} onChange={(e) => setType(e.target.value as SponsorType)}>
{SPONSOR_TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
</div>
<div className="field">
<label>Name</label>
<input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Nubank" />
</div>
</div>
<div className="grid-2">
<div className="field">
<label>Email</label>
<input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Phone</label>
<input className="input" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="—" />
</div>
</div>
<div className="grid-2">
<div className="field">
<label>Amount (EUR)</label>
<input className="input mono" type="number" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Contact (lookup)</label>
<select className="input" value={contactEmail} onChange={(e) => setContactEmail(e.target.value)}>
<option value="">— none —</option>
{contacts.map((c) => (
<option key={c.email} value={c.email}>
{c.full_name}
</option>
))}
</select>
</div>
</div>
<div className="row">
<Toggle checked={paid} onChange={setPaid} label="Paid (visible to attendees)" />
</div>
</Modal>
);
}
+2 -1
View File
@@ -2,7 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#d50000" />
<meta name="description" content="Convivo — turn a conference into a game. Scan, connect, climb the leaderboard." />
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

-10
View File
@@ -1,10 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#d50000"/>
<stop offset="1" stop-color="#ff5a4e"/>
</linearGradient>
</defs>
<rect width="100" height="100" rx="24" fill="url(#g)"/>
<text x="50" y="68" font-family="Poppins, Arial, sans-serif" font-size="52" font-weight="900" fill="#fff" text-anchor="middle">C</text>
</svg>

Before

Width:  |  Height:  |  Size: 455 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

After

Width:  |  Height:  |  Size: 28 KiB

+2 -1
View File
@@ -8,6 +8,7 @@
"theme_color": "#d50000",
"icons": [
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/apple-touch-icon.png", "sizes": "180x180", "type": "image/png", "purpose": "any" }
]
}
+29 -5
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { AuthProvider, useAuth } from './context/AuthContext';
import { ToastProvider } from './context/ToastContext';
import { Login } from './screens/Login';
@@ -10,6 +10,8 @@ import { Leaderboard } from './screens/Leaderboard';
import { Profile } from './screens/Profile';
import { Feedback } from './screens/Feedback';
import { Spinner } from './components/ui';
import { getMyConnections } from './lib/api';
import { usePolling } from './lib/usePolling';
type Tab = 'home' | 'agenda' | 'scan' | 'connections' | 'profile' | 'leaderboard';
const TABS: { id: Tab; ico: string; label: string }[] = [
@@ -21,9 +23,28 @@ const TABS: { id: Tab; ico: string; label: string }[] = [
];
function Shell() {
const { session, profile, loading } = useAuth();
const { session, contact, loading } = useAuth();
const [tab, setTab] = useState<Tab>('home');
const [feedbackSession, setFeedbackSession] = useState<string | null>(null);
const [pendingIncoming, setPendingIncoming] = useState(0);
const email = contact?.email ?? '';
const loadPending = useCallback(async () => {
try {
const conns = await getMyConnections();
setPendingIncoming(conns.filter((c) => c.status === 'pending' && c.to_email === email).length);
} catch {
/* non-fatal */
}
}, [email]);
useEffect(() => {
if (email) void loadPending();
}, [email, loadPending]);
// Keep the Connect red-dot fresh: poll every 5s while visible.
usePolling(() => void loadPending(), 5000, !!email);
if (loading) {
return (
@@ -35,7 +56,7 @@ function Shell() {
);
}
if (!session || !profile) {
if (!session || !contact) {
return (
<div className="app">
<Login />
@@ -52,7 +73,7 @@ function Shell() {
);
}
const scanLabel = profile.role === 'staff' || profile.role === 'admin' ? 'Check-in' : 'Scan';
const scanLabel = contact.is_admin ? 'Check-in' : 'Scan';
return (
<div className="app">
@@ -73,7 +94,10 @@ function Shell() {
{t.id === 'scan' ? (
<span className="scan-btn">📷</span>
) : (
<span className="ico">{t.ico}</span>
<span className="ico">
{t.ico}
{t.id === 'connections' && pendingIncoming > 0 && <span className="dot" />}
</span>
)}
<span>{t.id === 'scan' ? scanLabel : t.label}</span>
</button>
+28 -20
View File
@@ -1,14 +1,16 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import type { Session as SbSession, User } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
import type { Profile } from '../lib/types';
import { getMyContact, getMyRegistration } from '../lib/api';
import type { Contact, Registration } from '../lib/types';
interface AuthContextValue {
session: SbSession | null;
user: User | null;
profile: Profile | null;
contact: Contact | null;
registration: Registration | null;
loading: boolean;
refreshProfile: () => Promise<void>;
refresh: () => Promise<void>;
signOut: () => Promise<void>;
}
@@ -16,16 +18,18 @@ const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [session, setSession] = useState<SbSession | null>(null);
const [profile, setProfile] = useState<Profile | null>(null);
const [contact, setContact] = useState<Contact | null>(null);
const [registration, setRegistration] = useState<Registration | null>(null);
const [loading, setLoading] = useState(true);
const loadProfile = useCallback(async (userId: string) => {
const { data, error } = await supabase.from('profiles').select('*').eq('id', userId).maybeSingle();
if (error) {
console.error('Failed to load profile', error);
return;
const load = useCallback(async (email: string) => {
try {
const [c, r] = await Promise.all([getMyContact(email), getMyRegistration(email)]);
setContact(c);
setRegistration(r);
} catch (e) {
console.error('Failed to load contact', e);
}
setProfile((data as Profile) ?? null);
}, []);
useEffect(() => {
@@ -33,32 +37,36 @@ export function AuthProvider({ children }: { children: ReactNode }) {
supabase.auth.getSession().then(({ data }) => {
if (!active) return;
setSession(data.session);
if (data.session?.user) void loadProfile(data.session.user.id);
if (data.session?.user?.email) void load(data.session.user.email);
setLoading(false);
});
const { data: sub } = supabase.auth.onAuthStateChange((_event, newSession) => {
setSession(newSession);
if (newSession?.user) void loadProfile(newSession.user.id);
else setProfile(null);
if (newSession?.user?.email) void load(newSession.user.email);
else {
setContact(null);
setRegistration(null);
}
});
return () => {
active = false;
sub.subscription.unsubscribe();
};
}, [loadProfile]);
}, [load]);
const refreshProfile = useCallback(async () => {
if (session?.user) await loadProfile(session.user.id);
}, [session, loadProfile]);
const refresh = useCallback(async () => {
if (session?.user?.email) await load(session.user.email);
}, [session, load]);
const signOut = useCallback(async () => {
await supabase.auth.signOut();
setProfile(null);
setContact(null);
setRegistration(null);
}, []);
const value = useMemo<AuthContextValue>(
() => ({ session, user: session?.user ?? null, profile, loading, refreshProfile, signOut }),
[session, profile, loading, refreshProfile, signOut],
() => ({ session, user: session?.user ?? null, contact, registration, loading, refresh, signOut }),
[session, contact, registration, loading, refresh, signOut],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
+89 -17
View File
@@ -3,12 +3,15 @@ import type {
AgendaRow,
CheckinResult,
Connection,
Contact,
Event,
Feedback,
FeedbackResult,
LeaderboardRow,
PointsLogRow,
Preference,
PublicProfile,
PublicContact,
Registration,
Session,
Slot,
} from './types';
@@ -21,14 +24,15 @@ async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
return data as T;
}
/** Resolve a scanned lanyard QR token to a public profile (pre-login + connect). */
export async function lanyardLookup(qrToken: string): Promise<PublicProfile | null> {
const rows = await rpc<PublicProfile[]>('lanyard_lookup', { p_qr_token: qrToken });
/** Resolve a scanned lanyard QR token to public contact info (pre-login + connect). */
export async function lanyardLookup(qrToken: string): Promise<PublicContact | null> {
const rows = await rpc<PublicContact[]>('lanyard_lookup', { p_qr_token: qrToken });
return rows && rows.length > 0 ? rows[0] : null;
}
export async function getPublicProfiles(): Promise<PublicProfile[]> {
return rpc<PublicProfile[]>('get_public_profiles', {});
/** Public directory of contacts registered for the active event (for connection names). */
export async function getPublicContacts(): Promise<PublicContact[]> {
return rpc<PublicContact[]>('get_public_contacts', {});
}
export async function getAgenda(): Promise<AgendaRow[]> {
@@ -42,7 +46,15 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
let entry = map.get(r.slot_id);
if (!entry) {
entry = {
slot: { id: r.slot_id, name: r.slot_name, slot_date: r.slot_date, start_time: r.start_time, end_time: r.end_time },
slot: {
id: r.slot_id,
event_id: '',
type: r.slot_type,
name: r.slot_name,
slot_date: r.slot_date,
start_time: r.start_time,
end_time: r.end_time,
},
sessions: [],
};
map.set(r.slot_id, entry);
@@ -50,18 +62,43 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
if (r.session_id && r.title) {
entry.sessions.push({
id: r.session_id,
event_id: '',
slot_id: r.slot_id,
title: r.title,
description: r.description,
slot_id: r.slot_id,
room: r.room,
capacity: r.capacity,
average_feedback: r.average_feedback,
ai_generated_feedback: r.ai_generated_feedback,
material_path: r.material_path,
speakers: r.speakers,
created_at: '',
});
}
}
return [...map.values()].sort((a, b) => a.slot.id - b.slot.id);
}
/** 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();
if (error) throw new ApiError(error.message);
return (data as Contact) ?? null;
}
/** The signed-in contact's registration for the active event. */
export async function getMyRegistration(email: string): Promise<Registration | null> {
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).maybeSingle();
if (error) throw new ApiError(error.message);
return (data as Registration) ?? null;
}
export async function getActiveEvent(): Promise<Event | null> {
const { data, error } = await supabase.from('events').select('*').eq('is_active', true).maybeSingle();
if (error) throw new ApiError(error.message);
return (data as Event) ?? null;
}
export async function getMyPreferences(): Promise<Preference[]> {
const { data, error } = await supabase.from('preferences').select('*').order('slot_id');
if (error) throw new ApiError(error.message);
@@ -83,6 +120,7 @@ export async function getMyConnections(): Promise<Connection[]> {
}
export async function createConnectionRequest(targetQr: string): Promise<Connection> {
// create_connection_request returns a single composite row (a JSON object).
return rpc<Connection>('create_connection_request', { p_target_qr: targetQr });
}
@@ -94,8 +132,9 @@ export async function rejectConnection(id: string): Promise<Connection> {
return rpc<Connection>('reject_connection', { p_connection_id: id });
}
export async function getMyCheckins(): Promise<string[]> {
const { data, error } = await supabase.from('checkins').select('session_id');
/** Session ids the signed-in contact is checked into. */
export async function getMyCheckins(email: string): Promise<string[]> {
const { data, error } = await supabase.from('checkins').select('session_id').eq('contact_email', email);
if (error) throw new ApiError(error.message);
return (data as { session_id: string }[]).map((c) => c.session_id);
}
@@ -105,8 +144,8 @@ export async function checkinAttendee(sessionId: string, attendeeQr: string): Pr
return rows[0];
}
export async function getMyFeedback(): Promise<Feedback[]> {
const { data, error } = await supabase.from('feedback').select('*');
export async function getMyFeedback(email: string): Promise<Feedback[]> {
const { data, error } = await supabase.from('feedback').select('*').eq('contact_email', email);
if (error) throw new ApiError(error.message);
return data as Feedback[];
}
@@ -117,13 +156,46 @@ export async function submitFeedback(sessionId: string, rating: number, comment:
}
export async function getLeaderboard(): Promise<LeaderboardRow[]> {
const { data, error } = await supabase.from('leaderboard').select('*').order('points', { ascending: false });
if (error) throw new ApiError(error.message);
return data as LeaderboardRow[];
return rpc<LeaderboardRow[]>('get_leaderboard', {});
}
export async function getMyPointsLog(): Promise<PointsLogRow[]> {
const { data, error } = await supabase.from('points_log').select('*').order('created_at', { ascending: false });
export async function getMyPointsLog(email: string): Promise<PointsLogRow[]> {
const { data, error } = await supabase
.from('points_log')
.select('*')
.eq('contact_email', email)
.order('created_at', { ascending: false });
if (error) throw new ApiError(error.message);
return data as PointsLogRow[];
}
/** Public URL for a session material stored in the `materials` bucket. */
export function sessionMaterialUrl(path: string): string {
const { data } = supabase.storage.from('materials').getPublicUrl(path);
return data.publicUrl;
}
/** Session ids the signed-in contact is a speaker of (for material upload). */
export async function getMySpeakerSessions(email: string): Promise<string[]> {
const { data, error } = await supabase
.from('session_speakers')
.select('session_id')
.eq('contact_email', email);
if (error) throw new ApiError(error.message);
return (data as { session_id: string }[]).map((s) => s.session_id);
}
/** Upload a session material file to the `materials` bucket and set material_path.
* The path is persisted via the `set_session_material` RPC (the sessions table
* is admin-write only, so speakers need the security-definer RPC). */
export async function uploadSessionMaterial(sessionId: string, file: File): Promise<string> {
const path = `sessions/${sessionId}/${Date.now()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`;
const { error: upErr } = await supabase.storage.from('materials').upload(path, file, { upsert: true });
if (upErr) throw new ApiError(upErr.message);
const { error: dbErr } = await supabase.rpc('set_session_material', {
p_session_id: sessionId,
p_material_path: path,
});
if (dbErr) throw new ApiError(dbErr.message);
return path;
}
+68 -23
View File
@@ -1,27 +1,49 @@
export type Role = 'attendee' | 'staff' | 'admin';
export type RegistrationType = 'attendee' | 'speaker' | 'staff' | 'sponsor';
export interface Profile {
id: string;
export type SlotType = 'session' | 'lunch_break' | 'coffee_break' | 'keynote' | 'close_up';
/** The signed-in contact (own row, readable via RLS). */
export interface Contact {
email: string;
full_name: string;
company: string | null;
role: Role;
linkedin_url: string | null;
show_email: boolean;
show_linkedin: boolean;
is_admin: boolean;
qr_token: string | null;
created_at: string;
}
/** The signed-in contact's registration for the active event. */
export interface Registration {
id: string;
event_id: string;
contact_email: string;
type: RegistrationType;
checked_in: boolean;
points: number;
created_at: string;
}
/** Public projection of a profile (no email / qr_token). */
export interface PublicProfile {
export interface Event {
id: string;
full_name: string;
company: string | null;
role: Role;
points: number;
name: string;
start_date: string;
end_date: string;
location: string | null;
is_active: boolean;
avg_feedback: number | null;
num_sessions: number;
num_speakers: number;
num_registrations: number;
num_checked_in_registrations: number;
created_at: string;
}
export interface Slot {
id: number;
event_id: string;
type: SlotType;
name: string;
slot_date: string;
start_time: string;
@@ -30,12 +52,18 @@ export interface Slot {
export interface Session {
id: string;
event_id: string;
slot_id: number;
title: string;
description: string | null;
slot_id: number;
room: string | null;
capacity: number | null;
average_feedback: number | null;
ai_generated_feedback: string | null;
material_path: string | null;
/** Comma-separated speaker names (from the get_agenda RPC). */
speakers: string | null;
created_at: string;
}
/** Row shape returned by the get_agenda() RPC (slots with nested sessions). */
@@ -45,17 +73,22 @@ export interface AgendaRow {
slot_date: string;
start_time: string;
end_time: string;
slot_type: SlotType;
session_id: string | null;
title: string | null;
description: string | null;
room: string | null;
capacity: number | null;
average_feedback: number | null;
ai_generated_feedback: string | null;
material_path: string | null;
speakers: string | null;
}
export interface Preference {
id: string;
profile_id: string;
event_id: string;
contact_email: string;
session_id: string;
slot_id: number;
}
@@ -64,8 +97,9 @@ export type ConnectionStatus = 'pending' | 'accepted' | 'rejected';
export interface Connection {
id: string;
from_id: string;
to_id: string;
event_id: string;
from_email: string;
to_email: string;
status: ConnectionStatus;
created_at: string;
resolved_at: string | null;
@@ -73,15 +107,17 @@ export interface Connection {
export interface Checkin {
id: string;
profile_id: string;
event_id: string;
contact_email: string;
session_id: string;
staff_id: string;
staff_email: string;
created_at: string;
}
export interface Feedback {
id: string;
profile_id: string;
event_id: string;
contact_email: string;
session_id: string;
rating: number;
comment: string | null;
@@ -89,24 +125,33 @@ export interface Feedback {
}
export interface LeaderboardRow {
profile_id: string;
event_id: string;
contact_email: string;
full_name: string;
company: string | null;
points: number;
updated_at: string;
}
export interface PointsLogRow {
id: string;
profile_id: string;
event_id: string;
contact_email: string;
delta: number;
category: 'checkin' | 'connection' | 'feedback' | 'admin';
created_at: string;
}
/** Public projection of a contact (visibility toggles respected). */
export interface PublicContact {
email: string;
full_name: string;
linkedin_url: string | null;
show_email: boolean;
registration_type: RegistrationType | null;
}
export interface CheckinResult {
checkin_id: string;
attendee_id: string;
attendee_email: string;
attendee_name: string;
points: number;
already: boolean;
+20 -6
View File
@@ -1,29 +1,34 @@
import { useEffect, useState } from 'react';
import { getAgenda, groupAgenda } from './api';
import { getActiveEvent, getAgenda, groupAgenda } from './api';
import { DEFAULT_NOW } from './time';
import type { Session, Slot } from './types';
import type { Event, Session, Slot } from './types';
export interface EventData {
event: Event | null;
slots: { slot: Slot; sessions: Session[] }[];
sessionById: Map<string, Session>;
slotById: Map<number, Slot>;
now: Date;
loading: boolean;
error: string | null;
reload: () => void;
}
/** Loads the agenda once and exposes it grouped by slot, plus the event clock. */
/** Loads the active event + agenda, exposes them grouped by slot, plus the event clock. */
export function useEvent(): EventData {
const [event, setEvent] = useState<Event | null>(null);
const [slots, setSlots] = useState<{ slot: Slot; sessions: Session[] }[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [nonce, setNonce] = useState(0);
useEffect(() => {
let active = true;
(async () => {
try {
const rows = await getAgenda();
const [ev, rows] = await Promise.all([getActiveEvent(), getAgenda()]);
if (!active) return;
setEvent(ev);
setSlots(groupAgenda(rows));
} catch (e) {
if (active) setError(e instanceof Error ? e.message : 'Failed to load agenda');
@@ -34,7 +39,7 @@ export function useEvent(): EventData {
return () => {
active = false;
};
}, []);
}, [nonce]);
const sessionById = new Map<string, Session>();
const slotById = new Map<number, Slot>();
@@ -43,5 +48,14 @@ export function useEvent(): EventData {
for (const s of sessions) sessionById.set(s.id, s);
}
return { slots, sessionById, slotById, now: DEFAULT_NOW, loading, error };
return {
event,
slots,
sessionById,
slotById,
now: DEFAULT_NOW,
loading,
error,
reload: () => setNonce((n) => n + 1),
};
}
+31
View File
@@ -0,0 +1,31 @@
import { useEffect, useRef } from 'react';
/**
* Runs `fn` every `ms` milliseconds, but ONLY while the tab is visible
* (document.visibilityState === 'visible'). Also re-runs immediately when the
* tab becomes visible again. No background polling.
*/
export function usePolling(fn: () => void, ms: number, enabled = true): void {
const saved = useRef(fn);
saved.current = fn;
useEffect(() => {
if (!enabled) return;
let timer: number | undefined;
const tick = () => {
if (document.visibilityState === 'visible') saved.current();
};
timer = window.setInterval(tick, ms);
const onVis = () => {
if (document.visibilityState === 'visible') tick();
};
document.addEventListener('visibilitychange', onVis);
return () => {
if (timer !== undefined) window.clearInterval(timer);
document.removeEventListener('visibilitychange', onVis);
};
}, [ms, enabled]);
}
+88 -15
View File
@@ -1,26 +1,45 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import { clearPreference, getMyCheckins, getMyPreferences, setPreference } from '../lib/api';
import {
clearPreference,
getMyCheckins,
getMyPreferences,
getMySpeakerSessions,
sessionMaterialUrl,
setPreference,
uploadSessionMaterial,
} from '../lib/api';
import { fmtRange, slotStatus } from '../lib/time';
import type { Preference, Session } from '../lib/types';
import { Sheet, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) => void }) {
const { slots, now, loading } = useEvent();
const { contact } = useAuth();
const { event, slots, now, loading, reload } = useEvent();
const [prefs, setPrefs] = useState<Preference[]>([]);
const [checkins, setCheckins] = useState<string[]>([]);
const [mySpeakerSessions, setMySpeakerSessions] = useState<string[]>([]);
const [selected, setSelected] = useState<Session | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const { toast } = useToast();
const email = contact?.email ?? '';
useEffect(() => {
let active = true;
(async () => {
try {
const [p, c] = await Promise.all([getMyPreferences(), getMyCheckins()]);
const [p, c, sp] = await Promise.all([
getMyPreferences(),
getMyCheckins(email),
getMySpeakerSessions(email),
]);
if (!active) return;
setPrefs(p);
setCheckins(c);
setMySpeakerSessions(sp);
} catch {
/* non-fatal */
}
@@ -28,7 +47,7 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
return () => {
active = false;
};
}, []);
}, [email]);
if (loading) {
return (
@@ -40,6 +59,20 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
);
}
if (!event) {
return (
<section className="screen">
<div className="h1">Agenda</div>
<div className="card" style={{ marginTop: 16 }}>
<div className="empty">
<div className="big">📅</div>
No active event right now.
</div>
</div>
</section>
);
}
const pickFor = (slotId: number) => prefs.find((p) => p.slot_id === slotId)?.session_id;
async function togglePick(slotId: number, sessionId: string) {
@@ -62,15 +95,33 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
const selSlot = selected ? slots.find((s) => s.slot.id === selected.slot_id)?.slot : undefined;
const selStatus = selSlot ? slotStatus(selSlot, now) : 'next';
const selCheckedIn = selected ? checkins.includes(selected.id) : false;
const selISpeaker = selected ? mySpeakerSessions.includes(selected.id) : false;
const selNeedsMaterial = selISpeaker && !selected?.material_path;
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file || !selected) return;
try {
await uploadSessionMaterial(selected.id, file);
toast('Material uploaded ✓', 'ok');
setSelected(null);
// Refresh agenda so material_path updates.
reload();
} catch (err) {
toast(err instanceof Error ? err.message : 'Upload failed', 'err');
} finally {
if (fileRef.current) fileRef.current.value = '';
}
}
return (
<section className="screen">
<div className="row between">
<div>
<div className="h1">Agenda</div>
<div className="muted small">Wed 23 Oct · 09:00–17:00</div>
<div className="muted small">{event.name}</div>
</div>
<span className="pill violet">6 slots · 3 tracks</span>
<span className="pill violet">{slots.length} slots</span>
</div>
<div className="muted small" style={{ marginTop: -4 }}>
Pick <b>one session per slot</b> — you can change until the slot starts.
@@ -83,7 +134,9 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
<div className="slot-card" key={slot.id}>
<div className="slot-head">
<div className="grow">
<div className="name">{slot.name}</div>
<div className="name">
{slot.name} <span className={`pill slot-type-${slot.type}`}>{slot.type.replace('_', ' ')}</span>
</div>
<div className="time">{fmtRange(slot)}</div>
</div>
{status === 'done' && <span className="pill">Done</span>}
@@ -92,16 +145,17 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
</div>
{sessions.map((s) => {
const picked = pickFor(slot.id) === s.id;
const isMySession = mySpeakerSessions.includes(s.id);
return (
<button
key={s.id}
className={`sess ${picked ? 'picked' : ''}`}
onClick={() => setSelected(s)}
>
<button key={s.id} className={`sess ${picked ? 'picked' : ''}`} onClick={() => setSelected(s)}>
<div className="grow">
<div className="title">{s.title}</div>
<div className="title">
{s.title}
{isMySession && <span className="pill speaker-tag" style={{ marginLeft: 6 }}>🎤 you</span>}
</div>
<div className="meta">
{s.room} · {s.speakers}
{s.material_path && <span style={{ marginLeft: 6 }}>📎</span>}
</div>
</div>
<span className="check">✓</span>
@@ -128,11 +182,30 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
<div className="muted small" id="sd-desc" style={{ margin: '12px 0', lineHeight: 1.55 }}>
{selected.description}
</div>
<div className="row" style={{ gap: 8, marginBottom: 14 }}>
<div className="row" style={{ gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
<span className="pill">🎤 {selected.speakers}</span>
{selected.capacity && <span className="pill">👥 {selected.capacity}</span>}
{selCheckedIn && <span className="pill green">✓ Checked in</span>}
</div>
{/* Speaker material: non-dismissible notification until uploaded. */}
{selNeedsMaterial && (
<div className="material-notice">
<div className="mn-title">📎 Upload your session material</div>
<div className="muted small" style={{ marginBottom: 10 }}>
Attendees can download your slides/notes from this session.
</div>
<input ref={fileRef} type="file" className="input" onChange={handleUpload} />
</div>
)}
{/* Material download (all attendees). */}
{selected.material_path && (
<a className="btn primary" href={sessionMaterialUrl(selected.material_path)} target="_blank" rel="noreferrer">
📎 Download material
</a>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{selStatus === 'done' && selCheckedIn && (
<button className="btn primary" onClick={() => openFeedback(selected.id)}>
+26 -22
View File
@@ -1,23 +1,24 @@
import { useCallback, useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { acceptConnection, getMyConnections, getPublicProfiles, rejectConnection } from '../lib/api';
import type { Connection, PublicProfile } from '../lib/types';
import { acceptConnection, getMyConnections, getPublicContacts, rejectConnection } from '../lib/api';
import { usePolling } from '../lib/usePolling';
import type { Connection, PublicContact } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
export function Connections() {
const { profile } = useAuth();
const { contact } = useAuth();
const [tab, setTab] = useState<'mine' | 'req'>('mine');
const [conns, setConns] = useState<Connection[]>([]);
const [people, setPeople] = useState<Map<string, PublicProfile>>(new Map());
const [people, setPeople] = useState<Map<string, PublicContact>>(new Map());
const [loading, setLoading] = useState(true);
const { toast } = useToast();
const load = useCallback(async () => {
try {
const [c, p] = await Promise.all([getMyConnections(), getPublicProfiles()]);
const [c, p] = await Promise.all([getMyConnections(), getPublicContacts()]);
setConns(c);
setPeople(new Map(p.map((x) => [x.id, x])));
setPeople(new Map(p.map((x) => [x.email, x])));
} catch {
/* non-fatal */
} finally {
@@ -29,14 +30,17 @@ export function Connections() {
void load();
}, [load]);
if (!profile) return null;
const me = profile.id;
const nameOf = (id: string) => people.get(id)?.full_name ?? '…';
const companyOf = (id: string) => people.get(id)?.company ?? '';
// Live-ish updates: poll every 5s while the tab is visible.
usePolling(() => void load(), 5000, !loading);
if (!contact) return null;
const me = contact.email;
const nameOf = (email: string) => people.get(email)?.full_name ?? '…';
const typeOf = (email: string) => people.get(email)?.registration_type ?? null;
const accepted = conns.filter((c) => c.status === 'accepted');
const incoming = conns.filter((c) => c.status === 'pending' && c.to_id === me);
const outgoing = conns.filter((c) => c.status === 'pending' && c.from_id === me);
const incoming = conns.filter((c) => c.status === 'pending' && c.to_email === me);
const outgoing = conns.filter((c) => c.status === 'pending' && c.from_email === me);
async function resolve(id: string, accept: boolean) {
try {
@@ -74,13 +78,13 @@ export function Connections() {
<Empty icon="🤝" text="No connections yet. Scan a peer’s lanyard to start one." />
) : (
accepted.map((c) => {
const otherId = c.from_id === me ? c.to_id : c.from_id;
const otherEmail = c.from_email === me ? c.to_email : c.from_email;
return (
<div className="conn" key={c.id}>
<Avatar name={nameOf(otherId)} id={otherId} size={44} />
<Avatar name={nameOf(otherEmail)} id={otherEmail} size={44} />
<div className="grow">
<div className="name">{nameOf(otherId)}</div>
<div className="meta">{companyOf(otherId)}</div>
<div className="name">{nameOf(otherEmail)}</div>
{typeOf(otherEmail) && <div className="meta">{typeOf(otherEmail)!.replace('_', ' ')}</div>}
</div>
<span className="pill green">Connected</span>
</div>
@@ -98,10 +102,10 @@ export function Connections() {
<div className="muted small" style={{ marginBottom: 8, fontWeight: 700 }}>Incoming</div>
{incoming.map((c) => (
<div className="conn" key={c.id}>
<Avatar name={nameOf(c.from_id)} id={c.from_id} size={44} />
<Avatar name={nameOf(c.from_email)} id={c.from_email} size={44} />
<div className="grow">
<div className="name">{nameOf(c.from_id)}</div>
<div className="meta">{companyOf(c.from_id)}</div>
<div className="name">{nameOf(c.from_email)}</div>
{typeOf(c.from_email) && <div className="meta">{typeOf(c.from_email)!.replace('_', ' ')}</div>}
</div>
<button className="btn primary small" onClick={() => resolve(c.id, true)}>Accept</button>
<button className="btn small" onClick={() => resolve(c.id, false)}>Decline</button>
@@ -114,10 +118,10 @@ export function Connections() {
<div className="muted small" style={{ marginBottom: 8, fontWeight: 700 }}>Sent</div>
{outgoing.map((c) => (
<div className="conn" key={c.id}>
<Avatar name={nameOf(c.to_id)} id={c.to_id} size={44} />
<Avatar name={nameOf(c.to_email)} id={c.to_email} size={44} />
<div className="grow">
<div className="name">{nameOf(c.to_id)}</div>
<div className="meta">{companyOf(c.to_id)}</div>
<div className="name">{nameOf(c.to_email)}</div>
{typeOf(c.to_email) && <div className="meta">{typeOf(c.to_email)!.replace('_', ' ')}</div>}
</div>
<span className="pill amber">Pending</span>
</div>
+36 -55
View File
@@ -1,41 +1,21 @@
import { useEffect, useState } from 'react';
import { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import { getMyFeedback, submitFeedback } from '../lib/api';
import { fmtRange } from '../lib/time';
import { submitFeedback } from '../lib/api';
import { Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
export function Feedback({ sessionId, onDone }: { sessionId: string; onDone: () => void }) {
const { refreshProfile } = useAuth();
const { sessionById, slotById, loading } = useEvent();
const { contact } = useAuth();
const { sessionById, loading } = useEvent();
const [rating, setRating] = useState(0);
const [comment, setComment] = useState('');
const [existing, setExisting] = useState<{ rating: number; comment: string | null } | null>(null);
const [busy, setBusy] = useState(false);
const [done, setDone] = useState<{ earned: number } | null>(null);
const { toast } = useToast();
const session = sessionById.get(sessionId);
const slot = session ? slotById.get(session.slot_id) : undefined;
useEffect(() => {
let active = true;
(async () => {
try {
const fb = await getMyFeedback();
const mine = fb.find((f) => f.session_id === sessionId);
if (active && mine) setExisting({ rating: mine.rating, comment: mine.comment });
} catch {
/* non-fatal */
}
})();
return () => {
active = false;
};
}, [sessionId]);
if (loading || !session || !slot) {
if (loading || !session) {
return (
<section className="screen no-tab">
<div className="center" style={{ flex: 1 }}>
@@ -46,12 +26,12 @@ export function Feedback({ sessionId, onDone }: { sessionId: string; onDone: ()
}
async function submit() {
if (rating < 1) return;
if (rating === 0) return;
setBusy(true);
try {
const res = await submitFeedback(sessionId, rating, comment.trim());
await refreshProfile();
setDone({ earned: res.earned });
toast(`Thanks! +${res.earned} pts ⭐`, 'ok');
onDone();
} catch (e) {
toast(e instanceof Error ? e.message : 'Could not submit feedback', 'err');
} finally {
@@ -59,47 +39,48 @@ export function Feedback({ sessionId, onDone }: { sessionId: string; onDone: ()
}
}
if (done) {
return (
<section className="screen no-tab">
<div className="card success-box">
<div className="emoji">🎉</div>
<h3>{done.earned > 0 ? `+${done.earned} pts earned!` : 'Feedback updated!'}</h3>
<p>Thanks for the feedback — it helps everyone pick better sessions.</p>
<button className="btn primary" style={{ marginTop: 20 }} onClick={onDone}>Back to Home</button>
<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 session</div>
</div>
<span style={{ width: 60 }} />
</div>
</section>
);
}
return (
<section className="screen no-tab">
<button className="btn ghost small" style={{ alignSelf: 'flex-start' }} onClick={onDone}>← Back</button>
<div className="card" style={{ textAlign: 'center' }}>
<div className="muted small">{slot.name} · {fmtRange(slot)} · {session.room}</div>
<div className="h2" style={{ marginTop: 4 }}>{session.title}</div>
<div className="h1" style={{ marginTop: 18, fontSize: 22 }}>How was it? ⭐</div>
<div className="stars">
<div className="h2">{session.title}</div>
<div className="muted small" style={{ marginTop: 4 }}>{session.room} · {session.speakers}</div>
</div>
<div className="stars" style={{ justifyContent: 'center', margin: '20px 0' }}>
{[1, 2, 3, 4, 5].map((n) => (
<button key={n} className={`star ${rating >= n ? 'on' : ''}`} onClick={() => setRating(n)}>★</button>
<button
key={n}
className={`star ${n <= rating ? 'on' : ''}`}
onClick={() => setRating(n)}
aria-label={`${n} star${n > 1 ? 's' : ''}`}
>
★
</button>
))}
</div>
<div className="muted small" style={{ marginBottom: 10 }}>
{rating > 0 ? `${rating} star${rating > 1 ? 's' : ''}` : 'Tap a star'}
</div>
<textarea
className="input"
placeholder="What did you think? (bonus points for details)"
placeholder="Add a comment (optional) — comments earn bonus points"
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
/>
<div className="muted small" style={{ marginTop: 10, textAlign: 'center' }}>
Rating: <b>+5 pts</b> · With comments: <b>+10 pts</b>
</div>
</div>
<button className="btn primary" disabled={busy || rating < 1} onClick={submit}>
{busy ? 'Submitting…' : existing ? 'Update feedback' : 'Submit feedback'}
<button className="btn primary" disabled={busy || rating === 0} onClick={submit}>
{busy ? 'Submitting…' : 'Submit feedback'}
</button>
<div className="muted small" style={{ textAlign: 'center', marginTop: 8 }}>
{contact ? `Signing in as ${contact.full_name}` : ''}
</div>
</section>
);
}
+26 -11
View File
@@ -4,19 +4,21 @@ import { useEvent } from '../lib/useEvent';
import { getMyCheckins, getMyPreferences } from '../lib/api';
import { fmtRange, greeting, slotStatus } from '../lib/time';
import type { Preference } from '../lib/types';
import { Avatar, Spinner } from '../components/ui';
import { Avatar, Empty, Spinner } from '../components/ui';
export function Home({ go }: { go: (tab: string) => void }) {
const { profile } = useAuth();
const { slots, sessionById, now, loading } = useEvent();
const { contact, registration } = useAuth();
const { event, slots, sessionById, now, loading } = useEvent();
const [prefs, setPrefs] = useState<Preference[]>([]);
const [checkins, setCheckins] = useState<string[]>([]);
const email = contact?.email ?? '';
useEffect(() => {
let active = true;
(async () => {
try {
const [p, c] = await Promise.all([getMyPreferences(), getMyCheckins()]);
const [p, c] = await Promise.all([getMyPreferences(), getMyCheckins(email)]);
if (!active) return;
setPrefs(p);
setCheckins(c);
@@ -27,9 +29,9 @@ export function Home({ go }: { go: (tab: string) => void }) {
return () => {
active = false;
};
}, []);
}, [email]);
if (loading || !profile) {
if (loading || !contact) {
return (
<section className="screen">
<div className="center" style={{ flex: 1 }}>
@@ -39,6 +41,19 @@ export function Home({ go }: { go: (tab: string) => void }) {
);
}
if (!event) {
return (
<section className="screen">
<div className="h1">APPE</div>
<div className="card" style={{ marginTop: 16 }}>
<Empty icon="📅" text="No active event right now. Check back soon!" />
</div>
</section>
);
}
const points = registration?.points ?? 0;
const isStaff = contact.is_admin;
const pickFor = (slotId: number) => prefs.find((p) => p.slot_id === slotId)?.session_id;
const current = slots.find(({ slot }) => slotStatus(slot, now) === 'now');
const next = slots.find(({ slot }) => slotStatus(slot, now) === 'next');
@@ -46,16 +61,16 @@ export function Home({ go }: { go: (tab: string) => void }) {
const nowSession = current ? sessionById.get(pickFor(current.slot.id) ?? '') : undefined;
const nextSession = next ? sessionById.get(pickFor(next.slot.id) ?? '') : undefined;
const firstName = profile.full_name.split(' ')[0];
const firstName = contact.full_name.split(' ')[0];
return (
<section className="screen">
<div className="row between">
<div>
<div className="h1">{greeting(now)}, {firstName} 👋</div>
<div className="muted small">Wed 23 Oct · Convivo Conf</div>
<div className="muted small">{event.name}</div>
</div>
<div className="points-pill" onClick={() => go('leaderboard')}>⚡ {profile.points}</div>
<div className="points-pill" onClick={() => go('leaderboard')}>⚡ {points}</div>
</div>
{nowSession && current && (
@@ -114,7 +129,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
<div className="qa-grid">
<div className="qa" onClick={() => go('scan')}>
<span className="ico">📷</span>
<span className="lbl">{profile.role === 'staff' ? 'Check-in' : 'Scan & connect'}</span>
<span className="lbl">{isStaff ? 'Check-in' : 'Scan & connect'}</span>
</div>
<div className="qa" onClick={() => go('agenda')}>
<span className="ico">📅</span>
@@ -131,7 +146,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
</div>
<div style={{ height: 8 }} />
<div className="muted small" style={{ textAlign: 'center', opacity: 0.5 }}>
<Avatar name={profile.full_name} id={profile.id} size={22} fs={9} /> {profile.company ?? ''}
<Avatar name={contact.full_name} id={contact.email} size={22} fs={9} /> {registration?.type.replace('_', ' ') ?? ''}
</div>
</section>
);
+7 -8
View File
@@ -6,7 +6,7 @@ import type { LeaderboardRow } from '../lib/types';
import { Avatar, Spinner } from '../components/ui';
export function Leaderboard() {
const { profile } = useAuth();
const { contact } = useAuth();
const [rows, setRows] = useState<LeaderboardRow[]>([]);
const [loading, setLoading] = useState(true);
@@ -48,10 +48,10 @@ export function Leaderboard() {
);
}
const me = profile?.id;
const me = contact?.email;
const top3 = rows.slice(0, 3);
const rest = rows.slice(3);
const myRank = rows.findIndex((r) => r.profile_id === me) + 1;
const myRank = rows.findIndex((r) => r.contact_email === me) + 1;
return (
<section className="screen">
@@ -70,7 +70,7 @@ export function Leaderboard() {
if (!r) return <div key={idx} style={{ width: 96 }} />;
const cls = idx === 0 ? 'b1' : idx === 1 ? 'b2' : 'b3';
return (
<div className="pod" key={r.profile_id}>
<div className="pod" key={r.contact_email}>
<div className={`bar ${cls}`}>{r.points}</div>
<div className="pname">{r.full_name.split(' ')[0]}</div>
<div className="ppoints">#{idx + 1}</div>
@@ -83,14 +83,13 @@ export function Leaderboard() {
<div style={{ display: 'flex', flexDirection: 'column' }}>
{rest.map((r, i) => {
const rank = i + 4;
const isMe = r.profile_id === me;
const isMe = r.contact_email === me;
return (
<div className={`lb-row ${isMe ? 'me' : ''}`} key={r.profile_id}>
<div className={`lb-row ${isMe ? 'me' : ''}`} key={r.contact_email}>
<span className="rank">{rank}</span>
<Avatar name={r.full_name} id={r.profile_id} size={38} fs={13} />
<Avatar name={r.full_name} id={r.contact_email} size={38} fs={13} />
<div className="grow">
<div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name} {isMe && <span className="muted small">(you)</span>}</div>
<div className="muted small">{r.company ?? ''}</div>
</div>
<span className="pts">{r.points}</span>
</div>
+11 -9
View File
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { supabase } from '../lib/supabase';
import { lanyardLookup } from '../lib/api';
import type { PublicProfile } from '../lib/types';
import type { PublicContact } from '../lib/types';
import { Avatar, Scanner } from '../components/ui';
import { useToast } from '../context/ToastContext';
@@ -10,7 +10,7 @@ type Step = 'splash' | 'scan' | 'confirm';
export function Login() {
const [step, setStep] = useState<Step>('splash');
const [qrToken, setQrToken] = useState('');
const [found, setFound] = useState<PublicProfile | null>(null);
const [found, setFound] = useState<PublicContact | null>(null);
const [email, setEmail] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -22,9 +22,9 @@ export function Login() {
setQrToken(token);
setError(null);
try {
const profile = await lanyardLookup(token);
setFound(profile);
if (!profile) toast('No attendee found for that code', 'err');
const contact = await lanyardLookup(token);
setFound(contact);
if (!contact) toast('No attendee found for that code', 'err');
} catch {
setFound(null);
}
@@ -56,8 +56,8 @@ export function Login() {
if (step === 'splash') {
return (
<section className="screen no-tab splash" onClick={() => setStep('scan')}>
<div className="logo">C</div>
<div className="splash-title">Convivo</div>
<div className="logo">A</div>
<div className="splash-title">APPE</div>
<div className="splash-tag">Break the ice. Earn the points.</div>
<div className="tap-hint">Tap anywhere to continue</div>
</section>
@@ -81,13 +81,15 @@ export function Login() {
<section className="screen no-tab">
<div className="row" style={{ gap: 14 }}>
{found ? (
<Avatar name={found.full_name} id={found.id} size={64} fs={22} />
<Avatar name={found.full_name} id={found.email} size={64} fs={22} />
) : (
<span className="avatar" style={{ width: 64, height: 64, fontSize: 22, background: '#8a8484' }}>?</span>
)}
<div>
<div className="h2">{found ? found.full_name : 'Lanyard found'}</div>
<div className="muted small">{found ? found.company ?? '' : 'Confirm it’s you'}</div>
<div className="muted small">
{found ? (found.registration_type ? found.registration_type.replace('_', ' ') : 'Confirm it’s you') : 'Confirm it’s you'}
</div>
</div>
</div>
<div className="card">
+16 -12
View File
@@ -12,15 +12,17 @@ const CATEGORY_LABEL: Record<PointsLogRow['category'], string> = {
};
export function Profile() {
const { profile, signOut } = useAuth();
const { contact, registration, signOut } = useAuth();
const [log, setLog] = useState<PointsLogRow[]>([]);
const [loading, setLoading] = useState(true);
const email = contact?.email ?? '';
useEffect(() => {
let active = true;
(async () => {
try {
const data = await getMyPointsLog();
const data = await getMyPointsLog(email);
if (active) setLog(data);
} catch {
/* non-fatal */
@@ -31,10 +33,11 @@ export function Profile() {
return () => {
active = false;
};
}, []);
}, [email]);
if (!profile) return null;
if (!contact) return null;
const points = registration?.points ?? 0;
const totals: Record<string, number> = {};
for (const l of log) totals[l.category] = (totals[l.category] ?? 0) + l.delta;
@@ -42,19 +45,20 @@ export function Profile() {
<section className="screen">
<div className="h1">Profile</div>
<div className="card" style={{ textAlign: 'center' }}>
<Avatar name={profile.full_name} id={profile.id} size={72} fs={26} />
<div className="h2" style={{ marginTop: 10 }}>{profile.full_name}</div>
<div className="muted small">{profile.company ?? ''}</div>
<Avatar name={contact.full_name} id={contact.email} size={72} fs={26} />
<div className="h2" style={{ marginTop: 10 }}>{contact.full_name}</div>
<div className="muted small">{contact.email}</div>
<div className="row" style={{ justifyContent: 'center', marginTop: 10, gap: 8 }}>
<span className="pill violet">{profile.role}</span>
<span className="pill amber">⚡ {profile.points} pts</span>
{registration && <span className={`pill reg-${registration.type}`}>{registration.type.replace('_', ' ')}</span>}
{contact.is_admin && <span className="pill admin">staff</span>}
<span className="pill amber">⚡ {points} pts</span>
</div>
</div>
<div className="card qr-wrap">
<div className="h2">My QR code</div>
{profile.qr_token ? (
<QrImage value={profile.qr_token} size={180} />
{contact.qr_token ? (
<QrImage value={contact.qr_token} size={180} />
) : (
<div className="muted small">No QR token assigned.</div>
)}
@@ -79,7 +83,7 @@ export function Profile() {
))}
<div className="break-row">
<span style={{ fontWeight: 700 }}>Total</span>
<span className="v">{profile.points}</span>
<span className="v">{points}</span>
</div>
</>
)}
+30 -18
View File
@@ -2,16 +2,17 @@ import { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent';
import { checkinAttendee, createConnectionRequest, lanyardLookup } from '../lib/api';
import type { CheckinResult, PublicProfile } from '../lib/types';
import type { CheckinResult, PublicContact } from '../lib/types';
import { Avatar, Scanner, Sheet, Spinner } from '../components/ui';
import { useToast } from '../context/ToastContext';
export function Scan() {
const { profile } = useAuth();
const { contact } = useAuth();
const { slots, loading } = useEvent();
const [mode, setMode] = useState<'attendee' | 'staff'>(profile?.role === 'staff' || profile?.role === 'admin' ? 'staff' : 'attendee');
const isStaff = !!contact?.is_admin;
const [mode, setMode] = useState<'attendee' | 'staff'>(isStaff ? 'staff' : 'attendee');
const [sessionId, setSessionId] = useState<string>('');
const [connectTarget, setConnectTarget] = useState<{ profile: PublicProfile; qr: string } | null>(null);
const [connectTarget, setConnectTarget] = useState<{ contact: PublicContact; qr: string } | null>(null);
const [checkin, setCheckin] = useState<CheckinResult | null>(null);
const [busy, setBusy] = useState(false);
const { toast } = useToast();
@@ -23,7 +24,7 @@ export function Scan() {
}
}, [slots, sessionId]);
if (loading || !profile) {
if (loading || !contact) {
return (
<section className="screen">
<div className="center" style={{ flex: 1 }}>
@@ -33,13 +34,13 @@ export function Scan() {
);
}
const isStaff = mode === 'staff' && (profile.role === 'staff' || profile.role === 'admin');
const meId = profile.id;
const meEmail = contact.email;
const activeStaff = mode === 'staff' && isStaff;
async function handleScan(token: string) {
setBusy(true);
try {
if (isStaff) {
if (activeStaff) {
if (!sessionId) {
toast('Pick a session first', 'err');
return;
@@ -52,11 +53,11 @@ export function Scan() {
toast('No attendee found for that code', 'err');
return;
}
if (found.id === meId) {
if (found.email === meEmail) {
toast('That’s your own lanyard 🙂', 'err');
return;
}
setConnectTarget({ profile: found, qr: token });
setConnectTarget({ contact: found, qr: token });
}
} catch (e) {
toast(e instanceof Error ? e.message : 'Something went wrong', 'err');
@@ -87,16 +88,18 @@ export function Scan() {
<section className="screen">
<div className="row between">
<div>
<div className="h1">{isStaff ? 'Check-in' : 'Scan'}</div>
<div className="muted small">{isStaff ? 'Scan attendees to check them in' : 'Scan a peer’s lanyard to connect'}</div>
<div className="h1">{activeStaff ? 'Check-in' : 'Scan'}</div>
<div className="muted small">{activeStaff ? 'Scan attendees to check them in' : 'Scan a peer’s lanyard to connect'}</div>
</div>
{isStaff && (
<div className="seg" style={{ width: 170 }}>
<button className={mode === 'attendee' ? 'active' : ''} onClick={() => setMode('attendee')}>Attendee</button>
<button className={mode === 'staff' ? 'active' : ''} onClick={() => setMode('staff')}>Staff</button>
</div>
)}
</div>
{isStaff && (
{activeStaff && (
<div>
<div className="muted small" style={{ marginBottom: 7 }}>Checking in to session</div>
<select className="input" value={sessionId} onChange={(e) => setSessionId(e.target.value)}>
@@ -111,9 +114,9 @@ export function Scan() {
</div>
)}
<Scanner onResult={handleScan} label={isStaff ? 'Point at an attendee’s lanyard' : 'Point at a peer’s lanyard'} />
<Scanner onResult={handleScan} label={activeStaff ? 'Point at an attendee’s lanyard' : 'Point at a peer’s lanyard'} />
{busy && <div className="center"><Spinner /></div>}
{isStaff && selSession && (
{activeStaff && selSession && (
<div className="muted small" style={{ textAlign: 'center', opacity: 0.6 }}>
{selSession.room} · {selSession.speakers}
</div>
@@ -123,9 +126,18 @@ export function Scan() {
<Sheet open={!!connectTarget} onClose={() => setConnectTarget(null)}>
{connectTarget && (
<div style={{ textAlign: 'center' }}>
<Avatar name={connectTarget.profile.full_name} id={connectTarget.profile.id} size={72} fs={26} />
<h3 style={{ marginTop: 12 }}>{connectTarget.profile.full_name}</h3>
<div className="sub">{connectTarget.profile.company ?? ''}</div>
<Avatar name={connectTarget.contact.full_name} id={connectTarget.contact.email} size={72} fs={26} />
<h3 style={{ marginTop: 12 }}>{connectTarget.contact.full_name}</h3>
{connectTarget.contact.registration_type && (
<span className={`pill reg-${connectTarget.contact.registration_type}`} style={{ marginTop: 8 }}>
{connectTarget.contact.registration_type.replace('_', ' ')}
</span>
)}
{connectTarget.contact.linkedin_url && (
<div className="sub" style={{ marginTop: 6 }}>
<a href={connectTarget.contact.linkedin_url} target="_blank" rel="noreferrer">LinkedIn</a>
</div>
)}
<div style={{ marginTop: 16 }}>
<button className="btn primary" disabled={busy} onClick={confirmConnect}>
{busy ? 'Sending…' : 'Connect 🤝'}
+25
View File
@@ -55,6 +55,31 @@ body {
.pill.green { background: rgba(5,150,105,.12); border-color: rgba(5,150,105,.35); color: var(--green); }
.pill.violet { background: var(--accent-soft); border-color: rgba(213,0,0,.35); color: var(--accent); }
.pill.cyan { background: rgba(32,178,170,.13); border-color: rgba(32,178,170,.4); color: #0f766e; }
.pill.admin { background: var(--accent-soft); border-color: rgba(213,0,0,.35); color: var(--accent); }
/* registration types */
.pill.reg-attendee { background: rgba(148,163,184,.14); border-color: rgba(148,163,184,.4); color: #64748b; }
.pill.reg-speaker { background: rgba(124,58,237,.12); border-color: rgba(124,58,237,.4); color: #6d28d9; }
.pill.reg-staff { background: rgba(32,178,170,.13); border-color: rgba(32,178,170,.4); color: #0f766e; }
.pill.reg-sponsor { background: rgba(234,88,12,.13); border-color: rgba(234,88,12,.4); color: #c2410c; }
/* slot types */
.pill.slot-type-session { background: rgba(14,165,233,.12); border-color: rgba(14,165,233,.4); color: #0369a1; }
.pill.slot-type-lunch_break { background: rgba(245,158,11,.14); border-color: rgba(245,158,11,.4); color: #b45309; }
.pill.slot-type-coffee_break { background: rgba(120,113,108,.14); border-color: rgba(120,113,108,.4); color: #57534e; }
.pill.slot-type-keynote { background: var(--accent-soft); border-color: rgba(213,0,0,.35); color: var(--accent); }
.pill.slot-type-close_up { background: rgba(5,150,105,.12); border-color: rgba(5,150,105,.35); color: var(--green); }
.pill.speaker-tag { background: rgba(124,58,237,.12); border-color: rgba(124,58,237,.4); color: #6d28d9; padding: 2px 8px; font-size: 11px; }
/* pending-connection red dot on the Connect tab */
.tab .ico { position: relative; display: inline-flex; }
.dot {
position: absolute; top: -3px; right: -6px; width: 9px; height: 9px; border-radius: 50%;
background: var(--red); border: 2px solid #fff; box-shadow: 0 0 0 1px rgba(213,0,0,.3);
}
/* speaker material upload notice (non-dismissible) */
.material-notice {
background: rgba(32,178,170,.08); border: 1px solid rgba(32,178,170,.4); border-left: 3px solid var(--accent-2);
border-radius: 12px; padding: 14px; margin-bottom: 12px; display: flex; flex-direction: column; gap: 6px;
}
.material-notice .mn-title { font-weight: 800; font-size: 14px; }
.avatar { display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: 800; color: #fff; flex-shrink: 0; }
.input {
width: 100%; padding: 15px 16px; border-radius: 14px; border: 1px solid var(--line);
+7 -5
View File
@@ -4,9 +4,11 @@ Living documentation for **Convivo** — a conference networking app that turns
conference into a game. This folder is the single source of truth for *how the
system works*; the root [`README.md`](../README.md) is the quick-start.
> **Status:** Phases 0–2 are complete and verified. The project is now in the
> **Redesign** (Phases 3–6) — a new multi-event data model + APPE Admin rebrand.
> See the root [`roadmap.md`](../roadmap.md) and [next-steps.md](./next-steps.md).
> **Status:** Phases 0–6 are complete and verified. The **Redesign** (Phases
> 3–6) is done: the new multi-event data model is live, the admin app is
> rebranded to **APPE Admin**, the Convivo App has all the new behaviors, and both
> apps carry the APPE branding. See the root
> [`roadmap.md`](../roadmap.md) and [next-steps.md](./next-steps.md).
## Where things live
@@ -46,8 +48,8 @@ system works*; the root [`README.md`](../README.md) is the quick-start.
RPC reference instead of re-describing the RPCs.)
- **Code is the source of truth.** If a doc and the code disagree, the code wins —
fix the doc. Key files:
- Schema + RPCs + RLS: [`supabase/migrations/20260822000000_init.sql`](../supabase/migrations/20260822000000_init.sql)
- Admin app migration (admin read RLS + `reset_qr_token`): [`supabase/migrations/20260823000000_admin_app.sql`](../supabase/migrations/20260823000000_admin_app.sql)
- Schema + RPCs + RLS (the Redesign, **current**): [`supabase/migrations/20260824000000_redesign.sql`](../supabase/migrations/20260824000000_redesign.sql)
- Earlier migrations (applied, then replaced by the Redesign): [`20260822000000_init.sql`](../supabase/migrations/20260822000000_init.sql), [`20260823000000_admin_app.sql`](../supabase/migrations/20260823000000_admin_app.sql)
- Seed: [`supabase/seed.sql`](../supabase/seed.sql)
- Attendee app source: [`apps/convivo/src/`](../apps/convivo/src/)
- Admin app source: [`apps/admin/src/`](../apps/admin/src/)
+23 -17
View File
@@ -18,7 +18,7 @@ make connections, get checked in by staff, and rate sessions. Every action earns
flowchart LR
subgraph Browser["Browser"]
A["Convivo PWA<br/>React 18 + Vite 5 + TS<br/>mobile-first, installable"]
AD["Convivo Admin<br/>React 18 + Vite 5 + TS<br/>desktop-first console"]
AD["APPE Admin<br/>React 18 + Vite 5 + TS<br/>desktop-first console"]
end
subgraph Docker["Docker (local)"]
@@ -64,12 +64,14 @@ talks to Supabase through **same-origin paths**, so there is no CORS to manage.
### Backend — the Supabase core
Everything server-side lives in Postgres. See [backend/README.md](./backend/README.md):
- **Schema** — 9 tables (people, schedule, and the event's activity). → [backend/schema.md](./backend/schema.md)
- **Schema** — 13 tables (people, the event, participation, schedule, and the
event's activity). → [backend/schema.md](./backend/schema.md)
- **Business logic** — transactional `security definer` RPCs that award points and
keep the leaderboard consistent. → [backend/rpcs.md](./backend/rpcs.md)
- **Security** — Row Level Security on every table; the app only ever uses the
**anon key + the user's session JWT**. → [backend/rls.md](./backend/rls.md)
- **Data** — seed with 6 slots, 18 sessions, 13 demo users. → [backend/seed.md](./backend/seed.md)
- **Data** — seed with 1 event, 6 slots, 18 sessions, 14 contacts, 13
registrations, 3 sponsors. → [backend/seed.md](./backend/seed.md)
### Frontend — the attendee PWA
A single-page React app with a tab shell and a few full-screen takeovers. See
@@ -78,15 +80,17 @@ A single-page React app with a tab shell and a few full-screen takeovers. See
- **Screens** — Login, Home, Agenda, Scan/Check-in, Connections, Feedback, Leaderboard, Profile. → [frontend/screens.md](./frontend/screens.md)
- **API client** — a thin typed wrapper over `supabase.rpc` / `supabase.from`. → [frontend/api-client.md](./frontend/api-client.md)
### Frontend — the admin console
A separate desktop-first React app for organizers, guarded to the **admin** role.
See [frontend/admin-app.md](./frontend/admin-app.md):
- **Views** — Dashboard (live stats), Attendees (edit / reset QR / adjust
points), Schedule (manage slots + sessions), Activity (check-ins /
connections / feedback).
### Frontend — the admin console (APPE Admin)
A separate desktop-first React app for organizers, guarded to the **`is_admin`**
flag. See [frontend/admin-app.md](./frontend/admin-app.md):
- **Views** — Dashboard (active event + aggregates), Contacts, Registrations,
Sponsors, Schedule (slots/sessions/speakers/material/AI-evaluate), Activity,
Events.
- **Auth guard** — same QR + email login, but non-admin sessions are rejected.
- **New RPC** — `reset_qr_token` regenerates an attendee's lanyard token and
syncs the Auth password (see [backend/rpcs.md](./backend/rpcs.md)).
- **Key RPCs** — `reset_qr_token` (regenerate a lanyard token + sync the Auth
password), `adjust_points`, `upsert_contact`, `create_registration`,
`set_registration_type`, `evaluate_session_feedback` (AI stub), and
`set_session_material` (see [backend/rpcs.md](./backend/rpcs.md)).
## 5. How a request flows (example: staff check-in)
@@ -102,7 +106,7 @@ sequenceDiagram
N->>K: proxy (same-origin)
K->>R: route /rest
R->>DB: execute checkin_attendee() as `authenticated`
Note over DB: security definer → bypasses RLS<br/>1. insert checkin (ON CONFLICT do nothing)<br/>2. _award_points(+10) → profiles.points + points_log<br/>3. _sync_leaderboard()
Note over DB: security definer → bypasses RLS<br/>1. insert checkin (ON CONFLICT do nothing)<br/>2. _award_points(+10) → registrations.points + points_log<br/>3. _sync_leaderboard()
DB-->>R: {checkin_id, attendee_name, points, already}
R-->>K: JSON
K-->>N: JSON
@@ -119,8 +123,9 @@ the work atomically, and the `leaderboard` table change fans out over Realtime.
Login is a standard `signInWithPassword({ email, password: qrToken })`.
- `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 short-lived **session JWT** (in `localStorage`).
Every request sends the **anon key** (public) + the **session JWT** (identity).
- After login, the app holds a **session JWT** (in `localStorage`) that lasts
**24 hours** (`jwt_expiry = 86400`). Every request sends the **anon key**
(public) + the **session JWT** (identity).
- The **service-role key is never in the app** — it bypasses RLS and stays
server-side. See [backend/rls.md](./backend/rls.md) for what each role can do.
@@ -167,9 +172,10 @@ Convivo/
├─ supabase/
│ ├─ config.toml # Local stack config (ports, auth, RLS defaults)
│ ├─ migrations/
│ │ ├─ 20260822000000_init.sql # schema, RLS, points RPCs
│ │ └─ 20260823000000_admin_app.sql # admin read RLS + reset_qr_token RPC
│ └─ seed.sql # Slots, sessions, 13 demo users, Ana's demo state
│ │ ├─ 20260822000000_init.sql # original schema (replaced by the Redesign)
│ │ ├─ 20260823000000_admin_app.sql # admin read RLS + reset_qr_token (superseded)
│ │ └─ 20260824000000_redesign.sql # ← current: multi-event model, RPCs, RLS, materials
│ └─ seed.sql # 1 event, 6 slots, 18 sessions, 14 contacts, demo state
├─ docker-compose.yml # Runs both app sidecars on the Supabase network
├─ docs/ # ← this documentation
└─ mockup/index.html # Original interactive mockup (design reference)
+9 -6
View File
@@ -7,23 +7,24 @@ Postgres. This folder documents that core.
| File | What it covers |
|---|---|
| [supabase-core.md](./supabase-core.md) | The local stack: containers, ports, how to start/reset, config |
| [schema.md](./schema.md) | All 9 tables, columns, constraints, indexes |
| [schema.md](./schema.md) | All 13 tables, columns, constraints, indexes |
| [rpcs.md](./rpcs.md) | The transactional points RPCs (the business logic) |
| [rls.md](./rls.md) | Row Level Security policies + which key the app uses |
| [seed.md](./seed.md) | Seed data + the 13 demo accounts |
| [seed.md](./seed.md) | Seed data + the demo accounts |
| [docker.md](./docker.md) | Docker: the app image + root compose (how the core + app run together) |
## The big picture
```
Postgres 17 ── schema (9 tables)
Postgres 17 ── schema (13 tables, multi-event model)
── RLS (who can read/write what)
── RPCs (security definer, transactional points logic)
── seed (demo data)
```
- **Data + logic live in the database.** The app never computes points or writes
to `profiles.points` directly — it calls RPCs, and Postgres enforces the rules.
to `registrations.points` directly — it calls RPCs, and Postgres enforces the
rules.
- **RLS is the security boundary.** The app uses the **anon key + the user's
session JWT**; RLS decides what that user may see and do. The service-role key
is never shipped to the app. See [rls.md](./rls.md).
@@ -33,7 +34,9 @@ Postgres 17 ── schema (9 tables)
## Source of truth
- Schema + RPCs + RLS: [`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql)
- Admin app (Phase 2): admin read RLS + `reset_qr_token` RPC — [`supabase/migrations/20260823000000_admin_app.sql`](../../supabase/migrations/20260823000000_admin_app.sql)
- Schema + RPCs + RLS (the Redesign, **current**): [`supabase/migrations/20260824000000_redesign.sql`](../../supabase/migrations/20260824000000_redesign.sql)
- Earlier migrations (still applied, then replaced by the Redesign):
[`20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql) and
[`20260823000000_admin_app.sql`](../../supabase/migrations/20260823000000_admin_app.sql)
- Seed: [`supabase/seed.sql`](../../supabase/seed.sql)
- Stack config: [`supabase/config.toml`](../../supabase/config.toml)
+1 -1
View File
@@ -56,7 +56,7 @@ same-origin paths to the core:
| `/auth/` | `__SUPABASE_PROXY_TARGET__` | GoTrue |
| `/rest/` | `__SUPABASE_PROXY_TARGET__` | PostgREST (tables + RPCs) |
| `/realtime/` | `__SUPABASE_PROXY_TARGET__` | WebSocket — `Upgrade`/`Connection` headers + long timeouts |
| `/storage/` | `__SUPABASE_PROXY_TARGET__` | Storage (unused in v1) |
| `/storage/` | `__SUPABASE_PROXY_TARGET__` | Storage — the `materials` bucket (session material) |
`__SUPABASE_PROXY_TARGET__` is replaced at start with the value of the
`SUPABASE_PROXY_TARGET` env var (default `supabase_kong_Convivo:8000`).
+103 -61
View File
@@ -1,12 +1,12 @@
# Row Level Security (RLS)
RLS is the security boundary. It is **enabled on all 9 tables**, and every policy
is scoped to the `authenticated` role. The `anon` role has `GRANT select` at the
Postgres level, but RLS blocks it from reading anything — so an unauthenticated
request sees no rows.
RLS is the security boundary. It is **enabled on all 13 tables**, and every
policy is scoped to the `authenticated` role. The `anon` role has `GRANT select`
at the Postgres level, but RLS blocks it from reading anything — so an
unauthenticated request sees no rows.
Source of truth:
[`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql)
[`supabase/migrations/20260824000000_redesign.sql`](../../supabase/migrations/20260824000000_redesign.sql)
(RLS section).
## Which key does the app use?
@@ -26,91 +26,132 @@ Source of truth:
## Role helpers
Two `security definer` functions drive role checks (see [rpcs.md](./rpcs.md#role-helper-functions)):
- `is_admin()` — current user's profile has `role = 'admin'`
- `is_staff_or_admin()` — current user's profile has `role in ('staff','admin')`
`security definer` functions drive role checks (see
[rpcs.md](./rpcs.md#role-helper-functions)):
- `current_email()` — `auth.jwt() ->> 'email'` (the identity; `contacts` is keyed
by email)
- `is_admin()` — current contact has `is_admin = true`
- `is_staff_or_admin()` — = `is_admin()` (staff is merged into admin)
- `is_speaker_or_admin()` — admin, or a speaker of an active-event session, or a
`speaker`-type registration
## Policies by table
| Table | SELECT | INSERT | UPDATE | DELETE |
|---|---|---|---|---|
| `profiles` | own **or** admin | — | admin only | admin only |
| `contacts` | own **or** admin | — | admin only | admin only |
| `events` | all authenticated | admin only | admin only | admin only |
| `registrations` | own **or** admin | admin only | admin only | admin only |
| `sponsors` | admin **or** `paid` | admin only | admin only | admin only |
| `slots` | all authenticated | admin only | admin only | admin only |
| `sessions` | all authenticated | admin only | admin only | admin only |
| `preferences` | own **or** admin | — | — | — |
| `session_speakers` | all authenticated | admin only | admin only | admin only |
| `preferences` | own | — | — | — |
| `connections` | rows you're in **or** admin | — | — | — |
| `checkins` | own **or** staff/admin | — | — | — |
| `checkins` | own **or** admin | — | — | — |
| `feedback` | own **or** admin | — | — | — |
| `leaderboard` | all authenticated | — | — | — |
| `points_log` | own **or** admin | — | — | — |
> **Phase 2 addition** ([`20260823000000_admin_app.sql`](../../supabase/migrations/20260823000000_admin_app.sql)):
> admin-only `select` policies were added to `preferences`, `connections`, and
> `feedback` so the Admin console can read the full activity. The per-user
> policies above are unchanged — these are additive `OR is_admin()` reads.
**"—" (no policy)** means normal users have **no direct write access** — those
tables are written only by the `security definer` RPCs, which bypass RLS. This is
deliberate: a client cannot `UPDATE profiles SET points = 9999` or insert its own
check-in. See [rpcs.md](./rpcs.md).
deliberate: a client cannot `UPDATE registrations SET points = 9999` or insert its
own check-in. See [rpcs.md](./rpcs.md).
> **Admin reads the full activity.** The `connections`, `checkins`, and `feedback`
> select policies include `or public.is_admin()`, so the APPE Admin console's
> Activity view sees every row (an admin is "involved" in none of them, so a
> pure "involved/own" policy would show 0).
### The exact policies
```sql
-- profiles: read own or admin; write admin only
create policy "profiles_select_own_or_admin" on public.profiles for select to authenticated
using (id = auth.uid() or public.is_admin());
create policy "profiles_update_admin" on public.profiles for update to authenticated
-- contacts: read own or admin; write admin only
create policy "contacts_select_own_or_admin" on public.contacts for select to authenticated
using (email = public.current_email() or public.is_admin());
create policy "contacts_admin_update" on public.contacts for update to authenticated
using (public.is_admin()) with check (public.is_admin());
create policy "profiles_delete_admin" on public.profiles for delete to authenticated
create policy "contacts_admin_delete" on public.contacts for delete to authenticated
using (public.is_admin());
-- slots / sessions: readable by any authenticated user (public agenda); admin writes
-- events: readable by all authenticated; writable by admin
create policy "events_select_all" on public.events for select to authenticated using (true);
create policy "events_admin_insert" on public.events for insert to authenticated with check (public.is_admin());
create policy "events_admin_update" on public.events for update to authenticated
using (public.is_admin()) with check (public.is_admin());
create policy "events_admin_delete" on public.events for delete to authenticated using (public.is_admin());
-- registrations: own or admin
create policy "registrations_select_own_or_admin" on public.registrations for select to authenticated
using (contact_email = public.current_email() or public.is_admin());
-- (admin-only insert/update/delete)
-- sponsors: admin sees all; non-admin sees only paid sponsors
create policy "sponsors_select" on public.sponsors for select to authenticated
using (public.is_admin() or paid);
-- (admin-only insert/update/delete)
-- slots / sessions / session_speakers: readable by any authenticated user; admin writes
create policy "slots_select_all" on public.slots for select to authenticated using (true);
create policy "slots_admin_insert" on public.slots for insert to authenticated with check (public.is_admin());
create policy "slots_admin_update" on public.slots for update to authenticated using (public.is_admin()) with check (public.is_admin());
create policy "slots_admin_delete" on public.slots for delete to authenticated using (public.is_admin());
-- (sessions: identical four policies)
create policy "sessions_select_all" on public.sessions for select to authenticated using (true);
create policy "session_speakers_select_all" on public.session_speakers for select to authenticated using (true);
-- (each has admin-only insert/update/delete)
-- preferences: read own
create policy "prefs_select_own" on public.preferences for select to authenticated
using (profile_id = auth.uid());
using (contact_email = public.current_email());
-- connections: read rows you're involved in
create policy "conn_select_involved" on public.connections for select to authenticated
using (from_id = auth.uid() or to_id = auth.uid());
-- connections: read rows you're part of (or all if admin)
create policy "conn_select_involved_or_admin" on public.connections for select to authenticated
using (from_email = public.current_email() or to_email = public.current_email() or public.is_admin());
-- checkins: read own or staff/admin
create policy "checkins_select_own_or_staff" on public.checkins for select to authenticated
using (profile_id = auth.uid() or public.is_staff_or_admin());
-- checkins: read own, or all if admin
create policy "checkins_select_own_or_admin" on public.checkins for select to authenticated
using (contact_email = public.current_email() or public.is_admin());
-- feedback: read own
create policy "feedback_select_own" on public.feedback for select to authenticated
using (profile_id = auth.uid());
-- feedback: read own, or all if admin
create policy "feedback_select_own_or_admin" on public.feedback for select to authenticated
using (contact_email = public.current_email() or public.is_admin());
-- leaderboard: readable by any authenticated user
-- leaderboard: public to all authenticated (Realtime source)
create policy "leaderboard_select_all" on public.leaderboard for select to authenticated using (true);
-- points_log: read own or admin
create policy "points_log_select_own_or_admin" on public.points_log for select to authenticated
using (profile_id = auth.uid() or public.is_admin());
-- Phase 2 (20260823000000_admin_app.sql): additive admin-only reads for the
-- Admin console. These OR with the per-user policies above.
create policy "prefs_select_admin" on public.preferences for select to authenticated using (public.is_admin());
create policy "conn_select_admin" on public.connections for select to authenticated using (public.is_admin());
create policy "feedback_select_admin" on public.feedback for select to authenticated using (public.is_admin());
using (contact_email = public.current_email() or public.is_admin());
```
## Storage — `materials` bucket
The `materials` bucket (public read) stores session material. Policies on
`storage.objects`:
```sql
create policy "materials_read" on storage.objects for select to authenticated
using (bucket_id = 'materials');
create policy "materials_write" on storage.objects for insert to authenticated
with check (bucket_id = 'materials' and public.is_speaker_or_admin());
create policy "materials_update" on storage.objects for update to authenticated
using (bucket_id = 'materials' and public.is_speaker_or_admin());
create policy "materials_delete" on storage.objects for delete to authenticated
using (bucket_id = 'materials' and public.is_speaker_or_admin());
```
Speakers + admins can write; any authenticated attendee can read (download).
Because the `sessions` table is admin-write only, a speaker attaches their
uploaded file via the `set_session_material` RPC (see
[rpcs.md](./rpcs.md#set_session_materialp_session_id-p_material_path--sessions)).
## GRANTs
The new Supabase CLI does **not** auto-expose new tables to the Data API roles, so
the migration grants explicitly (RLS still governs what each role can actually see):
the migration grants explicitly (RLS still governs what each role can actually
see):
```sql
grant usage on schema public to anon, authenticated, service_role;
grant select on <all 9 tables> to anon, authenticated, service_role;
grant insert, update, delete on <all 9 tables> to authenticated, service_role;
grant select on <all 13 tables> to anon, authenticated, service_role;
grant insert, update, delete on <all 13 tables> to authenticated, service_role;
grant execute on function <all public RPCs + helpers> to authenticated;
```
@@ -119,20 +160,21 @@ full DML at the Postgres level, but **RLS narrows it** to the policies above.
## Net effect by role
- **Attendee** — sees their own profile/prefs/connections/feedback, the full
agenda, and the leaderboard; can only act through the RPCs (which re-check role
internally, e.g. only staff can call `checkin_attendee`).
- **Staff** — everything an attendee can do, plus can read all `checkins` and call
the check-in RPC.
- **Admin** — full read on everything (including all `preferences`,
`connections`, and `feedback`), and the only role with **direct** write access
to `profiles` / `slots` / `sessions`. This is exactly what the Admin console
(Phase 2, [`../frontend/admin-app.md`](../frontend/admin-app.md)) uses.
- **Attendee** — sees their own contact/registration/prefs/connections/feedback,
the full agenda, the public contact directory, and the leaderboard; can only act
through the RPCs (which re-check role internally, e.g. only staff can call
`checkin_attendee`).
- **Staff (= admin)** — everything an attendee can do, plus can read all
`checkins` / `connections` / `feedback` and call the check-in RPC.
- **Admin** — full read on everything, and the only role with **direct** write
access to `contacts` / `events` / `registrations` / `sponsors` / `slots` /
`sessions` / `session_speakers`. This is exactly what the APPE Admin console
([../frontend/admin-app.md](../frontend/admin-app.md)) uses.
## Things to revisit later
- `slots` / `sessions` are readable by *any* authenticated user (fine — it's a
public agenda). If you ever want the agenda hidden until the event, that's a
one-line policy change.
- `slots` / `sessions` / `session_speakers` are readable by *any* authenticated
user (fine — it's a public agenda). If you ever want the agenda hidden until the
event, that's a one-line policy change.
- `leaderboard` exposes every attendee's name + points to any authenticated user.
That's the intended product behavior (a public leaderboard).
+82 -44
View File
@@ -1,12 +1,13 @@
# Points RPCs (Business Logic)
All mutations go through **Postgres RPCs** (`security definer`, transactional).
The app never writes to `profiles.points`, `connections`, `checkins`, `feedback`,
or `leaderboard` directly — it calls these functions. This is what makes the
points system race-free and prevents a client from, e.g., setting its own points.
The app never writes to `registrations.points`, `connections`, `checkins`,
`feedback`, or `leaderboard` directly — it calls these functions. This is what
makes the points system race-free and prevents a client from, e.g., setting its
own points.
Source of truth:
[`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql).
[`supabase/migrations/20260824000000_redesign.sql`](../../supabase/migrations/20260824000000_redesign.sql).
## Why RPCs?
@@ -17,6 +18,8 @@ Source of truth:
re-sync the leaderboard* in **one transaction**. Either all happen or none do.
- **Idempotent where it matters** → re-check-in and re-feedback are detected and
never double-award.
- **Event-scoped** → every RPC resolves the **active event** first and scopes all
reads/writes to it.
## Points rules
@@ -30,27 +33,37 @@ Source of truth:
## Internal helpers
### `_award_points(p_profile_id, p_delta, p_category)`
### `_award_points(p_event_id, p_contact_email, p_delta, p_category)`
The single place points change. In one transaction it:
1. `update profiles set points = greatest(0, points + p_delta)` (floored at 0),
2. `insert into points_log (profile_id, delta, category)`,
3. calls `_sync_leaderboard(p_profile_id)`.
1. `update registrations set points = greatest(0, points + p_delta)` (floored at
0) for the (event, contact),
2. `insert into points_log (event_id, contact_email, delta, category)`,
3. calls `_sync_leaderboard(p_event_id, p_contact_email)`.
### `_sync_leaderboard(p_profile_id)`
Upserts the `leaderboard` row for that profile from `profiles`
(`on conflict (profile_id) do update ...`). This is what makes the leaderboard a
consistent, Realtime-friendly mirror.
### `_sync_leaderboard(p_event_id, p_contact_email)`
Upserts the `leaderboard` row for that (event, contact) from `registrations` +
`contacts` (`on conflict (event_id, contact_email) do update ...`). This is what
makes the leaderboard a consistent, Realtime-friendly mirror.
### `_recalc_event_aggregates(p_event_id)`
Recomputes the `events` aggregate columns (`num_sessions`, `num_speakers`,
`num_registrations`, `num_checked_in_registrations`, `avg_feedback`). Called by
triggers and the feedback RPC.
## Public read functions
| Function | Returns | Used for |
|---|---|---|
| `get_public_profiles()` | `id, full_name, company, role, points` (ordered by points) | Leaderboard initial load, id→name lookups |
| `lanyard_lookup(p_qr_token)` | `id, full_name, company, role` | Resolve a scanned QR (pre-login + connect) |
| `get_agenda()` | slots with their sessions (flat rows) | Agenda + Home |
| `get_leaderboard()` | `event_id, contact_email, full_name, points` (active event, ordered by points) | Leaderboard initial load + realtime re-fetch |
| `lanyard_lookup(p_qr_token)` | `email, full_name, linkedin_url` (null unless `show_linkedin`), `show_email`, `registration_type` | Resolve a scanned QR (pre-login + connect) |
| `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 |
All three are `security definer` and expose **only public columns** (no email, no
`qr_token`).
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
exposed). `lanyard_lookup` / `get_public_contacts` respect the contact's
`show_email` / `show_linkedin` visibility toggles.
## Mutation RPCs
@@ -63,28 +76,29 @@ Enforces "one pick per slot".
Removes the caller's pick for a slot.
### `create_connection_request(p_target_qr)` → `connections`
Creates a **pending** connection to the attendee whose QR was scanned.
Creates a **pending** connection to the contact whose QR was scanned.
- Resolves the target by `qr_token`; errors if not found or if it's yourself.
- **Idempotent:** if the pair already has a connection (either direction), returns
the existing one instead of creating a duplicate.
- **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`
Accepts an **incoming** request.
- Locks the row (`for update`), verifies the caller is the recipient
(`to_id = auth.uid()`) and the status is still `pending`.
(`to_email = current_email()`) and the status is still `pending`.
- Sets `status = 'accepted'`, `resolved_at = now()`.
- **Awards +5 to both** `from_id` and `to_id` (category `connection`).
- **Awards +5 to both** `from_email` and `to_email` (category `connection`).
### `reject_connection(p_connection_id)` → `connections`
Same guards as accept, but sets `status = 'rejected'`. No points.
### `checkin_attendee(p_session_id, p_attendee_qr)` → `(checkin_id, attendee_id, attendee_name, points, already)`
### `checkin_attendee(p_session_id, p_attendee_qr)` → `(checkin_id, attendee_email, attendee_name, points, already)`
Staff checks an attendee into a session.
- **Role check:** `is_staff_or_admin()` or it raises `staff or admin only`.
- **Role check:** `is_staff_or_admin()` (i.e. `is_admin()`) or it raises
`staff or admin only`.
- Resolves the attendee by `qr_token`.
- `insert into checkins ... on conflict (profile_id, session_id) do nothing
returning id` — if no row was inserted, the attendee was **already checked in**:
sets `already = true` and awards **no points**.
- `insert into checkins ... on conflict (event_id, contact_email, session_id) do
nothing returning id` — if no row was inserted, the attendee was **already
checked in**: sets `already = true` and awards **no points**.
- Otherwise awards **+10** to the attendee (category `checkin`).
- Returns the attendee's current total points.
@@ -102,20 +116,22 @@ Post-session feedback.
- **Idempotent:** if feedback already exists for (caller, session), it **updates**
the rating/comment and awards **0** (already rewarded on first submission).
- Otherwise inserts and awards `earned` (category `feedback`).
- Recalculates `sessions.average_feedback`, updates the `ai_generated_feedback`
state machine, and recalcs the event aggregates.
### `adjust_points(p_profile_id, p_delta, p_reason)` → `void`
**Admin-only** manual points adjustment (category `admin`). Used by the Admin
console (Phase 2) to award prizes or correct mistakes. Goes through
### `adjust_points(p_contact_email, p_delta, p_reason)` → `void`
**Admin-only** manual points adjustment (category `admin`) for the active event.
Used by the APPE Admin console to award prizes or correct mistakes. Goes through
`_award_points`, so it floors at 0, writes `points_log`, and re-syncs the
leaderboard.
### `reset_qr_token(p_profile_id)` → `(profile_id, qr_token)`
**Admin-only.** Regenerates an attendee's lanyard QR token.
- Generates a fresh `CVV-XXX-NNNN` token and writes it to `profiles.qr_token`.
- **Re-hashes it as the Auth password** (`extensions.crypt(token, extensions.gen_salt('bf'))`
on `auth.users.encrypted_password`), so the **old token stops working** and the
attendee must re-scan with the new one.
- **Deletes the attendee's existing `auth.sessions`**, forcing a re-login.
### `reset_qr_token(p_contact_email)` → `(email, qr_token)`
**Admin-only.** Regenerates a contact's lanyard QR token.
- Generates a fresh `CVV-XXX-NNNN` token and writes it to `contacts.qr_token`.
- **Re-hashes it as the Auth password** (`extensions.crypt(token,
extensions.gen_salt('bf'))` on `auth.users.encrypted_password`), so the **old
token stops working** and the contact must re-scan with the new one.
- **Deletes the contact's existing `auth.sessions`**, forcing a re-login.
- Returns the new token so the admin can print/show it as a QR code.
> **Implementation note:** pgcrypto's `gen_salt` / `crypt` live in the
@@ -124,22 +140,44 @@ leaderboard.
> `extensions.crypt(...)`. The function owner (`postgres`) can write
> `auth.users` and `auth.sessions`, which is what makes this possible.
Source of truth for this RPC:
[`supabase/migrations/20260823000000_admin_app.sql`](../../supabase/migrations/20260823000000_admin_app.sql).
### `upsert_contact(p_email, p_full_name, p_linkedin_url, p_is_admin, p_qr_token)` → `contacts`
**Admin-only.** Creates a contact if it doesn't exist (generating a QR token when
none is given) or updates the existing one. Returns the contact row.
### `create_registration(p_contact_email, p_type)` → `registrations`
**Admin-only.** Creates a registration for the active event (enforces the
sponsor-type rule).
### `set_registration_type(p_contact_email, p_type)` → `registrations`
**Admin-only.** Changes a contact's registration type for the active event.
### `evaluate_session_feedback(p_session_id)` → `sessions`
**Admin-only.** The **AI-feedback stub**: sets `ai_generated_feedback` to a
placeholder string ("AI evaluation stub: N comment(s) received. (LLM integration
pending.)"). Real LLM integration is a later phase.
### `set_session_material(p_session_id, p_material_path)` → `sessions`
Sets a session's `material_path`. Allowed for **admins and for any speaker of the
session** (the `sessions` table is admin-write only, so speakers need this
security-definer RPC to attach their uploaded material). The attendee app calls
this after uploading a file to the `materials` bucket.
## Role helper functions
| Function | Returns | Meaning |
|---|---|---|
| `is_admin()` | `boolean` | current user's profile has `role = 'admin'` |
| `is_staff_or_admin()` | `boolean` | current user's profile has `role in ('staff','admin')` |
| `current_email()` | `text` | `auth.jwt() ->> 'email'` (the identity) |
| `is_admin()` | `boolean` | current contact has `is_admin = true` |
| `is_staff_or_admin()` | `boolean` | = `is_admin()` (staff is merged into admin) |
| `is_speaker_or_admin()` | `boolean` | admin, **or** a speaker of a session in the active event (via `session_speakers`), **or** a contact whose registration type is `speaker` |
Both are `security definer` so they can read `profiles` inside RLS checks and RPC
guards.
All are `security definer` so they can read `contacts` / `registrations` /
`session_speakers` inside RLS checks and RPC guards.
## Error handling
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
connect with yourself`, `staff or admin only`, `you must be checked in to this
session to give feedback`). The frontend surfaces these via toasts — see
session to give feedback`, `not a speaker of this session`). The frontend
surfaces these via toasts — see
[../frontend/api-client.md](../frontend/api-client.md).
+164 -50
View File
@@ -1,152 +1,266 @@
# Database Schema
All tables live in the `public` schema. Source of truth:
[`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql).
[`supabase/migrations/20260824000000_redesign.sql`](../../supabase/migrations/20260824000000_redesign.sql)
(the Redesign migration, which **replaces** the old `profiles`-based schema).
There are **9 tables**: people, schedule, and the event's activity.
There are **13 tables**: people (`contacts`), the event (`events`), participation
(`registrations`, `sponsors`), the schedule (`slots`, `sessions`,
`session_speakers`), and the event's activity (`preferences`, `connections`,
`checkins`, `feedback`, `leaderboard`, `points_log`).
The old `profiles` table is **dropped**. People are now `contacts` (keyed by
email), and every activity table is scoped to an **event** + a **contact email**
instead of a single `profile_id`.
```mermaid
erDiagram
profiles ||--o{ preferences : "picks"
profiles ||--o{ connections : "from/to"
profiles ||--o{ checkins : "checked in"
profiles ||--o{ feedback : "rates"
profiles ||--o{ leaderboard : "mirrored"
profiles ||--o{ points_log : "audited"
contacts ||--o{ registrations : "participates"
contacts ||--o{ session_speakers : "speaks"
contacts ||--o{ preferences : "picks"
contacts ||--o{ connections : "from/to"
contacts ||--o{ checkins : "checked in"
contacts ||--o{ feedback : "rates"
contacts ||--o{ leaderboard : "mirrored"
contacts ||--o{ points_log : "audited"
events ||--o{ registrations : "has"
events ||--o{ sponsors : "has"
events ||--o{ slots : "has"
events ||--o{ sessions : "has"
events ||--o{ preferences : "scopes"
events ||--o{ connections : "scopes"
events ||--o{ checkins : "scopes"
events ||--o{ feedback : "scopes"
events ||--o{ leaderboard : "scopes"
events ||--o{ points_log : "scopes"
slots ||--o{ sessions : "contains"
sessions ||--o{ session_speakers : "has speakers"
sessions ||--o{ preferences : "picked"
sessions ||--o{ checkins : "checked into"
sessions ||--o{ feedback : "rated"
```
## `profiles` — people (source of truth)
## `contacts` — people (source of truth)
One row per attendee. `id` **is** the Supabase Auth user id.
One row per person. **`email` is the primary key** (a natural key that matches
`auth.users.email`). The `qr_token` doubles as the Supabase Auth password.
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | = `auth.users(id)`; `on delete cascade` |
| `email` | `text` **unique** | The ticket-purchase email (login identifier) |
| `email` | `text` **PK** | The ticket-purchase email (login identifier) |
| `full_name` | `text` | |
| `company` | `text` | nullable |
| `role` | `text` | `attendee` \| `staff` \| `admin` (default `attendee`) |
| `linkedin_url` | `text` | nullable |
| `show_email` | `boolean` | default `false` — visibility toggle |
| `show_linkedin` | `boolean` | default `false` — visibility toggle |
| `is_admin` | `boolean` | default `false` — **staff = admin (merged)**; grants check-in + APPE Admin access |
| `qr_token` | `text` **unique** | The lanyard token; **doubles as the Auth password** |
| `created_at` | `timestamptz` | |
Index: `contacts_qr_token_idx (qr_token)` — fast lanyard lookups.
## `events` — a conference
At most **one active event** at a time (partial unique index + trigger). The app
queries everything for the active event and handles "no active event" gracefully.
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | `gen_random_uuid()` |
| `name` | `text` | e.g. "APPE 2026" |
| `start_date` / `end_date` | `date` | |
| `location` | `text` | nullable |
| `is_active` | `boolean` | default `false` |
| `avg_feedback` | `numeric` | maintained aggregate |
| `num_sessions` | `integer` | maintained aggregate |
| `num_speakers` | `integer` | maintained aggregate |
| `num_registrations` | `integer` | maintained aggregate |
| `num_checked_in_registrations` | `integer` | maintained aggregate |
| `created_at` | `timestamptz` | |
**Constraint:** `unique index events_one_active on (is_active) where is_active`
— at most one active event. The aggregate columns are kept in sync by triggers
(counts) and the `submit_feedback` RPC (`avg_feedback`).
## `registrations` — a contact's participation in an event
Points are scoped **per event** here (one row per contact per event).
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `contact_email` | `text` FK → `contacts` | `on delete cascade` |
| `type` | `text` | `attendee` \| `speaker` \| `staff` \| `sponsor` (default `attendee`) |
| `checked_in` | `boolean` | default `false` |
| `points` | `integer` | `>= 0`, default 0 |
| `created_at` | `timestamptz` | |
**Constraint:** `unique (event_id, contact_email)` — one registration per contact
per event.
## `sponsors` — a sponsor for an event
Unpaid sponsors are hidden from non-admins (RLS).
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `type` | `text` | `headline` \| `platinum` \| `gold` \| `silver` \| `community` \| `swag` \| `catering` \| `diversity` |
| `name` | `text` | |
| `email` | `text` | nullable |
| `phone` | `text` | nullable |
| `paid` | `boolean` | default `false` — unpaid hidden from non-admins |
| `amount_eur` | `numeric` | nullable |
| `contact_email` | `text` FK → `contacts` | nullable lookup, `on delete set null` |
| `created_at` | `timestamptz` | |
## `slots` — schedule blocks
| Column | Type | Notes |
|---|---|---|
| `id` | `integer` PK | 1–6 |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `type` | `text` | `session` \| `lunch_break` \| `coffee_break` \| `keynote` \| `close_up` (default `session`) |
| `name` | `text` | e.g. "Slot 1" |
| `slot_date` | `date` | `2026-10-23` |
| `start_time` | `time` | |
| `end_time` | `time` | |
| `start_time` / `end_time` | `time` | |
## `sessions` — one per (slot, room)
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | `gen_random_uuid()` |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `slot_id` | `integer` FK → `slots` | `on delete cascade` |
| `title` | `text` | |
| `description` | `text` | nullable |
| `slot_id` | `integer` FK → `slots` | `on delete cascade` |
| `room` | `text` | "Main Stage" / "Room A" / "Room B" |
| `capacity` | `integer` | nullable (not enforced in v1) |
| `speakers` | `text` | |
| `capacity` | `integer` | nullable (not enforced) |
| `average_feedback` | `numeric` | maintained by `submit_feedback` |
| `ai_generated_feedback` | `text` | AI-feedback state (stub) |
| `material_path` | `text` | nullable — storage object path for session material |
| `created_at` | `timestamptz` | |
Index: `sessions_slot_id_idx (slot_id)`.
> **Speakers are no longer a `text` column** — they live in the `session_speakers`
> join table below (1:N). The `get_agenda()` RPC aggregates them into a
> comma-separated `speakers` string for display.
Indexes: `sessions_event_id_idx (event_id)`, `sessions_slot_id_idx (slot_id)`.
## `session_speakers` — M:N between sessions and contacts
A session must have **≥ 1 speaker** (enforced by a trigger).
| Column | Type | Notes |
|---|---|---|
| `session_id` | `uuid` FK → `sessions` | `on delete cascade` |
| `contact_email` | `text` FK → `contacts` | `on delete cascade` |
**PK:** `(session_id, contact_email)`.
## `preferences` — one pick per slot
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | |
| `profile_id` | `uuid` FK → `profiles` | |
| `session_id` | `uuid` FK → `sessions` | |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `contact_email` | `text` FK → `contacts` | `on delete cascade` |
| `session_id` | `uuid` FK → `sessions` | `on delete cascade` |
| `slot_id` | `integer` | denormalized for easy "one per slot" |
| `created_at` | `timestamptz` | |
**Constraint:** `unique (profile_id, slot_id)` — an attendee can pick at most one
session per slot. Enforced in the DB *and* by the `set_preference` RPC (which
deletes the old pick for the slot before inserting).
**Constraint:** `unique (event_id, contact_email, slot_id)` — one pick per slot.
Enforced in the DB *and* by the `set_preference` RPC (which deletes the old pick
for the slot before inserting).
## `connections` — the networking relationship
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | |
| `from_id` | `uuid` FK → `profiles` | the requester |
| `to_id` | `uuid` FK → `profiles` | the recipient |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `from_email` | `text` FK → `contacts` | the requester |
| `to_email` | `text` FK → `contacts` | the recipient |
| `status` | `text` | `pending` \| `accepted` \| `rejected` (default `pending`) |
| `created_at` | `timestamptz` | |
| `resolved_at` | `timestamptz` | set when accepted/rejected |
**Constraint:** unique per **unordered pair** via
`unique index connections_pair_uniq on (least(from_id, to_id), greatest(from_id, to_id))`.
So Ana→Bruno and Bruno→Ana are the *same* connection — a pair can only ever have
one.
**Constraint:** unique per **unordered pair per event** via
`unique index connections_pair_uniq on (event_id, least(from_email, to_email),
greatest(from_email, to_email))`. So Ana→Bruno and Bruno→Ana are the *same*
connection.
## `checkins` — staff check-in of an attendee
## `checkins` — staff check-in of a contact
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | |
| `profile_id` | `uuid` FK → `profiles` | the attendee being checked in |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `contact_email` | `text` FK → `contacts` | the attendee being checked in |
| `session_id` | `uuid` FK → `sessions` | |
| `staff_id` | `uuid` FK → `profiles` | the staff member who scanned |
| `staff_email` | `text` FK → `contacts` | the staff member who scanned |
| `created_at` | `timestamptz` | |
**Constraint:** `unique (profile_id, session_id)` — one check-in per attendee per
session (prevents double points).
**Constraint:** `unique (event_id, contact_email, session_id)` — one check-in per
contact per session (prevents double points).
## `feedback` — post-session rating
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | |
| `profile_id` | `uuid` FK → `profiles` | |
| `event_id` | `uuid` FK → `events` | `on delete cascade` |
| `contact_email` | `text` FK → `contacts` | |
| `session_id` | `uuid` FK → `sessions` | |
| `rating` | `integer` | `1–5` |
| `comment` | `text` | nullable (bonus points if present) |
| `created_at` | `timestamptz` | |
**Constraint:** `unique (profile_id, session_id)` — one feedback per attendee per
session.
**Constraint:** `unique (event_id, contact_email, session_id)` — one feedback per
contact per session.
## `leaderboard` — Realtime mirror
A public, Realtime-friendly mirror of points. **Not** the source of truth — it is
kept in sync transactionally by the RPCs (see [rpcs.md](./rpcs.md#_sync_leaderboard)).
A public, Realtime-friendly mirror of points **per event**. **Not** the source of
truth — it is kept in sync transactionally by the RPCs (see
[rpcs.md](./rpcs.md#_sync_leaderboard)).
| Column | Type | Notes |
|---|---|---|
| `profile_id` | `uuid` PK FK → `profiles` | |
| `event_id` | `uuid` PK FK → `events` | |
| `contact_email` | `text` PK FK → `contacts` | |
| `full_name` | `text` | denormalized for display |
| `company` | `text` | denormalized |
| `points` | `integer` | |
| `updated_at` | `timestamptz` | |
The app subscribes to `postgres_changes` on this table to update the leaderboard
live. See [../frontend/screens.md#leaderboard](../frontend/screens.md#leaderboard).
**PK:** `(event_id, contact_email)`. The app subscribes to `postgres_changes` on
this table to update the leaderboard live. See
[../frontend/screens.md#leaderboard](../frontend/screens.md#leaderboard).
## `points_log` — audit trail
Powers the per-category points breakdown on the Profile screen.
Powers the per-category points breakdown on the Profile screen (per event).
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | |
| `profile_id` | `uuid` FK → `profiles` | |
| `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` |
| `created_at` | `timestamptz` | |
Index: `points_log_profile_id_idx (profile_id)`.
Index: `points_log_event_id_idx (event_id)`.
## Other indexes
- `profiles_qr_token_idx (qr_token)` — fast lanyard lookups.
- `checkins_session_id_idx (session_id)`.
- `slots_event_id_idx (event_id)`, `registrations_event_id_idx (event_id)`,
`checkins_session_id_idx (session_id)`.
## Storage
A **`materials`** bucket (public read) stores session material. Speakers + admins
can write (see [rls.md](./rls.md#storage--materials-bucket)). A session's
`material_path` points at the object; the public URL is
`/storage/v1/object/public/materials/{material_path}`.
+47 -29
View File
@@ -7,12 +7,16 @@ Source of truth: [`supabase/seed.sql`](../../supabase/seed.sql). The seed runs o
| Data | Count | Notes |
|---|---|---|
| `auth.users` + `auth.identities` | 13 | 12 attendees + 1 admin; **QR token = bcrypt password** |
| `contacts` | 14 | 13 with QR tokens + 1 external keynote speaker (no token) |
| `events` | 1 | **APPE 2026**, 2026-10-23, São Paulo, Brazil, **active** |
| `registrations` | 13 | one per contact (Elena has none); points scoped here |
| `sponsors` | 3 | Nubank (headline, paid), Acme Corp (gold, paid), Globant (community, unpaid) |
| `slots` | 6 | 23 Oct, 09:00–15:45 (see table below) |
| `sessions` | 18 | 3 per slot (Main Stage / Room A / Room B) |
| `auth.users` + `auth.identities` | 13 | 12 attendees + 1 admin; **QR token = bcrypt password** |
| `profiles` | 13 | one per user, with role + starting points |
| `leaderboard` | 13 | mirrored from `profiles` |
| `points_log` | 21 | Ana's coherent breakdown + one `admin` entry per other user |
| `session_speakers` | 22 | M:N session → contact |
| `leaderboard` | 13 | mirrored from `registrations` |
| `points_log` | 16 | Ana's coherent breakdown + one `admin` entry per other user |
| Ana's demo state | — | 6 preferences, 2 check-ins, 4 connections, 1 feedback |
> **GoTrue gotcha:** manually-inserted `auth.users` must have
@@ -21,40 +25,49 @@ Source of truth: [`supabase/seed.sql`](../../supabase/seed.sql). The seed runs o
> grant can't scan a NULL `confirmation_token`. `phone` is left NULL (unique
> constraint).
> **Staff = admin (merged).** Bruno, Rita, and the APPE Admin have
> `is_admin = true` on their `contacts` row. Their registration `type` is
> `staff` (the ticket type shown on the lanyard).
## Slots
| id | Time |
|---|---|
| 1 | 09:00–09:45 |
| 2 | 10:00–10:45 |
| 3 | 11:30–12:15 |
| 4 | 13:15–14:00 |
| 5 | 14:00–14:45 |
| 6 | 15:00–15:45 |
| id | Type | Time |
|---|---|---|
| 1 | keynote | 09:00–09:45 |
| 2 | session | 10:00–10:45 |
| 3 | session | 11:30–12:15 |
| 4 | lunch_break | 13:15–14:00 |
| 5 | session | 14:00–14:45 |
| 6 | close_up | 15:00–15:45 |
## Demo accounts
Login = **QR code** (typed or scanned) + **email**. The QR token is the password.
| Person | Role | QR code | Email | Company | Start pts |
|---|---|---|---|---|---|
| **Ana Silva** | attendee | `CVV-ANA-4821` | ana.silva@nubank.com | Nubank | 40 |
| **Bruno Costa** | staff | `CVV-BRU-1177` | bruno.costa@acme.com | Acme Corp | 140 |
| **Rita Lopes** | staff | `CVV-RIT-9034` | rita.lopes@globant.com | Globant | 95 |
| **Convivo Admin** | admin | `CVV-ADM-0001` | admin@appe.at | Convivo | 0 |
| Tomás Ribeiro | attendee | `CVV-TOM-5566` | tomas.ribeiro@dataprev.com | Dataprev | 88 |
| Sofia Almeida | attendee | `CVV-SOF-2299` | sofia.almeida@loop.com | Loop | 76 |
| Marco Chen | attendee | `CVV-MRC-7712` | marco.chen@deepmind.com | DeepMind | 70 |
| Julia Santos | attendee | `CVV-JUL-3345` | julia.santos@ifood.com | iFood | 64 |
| Pedro Nunes | attendee | `CVV-PED-8801` | pedro.nunes@microsoft.com | Microsoft | 58 |
| Carla Mendes | attendee | `CVV-CAR-6623` | carla.mendes@quintoessencial.com | QuintoEssencial | 52 |
| Diego Ferreira | attendee | `CVV-DIE-4458` | diego.ferreira@stone.com | Stone | 35 |
| Marina Costa | attendee | `CVV-MNA-2210` | marina.costa@olx.com | OLX | 28 |
| Lucas Oliveira | attendee | `CVV-LUC-9987` | lucas.oliveira@usp.br | USP | 15 |
| Person | Type | QR code | Email | Start pts |
|---|---|---|---|---|
| **Ana Silva** | attendee | `CVV-ANA-4821` | ana.silva@nubank.com | 40 |
| **Bruno Costa** | staff (admin) | `CVV-BRU-1177` | bruno.costa@acme.com | 140 |
| **Rita Lopes** | staff (admin) | `CVV-RIT-9034` | rita.lopes@globant.com | 95 |
| **APPE Admin** | staff (admin) | `CVV-ADM-0001` | admin@appe.at | 0 |
| Tomás Ribeiro | attendee | `CVV-TOM-5566` | tomas.ribeiro@dataprev.com | 88 |
| Sofia Almeida | attendee | `CVV-SOF-2299` | sofia.almeida@loop.com | 76 |
| Marco Chen | attendee | `CVV-MRC-7712` | marco.chen@deepmind.com | 70 |
| Julia Santos | attendee | `CVV-JUL-3345` | julia.santos@ifood.com | 64 |
| Pedro Nunes | attendee | `CVV-PED-8801` | pedro.nunes@microsoft.com | 58 |
| Carla Mendes | attendee | `CVV-CAR-6623` | carla.mendes@quintoessencial.com | 52 |
| Diego Ferreira | attendee | `CVV-DIE-4458` | diego.ferreira@stone.com | 35 |
| Marina Costa | attendee | `CVV-MNA-2210` | marina.costa@olx.com | 28 |
| Lucas Oliveira | attendee | `CVV-LUC-9987` | lucas.oliveira@usp.br | 15 |
| Dr. Elena Vasquez | (external speaker) | — | elena.vasquez@keynote.com | — |
> **Dr. Elena Vasquez** is an external keynote speaker: she has a `contacts` row
> (and speaks in `session_speakers`) but **no QR token and no auth user**, so she
> can't log in — she only appears as a speaker on the agenda.
## Ana's demo state (so the app looks alive on first login)
Ana (id `11111111-…`) is seeded with a coherent 40-point history:
Ana (`[email protected]`) is seeded with a coherent 40-point history:
- **Points breakdown** (`points_log`): 2× check-in (+10 each), 2× connection
(+5 each), 1× feedback (+10) = **40**.
@@ -70,7 +83,10 @@ Ana (id `11111111-…`) is seeded with a coherent 40-point history:
- accepted with **Bruno** and **Rita**
- incoming (pending) from **Sofia**
- outgoing (pending) to **Julia**
- **Feedback** — rated Slot 1's *Designing for Trust in AI Products* 5★ with a comment.
- **Feedback** — rated Slot 1's *Designing for Trust in AI Products* 5★ with a
comment.
- **Speaker** — Ana is a speaker of Slot 6's *Open Space: Your Ideas* (so the
Agenda shows a "🎤 you" tag and the material-upload notice).
> Everyone else gets a single `admin` `points_log` entry for their starting points
> (so the Profile breakdown shows "Other"), and no other activity.
@@ -82,3 +98,5 @@ Ana (id `11111111-…`) is seeded with a coherent 40-point history:
3. Log in as **Bruno** (staff) → the Scan tab becomes **Check-in** → pick a
session → scan **Carla** (`CVV-CAR-6623`) → she gets +10.
4. Watch the **Leaderboard** update live (Realtime).
5. Log in as **APPE Admin** (`CVV-ADM-0001` / `[email protected]`) in the admin app
→ Dashboard, Contacts, Registrations, Sponsors, Schedule, Activity, Events.
+8 -5
View File
@@ -14,7 +14,7 @@ the "main docker" of the project.
| `supabase_auth_Convivo` | `supabase/gotrue` | Auth (QR + email login) |
| `supabase_rest_Convivo` | `supabase/postgrest` | REST API over Postgres (tables + RPCs) |
| `supabase_realtime_Convivo` | `supabase/realtime` | WebSocket realtime (leaderboard) |
| `supabase_storage_Convivo` | `supabase/storage-api` | Storage (unused in v1) |
| `supabase_storage_Convivo` | `supabase/storage-api` | Storage — the `materials` bucket (session material) |
| `supabase_kong_Convivo` | `supabase/kong` | **API gateway** — fronts everything on one port |
| `supabase_studio_Convivo` | `supabase/studio` | Web UI (Studio) |
| `supabase_inbucket_Convivo` | `supabase/mailpit` | Captures emails (none sent in this flow) |
@@ -58,10 +58,12 @@ npm run db:stop # = supabase stop
npx supabase status
```
- `db:reset` drops and recreates the database, applies
[`migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql),
then runs [`seed.sql`](../../supabase/seed.sql). Use it any time you want a
clean demo state.
- `db:reset` drops and recreates the database, applies **all** migrations in
order (`20260822000000_init.sql` → `20260823000000_admin_app.sql` →
[`20260824000000_redesign.sql`](../../supabase/migrations/20260824000000_redesign.sql),
the last of which replaces the old schema), then runs
[`seed.sql`](../../supabase/seed.sql). Use it any time you want a clean demo
state.
- Migrations and seed are **idempotent** (`on conflict ... do nothing`), so a
reset is safe to repeat.
@@ -74,6 +76,7 @@ npx supabase status
| `[db] port` | `54322` | Postgres port |
| `[studio] port` | `54323` | Studio port |
| `[auth.email] enable_confirmations` | `false` | **No email is sent** — the QR+email login never emails the user |
| `[auth] jwt_expiry` | `86400` | **24-hour login** — the session JWT lives a full day |
| `[auth] site_url` | `http://127.0.0.1:3000` | The app origin |
| `[db.seed] sql_paths` | `["./seed.sql"]` | Seed runs on reset |
+13 -11
View File
@@ -5,10 +5,10 @@ same-origin paths:
- **Attendee PWA** — a mobile-first single-page app in
[`apps/convivo/`](../../apps/convivo/). The same app for attendees, staff, and
admins — the user's `role` changes what they see (e.g. the Scan tab becomes a
Check-in tab for staff).
- **Admin console** — a desktop-first app in
[`apps/admin/`](../../apps/admin/), guarded to the `admin` role. See
admins — the user's `is_admin` flag changes what they see (e.g. the Scan tab
becomes a Check-in tab for staff).
- **Admin console (APPE Admin)** — a desktop-first app in
[`apps/admin/`](../../apps/admin/), guarded to the `is_admin` flag. See
[admin-app.md](./admin-app.md).
| File | What it covers |
@@ -38,14 +38,15 @@ apps/convivo/src/
├─ App.tsx # Providers + Shell (tab nav + Feedback takeover)
├─ styles.css # All styling (ported from mockup/index.html)
├─ context/
│ ├─ AuthContext.tsx # session + profile + signOut
│ ├─ AuthContext.tsx # session + contact + registration + signOut
│ └─ ToastContext.tsx # transient toasts
├─ lib/
│ ├─ supabase.ts # createClient (same-origin)
│ ├─ api.ts # typed wrapper over rpc/from
│ ├─ types.ts # TS types mirroring the DB
│ ├─ time.ts # event clock + slot status + formatting
│ └─ useEvent.ts # loads the agenda once, exposes it grouped
│ ├─ useEvent.ts # loads the active event + agenda, exposes it grouped
│ └─ usePolling.ts # 5s visibility-aware polling hook
├─ components/
│ └─ ui.tsx # Avatar, Spinner, Empty, Sheet, QrImage, Scanner
└─ screens/
@@ -55,15 +56,16 @@ apps/convivo/src/
## Data flow (high level)
- **Auth** — `AuthContext` holds the Supabase session + the current `Profile`.
See [app-structure.md](./app-structure.md#authcontext).
- **Event data** — `useEvent()` loads the agenda once via the `get_agenda()` RPC
and exposes it grouped by slot plus the event clock. See
- **Auth** — `AuthContext` holds the Supabase session + the current `Contact`
and `Registration`. See [app-structure.md](./app-structure.md#authcontext).
- **Event data** — `useEvent()` loads the active event + agenda via the
`get_agenda()` RPC and exposes it grouped by slot plus the event clock. See
[app-structure.md](./app-structure.md#the-event-hook-useevent).
- **Per-screen data** — each screen fetches what it needs through the typed
[api client](./api-client.md) (e.g. Home fetches preferences + check-ins).
- **Live updates** — the Leaderboard subscribes to Realtime on the `leaderboard`
table. See [screens.md#leaderboard](./screens.md#leaderboard).
table; Connections polls every 5s while the tab is visible (`usePolling`). See
[screens.md#leaderboard](./screens.md#leaderboard).
The app only ever uses the **anon key + the user's session JWT**; all security is
enforced by RLS in the database. See [../backend/rls.md](../backend/rls.md).
+52 -33
View File
@@ -1,9 +1,10 @@
# Frontend — Admin console
# Frontend — APPE Admin
The admin console is a **desktop-first single-page React app** in
[`apps/admin/`](../../apps/admin/). It is a separate app from the attendee PWA
(same stack, same Supabase core, same same-origin proxy pattern) and is **guarded
to the `admin` role** — anyone else who signs in is immediately signed out.
[`apps/admin/`](../../apps/admin/), branded **APPE Admin**. It is a separate app
from the attendee PWA (same stack, same Supabase core, same same-origin proxy
pattern) and is **guarded to the `is_admin` flag** — anyone else who signs in is
immediately signed out.
It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
(nginx). The attendee app stays on 3000.
@@ -12,18 +13,21 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
| View | Purpose |
|---|---|
| **Dashboard** | Live event stats (attendees, check-ins, connections, avg rating, sessions) + top points + recent activity. |
| **Attendees** | Searchable table of all people. Edit name/company/role, view + **reset the QR token**, and **adjust points**. |
| **Schedule** | Manage **slots** and **sessions** — create, edit, delete. |
| **Activity** | Tables of check-ins, connections, and feedback. |
| **Dashboard** | Active event card (name, dates, location, aggregates: avg feedback, #sessions, #speakers, #registrations, #checked-in) + top points + recent activity. |
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`, QR token). Edit, **reset the QR token**, toggle `is_admin`, set visibility. |
| **Registrations** | Per active event: list (contact, type, checked_in). Change type (enforces the sponsor rule), mark checked-in. |
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, contact lookup). |
| **Schedule** | Slots (with type) + sessions (with speakers 1:N, material upload, `average_feedback`, `ai_generated_feedback` + an **Evaluate** stub button). |
| **Activity** | Tables of check-ins, connections, and feedback (per active event). |
| **Events** | Create event, set active (only one), edit dates/location. |
## Auth guard
Login is the same QR + email flow as the attendee app
(`signInWithPassword({ email, password: qrToken })`), but `AuthContext` checks the
profile's `role` after signing in:
contact's `is_admin` flag after signing in:
- If `role === 'admin'` → the session is accepted and the console is shown.
- If `is_admin === true` → the session is accepted and the console is shown.
- Otherwise → the app calls `signOut()` and shows **"This account is not an
admin."** The same check runs on session restore (page reload) and on every
`onAuthStateChange`, so a non-admin can never see the console.
@@ -38,21 +42,24 @@ apps/admin/src/
├─ App.tsx # Providers + Shell (sidebar nav + view switch)
├─ styles.css # Desktop-first styling (same design tokens as the PWA)
├─ context/
│ ├─ AuthContext.tsx # session + profile + admin-role guard
│ ├─ AuthContext.tsx # session + contact + is_admin guard
│ └─ ToastContext.tsx # transient toasts
├─ lib/
│ ├─ supabase.ts # createClient (same-origin)
│ ├─ api.ts # typed wrapper: reads + updateProfile / adjustPoints / resetQrToken
│ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points)
│ └─ types.ts # TS types mirroring the DB
├─ components/
│ └─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, RoleBadge
│ └─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, TypeBadge, Toggle
├─ screens/
│ └─ Login.tsx # QR + email login (admin-only)
└─ views/
├─ Dashboard.tsx # stats + top points + recent activity
├─ Attendees.tsx # table + edit / QR-reset / points modals
├─ Schedule.tsx # slots + sessions CRUD
└─ Activity.tsx # check-ins / connections / feedback tables
├─ Dashboard.tsx # active event + aggregates + top points + activity
├─ Contacts.tsx # table + edit / QR-reset / is_admin / visibility
├─ Registrations.tsx# per-event list + type / checked-in
├─ Sponsors.tsx # sponsor CRUD
├─ Schedule.tsx # slots + sessions + speakers + material + AI-evaluate
├─ Activity.tsx # check-ins / connections / feedback tables
└─ Events.tsx # event management
```
## Data access
@@ -60,31 +67,43 @@ apps/admin/src/
The admin app uses the **anon key + the admin's session JWT** — no service-role
key. Everything it can do is allowed by RLS:
- **Reads** — admin-only `select` policies on `profiles`, `connections`,
`feedback`, `preferences`, `checkins`, `points_log`, plus the public
`slots` / `sessions` / `leaderboard`. See [../backend/rls.md](../backend/rls.md).
- **Writes** — direct `insert` / `update` / `delete` on `profiles`, `slots`, and
`sessions` (admin-only policies).
- **RPCs** — `reset_qr_token` (regenerate a lanyard token) and `adjust_points`
(manual, audited as `admin`). See [../backend/rpcs.md](../backend/rpcs.md).
- **Reads** — admin-only `select` policies on `contacts`, `registrations`,
`sponsors`, `connections`, `feedback`, `checkins`, `points_log`, plus the public
`events` / `slots` / `sessions` / `session_speakers` / `leaderboard`. See
[../backend/rls.md](../backend/rls.md).
- **Writes** — direct `insert` / `update` / `delete` on `contacts`, `events`,
`registrations`, `sponsors`, `slots`, `sessions`, and `session_speakers`
(admin-only policies).
- **RPCs** — `reset_qr_token` (regenerate a lanyard token), `adjust_points`
(manual, audited as `admin`), `upsert_contact`, `create_registration`,
`set_registration_type`, `evaluate_session_feedback` (AI stub), and
`set_session_material` (attach uploaded material). See
[../backend/rpcs.md](../backend/rpcs.md).
### Resetting a QR token
`reset_qr_token(profile_id)` generates a new `CVV-XXX-NNNN` token, writes it to
`profiles.qr_token`, **re-hashes it as the Auth password** (so the old token stops
working), and deletes the attendee's existing sessions (forcing a re-login). The
UI shows the new token as a scannable QR code.
`reset_qr_token(contact_email)` generates a new `CVV-XXX-NNNN` token, writes it to
`contacts.qr_token`, **re-hashes it as the Auth password** (so the old token stops
working), and deletes the contact's existing sessions (forcing a re-login). The UI
shows the new token as a scannable QR code.
### Adjusting points
`adjust_points(profile_id, delta, reason)` is the same transactional RPC the
`adjust_points(contact_email, delta, reason)` is the same transactional RPC the
event uses, but the `category` is `admin` so manual adjustments are auditable in
`points_log`. It keeps `profiles.points` and the `leaderboard` mirror in sync.
`points_log`. It keeps `registrations.points` and the `leaderboard` mirror in sync.
### Session material
The Schedule view uploads a session's material to the `materials` bucket and sets
`sessions.material_path` (admins can write `sessions` directly). The **Evaluate**
button calls `evaluate_session_feedback` (the AI stub) to set
`ai_generated_feedback`.
## Styling
The admin app reuses the attendee app's **design tokens** (colors, Poppins font,
card/pill/button styles) but is laid out **desktop-first**: a dark sidebar with
the nav + admin identity, and a wide content area with stat cards and data
tables. Below ~760px the sidebar collapses to a top bar so it still works on a
phone.
the **APPE / Admin** brand + nav + admin identity, and a wide content area with
stat cards and data tables. Below ~760px the sidebar collapses to a top bar so it
still works on a phone.
+33 -18
View File
@@ -25,7 +25,8 @@ export const supabase = createClient(url, anonKey, {
user's identity comes from the session JWT, and RLS enforces access. See
[../backend/rls.md](../backend/rls.md).
- **Session persistence** — the session is stored in `localStorage` and
auto-refreshed, so a reload keeps you logged in.
auto-refreshed, so a reload keeps you logged in. The JWT expiry is **24h**
(`jwt_expiry = 86400`), so a login lasts a full day.
## The typed wrapper (`lib/api.ts`)
@@ -40,9 +41,10 @@ These map 1:1 to the Postgres RPCs documented in
| Client function | RPC | Purpose |
|---|---|---|
| `lanyardLookup(qrToken)` | `lanyard_lookup` | Resolve a scanned QR to a public profile |
| `getPublicProfiles()` | `get_public_profiles` | All public profiles (leaderboard, name lookups) |
| `lanyardLookup(qrToken)` | `lanyard_lookup` | Resolve a scanned QR to a public contact + registration type |
| `getPublicContacts()` | `get_public_contacts` | Active-event contact directory (names + types) |
| `getAgenda()` | `get_agenda` | Slots + sessions (flat rows) |
| `getActiveEvent()` | `get_active_event` | The active event row |
| `setPreference(sessionId)` | `set_preference` | Pick a session for its slot |
| `clearPreference(slotId)` | `clear_preference` | Remove a pick |
| `createConnectionRequest(targetQr)` | `create_connection_request` | Send a connection request |
@@ -50,32 +52,41 @@ These map 1:1 to the Postgres RPCs documented in
| `rejectConnection(id)` | `reject_connection` | Decline |
| `checkinAttendee(sessionId, attendeeQr)` | `checkin_attendee` | Staff check-in (+10) |
| `submitFeedback(sessionId, rating, comment)` | `submit_feedback` | Rate a session (+5/+10) |
| `getLeaderboard()` | `get_leaderboard` | Active-event leaderboard |
| `uploadSessionMaterial(sessionId, file)` | `set_session_material` | Upload to `materials` bucket + set `material_path` |
### Direct table reads (RLS-scoped)
These read the caller's own rows (RLS returns only what the user may see):
These read the caller's own rows (RLS returns only what the user may see). For an
admin contact, RLS returns **all** rows, so the "my" reads filter by email
client-side to avoid leaking other people's data:
| Client function | Table | Returns |
|---|---|---|
| `getMyContact(email)` | `contacts` | the caller's contact |
| `getMyRegistration(email)` | `registrations` | the caller's registration (active event) |
| `getMyPreferences()` | `preferences` | the caller's picks |
| `getMyConnections()` | `connections` | connections the caller is in |
| `getMyCheckins()` | `checkins` | the caller's checked-in session ids |
| `getMyFeedback()` | `feedback` | the caller's feedback |
| `getLeaderboard()` | `leaderboard` | all rows (public to authenticated) |
| `getMyPointsLog()` | `points_log` | the caller's points history |
| `getMyCheckins(email)` | `checkins` | the caller's checked-in session ids |
| `getMyFeedback(email)` | `feedback` | the caller's feedback |
| `getMyPointsLog(email)` | `points_log` | the caller's points history |
| `getMySpeakerSessions(email)` | `session_speakers` | session ids the caller speaks |
### Helpers
- **`groupAgenda(rows)`** — turns the flat `get_agenda()` rows into
`{ slot, sessions[] }[]` ordered by slot id. Used by `useEvent()`.
- **`sessionMaterialUrl(path)`** — builds the public URL for a session material
in the `materials` bucket.
## Types (`lib/types.ts`)
TypeScript interfaces mirroring the DB tables and RPC return shapes
(`Profile`, `PublicProfile`, `Slot`, `Session`, `AgendaRow`, `Preference`,
`Connection`, `Checkin`, `Feedback`, `LeaderboardRow`, `PointsLogRow`,
`CheckinResult`, `FeedbackResult`). `PublicProfile` is the safe projection
(no email / qr_token) returned by the public read functions.
(`Contact`, `Registration`, `Event`, `Slot`, `Session`, `AgendaRow`,
`Preference`, `Connection`, `Checkin`, `Feedback`, `LeaderboardRow`,
`PointsLogRow`, `PublicContact`, `CheckinResult`, `FeedbackResult`).
`PublicContact` is the safe projection (email + name + visibility-respected
linkedin + registration type) returned by the public read functions.
## Error handling
@@ -83,11 +94,15 @@ TypeScript interfaces mirroring the DB tables and RPC return shapes
- Screens catch errors and surface them via toasts
(`useToast().toast(message, 'err')`). RPCs raise human-readable messages
(e.g. "staff or admin only", "you must be checked in to this session to give
feedback") — see [../backend/rpcs.md#error-handling](../backend/rpcs.md#error-handling).
feedback", "not a speaker of this session") — see
[../backend/rpcs.md#error-handling](../backend/rpcs.md#error-handling).
## Realtime
## Realtime + polling
The only realtime subscription is on the `leaderboard` table (see
[screens.md#leaderboard](./screens.md#leaderboard)). The `leaderboard` table is
the Realtime source and is kept in sync transactionally by the RPCs — see
[../backend/schema.md#leaderboard--realtime-mirror](../backend/schema.md#leaderboard--realtime-mirror).
- **Realtime** — the only realtime subscription is on the `leaderboard` table
(see [screens.md#leaderboard](./screens.md#leaderboard)). The `leaderboard`
table is the Realtime source and is kept in sync transactionally by the RPCs —
see [../backend/schema.md#leaderboard--realtime-mirror](../backend/schema.md#leaderboard--realtime-mirror).
- **Polling** — Connections and the Shell's pending-connection red dot use
`usePolling` (5s, visibility-aware) — see
[app-structure.md#the-polling-hook-libusepollingts](./app-structure.md#the-polling-hook-libusepollingts).
+27 -13
View File
@@ -23,18 +23,22 @@ see [api-client.md](./api-client.md).
## AuthContext (`context/AuthContext.tsx`)
Holds the Supabase **session**, the current **`Profile`**, and a `loading` flag.
Holds the Supabase **session**, the current **`Contact`**, the current
**`Registration`**, and a `loading` flag.
- On mount, reads the persisted session (`supabase.auth.getSession()`) and loads
the profile for that user id.
the contact + registration for that user's email.
- Subscribes to `onAuthStateChange` so login/logout anywhere updates the context.
- `loadProfile(userId)` fetches `profiles` where `id = userId` (RLS returns only
the caller's own row — see [../backend/rls.md](../backend/rls.md)).
- Exposes: `session`, `user`, `profile`, `loading`, `refreshProfile()`, `signOut()`.
- `loadContact(email)` fetches `contacts` where `email = email` (RLS returns only
the caller's own row — see [../backend/rls.md](../backend/rls.md));
`loadRegistration(email)` fetches the caller's `registrations` row for the
active event.
- Exposes: `session`, `user`, `contact`, `registration`, `loading`,
`refresh()`, `signOut()`.
> The profile is the app's source of truth for the current user's `role` and
> `points`. After any points-changing action, screens call `refreshProfile()` to
> re-fetch.
> The contact is the app's source of truth for the current user's `is_admin`
> (staff powers) and `qr_token`; the registration holds the user's `type` and
> `points`. After any points-changing action, screens re-fetch.
## ToastContext (`context/ToastContext.tsx`)
@@ -43,21 +47,24 @@ Used for login success, connection results, check-in results, and RPC errors.
## The event hook (`lib/useEvent.ts`)
Loads the agenda **once** and exposes it in a convenient shape:
Loads the active event + agenda and exposes it in a convenient shape:
```ts
interface EventData {
event: Event | null; // the active event (name, dates, location)
slots: { slot: Slot; sessions: Session[] }[]; // grouped, ordered by slot id
sessionById: Map<string, Session>;
slotById: Map<number, Slot>;
now: Date; // the (simulated) event clock
loading: boolean;
error: string | null;
reload: () => void; // re-fetch (e.g. after a material upload)
}
```
- Calls `getAgenda()` (the `get_agenda()` RPC) and groups the flat rows with
`groupAgenda()` (see [api-client.md](./api-client.md)).
`groupAgenda()` (see [api-client.md](./api-client.md)); also loads the active
event via `getActiveEvent()`.
- Every screen that needs the schedule calls `useEvent()` — the agenda is fetched
per screen mount (cheap, and keeps each screen self-contained).
@@ -84,6 +91,13 @@ At `10:20`, **Slot 1 (09:00–09:45) is `done`** and **Slot 2 (10:00–10:45) is
> clock just decides which slot is "live" for display. To use the real clock,
> replace `DEFAULT_NOW` with `new Date()`.
## The polling hook (`lib/usePolling.ts`)
`usePolling(fn, ms, enabled)` runs `fn` every `ms` milliseconds, but **only while
the tab is visible** (`document.visibilityState === 'visible'`), and re-runs
immediately when the tab becomes visible again. No background polling. Used by
the Connections screen (5s) and the Shell's pending-connection red dot (5s).
## The Shell (`App.tsx`)
The `Shell` is the navigation container. Render logic, in order:
@@ -100,11 +114,11 @@ The `Shell` is the navigation container. Render logic, in order:
| `home` | 🏠 Home | `Home` | default tab |
| `agenda` | 📅 Agenda | `Agenda` | |
| `scan` | 📷 **Scan** / **Check-in** | `Scan` | label is role-aware (below) |
| `connections` | 🤝 Connect | `Connections` | |
| `connections` | 🤝 Connect | `Connections` | red dot when there are pending incoming requests |
| `profile` | 👤 Profile | `Profile` | |
- **Role-aware Scan tab:** if `profile.role` is `staff` or `admin`, the tab label
is **"Check-in"** and the `Scan` screen defaults to staff mode. Otherwise it's
- **Role-aware Scan tab:** if `contact.is_admin` is true, the tab label is
**"Check-in"** and the `Scan` screen defaults to staff mode. Otherwise it's
**"Scan"**.
- **Leaderboard** is *not* a tab — it's reached from the Home points pill and the
Home quick-actions. It renders as a tab in the shell but is opened via
+49 -34
View File
@@ -4,7 +4,7 @@ Every screen in [`apps/convivo/src/screens/`](../../apps/convivo/src/screens/).
All screens are mobile-first and use the shared UI components
([app-structure.md#shared-ui-components](./app-structure.md#shared-ui-components)).
Data comes from the typed [api client](./api-client.md); the current user comes
from `useAuth()`.
from `useAuth()` (`contact` + `registration`).
| Screen | File | Reach |
|---|---|---|
@@ -21,9 +21,10 @@ from `useAuth()`.
A 3-step flow: **splash → scan → confirm**.
1. **Splash** — "Convivo / Break the ice. Earn the points." Tap anywhere to continue.
1. **Splash** — "APPE / Break the ice. Earn the points." Tap anywhere to continue.
2. **Scan** — scan (or type) your lanyard QR. Calls `lanyardLookup(qrToken)` to
resolve the attendee (pre-login, public). Shows the resolved name/company.
resolve the contact (pre-login, public). Shows the resolved name + registration
type badge.
3. **Confirm** — enter the **email used to buy the ticket**, then
`signInWithPassword({ email, password: qrToken })`. On success the
`AuthContext` updates and the Shell renders the app. On mismatch, an error is
@@ -37,41 +38,54 @@ A 3-step flow: **splash → scan → confirm**.
The landing screen. Shows:
- **Greeting + points pill** — "Good morning, Ana 👋" and `⚡ {points}` (tapping
the pill opens the Leaderboard).
the pill opens the Leaderboard). The event name (`event.name`) is shown under
the greeting.
- **Now card** — the session the user picked for the current slot, with a
"✓ Checked in" or "Show your QR to staff to check in" pill.
- **Next card** — the pick for the next slot.
- **My picks today** — the user's pick per slot (tap to change → opens Agenda).
- **Quick actions** — Scan & connect, Agenda, Connections, Leaderboard.
- **Quick actions** — Scan & connect / Check-in, Agenda, Connections, Leaderboard.
- **No active event** — a graceful empty state ("No active event right now.
Check back soon!").
Data: `useEvent()` (agenda + clock) + `getMyPreferences()` + `getMyCheckins()`.
Slot status comes from `slotStatus(slot, now)` ([app-structure.md#the-event-clock](./app-structure.md#the-event-clock)).
Data: `useEvent()` (event + agenda + clock) + `getMyPreferences()` +
`getMyCheckins(email)`. Slot status comes from `slotStatus(slot, now)`
([app-structure.md#the-event-clock](./app-structure.md#the-event-clock)).
## Agenda
Lists all 6 slots, each with its 3 sessions and a status pill (**Done / ● Live /
Up next**). The user's pick per slot is highlighted (filled check).
Lists all slots, each with its sessions, a **slot-type badge** (keynote / session
/ lunch break / coffee break / close up), and a status pill (**Done / ● Live /
Up next**). The user's pick per slot is highlighted (filled check). A session the
user speaks shows a **"🎤 you"** tag; a session with material shows a **📎**.
- **Tap a session** → opens a bottom **sheet** with details (description, speaker,
room, capacity, checked-in state) and actions:
- **Tap a session** → opens a bottom **sheet** with details (description,
speakers, room, capacity, checked-in state) and actions:
- **Give feedback ⭐** — only when the session is *done* **and** the user is
checked in. Opens the Feedback takeover (`openFeedback(sessionId)`).
- **Pick / Remove my pick** — `setPreference(sessionId)` / `clearPreference(slotId)`.
- **Speaker material** — if the user is a speaker of the session and no material
is uploaded yet, a **non-dismissible** "📎 Upload your session material" notice
with a file input. Uploading stores the file in the `materials` bucket and
calls `set_session_material` (via `uploadSessionMaterial`). Once uploaded, the
notice is gone and a **📎 Download material** link appears (visible to **all**
attendees).
- Picking is "one per slot" — picking a new session in a slot replaces the old
pick (enforced by the `set_preference` RPC).
Data: `useEvent()` + `getMyPreferences()` + `getMyCheckins()`.
Data: `useEvent()` + `getMyPreferences()` + `getMyCheckins(email)` +
`getMySpeakerSessions(email)`.
## Scan / Check-in
One screen, two modes (segmented control: **Attendee / Staff**). The default mode
and the tab label are role-aware: staff/admin default to **Staff** mode and the
tab reads **Check-in**.
and the tab label are role-aware: staff (`contact.is_admin`) default to **Staff**
mode and the tab reads **Check-in**.
- **Attendee mode (connect):** scan a peer's lanyard → `lanyardLookup` → a
"Connect with {name}?" sheet → `createConnectionRequest(qr)`. Guards: can't
connect with yourself. Result toast reflects the connection status (sent /
already connected).
"Connect with {name}?" sheet (with the peer's registration-type badge + LinkedIn
link if visible) → `createConnectionRequest(qr)`. Guards: can't connect with
yourself. Result toast reflects the connection status (sent / already connected).
- **Staff mode (check-in):** pick a session (dropdown grouped by slot), then scan
an attendee's lanyard → `checkinAttendee(sessionId, qr)`. Shows a result sheet:
"✓ {name} — Checked in — +10 pts · now {total}" or "⚠️ Already checked in — no
@@ -83,13 +97,16 @@ Data: `useEvent()` (for the session list) + the RPCs above.
Two tabs: **My connections** and **Requests** (with a count badge).
- **My connections** — accepted connections (the other person's name/company).
- **Requests** — incoming (`to_id = me`, pending) with **Accept / Decline**
buttons (`acceptConnection` / `rejectConnection`), and outgoing (`from_id = me`,
pending) shown as "Sent".
- Accepting awards +5 to both (see [../backend/rpcs.md#accept_connectionp_connection_id--connections](../backend/rpcs.md#accept_connectionp_connection_id--connections)).
- **My connections** — accepted connections (the other person's name +
registration type).
- **Requests** — incoming (`to_email = me`, pending) with **Accept / Decline**
buttons (`acceptConnection` / `rejectConnection`), and outgoing (`from_email =
me`, pending) shown as "Sent".
- Accepting awards +5 to both (see
[../backend/rpcs.md#accept_connectionp_connection_id--connections](../backend/rpcs.md#accept_connectionp_connection_id--connections)).
- **Live-ish:** polls every 5s while the tab is visible (`usePolling`).
Data: `getMyConnections()` + `getPublicProfiles()` (to resolve names/companies).
Data: `getMyConnections()` + `getPublicContacts()` (to resolve names + types).
## Feedback
@@ -97,13 +114,10 @@ A **full-screen takeover** (no tab bar), opened from the Agenda session sheet.
- Shows the session (slot · time · room · title).
- **1–5 star** rating + optional comment ("bonus points for details").
- If the user already rated this session, it pre-fills and the button reads
**"Update feedback"** (the RPC updates without re-awarding points).
- On submit: `submitFeedback(sessionId, rating, comment)` → `refreshProfile()` →
a success card ("+N pts earned!" or "Feedback updated!").
- On submit: `submitFeedback(sessionId, rating, comment)` → a success toast
("+N pts ⭐").
Data: `useEvent()` (session/slot) + `getMyFeedback()` (to detect existing) +
`submitFeedback`.
Data: `useEvent()` (session/slot) + `submitFeedback`.
## Leaderboard
@@ -122,17 +136,18 @@ supabase.channel('leaderboard-live')
.subscribe();
```
Data: `getLeaderboard()` (initial + on each realtime event). The `leaderboard`
table is kept in sync transactionally by the RPCs — see
Data: `getLeaderboard()` (the `get_leaderboard()` RPC — initial + on each realtime
event). The `leaderboard` table is kept in sync transactionally by the RPCs — see
[../backend/schema.md#leaderboard--realtime-mirror](../backend/schema.md#leaderboard--realtime-mirror).
## Profile
- **Header** — avatar, name, company, role pill, points pill.
- **My QR code** — renders `profile.qr_token` as a scannable QR (`QrImage`).
- **Header** — avatar, name, email, registration-type pill, a **staff** pill when
`contact.is_admin`, and a points pill.
- **My QR code** — renders `contact.qr_token` as a scannable QR (`QrImage`).
"Show this to staff for check-in and to peers to connect."
- **Points breakdown** — sums `points_log` by category
(Session check-ins / Connections / Feedback / Other) + Total.
- **Log out** — `signOut()`.
Data: `useAuth()` (profile) + `getMyPointsLog()`.
Data: `useAuth()` (contact + registration) + `getMyPointsLog(email)`.
+19 -14
View File
@@ -4,15 +4,16 @@ What's done, what's next, and the open decisions. The full roadmap lives in the
root [`roadmap.md`](../roadmap.md); this file is the working detail for the
current phase.
> **Current state:** Phases 0–2 are complete and verified. The project is now in
> the **Redesign** (Phases 3–6), driven by a new multi-event data model. We work
> through the redesign phase by phase and stop for review at the end of each.
> **Current state:** Phases 0–6 are complete and verified, including the full
> **Redesign** (Phases 3–6) on the new multi-event data model. The next work is
> the **Pretix** (Phase 7) and **Sessionize** (Phase 8) interfaces.
## Done
### Phase 0 — Dockerized Supabase core ✅
- Full schema (9 tables), RLS on every table, transactional points RPCs.
- Seed: 6 slots, 18 sessions, 13 demo users (QR token = auth password).
- Full schema (13 tables), RLS on every table, transactional points RPCs.
- Seed: 1 event, 6 slots, 18 sessions, 14 contacts, 13 registrations, 3 sponsors
(QR token = auth password).
- Runs via the Supabase CLI (`supabase start` / `supabase db reset`).
- Details: [backend/README.md](./backend/README.md).
@@ -40,11 +41,15 @@ A separate desktop-first web app on :3001, guarded to the admin role.
- Details: [frontend/admin-app.md](./frontend/admin-app.md).
> **Note:** Phases 0–2 built the `profiles`-based single-event model. Phase 3
> **replaces** that schema.
> **replaced** that schema; Phase 4 rebuilt this console on the new model and
> rebranded it to **APPE Admin**.
## The Redesign (Phases 3–6)
## The Redesign (Phases 3–6) — ✅ complete
### Phase 3 — Data model 🔨 (in progress)
All four redesign phases are done and browser-verified. The specs below are kept
as the record of what was built.
### Phase 3 — Data model ✅
A new migration (`20260824000000_redesign.sql`) + seed rewrite. The `profiles`
table is dropped; everything is re-scoped to **event + contact**.
@@ -95,9 +100,9 @@ table is dropped; everything is re-scoped to **event + contact**.
- New `materials` storage bucket (read for event attendees, write for
speakers/admins).
### Phase 4 — APPE Admin ⬜
Rebrand "Convivo Admin" → **APPE Admin** (title, sidebar, manifest, docs) and
rebuild the views on the new model:
### Phase 4 — APPE Admin ✅
Rebranded "Convivo Admin" → **APPE Admin** (title, sidebar, manifest, docs) and
rebuilt the views on the new model:
- **Dashboard** — active event card (name, dates, location, aggregates) + top
points + recent activity; graceful "no active event".
- **Contacts** — table (email, name, LinkedIn, visibility toggles, `is_admin`,
@@ -112,7 +117,7 @@ rebuild the views on the new model:
- **Event management** — create event, set active (only one), edit
dates/location.
### Phase 5 — Convivo App ⬜
### Phase 5 — Convivo App ✅
- **Login ≥24h** — `jwt_expiry` = 86400 in `config.toml`; session persists in
localStorage.
- **5s visibility-aware polling** — poll schedule/connections/points every 5s
@@ -129,9 +134,9 @@ rebuild the views on the new model:
- **Browser-accessible** — responsive layout works in a desktop browser.
- **No active event** — graceful empty state.
### Phase 6 — Branding ⬜
### Phase 6 — Branding ✅
- `https://www.appe.at/assets/appe_full.png` as favicon + PWA icon (192/512)
for **both** apps. Update `index.html` + `manifest.webmanifest` + `public/`.
for **both** apps. Updated `index.html` + `manifest.webmanifest` + `public/`.
## Later (post-redesign)
+10 -8
View File
@@ -3,13 +3,15 @@
Living roadmap. The top section is the **current focus**; completed phases are
summarized below. For *how* each piece works, see [`docs/`](./docs/README.md).
> **Status:** Phases 0–2 are complete and verified. The project is now in the
> **Redesign** (Phases 3–6), driven by a new multi-event data model. We work
> through the redesign phase by phase and stop for review at the end of each.
> **Status:** Phases 0–6 are complete and verified. The **Redesign** (Phases
> 3–6) is done: the new multi-event data model is live, the admin app is
> rebranded to **APPE Admin**, the Convivo App has all the new behaviors, and
> both apps carry the APPE branding. Next up: the Pretix + Sessionize
> interfaces (Phases 7–8).
---
## Current focus — the Redesign (Phases 3–6)
## Current focus — the Redesign (Phases 3–6) ✅ DONE
A new data model replaces the single-event `profiles` schema with a
**multi-event** model, the admin app is rebranded to **APPE Admin**, and the
@@ -18,10 +20,10 @@ Convivo App gains several behaviors. Details live in
| Phase | Scope | Status |
|---|---|---|
| **3** | **Data model** — `contacts` (email PK), `events` (one active), `registrations` (per ticket), `sponsors`; slot types; session speakers (1:N); session `average_feedback` / `ai_generated_feedback` / `material`; activity tables re-scoped to event + contact; drop `profiles`; new RPCs + RLS + `materials` bucket | 🔨 in progress |
| **4** | **APPE Admin** — rebrand + new views: Dashboard (active event + aggregates), Contacts, Registrations, Sponsors, Schedule (slots/sessions/speakers/material/AI-evaluate), Activity, event management | ⬜ |
| **5** | **Convivo App** — 24h login, 5s visibility-aware polling, staff-only check-in, QR type badge, pending-connection red dot, speaker material upload/download, graceful "no active event" | ⬜ |
| **6** | **Branding** — `appe_full.png` as favicon + PWA icon for both apps | ⬜ |
| **3** | **Data model** — `contacts` (email PK), `events` (one active), `registrations` (per ticket), `sponsors`; slot types; session speakers (1:N); session `average_feedback` / `ai_generated_feedback` / `material`; activity tables re-scoped to event + contact; drop `profiles`; new RPCs + RLS + `materials` bucket | ✅ |
| **4** | **APPE Admin** — rebrand + new views: Dashboard (active event + aggregates), Contacts, Registrations, Sponsors, Schedule (slots/sessions/speakers/material/AI-evaluate), Activity, event management | ✅ |
| **5** | **Convivo App** — 24h login, 5s visibility-aware polling, staff-only check-in, QR type badge, pending-connection red dot, speaker material upload/download, graceful "no active event" | ✅ |
| **6** | **Branding** — `appe_full.png` as favicon + PWA icon for both apps | ✅ |
### Redesign decisions (locked)
- **Staff = admin (merged).** A contact has `is_admin` + a QR token (its login
+1 -1
View File
@@ -162,7 +162,7 @@ site_url = "http://127.0.0.1:3000"
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
additional_redirect_urls = ["https://127.0.0.1:3000"]
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
jwt_expiry = 3600
jwt_expiry = 86400
# JWT issuer URL. If not set, defaults to auth.external_url.
# jwt_issuer = ""
# Path to JWT signing key. DO NOT commit your signing keys file to git.
File diff suppressed because it is too large. Load diff
+188 -109
View File
@@ -1,50 +1,20 @@
-- =============================================================================
-- Convivo — Phase 0: seed data
-- Ports the mockup's slots/sessions/people into real Supabase Auth users + rows.
-- Convivo — Phase 3 (Redesign): seed data for the multi-event model
--
-- Ports the mockup's people/schedule into the new model:
-- contacts (PK = email) / events / registrations / sponsors / slots /
-- sessions / session_speakers / preferences / connections / checkins /
-- feedback / leaderboard / points_log.
--
-- The QR token is the Auth password (QR + email login, no email sent).
-- Staff is merged into admin: Bruno, Rita, and the APPE Admin have is_admin.
-- =============================================================================
-- -----------------------------------------------------------------------------
-- SLOTS (23 Oct)
-- -----------------------------------------------------------------------------
insert into public.slots (id, name, slot_date, start_time, end_time) values
(1, 'Slot 1', '2026-10-23', '09:00:00', '09:45:00'),
(2, 'Slot 2', '2026-10-23', '10:00:00', '10:45:00'),
(3, 'Slot 3', '2026-10-23', '11:30:00', '12:15:00'),
(4, 'Slot 4', '2026-10-23', '13:15:00', '14:00:00'),
(5, 'Slot 5', '2026-10-23', '14:00:00', '14:45:00'),
(6, 'Slot 6', '2026-10-23', '15:00:00', '15:45:00')
on conflict (id) do nothing;
-- -----------------------------------------------------------------------------
-- SESSIONS (18 — 3 per slot)
-- -----------------------------------------------------------------------------
insert into public.sessions (id, title, description, slot_id, room, capacity, speakers) values
('10000000-0000-0000-0000-000000000001', 'Opening Keynote: The Next Decade of AI', 'A wide-angle look at where AI is heading over the next ten years — and what it means for product teams.', 1, 'Main Stage', 300, 'Dr. Elena Vasquez'),
('10000000-0000-0000-0000-000000000002', 'Designing for Trust in AI Products', 'Practical patterns for making AI features transparent, explainable, and safe for your users.', 1, 'Room A', 80, 'Marco Chen'),
('10000000-0000-0000-0000-000000000003', 'From Hackathon to Product', 'How a weekend prototype became a product with 40k users — the messy middle included.', 1, 'Room B', 60, 'Sofia Almeida'),
('10000000-0000-0000-0000-000000000004', 'AI in Practice: Lessons from Production', 'Lessons learned shipping LLM features to production: latency, cost, evals, and the surprises.', 2, 'Main Stage', 300, 'Bruno Costa'),
('10000000-0000-0000-0000-000000000005', 'The Introvert''s Guide to Networking', 'Small, low-energy ways to have big conversations at any event. (Yes, this one is for you.)', 2, 'Room A', 80, 'Rita Lopes'),
('10000000-0000-0000-0000-000000000006', 'Building with Dataverse: Beyond the Basics', 'Go beyond the basics: relationships, security roles, and automations that actually scale.', 2, 'Room B', 60, 'Tomás Ribeiro'),
('10000000-0000-0000-0000-000000000007', 'Scaling Teams at 10x', 'What breaks when you grow 10x in two years, and the rituals that kept us sane.', 3, 'Main Stage', 300, 'Julia Santos'),
('10000000-0000-0000-0000-000000000008', 'Security by Design', 'Baking security into the product from day one instead of bolting it on at the end.', 3, 'Room A', 80, 'Pedro Nunes'),
('10000000-0000-0000-0000-000000000009', 'Data Storytelling', 'Turn dashboards into narratives your stakeholders actually remember.', 3, 'Room B', 60, 'Carla Mendes'),
('10000000-0000-0000-0000-000000000010', 'The Future of Work', 'Hybrid, async, and AI-augmented: where work is going and how to prepare for it.', 4, 'Main Stage', 300, 'Dr. Elena Vasquez'),
('10000000-0000-0000-0000-000000000011', 'Prototyping with AI', 'From idea to clickable prototype in an afternoon — tools and workflows that work.', 4, 'Room A', 80, 'Diego Ferreira'),
('10000000-0000-0000-0000-000000000012', 'Pricing SaaS in 2026', 'Usage-based, seat-based, or hybrid? What is actually working right now.', 4, 'Room B', 60, 'Marina Costa'),
('10000000-0000-0000-0000-000000000013', 'Community-Led Growth', 'Building a community that sells for you — case studies and playbooks.', 5, 'Main Stage', 300, 'Lucas Oliveira'),
('10000000-0000-0000-0000-000000000014', 'Accessibility First', 'Why accessible products are better products, and how to start this sprint.', 5, 'Room A', 80, 'Carla Mendes'),
('10000000-0000-0000-0000-000000000015', 'The Art of the Demo', 'Structure, pacing, and the moments that make a demo land.', 5, 'Room B', 60, 'Pedro Nunes'),
('10000000-0000-0000-0000-000000000016', 'Closing Panel: What''s Next', 'Founders, researchers, and builders on what comes next — with audience Q&A.', 6, 'Main Stage', 300, 'Elena · Bruno · Rita'),
('10000000-0000-0000-0000-000000000017', 'Open Space: Your Ideas', 'You bring the topic, we bring the room. 45 minutes of your ideas.', 6, 'Room A', 80, 'Facilitated by Ana Silva'),
('10000000-0000-0000-0000-000000000018', 'Lightning Talks', 'Eight speakers, five minutes each. Fast, fun, and unpredictable.', 6, 'Room B', 60, '8 speakers')
on conflict (id) do nothing;
-- -----------------------------------------------------------------------------
-- AUTH USERS (QR token = password). 12 attendees + 1 admin.
-- -----------------------------------------------------------------------------
-- NOTE: confirmation_token is set to '' (not NULL) because GoTrue's password
-- grant cannot scan a NULL confirmation_token on manually-inserted users.
-- -----------------------------------------------------------------------------
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', '11111111-1111-1111-1111-111111111111', 'authenticated', 'authenticated', '[email protected]', crypt('CVV-ANA-4821', gen_salt('bf')), now(), '', '', '', '', '{"provider":"email","providers":["email"]}', '{"full_name":"Ana Silva"}', now(), now(), now(), now()),
('00000000-0000-0000-0000-000000000000', '22222222-2222-2222-2222-222222222222', 'authenticated', 'authenticated', '[email protected]', crypt('CVV-BRU-1177', gen_salt('bf')), now(), '', '', '', '', '{"provider":"email","providers":["email"]}', '{"full_name":"Bruno Costa"}', now(), now(), now(), now()),
@@ -58,7 +28,7 @@ insert into auth.users (instance_id, id, aud, role, email, encrypted_password, e
('00000000-0000-0000-0000-000000000000', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'authenticated', 'authenticated', '[email protected]', crypt('CVV-DIE-4458', gen_salt('bf')), now(), '', '', '', '', '{"provider":"email","providers":["email"]}', '{"full_name":"Diego Ferreira"}', now(), now(), now(), now()),
('00000000-0000-0000-0000-000000000000', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'authenticated', 'authenticated', '[email protected]', crypt('CVV-MNA-2210', gen_salt('bf')), now(), '', '', '', '', '{"provider":"email","providers":["email"]}', '{"full_name":"Marina Costa"}', now(), now(), now(), now()),
('00000000-0000-0000-0000-000000000000', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'authenticated', 'authenticated', '[email protected]', crypt('CVV-LUC-9987', gen_salt('bf')), now(), '', '', '', '', '{"provider":"email","providers":["email"]}', '{"full_name":"Lucas Oliveira"}', now(), now(), now(), now()),
('00000000-0000-0000-0000-000000000000', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'authenticated', 'authenticated', '[email protected]', crypt('CVV-ADM-0001', gen_salt('bf')), now(), '', '', '', '', '{"provider":"email","providers":["email"]}', '{"full_name":"Convivo Admin"}', now(), now(), now(), now())
('00000000-0000-0000-0000-000000000000', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'authenticated', 'authenticated', '[email protected]', crypt('CVV-ADM-0001', gen_salt('bf')), now(), '', '', '', '', '{"provider":"email","providers":["email"]}', '{"full_name":"APPE Admin"}', now(), now(), now(), now())
on conflict (id) do nothing;
insert into auth.identities (id, provider_id, identity_data, provider, user_id, created_at, updated_at, last_sign_in_at) values
@@ -78,83 +48,192 @@ insert into auth.identities (id, provider_id, identity_data, provider, user_id,
on conflict (id) do nothing;
-- -----------------------------------------------------------------------------
-- PROFILES
-- CONTACTS (PK = email). Mirrors auth.users.
-- Staff is merged into admin: Bruno, Rita, and the APPE Admin have is_admin.
-- Dr. Elena Vasquez is an external keynote speaker (no QR token / auth user).
-- -----------------------------------------------------------------------------
insert into public.profiles (id, email, full_name, company, role, qr_token, points) values
('11111111-1111-1111-1111-111111111111', '[email protected]', 'Ana Silva', 'Nubank', 'attendee', 'CVV-ANA-4821', 40),
('22222222-2222-2222-2222-222222222222', '[email protected]', 'Bruno Costa', 'Acme Corp', 'staff', 'CVV-BRU-1177', 140),
('33333333-3333-3333-3333-333333333333', '[email protected]', 'Rita Lopes', 'Globant', 'staff', 'CVV-RIT-9034', 95),
('44444444-4444-4444-4444-444444444444', '[email protected]', 'Tomás Ribeiro', 'Dataprev', 'attendee', 'CVV-TOM-5566', 88),
('55555555-5555-5555-5555-555555555555', '[email protected]', 'Sofia Almeida', 'Loop', 'attendee', 'CVV-SOF-2299', 76),
('66666666-6666-6666-6666-666666666666', '[email protected]', 'Marco Chen', 'DeepMind', 'attendee', 'CVV-MRC-7712', 70),
('77777777-7777-7777-7777-777777777777', '[email protected]', 'Julia Santos', 'iFood', 'attendee', 'CVV-JUL-3345', 64),
('88888888-8888-8888-8888-888888888888', '[email protected]', 'Pedro Nunes', 'Microsoft', 'attendee', 'CVV-PED-8801', 58),
('99999999-9999-9999-9999-999999999999', '[email protected]', 'Carla Mendes', 'QuintoEssencial', 'attendee', 'CVV-CAR-6623', 52),
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Diego Ferreira', 'Stone', 'attendee', 'CVV-DIE-4458', 35),
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '[email protected]', 'Marina Costa', 'OLX', 'attendee', 'CVV-MNA-2210', 28),
('cccccccc-cccc-cccc-cccc-cccccccccccc', '[email protected]', 'Lucas Oliveira', 'USP', 'attendee', 'CVV-LUC-9987', 15),
('dddddddd-dddd-dddd-dddd-dddddddddddd', '[email protected]', 'Convivo Admin', 'Convivo', 'admin', 'CVV-ADM-0001', 0)
insert into public.contacts (email, full_name, linkedin_url, show_email, show_linkedin, is_admin, qr_token) values
('[email protected]', 'Ana Silva', 'https://linkedin.com/in/anasilva', true, true, false, 'CVV-ANA-4821'),
('[email protected]', 'Bruno Costa', 'https://linkedin.com/in/brunocosta', false, true, true, 'CVV-BRU-1177'),
('[email protected]', 'Rita Lopes', null, false, false, true, 'CVV-RIT-9034'),
('[email protected]','Tomás Ribeiro', null, false, false, false, 'CVV-TOM-5566'),
('[email protected]', 'Sofia Almeida', null, false, false, false, 'CVV-SOF-2299'),
('[email protected]', 'Marco Chen', null, false, false, false, 'CVV-MRC-7712'),
('[email protected]', 'Julia Santos', null, false, false, false, 'CVV-JUL-3345'),
('[email protected]', 'Pedro Nunes', null, false, false, false, 'CVV-PED-8801'),
('[email protected]', 'Carla Mendes', null, false, false, false, 'CVV-CAR-6623'),
('[email protected]', 'Diego Ferreira', null, false, false, false, 'CVV-DIE-4458'),
('[email protected]', 'Marina Costa', null, false, false, false, 'CVV-MNA-2210'),
('[email protected]', 'Lucas Oliveira', null, false, false, false, 'CVV-LUC-9987'),
('[email protected]', 'APPE Admin', null, false, false, true, 'CVV-ADM-0001'),
('[email protected]', 'Dr. Elena Vasquez', null, false, false, false, null)
on conflict (email) do nothing;
-- -----------------------------------------------------------------------------
-- EVENT (single active event)
-- -----------------------------------------------------------------------------
insert into public.events (id, name, start_date, end_date, location, is_active) values
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'APPE 2026', '2026-10-23', '2026-10-23', 'São Paulo, Brazil', true)
on conflict (id) do nothing;
-- -----------------------------------------------------------------------------
-- LEADERBOARD (mirror of points)
-- REGISTRATIONS (per event). Points scoped here.
-- Ana is checked in (has check-ins below).
-- -----------------------------------------------------------------------------
insert into public.leaderboard (profile_id, full_name, company, points)
select id, full_name, company, points from public.profiles
on conflict (profile_id) do update
set full_name = excluded.full_name, company = excluded.company, points = excluded.points, updated_at = now();
insert into public.registrations (event_id, contact_email, type, checked_in, points) values
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', true, 40),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'staff', false, 140),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'staff', false, 95),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]','attendee', false, 88),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 76),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 70),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 64),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 58),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 52),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 35),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 28),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'attendee', false, 15),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'staff', false, 0)
on conflict (event_id, contact_email) do nothing;
-- -----------------------------------------------------------------------------
-- SPONSORS (2 paid, 1 unpaid — unpaid is hidden from non-admins via RLS)
-- -----------------------------------------------------------------------------
insert into public.sponsors (event_id, type, name, email, phone, paid, amount_eur, contact_email) values
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'headline', 'Nubank', '[email protected]', '+55 11 4000-0000', true, 50000, '[email protected]'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'gold', 'Acme Corp', '[email protected]', '+55 11 4000-0001', true, 20000, '[email protected]'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'community','Globant', '[email protected]', '+55 11 4000-0002', false, 0, '[email protected]')
on conflict do nothing;
-- -----------------------------------------------------------------------------
-- SLOTS (23 Oct). Slot 1 done, Slot 2 live (simulated clock).
-- -----------------------------------------------------------------------------
insert into public.slots (id, event_id, type, name, slot_date, start_time, end_time) values
(1, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'keynote', 'Slot 1', '2026-10-23', '09:00:00', '09:45:00'),
(2, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'session', 'Slot 2', '2026-10-23', '10:00:00', '10:45:00'),
(3, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'session', 'Slot 3', '2026-10-23', '11:30:00', '12:15:00'),
(4, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'lunch_break', 'Slot 4', '2026-10-23', '13:15:00', '14:00:00'),
(5, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'session', 'Slot 5', '2026-10-23', '14:00:00', '14:45:00'),
(6, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'close_up', 'Slot 6', '2026-10-23', '15:00:00', '15:45:00')
on conflict (id) do nothing;
-- -----------------------------------------------------------------------------
-- SESSIONS (18 — 3 per slot)
-- -----------------------------------------------------------------------------
insert into public.sessions (id, event_id, slot_id, title, description, room, capacity) values
('10000000-0000-0000-0000-000000000001', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 1, 'Opening Keynote: The Next Decade of AI', 'A wide-angle look at where AI is heading over the next ten years — and what it means for product teams.', 'Main Stage', 300),
('10000000-0000-0000-0000-000000000002', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 1, 'Designing for Trust in AI Products', 'Practical patterns for making AI features transparent, explainable, and safe for your users.', 'Room A', 80),
('10000000-0000-0000-0000-000000000003', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 1, 'From Hackathon to Product', 'How a weekend prototype became a product with 40k users — the messy middle included.', 'Room B', 60),
('10000000-0000-0000-0000-000000000004', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 2, 'AI in Practice: Lessons from Production', 'Lessons learned shipping LLM features to production: latency, cost, evals, and the surprises.', 'Main Stage', 300),
('10000000-0000-0000-0000-000000000005', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 2, 'The Introvert''s Guide to Networking', 'Small, low-energy ways to have big conversations at any event. (Yes, this one is for you.)', 'Room A', 80),
('10000000-0000-0000-0000-000000000006', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 2, 'Building with Dataverse: Beyond the Basics', 'Go beyond the basics: relationships, security roles, and automations that actually scale.', 'Room B', 60),
('10000000-0000-0000-0000-000000000007', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 3, 'Scaling Teams at 10x', 'What breaks when you grow 10x in two years, and the rituals that kept us sane.', 'Main Stage', 300),
('10000000-0000-0000-0000-000000000008', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 3, 'Security by Design', 'Baking security into the product from day one instead of bolting it on at the end.', 'Room A', 80),
('10000000-0000-0000-0000-000000000009', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 3, 'Data Storytelling', 'Turn dashboards into narratives your stakeholders actually remember.', 'Room B', 60),
('10000000-0000-0000-0000-000000000010', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 4, 'The Future of Work', 'Hybrid, async, and AI-augmented: where work is going and how to prepare for it.', 'Main Stage', 300),
('10000000-0000-0000-0000-000000000011', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 4, 'Prototyping with AI', 'From idea to clickable prototype in an afternoon — tools and workflows that work.', 'Room A', 80),
('10000000-0000-0000-0000-000000000012', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 4, 'Pricing SaaS in 2026', 'Usage-based, seat-based, or hybrid? What is actually working right now.', 'Room B', 60),
('10000000-0000-0000-0000-000000000013', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 5, 'Community-Led Growth', 'Building a community that sells for you — case studies and playbooks.', 'Main Stage', 300),
('10000000-0000-0000-0000-000000000014', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 5, 'Accessibility First', 'Why accessible products are better products, and how to start this sprint.', 'Room A', 80),
('10000000-0000-0000-0000-000000000015', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 5, 'The Art of the Demo', 'Structure, pacing, and the moments that make a demo land.', 'Room B', 60),
('10000000-0000-0000-0000-000000000016', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 6, 'Closing Panel: What''s Next', 'Founders, researchers, and builders on what comes next — with audience Q&A.', 'Main Stage', 300),
('10000000-0000-0000-0000-000000000017', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 6, 'Open Space: Your Ideas', 'You bring the topic, we bring the room. 45 minutes of your ideas.', 'Room A', 80),
('10000000-0000-0000-0000-000000000018', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 6, 'Lightning Talks', 'Eight speakers, five minutes each. Fast, fun, and unpredictable.', 'Room B', 60)
on conflict (id) do nothing;
-- -----------------------------------------------------------------------------
-- SESSION SPEAKERS (M:N). Every session has >= 1 speaker.
-- -----------------------------------------------------------------------------
insert into public.session_speakers (session_id, contact_email) values
('10000000-0000-0000-0000-000000000001', '[email protected]'),
('10000000-0000-0000-0000-000000000002', '[email protected]'),
('10000000-0000-0000-0000-000000000003', '[email protected]'),
('10000000-0000-0000-0000-000000000004', '[email protected]'),
('10000000-0000-0000-0000-000000000005', '[email protected]'),
('10000000-0000-0000-0000-000000000006', '[email protected]'),
('10000000-0000-0000-0000-000000000007', '[email protected]'),
('10000000-0000-0000-0000-000000000008', '[email protected]'),
('10000000-0000-0000-0000-000000000009', '[email protected]'),
('10000000-0000-0000-0000-000000000010', '[email protected]'),
('10000000-0000-0000-0000-000000000011', '[email protected]'),
('10000000-0000-0000-0000-000000000012', '[email protected]'),
('10000000-0000-0000-0000-000000000013', '[email protected]'),
('10000000-0000-0000-0000-000000000014', '[email protected]'),
('10000000-0000-0000-0000-000000000015', '[email protected]'),
('10000000-0000-0000-0000-000000000016', '[email protected]'),
('10000000-0000-0000-0000-000000000016', '[email protected]'),
('10000000-0000-0000-0000-000000000016', '[email protected]'),
('10000000-0000-0000-0000-000000000017', '[email protected]'),
('10000000-0000-0000-0000-000000000018', '[email protected]'),
('10000000-0000-0000-0000-000000000018', '[email protected]'),
('10000000-0000-0000-0000-000000000018', '[email protected]')
on conflict (session_id, contact_email) do nothing;
-- s2 has a comment from Ana → AI feedback is pending evaluation.
update public.sessions set ai_generated_feedback = 'Pending AI Evaluation'
where id = '10000000-0000-0000-0000-000000000002';
-- -----------------------------------------------------------------------------
-- ANA'S DEMO STATE (so the app looks alive on first login)
-- -----------------------------------------------------------------------------
-- Preferences: one pick per slot (matches the mockup).
insert into public.preferences (event_id, contact_email, session_id, slot_id) values
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000002', 1),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000004', 2),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000009', 3),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000011', 4),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000013', 5),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000016', 6)
on conflict (event_id, contact_email, slot_id) do nothing;
-- Check-ins: Ana is checked into Slot 1 (s2) and Slot 2 (s4), by staff Bruno.
insert into public.checkins (event_id, contact_email, session_id, staff_email) values
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000002', '[email protected]'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000004', '[email protected]')
on conflict (event_id, contact_email, session_id) do nothing;
-- Connections: accepted with Bruno & Rita; incoming from Sofia; outgoing to Julia.
insert into public.connections (id, event_id, from_email, to_email, status, created_at, resolved_at) values
('e0000000-0000-0000-0000-000000000001', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '[email protected]', 'accepted', now() - interval '2 hours', now() - interval '2 hours'),
('e0000000-0000-0000-0000-000000000002', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '[email protected]', 'accepted', now() - interval '90 minutes', now() - interval '90 minutes'),
('e0000000-0000-0000-0000-000000000003', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '[email protected]', 'pending', now() - interval '15 minutes', null),
('e0000000-0000-0000-0000-000000000004', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '[email protected]', 'pending', now() - interval '5 minutes', null)
on conflict (id) do nothing;
-- Feedback: Ana rated Slot 1 (s2).
insert into public.feedback (event_id, contact_email, session_id, rating, comment) values
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', '10000000-0000-0000-0000-000000000002', 5, 'Great patterns, very practical. Wish it were longer!')
on conflict (event_id, contact_email, session_id) do nothing;
-- -----------------------------------------------------------------------------
-- LEADERBOARD (mirror of registration points, per event)
-- -----------------------------------------------------------------------------
insert into public.leaderboard (event_id, contact_email, full_name, points)
select r.event_id, r.contact_email, c.full_name, r.points
from public.registrations r
join public.contacts c on c.email = r.contact_email
on conflict (event_id, contact_email) do update
set full_name = excluded.full_name, points = excluded.points, updated_at = now();
-- -----------------------------------------------------------------------------
-- POINTS LOG
-- Ana: a coherent breakdown (2 checkins, 2 connections, 1 feedback = 40).
-- Everyone else: a single 'admin' seed entry for their starting points.
-- -----------------------------------------------------------------------------
insert into public.points_log (profile_id, delta, category) values
('11111111-1111-1111-1111-111111111111', 10, 'checkin'),
('11111111-1111-1111-1111-111111111111', 10, 'checkin'),
('11111111-1111-1111-1111-111111111111', 5, 'connection'),
('11111111-1111-1111-1111-111111111111', 5, 'connection'),
('11111111-1111-1111-1111-111111111111', 10, 'feedback'),
('22222222-2222-2222-2222-222222222222', 140, 'admin'),
('33333333-3333-3333-3333-333333333333', 95, 'admin'),
('44444444-4444-4444-4444-444444444444', 88, 'admin'),
('55555555-5555-5555-5555-555555555555', 76, 'admin'),
('66666666-6666-6666-6666-666666666666', 70, 'admin'),
('77777777-7777-7777-7777-777777777777', 64, 'admin'),
('88888888-8888-8888-8888-888888888888', 58, 'admin'),
('99999999-9999-9999-9999-999999999999', 52, 'admin'),
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 35, 'admin'),
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 28, 'admin'),
('cccccccc-cccc-cccc-cccc-cccccccccccc', 15, 'admin');
-- -----------------------------------------------------------------------------
-- ANA'S DEMO STATE (so the app looks alive on first login)
-- -----------------------------------------------------------------------------
-- Preferences: one pick per slot (matches the mockup).
insert into public.preferences (profile_id, session_id, slot_id) values
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000002', 1),
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000004', 2),
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000009', 3),
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000011', 4),
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000013', 5),
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000016', 6)
on conflict (profile_id, slot_id) do nothing;
-- Check-ins: Ana is checked into Slot 1 (s2) and Slot 2 (s4), by staff Bruno.
insert into public.checkins (profile_id, session_id, staff_id) values
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000002', '22222222-2222-2222-2222-222222222222'),
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000004', '22222222-2222-2222-2222-222222222222')
on conflict (profile_id, session_id) do nothing;
-- Connections: accepted with Bruno & Rita; incoming from Sofia; outgoing to Julia.
insert into public.connections (id, from_id, to_id, status, created_at, resolved_at) values
('e0000000-0000-0000-0000-000000000001', '11111111-1111-1111-1111-111111111111', '22222222-2222-2222-2222-222222222222', 'accepted', now() - interval '2 hours', now() - interval '2 hours'),
('e0000000-0000-0000-0000-000000000002', '33333333-3333-3333-3333-333333333333', '11111111-1111-1111-1111-111111111111', 'accepted', now() - interval '90 minutes', now() - interval '90 minutes'),
('e0000000-0000-0000-0000-000000000003', '55555555-5555-5555-5555-555555555555', '11111111-1111-1111-1111-111111111111', 'pending', now() - interval '15 minutes', null),
('e0000000-0000-0000-0000-000000000004', '11111111-1111-1111-1111-111111111111', '77777777-7777-7777-7777-777777777777', 'pending', now() - interval '5 minutes', null)
on conflict (id) do nothing;
-- Feedback: Ana rated Slot 1 (s2).
insert into public.feedback (profile_id, session_id, rating, comment) values
('11111111-1111-1111-1111-111111111111', '10000000-0000-0000-0000-000000000002', 5, 'Great patterns, very practical. Wish it were longer!')
on conflict (profile_id, session_id) do nothing;
insert into public.points_log (event_id, contact_email, delta, category) values
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 10, 'checkin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 10, 'checkin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 5, 'connection'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 5, 'connection'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 10, 'feedback'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 140, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 95, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 88, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 76, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 70, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 64, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 58, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 52, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 35, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 28, 'admin'),
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 15, 'admin');