Phase 2: Admin console (admin.appe.at)

A desktop-first React app for organizers, guarded to the admin role.

Backend (supabase/migrations/20260823000000_admin_app.sql):
- Admin-only SELECT policies on preferences, connections, feedback
- reset_qr_token RPC: regenerates a lanyard token, re-hashes it as the
  Auth password (old token stops working), and clears the attendee's
  sessions to force re-login

App (apps/admin, port 3001):
- Login: same QR+email flow, but non-admin sessions are rejected
- Dashboard: live stats + top points + recent activity
- Attendees: search, edit name/company/role, reset QR, adjust points
- Schedule: manage slots + sessions (create/edit/delete)
- Activity: check-ins / connections / feedback tables
- Same-origin proxy (Vite dev / nginx in Docker), same design tokens

Docker + scripts:
- convivo-admin service in docker-compose.yml (:3001)
- admin:dev / admin:build root scripts
- fixed db:reset script (supabase reset -> supabase db reset)

Docs: new frontend/admin-app.md; updated architecture, rls, rpcs,
docker, next-steps, and READMEs.

Verified: build clean, all views + flows browser-tested, Docker build +
proxy + login + admin guard confirmed. DB reset to clean seed.
This commit is contained in:
Lago committed 2026-08-22 19:47:22 +02:00
1 parent 0cbfb25714
commit cf70f39903
45 files changed
+4425 -87

No files matched your search

+3
View File
@@ -24,3 +24,6 @@ npm-debug.log*
Thumbs.db Thumbs.db
.vscode/ .vscode/
.idea/ .idea/
# Browser test artifacts
.playwright-mcp/
+16 -12
View File
@@ -2,11 +2,12 @@
**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. **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:** Phase 0 + Phase 1 complete. > **Status:** Phase 0 + Phase 1 + Phase 2 complete.
> - **Phase 0** — Dockerized Supabase core (Postgres + GoTrue + PostgREST + Realtime + Kong + Studio) with the full schema, RLS, and transactional points RPCs. > - **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 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.
> >
> Next: Phase 2 (Admin app), Phase 3 (Pretix ticketing interface), Phase 4 (Sessionize interface). > Next: Phase 3 (Pretix ticketing interface), Phase 4 (Sessionize interface).
--- ---
@@ -43,7 +44,7 @@ The schedule is **data-driven** (stored in Postgres), so times and sessions can
|---|---| |---|---|
| **Attendee** | Log in, view agenda, mark preferences, scan peers to connect, get checked in, give feedback, view leaderboard | | **Attendee** | Log in, view agenda, mark preferences, scan peers to connect, get checked in, give feedback, view leaderboard |
| **Staff** | Everything an attendee can do, **plus** a Check-in mode: pick a session, scan attendee lanyards to check them in | | **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 future Admin app) | | **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 an attribute on the profile and changes the Scan tab into a Check-in tab.
@@ -197,20 +198,21 @@ npm run db:start
# 2. (Re)apply migrations + seed, then restart the stack # 2. (Re)apply migrations + seed, then restart the stack
npm run db:reset npm run db:reset
# 3. Run the app (Vite dev server on :3000, proxies to the core) # 3. Run the apps (Vite dev servers, proxy to the core)
npm run app:dev npm run app:dev # attendee app on :3000
npm run admin:dev # admin console on :3001
``` ```
Open **http://localhost:3000**. Studio is at **http://localhost:54323** (user `postgres`, password `postgres`). Open **http://localhost:3000** (attendee) and **http://localhost:3001** (admin). Studio is at **http://localhost:54323** (user `postgres`, password `postgres`).
### Option B — Docker (app as a sidecar) ### Option B — Docker (apps as sidecars)
```bash ```bash
# 1. Start the Supabase core (creates the supabase_network_Convivo network) # 1. Start the Supabase core (creates the supabase_network_Convivo network)
npm run db:start npm run db:start
# 2. Build + run the app container on :3000 (joins the Supabase network) # 2. Build + run both app containers (joins the Supabase network)
docker compose up --build docker compose up --build
``` ```
Open **http://localhost:3000**. The app's nginx proxies the Supabase paths to the Kong container on the shared network. Open **http://localhost:3000** (attendee) and **http://localhost:3001** (admin). Each app's nginx proxies the Supabase paths to the Kong container on the shared network.
> **Reset the demo data at any time:** `npm run db:reset` (re-applies migrations + seed). > **Reset the demo data at any time:** `npm run db:reset` (re-applies migrations + seed).
@@ -218,7 +220,8 @@ Open **http://localhost:3000**. The app's nginx proxies the Supabase paths to th
| Service | Port | | Service | Port |
|---|---| |---|---|
| Convivo app | **3000** | | Convivo app (attendee) | **3000** |
| Convivo admin | **3001** |
| Supabase API (Kong) | 54321 | | Supabase API (Kong) | 54321 |
| Supabase Studio | 54323 | | Supabase Studio | 54323 |
| Postgres | 54322 | | Postgres | 54322 |
@@ -249,6 +252,7 @@ Login = **QR code** (typed or scanned) + **email**. The QR token is the password
2. Scan **Marco** (`CVV-MRC-7712`) → send a connection request. 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. 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. 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.
## 13. Roadmap ## 13. Roadmap
@@ -256,8 +260,8 @@ Login = **QR code** (typed or scanned) + **email**. The QR token is the password
|---|---|---| |---|---|---|
| **0** | Dockerized Supabase core: schema, RLS, transactional points RPCs, seed | ✅ | | **0** | Dockerized Supabase core: schema, RLS, transactional points RPCs, seed | ✅ |
| **1** | Attendee web PWA: login, Home, Agenda, Scan/Connect, Check-in, Feedback, Leaderboard, Profile | ✅ | | **1** | Attendee web PWA: login, Home, Agenda, Scan/Connect, Check-in, Feedback, Leaderboard, Profile | ✅ |
| **2** | **Admin app** (admin.appe.at) — manage attendees, sessions, points, event | ⬜ next | | **2** | **Admin app** (admin.appe.at) — manage attendees, sessions, points, event | ✅ |
| **3** | **Pretix** interface — sync tickets → attendees (QR tokens, roles) | ⬜ | | **3** | **Pretix** interface — sync tickets → attendees (QR tokens, roles) | ⬜ next |
| **4** | **Sessionize** interface — sync the real agenda (slots, sessions, speakers) | ⬜ | | **4** | **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. > **Subdomains** (`convivo.appe.at`, `admin.appe.at`, `db.appe.at`, `pretix.eu`, `sessionize.com`) do not exist yet — everything runs on **localhost** for now.
+13
View File
@@ -0,0 +1,13 @@
# Keep the Docker build context small and avoid leaking local state.
# NOTE: nginx.conf.template and docker-entrypoint.sh are COPYed by the
# Dockerfile, so they must NOT be excluded here.
node_modules
dist
.env
.env.*
!.env.example
*.tsbuildinfo
.git
.gitignore
Dockerfile
.dockerignore
+9
View File
@@ -0,0 +1,9 @@
# Convivo Admin — Supabase local stack.
#
# Same-origin paths (/auth, /rest, /realtime, /storage) are proxied to the local
# Supabase stack (Vite dev server in dev, nginx in Docker). So no URL is needed —
# the client falls back to window.location.origin. Only the anon key is required.
#
# VITE_SUPABASE_URL is intentionally left unset (same-origin).
# The value below is the standard local Supabase anon key (not a secret).
VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
+35
View File
@@ -0,0 +1,35 @@
# Convivo Admin app — multi-stage build.
#
# Stage 1 (build): compile the Vite/React/TS app into static assets.
# Stage 2 (serve): nginx serves the static build and proxies the Supabase
# same-origin paths (/auth, /rest, /realtime, /storage) to the Supabase core.
#
# The Supabase core itself is NOT built here — it runs via the Supabase CLI
# (`supabase start`) or as a separate container. See the root docker-compose.yml.
# ---- Build stage -------------------------------------------------------------
FROM node:20-alpine AS build
WORKDIR /app
# Install deps first for better layer caching (reproducible via lock file).
COPY package.json package-lock.json ./
RUN npm ci
# Copy sources and build. The anon key is baked in at build time (it is not a
# secret — it is the standard local Supabase anon key). Override with
# --build-arg VITE_SUPABASE_ANON_KEY=... if you use a custom key.
ARG VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
ENV VITE_SUPABASE_ANON_KEY=$VITE_SUPABASE_ANON_KEY
COPY . .
RUN npm run build
# ---- Serve stage -------------------------------------------------------------
FROM nginx:1.27-alpine AS serve
# nginx template: serve the SPA + proxy Supabase paths to the core. The proxy
# target is injected at container start (see docker-entrypoint.sh).
COPY nginx.conf.template /etc/nginx/conf.d/default.conf.template
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 3001
ENTRYPOINT ["/docker-entrypoint.sh"]
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Convivo Admin app — container entrypoint.
#
# Injects the Supabase proxy target into the nginx config template, then starts
# nginx. The target defaults to the Kong container on the shared Supabase
# network (supabase_kong_Convivo:8000 — Kong's internal port; 54321 is the
# host-only mapping). Override with SUPABASE_PROXY_TARGET
# (e.g. host.docker.internal:54321) if the core is not on the shared network.
set -eu
TARGET="${SUPABASE_PROXY_TARGET:-supabase_kong_Convivo:8000}"
TEMPLATE=/etc/nginx/conf.d/default.conf.template
CONF=/etc/nginx/conf.d/default.conf
echo "[convivo-admin] Proxying Supabase paths to: ${TARGET}"
sed "s|__SUPABASE_PROXY_TARGET__|${TARGET}|g" "${TEMPLATE}" > "${CONF}"
# Run nginx in the foreground.
exec nginx -g "daemon off;"
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<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." />
<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>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+77
View File
@@ -0,0 +1,77 @@
# Convivo Admin app — nginx server block (template).
#
# Serves the built SPA and proxies the Supabase same-origin paths
# (/auth, /rest, /realtime, /storage) to the Supabase core.
#
# The proxy target is injected at container start by /docker-entrypoint.sh
# from the SUPABASE_PROXY_TARGET env var (default: supabase_kong_Convivo:8000,
# i.e. the Kong container on the shared Supabase network — Kong's internal port).
#
# The placeholder __SUPABASE_PROXY_TARGET__ is replaced before nginx starts.
server {
listen 3001;
server_name _;
root /usr/share/nginx/html;
index index.html;
gzip on;
gzip_types text/plain text/css application/json application/javascript image/svg+xml;
# SPA fallback: any non-file, non-proxied route serves index.html so the
# client-side router can take over.
location / {
try_files $uri $uri/ /index.html;
}
# Long-cache immutable build assets.
location /assets/ {
expires 30d;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
# ---- Supabase same-origin proxy -------------------------------------
# No trailing slash on proxy_pass => the original URI is passed through
# unchanged (e.g. /auth/v1/token -> http://<target>/auth/v1/token).
location /auth/ {
proxy_pass http://__SUPABASE_PROXY_TARGET__;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /rest/ {
proxy_pass http://__SUPABASE_PROXY_TARGET__;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Realtime uses WebSockets — enable the upgrade handshake.
location /realtime/ {
proxy_pass http://__SUPABASE_PROXY_TARGET__;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
location /storage/ {
proxy_pass http://__SUPABASE_PROXY_TARGET__;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 50M;
}
}
+1910
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@convivo/admin",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@supabase/supabase-js": "^2.45.4",
"qrcode.react": "^4.0.1",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"typescript": "^5.5.4",
"vite": "^5.4.8"
}
}
+10
View File
@@ -0,0 +1,10 @@
<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>

After

Width:  |  Height:  |  Size: 455 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

+13
View File
@@ -0,0 +1,13 @@
{
"name": "Convivo Admin",
"short_name": "Convivo Admin",
"description": "Manage attendees, schedule, and points for the Convivo event.",
"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" }
]
}
+95
View File
@@ -0,0 +1,95 @@
import { useState } from 'react';
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 { Schedule } from './views/Schedule';
import { Activity } from './views/Activity';
import { Spinner } from './components/ui';
type View = 'dashboard' | 'attendees' | 'schedule' | 'activity';
const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'dashboard', label: 'Dashboard', ico: '📊' },
{ id: 'attendees', label: 'Attendees', ico: '👥' },
{ id: 'schedule', label: 'Schedule', ico: '🗓️' },
{ id: 'activity', label: 'Activity', ico: '⚡' },
];
function Shell() {
const { profile, loading, signOut } = useAuth();
const [view, setView] = useState<View>('dashboard');
if (loading) {
return (
<div className="loading-screen">
<Spinner />
</div>
);
}
if (!profile) return <Login />;
return (
<div className="app">
<aside className="sidebar">
<div className="brand">
<div className="logo">C</div>
<div>
<div className="name">Convivo</div>
<div className="sub">Admin Console</div>
</div>
</div>
<nav className="nav">
{NAV.map((n) => (
<button
key={n.id}
className={`nav-item ${view === n.id ? 'active' : ''}`}
onClick={() => setView(n.id)}
>
<span className="ico">{n.ico}</span>
{n.label}
</button>
))}
</nav>
<div className="sidebar-foot">
<div className="admin-card">
<span className="avatar" style={{ width: 36, height: 36, fontSize: 13, background: '#d50000' }}>
{profile.full_name
.split(' ')
.map((w) => w[0])
.slice(0, 2)
.join('')
.toUpperCase()}
</span>
<div className="who">
<div className="n">{profile.full_name}</div>
<div className="e">{profile.email}</div>
</div>
</div>
<button className="signout" onClick={signOut}>
Sign out
</button>
</div>
</aside>
<main className="content">
{view === 'dashboard' && <Dashboard onNavigate={setView} />}
{view === 'attendees' && <Attendees />}
{view === 'schedule' && <Schedule />}
{view === 'activity' && <Activity />}
</main>
</div>
);
}
export function App() {
return (
<ToastProvider>
<AuthProvider>
<Shell />
</AuthProvider>
</ToastProvider>
);
}
+85
View File
@@ -0,0 +1,85 @@
import { type ReactNode } from 'react';
import { QRCodeSVG } from 'qrcode.react';
const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777'];
export function initials(name: string): string {
return name
.split(' ')
.map((w) => w[0])
.slice(0, 2)
.join('')
.toUpperCase();
}
export function avColor(seed: string): string {
let h = 0;
for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;
return AV_COLORS[h % AV_COLORS.length];
}
export function Avatar({ name, id, size = 40, fs = 14 }: { name: string; id: string; size?: number; fs?: number }) {
return (
<span className="avatar" style={{ width: size, height: size, fontSize: fs, background: avColor(id) }}>
{initials(name)}
</span>
);
}
export function Spinner() {
return <span className="spinner" />;
}
export function Empty({ icon, text }: { icon: string; text: string }) {
return (
<div className="empty">
<div className="big">{icon}</div>
{text}
</div>
);
}
/** Centered modal dialog (desktop-first). */
export function Modal({
open,
onClose,
title,
children,
footer,
}: {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
footer?: ReactNode;
}) {
if (!open) return null;
return (
<div className="backdrop" onClick={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal" role="dialog" aria-modal="true" aria-label={title}>
<div className="modal-head">
<h3>{title}</h3>
<button className="icon-btn" onClick={onClose} aria-label="Close">
✕
</button>
</div>
<div className="modal-body">{children}</div>
{footer && <div className="modal-foot">{footer}</div>}
</div>
</div>
);
}
/** Render a string (e.g. a QR token) as a scannable QR code. */
export function QrImage({ value, size = 180 }: { value: string; size?: number }) {
return (
<div className="qr-frame">
<QRCodeSVG value={value} size={size} level="M" marginSize={0} />
</div>
);
}
/** Small colored badge for a role. */
export function RoleBadge({ role }: { role: string }) {
return <span className={`pill pill-${role}`}>{role}</span>;
}
+108
View File
@@ -0,0 +1,108 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { supabase } from '../lib/supabase';
import type { Profile } from '../lib/types';
interface AuthState {
profile: Profile | null;
loading: boolean;
signIn: (email: string, qrToken: string) => Promise<void>;
signOut: () => Promise<void>;
}
const AuthContext = createContext<AuthState | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [profile, setProfile] = useState<Profile | null>(null);
const [loading, setLoading] = useState(true);
// On mount: restore any existing session and load the profile. If the
// session belongs to a non-admin, sign out immediately (admin-only app).
useEffect(() => {
let cancelled = false;
async function init() {
const { data } = await supabase.auth.getSession();
const session = data.session;
if (!session) {
if (!cancelled) setLoading(false);
return;
}
const { data: prof } = await supabase
.from('profiles')
.select('*')
.eq('id', session.user.id)
.maybeSingle();
if (cancelled) return;
if (prof && prof.role === 'admin') {
setProfile(prof as Profile);
} else {
// Not an admin — clear the session.
await supabase.auth.signOut();
}
setLoading(false);
}
init();
const { data: sub } = supabase.auth.onAuthStateChange(async (_event, session) => {
if (!session) {
setProfile(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);
} else {
await supabase.auth.signOut();
setProfile(null);
}
});
return () => {
cancelled = true;
sub.subscription.unsubscribe();
};
}, []);
async function signIn(email: string, qrToken: string) {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password: qrToken,
});
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') {
// 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);
}
async function signOut() {
await supabase.auth.signOut();
setProfile(null);
}
return (
<AuthContext.Provider value={{ profile, loading, signIn, signOut }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthState {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
}
+53
View File
@@ -0,0 +1,53 @@
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react';
type ToastKind = 'success' | 'error' | 'info';
interface Toast {
id: number;
kind: ToastKind;
message: string;
}
interface ToastState {
toasts: Toast[];
push: (kind: ToastKind, message: string) => void;
dismiss: (id: number) => void;
}
const ToastContext = createContext<ToastState | null>(null);
let nextId = 1;
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const dismiss = useCallback((id: number) => {
setToasts((t) => t.filter((x) => x.id !== id));
}, []);
const push = useCallback(
(kind: ToastKind, message: string) => {
const id = nextId++;
setToasts((t) => [...t, { id, kind, message }]);
window.setTimeout(() => dismiss(id), 3800);
},
[dismiss],
);
return (
<ToastContext.Provider value={{ toasts, push, dismiss }}>
{children}
<div className="toast-stack" role="status" aria-live="polite">
{toasts.map((t) => (
<div key={t.id} className={`toast toast-${t.kind}`} onClick={() => dismiss(t.id)}>
{t.message}
</div>
))}
</div>
</ToastContext.Provider>
);
}
export function useToast(): ToastState {
const ctx = useContext(ToastContext);
if (!ctx) throw new Error('useToast must be used within ToastProvider');
return ctx;
}
+61
View File
@@ -0,0 +1,61 @@
import { supabase } from './supabase';
import type {
Checkin,
Connection,
Feedback,
LeaderboardRow,
PointsLogRow,
Profile,
ResetQrResult,
Session,
Slot,
} from './types';
export class ApiError extends Error {}
async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
const { data, error } = await supabase.rpc(fn, args);
if (error) throw new ApiError(error.message);
return data as T;
}
async function all<T>(table: string, order?: { col: string; asc?: boolean }): Promise<T[]> {
let q = supabase.from(table).select('*');
if (order) q = q.order(order.col, { ascending: order.asc ?? true });
const { data, error } = await q;
if (error) throw new ApiError(error.message);
return data as T[];
}
// ---- 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 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) ----------------------------------------------------
/** 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'] },
): Promise<void> {
const { error } = await supabase.from('profiles').update(patch).eq('id', id);
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 });
return rows[0];
}
+22
View File
@@ -0,0 +1,22 @@
import { createClient } from '@supabase/supabase-js';
// The app talks to Supabase through same-origin paths (/auth, /rest, /realtime,
// /storage). In dev the Vite server proxies them to the local Supabase stack;
// in Docker the app's nginx does the same. This avoids CORS entirely.
const url = import.meta.env.VITE_SUPABASE_URL || window.location.origin;
const anonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
if (!anonKey) {
console.warn('[convivo-admin] VITE_SUPABASE_ANON_KEY is not set.');
}
export const supabase = createClient(url, anonKey, {
auth: {
persistSession: true,
autoRefreshToken: true,
detectSessionInUrl: false,
},
realtime: {
params: { eventsPerSecond: 10 },
},
});
+80
View File
@@ -0,0 +1,80 @@
export type Role = 'attendee' | 'staff' | 'admin';
export interface Profile {
id: string;
email: string;
full_name: string;
company: string | null;
role: Role;
qr_token: string | null;
points: number;
created_at: string;
}
export interface Slot {
id: number;
name: string;
slot_date: string;
start_time: string;
end_time: string;
}
export interface Session {
id: string;
title: string;
description: string | null;
slot_id: number;
room: string | null;
capacity: number | null;
speakers: string | null;
created_at: string;
}
export type ConnectionStatus = 'pending' | 'accepted' | 'rejected';
export interface Connection {
id: string;
from_id: string;
to_id: string;
status: ConnectionStatus;
created_at: string;
resolved_at: string | null;
}
export interface Checkin {
id: string;
profile_id: string;
session_id: string;
staff_id: string;
created_at: string;
}
export interface Feedback {
id: string;
profile_id: string;
session_id: string;
rating: number;
comment: string | null;
created_at: string;
}
export interface LeaderboardRow {
profile_id: string;
full_name: string;
company: string | null;
points: number;
updated_at: string;
}
export interface PointsLogRow {
id: string;
profile_id: string;
delta: number;
category: 'checkin' | 'connection' | 'feedback' | 'admin';
created_at: string;
}
export interface ResetQrResult {
profile_id: string;
qr_token: string;
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
import './styles.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
+72
View File
@@ -0,0 +1,72 @@
import { useState, type FormEvent } from 'react';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
export function Login() {
const { signIn } = useAuth();
const { push } = useToast();
const [email, setEmail] = useState('');
const [token, setToken] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function onSubmit(e: FormEvent) {
e.preventDefault();
if (!email.trim() || !token.trim()) return;
setBusy(true);
setError(null);
try {
await signIn(email.trim(), token.trim().toUpperCase());
push('success', 'Welcome back');
} catch (err) {
const msg = err instanceof Error ? err.message : 'Sign in failed';
setError(msg);
push('error', msg);
} finally {
setBusy(false);
}
}
return (
<div className="login-wrap">
<div className="login-card">
<div className="login-brand">
<div className="logo">C</div>
<div>
<h1>Convivo Admin</h1>
<p>Sign in with your admin QR token and email.</p>
</div>
</div>
<form className="login-form" onSubmit={onSubmit}>
<div className="field">
<label>Email</label>
<input
className="input"
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
autoComplete="username"
required
/>
</div>
<div className="field">
<label>QR token</label>
<input
className="input mono"
placeholder="CVV-ADM-0001"
value={token}
onChange={(e) => setToken(e.target.value)}
autoComplete="current-password"
required
/>
</div>
{error && <div className="login-err">{error}</div>}
<button className="btn primary" type="submit" disabled={busy}>
{busy ? 'Signing in…' : 'Sign in'}
</button>
</form>
</div>
</div>
);
}
+219
View File
@@ -0,0 +1,219 @@
* { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
:root {
--bg: #f0f2f6; --surface: #ffffff; --surface-2: #f4f5f9;
--line: #e4e6ee; --text: #423c3c; --muted: #8a8484;
--accent: #d50000; --accent-2: #20b2aa; --accent-soft: rgba(213,0,0,.08);
--cyan: #20b2aa; --amber: #f59e0b; --green: #059669; --red: #d50000;
--sidebar: #1f1b1b; --sidebar-2: #2a2424;
}
html, body, #root { height: 100%; }
body {
background: radial-gradient(1100px 700px at 80% -10%, rgba(213,0,0,.05) 0%, var(--bg) 55%);
font-family: 'Poppins', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
color: var(--text);
}
/* ---------- App shell (sidebar + content) ---------- */
.app { display: flex; height: 100dvh; overflow: hidden; }
.sidebar {
width: 248px; flex-shrink: 0; background: var(--sidebar); color: #fff;
display: flex; flex-direction: column; padding: 22px 16px; gap: 6px;
}
.brand { display: flex; align-items: center; gap: 12px; padding: 4px 8px 20px; }
.brand .logo {
width: 44px; height: 44px; border-radius: 13px; display: flex; align-items: center; justify-content: center;
font-size: 22px; font-weight: 900; background: linear-gradient(135deg, var(--accent), #ff5a4e);
box-shadow: 0 8px 20px rgba(213,0,0,.4); color: #fff;
}
.brand .name { font-weight: 800; font-size: 17px; letter-spacing: -.3px; }
.brand .sub { font-size: 11px; color: rgba(255,255,255,.5); font-weight: 600; }
.nav { display: flex; flex-direction: column; gap: 4px; margin-top: 6px; }
.nav-item {
display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 12px;
background: none; border: none; color: rgba(255,255,255,.62); font-size: 14.5px; font-weight: 600;
cursor: pointer; font-family: inherit; text-align: left; transition: background .12s, color .12s;
}
.nav-item .ico { font-size: 19px; width: 22px; text-align: center; }
.nav-item:hover { background: var(--sidebar-2); color: #fff; }
.nav-item.active { background: var(--accent); color: #fff; box-shadow: 0 6px 16px rgba(213,0,0,.35); }
.sidebar-foot { margin-top: auto; padding-top: 14px; border-top: 1px solid rgba(255,255,255,.1); }
.admin-card { display: flex; align-items: center; gap: 10px; padding: 8px; }
.admin-card .who { min-width: 0; }
.admin-card .who .n { font-weight: 700; font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.admin-card .who .e { font-size: 11px; color: rgba(255,255,255,.5); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.signout {
margin-top: 10px; width: 100%; padding: 10px; border-radius: 10px; border: 1px solid rgba(255,255,255,.16);
background: none; color: rgba(255,255,255,.7); font-weight: 700; font-size: 13px; cursor: pointer; font-family: inherit;
}
.signout:hover { background: rgba(255,255,255,.08); color: #fff; }
.content { flex: 1; overflow-y: auto; padding: 30px 34px 60px; }
.content::-webkit-scrollbar { width: 10px; }
.content::-webkit-scrollbar-thumb { background: #d5d8e2; border-radius: 8px; }
.page-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 22px; gap: 16px; flex-wrap: wrap; }
.page-head h1 { font-size: 26px; font-weight: 800; letter-spacing: -.6px; }
.page-head .sub { color: var(--muted); font-size: 14px; margin-top: 3px; }
/* ---------- Primitives ---------- */
.card { background: var(--surface); border: 1px solid var(--line); border-radius: 16px; padding: 18px; box-shadow: 0 8px 24px rgba(66,60,60,.06); }
.muted { color: var(--muted); }
.small { font-size: 12.5px; }
.h2 { font-size: 16px; font-weight: 700; }
.row { display: flex; align-items: center; gap: 10px; }
.row.between { justify-content: space-between; }
.grow { flex: 1; min-width: 0; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
padding: 11px 18px; border-radius: 12px; border: 1px solid var(--line);
background: var(--surface-2); color: var(--text); font-size: 14px; font-weight: 700;
cursor: pointer; transition: transform .08s ease, opacity .15s; font-family: inherit; white-space: nowrap;
}
.btn:active { transform: scale(.98); }
.btn.primary { background: var(--accent); border: none; color: #fff; box-shadow: 0 8px 20px rgba(213,0,0,.22); }
.btn.ghost { background: transparent; }
.btn.danger { background: rgba(213,0,0,.08); border-color: rgba(213,0,0,.35); color: var(--red); }
.btn.small { padding: 8px 12px; font-size: 12.5px; border-radius: 10px; }
.btn:disabled { opacity: .45; cursor: not-allowed; }
.icon-btn {
width: 34px; height: 34px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface);
color: var(--muted); font-size: 15px; cursor: pointer; display: inline-flex; align-items: center; justify-content: center;
}
.icon-btn:hover { background: var(--surface-2); color: var(--text); }
.pill {
display: inline-flex; align-items: center; gap: 6px; padding: 4px 11px; border-radius: 999px;
font-size: 11.5px; font-weight: 700; background: var(--surface-2); border: 1px solid var(--line); text-transform: capitalize;
}
.pill.attendee { background: rgba(148,163,184,.14); border-color: rgba(148,163,184,.4); color: #64748b; }
.pill.staff { 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); }
.pill.amber { background: rgba(245,158,11,.14); border-color: rgba(245,158,11,.4); color: #b45309; }
.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; }
.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);
background: var(--surface-2); color: var(--text); font-size: 14px; outline: none; font-family: inherit;
}
.input:focus { border-color: var(--accent); }
textarea.input { resize: none; min-height: 84px; }
.field { display: flex; flex-direction: column; gap: 6px; }
.field label { font-size: 12.5px; font-weight: 700; color: var(--muted); }
.divider { height: 1px; background: var(--line); margin: 4px 0; }
/* ---------- Stat cards ---------- */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin-bottom: 22px; }
.stat {
background: var(--surface); border: 1px solid var(--line); border-radius: 16px; padding: 18px;
box-shadow: 0 8px 24px rgba(66,60,60,.06); display: flex; flex-direction: column; gap: 6px;
}
.stat .ico { font-size: 22px; }
.stat .val { font-size: 30px; font-weight: 900; letter-spacing: -1px; }
.stat .lbl { color: var(--muted); font-size: 13px; font-weight: 600; }
.stat.accent { background: linear-gradient(135deg, rgba(213,0,0,.1), rgba(32,178,170,.08)); border-color: rgba(213,0,0,.3); }
/* ---------- Table ---------- */
.table-wrap { background: var(--surface); border: 1px solid var(--line); border-radius: 16px; overflow: hidden; box-shadow: 0 8px 24px rgba(66,60,60,.06); }
table.data { width: 100%; border-collapse: collapse; font-size: 14px; }
table.data th {
text-align: left; padding: 13px 16px; font-size: 11.5px; font-weight: 800; text-transform: uppercase;
letter-spacing: .4px; color: var(--muted); background: var(--surface-2); border-bottom: 1px solid var(--line);
}
table.data td { padding: 13px 16px; border-bottom: 1px solid var(--line); vertical-align: middle; }
table.data tr:last-child td { border-bottom: none; }
table.data tr:hover td { background: rgba(244,245,249,.6); }
.cell-person { display: flex; align-items: center; gap: 11px; }
.cell-person .n { font-weight: 700; }
.cell-person .e { font-size: 12px; color: var(--muted); }
.pts { font-weight: 800; color: #b45309; }
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; }
/* ---------- Modal ---------- */
.backdrop { position: fixed; inset: 0; background: rgba(5,5,10,.6); backdrop-filter: blur(3px); z-index: 70; display: flex; align-items: center; justify-content: center; padding: 20px; }
.modal {
width: 100%; max-width: 460px; background: var(--surface); border-radius: 20px;
border: 1px solid var(--line); box-shadow: 0 30px 80px rgba(66,60,60,.35);
max-height: 88dvh; overflow-y: auto; animation: pop .18s ease;
}
@keyframes pop { from { transform: scale(.96); opacity: .4 } to { transform: none; opacity: 1 } }
.modal-head { display: flex; align-items: center; justify-content: space-between; padding: 18px 20px 0; }
.modal-head h3 { font-size: 18px; font-weight: 800; letter-spacing: -.3px; }
.modal-body { padding: 16px 20px 20px; display: flex; flex-direction: column; gap: 14px; }
.modal-foot { display: flex; gap: 10px; justify-content: flex-end; padding: 0 20px 20px; }
.modal-foot .btn { width: auto; }
/* ---------- Segmented control ---------- */
.seg { display: flex; background: var(--surface); border: 1px solid var(--line); border-radius: 13px; padding: 4px; }
.seg button {
flex: 1; padding: 10px; border: none; border-radius: 10px; background: none; color: var(--muted);
font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit; white-space: nowrap;
}
.seg button.active { background: var(--accent-soft); color: var(--accent); }
/* ---------- QR ---------- */
.qr-wrap { display: flex; flex-direction: column; align-items: center; gap: 12px; }
.qr-frame { background: #fff; border-radius: 12px; padding: 12px; border: 1px solid var(--line); }
.token-big { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 20px; font-weight: 800; letter-spacing: 1px; color: var(--accent); }
/* ---------- Login ---------- */
.login-wrap { height: 100dvh; display: flex; align-items: center; justify-content: center; padding: 20px; }
.login-card {
width: 100%; max-width: 400px; background: var(--surface); border: 1px solid var(--line);
border-radius: 24px; padding: 34px 30px; box-shadow: 0 30px 80px rgba(66,60,60,.2);
display: flex; flex-direction: column; gap: 18px;
}
.login-brand { display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center; }
.login-brand .logo {
width: 72px; height: 72px; border-radius: 20px; display: flex; align-items: center; justify-content: center;
font-size: 32px; font-weight: 900; background: linear-gradient(135deg, var(--accent), #ff5a4e);
box-shadow: 0 16px 40px rgba(213,0,0,.35); color: #fff;
}
.login-brand h1 { font-size: 24px; font-weight: 900; letter-spacing: -.5px; }
.login-brand p { color: var(--muted); font-size: 13.5px; }
.login-form { display: flex; flex-direction: column; gap: 14px; }
.login-err { color: var(--red); font-size: 13px; font-weight: 600; text-align: center; }
/* ---------- Misc ---------- */
.spinner {
width: 22px; height: 22px; border: 3px solid var(--line); border-top-color: var(--accent);
border-radius: 50%; animation: spin .8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.center { display: flex; align-items: center; justify-content: center; }
.loading-screen { height: 100dvh; display: flex; align-items: center; justify-content: center; }
.empty {
text-align: center; padding: 40px 20px; color: var(--muted); font-size: 14px;
border: 1.5px dashed var(--line); border-radius: 16px;
}
.empty .big { font-size: 34px; margin-bottom: 10px; }
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
@media (max-width: 900px) { .grid-2 { grid-template-columns: 1fr; } }
/* ---------- Toast ---------- */
.toast-stack { position: fixed; right: 20px; bottom: 20px; z-index: 90; display: flex; flex-direction: column; gap: 10px; }
.toast {
background: #fff; border: 1px solid var(--line); border-radius: 14px;
padding: 13px 18px; font-size: 13.5px; font-weight: 600; min-width: 240px; max-width: 360px;
box-shadow: 0 12px 30px rgba(66,60,60,.22); animation: toast-in .25s ease; cursor: pointer;
}
@keyframes toast-in { from { transform: translateY(12px); opacity: 0 } to { transform: none; opacity: 1 } }
.toast-success { border-color: rgba(5,150,105,.5); }
.toast-error { border-color: rgba(213,0,0,.55); }
.toast-info { border-color: rgba(32,178,170,.5); }
/* ---------- Responsive: collapse sidebar to top bar on narrow screens ---------- */
@media (max-width: 760px) {
.app { flex-direction: column; }
.sidebar { width: 100%; flex-direction: row; align-items: center; padding: 12px 14px; gap: 10px; overflow-x: auto; }
.brand { padding: 0 8px 0 0; }
.brand .sub { display: none; }
.nav { flex-direction: row; margin-top: 0; }
.nav-item { padding: 9px 12px; white-space: nowrap; }
.sidebar-foot { display: none; }
.content { padding: 20px 16px 50px; }
}
+186
View File
@@ -0,0 +1,186 @@
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 { Avatar, Empty, Spinner } from '../components/ui';
type Tab = 'checkins' | 'connections' | 'feedback';
export function Activity() {
const [profiles, setProfiles] = useState<Profile[] | null>(null);
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 () => {
try {
const [p, s, c, conn, f] = await Promise.all([
getAllProfiles(),
getAllSessions(),
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');
}
})();
return () => {
cancelled = true;
};
}, []);
const byId = useMemo(() => new Map((profiles ?? []).map((p) => [p.id, p])), [profiles]);
const sessById = useMemo(() => new Map(sessions.map((s) => [s.id, s])), [sessions]);
if (error) return <Empty icon="⚠️" text={error} />;
if (!profiles)
return (
<div className="loading-screen">
<Spinner />
</div>
);
return (
<div>
<div className="page-head">
<div>
<h1>Activity</h1>
<div className="sub">Check-ins, connections, and feedback.</div>
</div>
</div>
<div className="seg" style={{ maxWidth: 420, marginBottom: 18 }}>
<button className={tab === 'checkins' ? 'active' : ''} onClick={() => setTab('checkins')}>
Check-ins ({checkins.length})
</button>
<button className={tab === 'connections' ? 'active' : ''} onClick={() => setTab('connections')}>
Connections ({connections.length})
</button>
<button className={tab === 'feedback' ? 'active' : ''} onClick={() => setTab('feedback')}>
Feedback ({feedback.length})
</button>
</div>
{tab === 'checkins' && (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Attendee</th>
<th>Session</th>
<th>Checked in by</th>
<th>When</th>
</tr>
</thead>
<tbody>
{checkins.map((c) => (
<tr key={c.id}>
<td>
<PersonCell p={byId.get(c.profile_id)} />
</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>
</tr>
))}
</tbody>
</table>
{checkins.length === 0 && <div style={{ padding: 16 }}><Empty icon="✅" text="No check-ins yet" /></div>}
</div>
)}
{tab === 'connections' && (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>From</th>
<th>To</th>
<th>Status</th>
<th>When</th>
</tr>
</thead>
<tbody>
{connections.map((c) => (
<tr key={c.id}>
<td>
<PersonCell p={byId.get(c.from_id)} />
</td>
<td>
<PersonCell p={byId.get(c.to_id)} />
</td>
<td>
<span className={`pill ${c.status === 'accepted' ? 'green' : c.status === 'rejected' ? 'violet' : 'amber'}`}>
{c.status}
</span>
</td>
<td className="muted small">{fmt(c.resolved_at ?? c.created_at)}</td>
</tr>
))}
</tbody>
</table>
{connections.length === 0 && <div style={{ padding: 16 }}><Empty icon="🤝" text="No connections yet" /></div>}
</div>
)}
{tab === 'feedback' && (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Attendee</th>
<th>Session</th>
<th>Rating</th>
<th>Comment</th>
<th>When</th>
</tr>
</thead>
<tbody>
{feedback.map((f) => (
<tr key={f.id}>
<td>
<PersonCell p={byId.get(f.profile_id)} />
</td>
<td>{sessById.get(f.session_id)?.title ?? '—'}</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>
</tr>
))}
</tbody>
</table>
{feedback.length === 0 && <div style={{ padding: 16 }}><Empty icon="⭐" text="No feedback yet" /></div>}
</div>
)}
</div>
);
}
function PersonCell({ p }: { p: Profile | undefined }) {
if (!p) return <span className="muted small">—</span>;
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>
);
}
function fmt(iso: string): string {
return new Date(iso).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}
+332
View File
@@ -0,0 +1,332 @@
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>
);
}
+196
View File
@@ -0,0 +1,196 @@
import { useEffect, useState } from 'react';
import {
getAllCheckins,
getAllConnections,
getAllFeedback,
getAllProfiles,
getAllSessions,
getLeaderboard,
} from '../lib/api';
import type { Checkin, Connection, Feedback, LeaderboardRow, Profile, Session } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui';
type View = 'dashboard' | 'attendees' | 'schedule' | 'activity';
export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
const [profiles, setProfiles] = useState<Profile[] | null>(null);
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);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const [p, c, conn, f, s, l] = await Promise.all([
getAllProfiles(),
getAllCheckins(),
getAllConnections(),
getAllFeedback(),
getAllSessions(),
getLeaderboard(),
]);
if (cancelled) return;
setProfiles(p);
setCheckins(c);
setConnections(conn);
setFeedback(f);
setSessions(s);
setLb(l);
} catch (e) {
if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
}
})();
return () => {
cancelled = true;
};
}, []);
if (error) return <Empty icon="⚠️" text={error} />;
if (!profiles)
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);
return (
<div>
<div className="page-head">
<div>
<h1>Dashboard</h1>
<div className="sub">Live overview of the event.</div>
</div>
</div>
<div className="stat-grid">
<div className="stat">
<span className="ico">👥</span>
<span className="val">{attendees.length}</span>
<span className="lbl">Attendees</span>
</div>
<div className="stat">
<span className="ico">✅</span>
<span className="val">{checkins.length}</span>
<span className="lbl">Check-ins</span>
</div>
<div className="stat">
<span className="ico">🤝</span>
<span className="val">{accepted}</span>
<span className="lbl">Connections accepted</span>
</div>
<div className="stat">
<span className="ico">⭐</span>
<span className="val">{avgRating}</span>
<span className="lbl">Avg. session rating</span>
</div>
<div className="stat accent">
<span className="ico">🏆</span>
<span className="val">{sessions.length}</span>
<span className="lbl">Sessions scheduled</span>
</div>
</div>
<div className="grid-2">
<div className="card">
<div className="row between" style={{ marginBottom: 14 }}>
<h2 className="h2">🏆 Top points</h2>
<button className="btn small ghost" onClick={() => onNavigate('attendees')}>
View all →
</button>
</div>
{top.length === 0 ? (
<Empty icon="🏆" text="No points yet" />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{top.map((r, i) => (
<div key={r.profile_id} 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} />
<div className="grow">
<div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name}</div>
{r.company && <div className="muted small">{r.company}</div>}
</div>
<span className="pts">{r.points}</span>
</div>
))}
</div>
)}
</div>
<div className="card">
<div className="row between" style={{ marginBottom: 14 }}>
<h2 className="h2">⚡ Recent activity</h2>
<button className="btn small ghost" onClick={() => onNavigate('activity')}>
View all →
</button>
</div>
<ActivityFeed checkins={checkins} connections={connections} feedback={feedback} profiles={profiles} limit={6} />
</div>
</div>
</div>
);
}
function ActivityFeed({
checkins,
connections,
feedback,
profiles,
limit,
}: {
checkins: Checkin[];
connections: Connection[];
feedback: Feedback[];
profiles: Profile[];
limit: number;
}) {
const byId = new Map(profiles.map((p) => [p.id, p]));
type Item = { at: string; icon: string; text: string };
const items: Item[] = [
...checkins.map((c) => ({
at: c.created_at,
icon: '✅',
text: `${byId.get(c.profile_id)?.full_name ?? 'Someone'} 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'}`,
})),
...feedback.map((f) => ({
at: f.created_at,
icon: '⭐',
text: `${byId.get(f.profile_id)?.full_name ?? 'Someone'} rated a session ${f.rating}★`,
})),
]
.sort((a, b) => (a.at < b.at ? 1 : -1))
.slice(0, limit);
if (items.length === 0) return <Empty icon="⚡" text="No activity yet" />;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{items.map((it, i) => (
<div key={i} className="row" style={{ gap: 10 }}>
<span style={{ fontSize: 18 }}>{it.icon}</span>
<div className="grow" style={{ fontSize: 13.5 }}>
{it.text}
</div>
<span className="muted small">{new Date(it.at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
</div>
))}
</div>
);
}
+332
View File
@@ -0,0 +1,332 @@
import { useEffect, useState } from 'react';
import { supabase } from '../lib/supabase';
import { getAllSessions, getAllSlots } from '../lib/api';
import type { Session, Slot } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner } from '../components/ui';
export function Schedule() {
const { push } = useToast();
const [slots, setSlots] = useState<Slot[] | null>(null);
const [sessions, setSessions] = useState<Session[]>([]);
const [error, setError] = useState<string | null>(null);
const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null);
const [sessModal, setSessModal] = useState<{ session: Session | null; slotId: number } | null>(null);
const [busy, setBusy] = useState(false);
async function load() {
try {
const [s, ss] = await Promise.all([getAllSlots(), getAllSessions()]);
setSlots(s);
setSessions(ss);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}
useEffect(() => {
load();
}, []);
async function deleteSlot(slot: Slot) {
if (!confirm(`Delete "${slot.name}" and all its sessions?`)) return;
setBusy(true);
try {
const { error: err } = await supabase.from('slots').delete().eq('id', slot.id);
if (err) throw err;
await load();
push('success', `Deleted ${slot.name}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setBusy(false);
}
}
async function deleteSession(sess: Session) {
if (!confirm(`Delete session "${sess.title}"?`)) return;
setBusy(true);
try {
const { error: err } = await supabase.from('sessions').delete().eq('id', sess.id);
if (err) throw err;
await load();
push('success', `Deleted ${sess.title}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Delete failed');
} finally {
setBusy(false);
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!slots)
return (
<div className="loading-screen">
<Spinner />
</div>
);
return (
<div>
<div className="page-head">
<div>
<h1>Schedule</h1>
<div className="sub">{slots.length} slots · {sessions.length} sessions.</div>
</div>
<button className="btn primary" onClick={() => setSlotModal({ slot: null })}>
+ New slot
</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{slots.map((slot) => {
const slotSessions = sessions.filter((s) => s.slot_id === slot.id);
return (
<div key={slot.id} className="card">
<div className="row between" style={{ marginBottom: 12 }}>
<div className="row" style={{ gap: 12 }}>
<div>
<div style={{ fontWeight: 800, fontSize: 16 }}>{slot.name}</div>
<div className="muted small">
{fmtDate(slot.slot_date)} · {fmtTime(slot.start_time)}–{fmtTime(slot.end_time)}
</div>
</div>
</div>
<div className="row-actions">
<button className="btn small" onClick={() => setSessModal({ session: null, slotId: slot.id })}>
+ Session
</button>
<button className="btn small" onClick={() => setSlotModal({ slot })}>
Edit
</button>
<button className="btn small danger" disabled={busy} onClick={() => deleteSlot(slot)}>
Delete
</button>
</div>
</div>
{slotSessions.length === 0 ? (
<div className="muted small" style={{ padding: '4px 0' }}>
No sessions in this slot.
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{slotSessions.map((s) => (
<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(' · ') || '—'}
</div>
</div>
<div className="row-actions">
<button className="btn small" onClick={() => setSessModal({ session: s, slotId: slot.id })}>
Edit
</button>
<button className="btn small danger" disabled={busy} onClick={() => deleteSession(s)}>
Delete
</button>
</div>
</div>
))}
</div>
)}
</div>
);
})}
</div>
{slotModal && (
<SlotModal
slot={slotModal.slot}
onClose={() => setSlotModal(null)}
onSaved={async (msg) => {
setSlotModal(null);
await load();
push('success', msg);
}}
/>
)}
{sessModal && (
<SessionModal
session={sessModal.session}
slotId={sessModal.slotId}
onClose={() => setSessModal(null)}
onSaved={async (msg) => {
setSessModal(null);
await load();
push('success', msg);
}}
/>
)}
</div>
);
}
function SlotModal({
slot,
onClose,
onSaved,
}: {
slot: Slot | null;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [name, setName] = useState(slot?.name ?? '');
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');
const [busy, setBusy] = useState(false);
async function save() {
if (!name.trim() || !date) return;
setBusy(true);
try {
const payload = { name: name.trim(), slot_date: date, start_time: start, end_time: end };
if (slot) {
const { error: err } = await supabase.from('slots').update(payload).eq('id', slot.id);
if (err) throw err;
} else {
const { error: err } = await supabase.from('slots').insert(payload);
if (err) throw err;
}
onSaved(slot ? 'Slot updated' : 'Slot created');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Save failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={slot ? 'Edit slot' : 'New slot'}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !name.trim() || !date} 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. Morning keynote" />
</div>
<div className="field">
<label>Date</label>
<input className="input" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</div>
<div className="grid-2">
<div className="field">
<label>Start</label>
<input className="input" type="time" value={start} onChange={(e) => setStart(e.target.value)} />
</div>
<div className="field">
<label>End</label>
<input className="input" type="time" value={end} onChange={(e) => setEnd(e.target.value)} />
</div>
</div>
</Modal>
);
}
function SessionModal({
session,
slotId,
onClose,
onSaved,
}: {
session: Session | null;
slotId: number;
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 [busy, setBusy] = useState(false);
async function save() {
if (!title.trim()) return;
setBusy(true);
try {
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,
};
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);
if (err) throw err;
}
onSaved(session ? 'Session updated' : 'Session created');
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Save failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={session ? 'Edit session' : 'New session'}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !title.trim()} onClick={save}>
{busy ? 'Saving…' : 'Save'}
</button>
</>
}
>
<div className="field">
<label>Title</label>
<input className="input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. The future of networking" />
</div>
<div className="grid-2">
<div className="field">
<label>Room</label>
<input className="input" value={room} onChange={(e) => setRoom(e.target.value)} placeholder="—" />
</div>
<div className="field">
<label>Capacity</label>
<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>
</Modal>
);
}
function fmtDate(d: string): string {
return new Date(d + 'T00:00:00').toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
}
function fmtTime(t: string): string {
return t.slice(0, 5);
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_SUPABASE_URL: string;
readonly VITE_SUPABASE_ANON_KEY: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true,
"noEmit": true
},
"include": ["vite.config.ts"]
}
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// Dev server proxies /auth, /rest, /realtime, /storage to the local Supabase
// stack so the app can use relative URLs (works in Docker + localhost).
const SUPABASE_TARGET = 'http://127.0.0.1:54321';
export default defineConfig({
plugins: [react()],
server: {
host: true,
port: 3001,
proxy: {
'/auth': { target: SUPABASE_TARGET, changeOrigin: true },
'/rest': { target: SUPABASE_TARGET, changeOrigin: true },
'/realtime': { target: SUPABASE_TARGET, changeOrigin: true, ws: true },
'/storage': { target: SUPABASE_TARGET, changeOrigin: true },
},
},
});
+32 -5
View File
@@ -9,14 +9,18 @@
# (supabase_network_<project_id>; here: supabase_network_Convivo) and a Kong # (supabase_network_<project_id>; here: supabase_network_Convivo) and a Kong
# container (supabase_kong_Convivo) that fronts the API on port 54321. # container (supabase_kong_Convivo) that fronts the API on port 54321.
# #
# This compose file runs the attendee app as a sidecar that JOINS that network # This compose file runs the attendee app (:3000) and the admin app (:3001) as
# and proxies the Supabase same-origin paths to the Kong container. # sidecars that JOIN that network and proxy the Supabase same-origin paths to
# the Kong container.
# #
# 1. npm run db:start # start the Supabase core (CLI) # 1. npm run db:start # start the Supabase core (CLI)
# 2. docker compose up --build # build + run the app on :3000 # 2. docker compose up --build # build + run both apps
# #
# Then open http://localhost:3000 and log in with a demo QR code # Then open:
# (e.g. CVV-ANA-4821 / [email protected]). # - http://localhost:3000 (attendee app) — log in with a demo QR code
# (e.g. CVV-ANA-4821 / [email protected])
# - http://localhost:3001 (admin app) — log in as admin
# (CVV-ADM-0001 / [email protected])
name: convivo name: convivo
@@ -49,6 +53,29 @@ services:
retries: 5 retries: 5
start_period: 10s start_period: 10s
convivo-admin:
build:
context: ./apps/admin
args:
# Standard local Supabase anon key (not a secret). Override if needed.
VITE_SUPABASE_ANON_KEY: ${VITE_SUPABASE_ANON_KEY:-eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0}
image: convivo-admin:latest
container_name: convivo-admin
ports:
- "3001:3001"
environment:
# Same proxy target as the attendee app (Kong on the shared network).
SUPABASE_PROXY_TARGET: ${SUPABASE_PROXY_TARGET:-supabase_kong_Convivo:8000}
networks:
- supabase
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3001/"]
interval: 15s
timeout: 5s
retries: 5
start_period: 10s
networks: networks:
supabase: supabase:
# External network created by `supabase start`. Name = supabase_network_<project_id>. # External network created by `supabase start`. Name = supabase_network_<project_id>.
+11 -7
View File
@@ -4,8 +4,8 @@ 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 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. system works*; the root [`README.md`](../README.md) is the quick-start.
> **Status:** Phase 0 (Dockerized Supabase core) + Phase 1 (attendee web PWA) > **Status:** Phase 0 (Dockerized Supabase core) + Phase 1 (attendee web PWA) +
> are complete and verified. Phases 2–4 are planned — see > Phase 2 (admin console) are complete and verified. Phases 3–4 are planned — see
> [next-steps.md](./next-steps.md). > [next-steps.md](./next-steps.md).
## Where things live ## Where things live
@@ -20,11 +20,12 @@ system works*; the root [`README.md`](../README.md) is the quick-start.
| Row Level Security policies | [backend/rls.md](./backend/rls.md) | | Row Level Security policies | [backend/rls.md](./backend/rls.md) |
| Seed data + demo accounts | [backend/seed.md](./backend/seed.md) | | Seed data + demo accounts | [backend/seed.md](./backend/seed.md) |
| Docker (app image + compose) | [backend/docker.md](./backend/docker.md) | | Docker (app image + compose) | [backend/docker.md](./backend/docker.md) |
| **Frontend (attendee PWA) — overview** | [frontend/README.md](./frontend/README.md) | | **Frontend — overview (both apps)** | [frontend/README.md](./frontend/README.md) |
| App structure, state, contexts, routing | [frontend/app-structure.md](./frontend/app-structure.md) | | Attendee app: structure, state, contexts, routing | [frontend/app-structure.md](./frontend/app-structure.md) |
| Every screen (Login, Home, Agenda, Scan, …) | [frontend/screens.md](./frontend/screens.md) | | Attendee app: every screen (Login, Home, Agenda, Scan, …) | [frontend/screens.md](./frontend/screens.md) |
| API client (how the app talks to Supabase) | [frontend/api-client.md](./frontend/api-client.md) | | API client (how the app talks to Supabase) | [frontend/api-client.md](./frontend/api-client.md) |
| **What's next (Phase 2/3/4 + open items)** | [next-steps.md](./next-steps.md) | | **Admin console** (views, auth guard, QR reset, points, schedule) | [frontend/admin-app.md](./frontend/admin-app.md) |
| **What's next (Phase 3/4 + open items)** | [next-steps.md](./next-steps.md) |
## Reading order ## Reading order
@@ -35,6 +36,7 @@ system works*; the root [`README.md`](../README.md) is the quick-start.
[backend/rls.md](./backend/rls.md). [backend/rls.md](./backend/rls.md).
3. **Working on the UI?** Go to [frontend/app-structure.md](./frontend/app-structure.md) 3. **Working on the UI?** Go to [frontend/app-structure.md](./frontend/app-structure.md)
→ [frontend/screens.md](./frontend/screens.md) → [frontend/api-client.md](./frontend/api-client.md). → [frontend/screens.md](./frontend/screens.md) → [frontend/api-client.md](./frontend/api-client.md).
For the admin console, read [frontend/admin-app.md](./frontend/admin-app.md).
4. **Planning the next phase?** Read [next-steps.md](./next-steps.md). 4. **Planning the next phase?** Read [next-steps.md](./next-steps.md).
## Conventions ## Conventions
@@ -45,7 +47,9 @@ system works*; the root [`README.md`](../README.md) is the quick-start.
- **Code is the source of truth.** If a doc and the code disagree, the code wins — - **Code is the source of truth.** If a doc and the code disagree, the code wins —
fix the doc. Key files: fix the doc. Key files:
- Schema + RPCs + RLS: [`supabase/migrations/20260822000000_init.sql`](../supabase/migrations/20260822000000_init.sql) - 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)
- Seed: [`supabase/seed.sql`](../supabase/seed.sql) - Seed: [`supabase/seed.sql`](../supabase/seed.sql)
- App source: [`apps/convivo/src/`](../apps/convivo/src/) - Attendee app source: [`apps/convivo/src/`](../apps/convivo/src/)
- Admin app source: [`apps/admin/src/`](../apps/admin/src/)
- **Keep it current.** Update the relevant doc in the same change that changes the - **Keep it current.** Update the relevant doc in the same change that changes the
behavior it describes. behavior it describes.
+30 -6
View File
@@ -16,14 +16,18 @@ make connections, get checked in by staff, and rate sessions. Every action earns
```mermaid ```mermaid
flowchart LR flowchart LR
subgraph Browser["Browser (attendee / staff phone)"] subgraph Browser["Browser"]
A["Convivo PWA<br/>React 18 + Vite 5 + TS<br/>mobile-first, installable"] 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"]
end end
subgraph Docker["Docker (local)"] subgraph Docker["Docker (local)"]
subgraph AppC["convivo-app container (:3000)"] subgraph AppC["convivo-app container (:3000)"]
N["nginx<br/>serves SPA + proxies Supabase paths"] N["nginx<br/>serves SPA + proxies Supabase paths"]
end end
subgraph AdminC["convivo-admin container (:3001)"]
NA["nginx<br/>serves SPA + proxies Supabase paths"]
end
subgraph Core["Supabase core (Supabase CLI)"] subgraph Core["Supabase core (Supabase CLI)"]
K["Kong API gateway<br/>:54321"] K["Kong API gateway<br/>:54321"]
K --> G["GoTrue (Auth)"] K --> G["GoTrue (Auth)"]
@@ -37,7 +41,9 @@ flowchart LR
end end
A -->|"same-origin /auth /rest /realtime /storage"| N A -->|"same-origin /auth /rest /realtime /storage"| N
AD -->|"same-origin /auth /rest /realtime /storage"| NA
N -->|"proxy (supabase_kong_Convivo:8000)"| K N -->|"proxy (supabase_kong_Convivo:8000)"| K
NA -->|"proxy (supabase_kong_Convivo:8000)"| K
``` ```
**Key idea:** there is **no custom backend**. Supabase provides auth, data, **Key idea:** there is **no custom backend**. Supabase provides auth, data,
@@ -72,6 +78,16 @@ 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) - **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) - **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).
- **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)).
## 5. How a request flows (example: staff check-in) ## 5. How a request flows (example: staff check-in)
```mermaid ```mermaid
@@ -113,7 +129,8 @@ the work atomically, and the `leaderboard` table change fans out over Realtime.
| Service | Port | Notes | | Service | Port | Notes |
|---|---|---| |---|---|---|
| **Convivo app** | **3000** | Vite dev server (dev) or nginx (Docker) | | **Convivo app** | **3000** | Vite dev server (dev) or nginx (Docker) |
| Supabase API (Kong) | 54321 | The single gateway the app proxies to | | **Convivo admin** | **3001** | Vite dev server (dev) or nginx (Docker) |
| Supabase API (Kong) | 54321 | The single gateway the apps proxy to |
| Supabase Studio | 54323 | UI — login `postgres` / `postgres` | | Supabase Studio | 54323 | UI — login `postgres` / `postgres` |
| Postgres | 54322 | Direct DB access (`postgres` / `postgres`) | | Postgres | 54322 | Direct DB access (`postgres` / `postgres`) |
| SMTP (Mailpit) | 54324 | Captures emails (none are sent in this flow) | | SMTP (Mailpit) | 54324 | Captures emails (none are sent in this flow) |
@@ -122,9 +139,10 @@ the work atomically, and the `leaderboard` table change fans out over Realtime.
```bash ```bash
npm run db:start # start the Supabase core (Docker) npm run db:start # start the Supabase core (Docker)
npm run db:reset # (re)apply migrations + seed npm run db:reset # (re)apply migrations + seed
npm run app:dev # dev server on :3000 npm run app:dev # attendee dev server on :3000
npm run admin:dev # admin dev server on :3001
# — or — # — or —
docker compose up --build # app as a Docker sidecar on :3000 docker compose up --build # both apps as Docker sidecars (:3000 + :3001)
``` ```
## 8. The demo clock ## 8. The demo clock
@@ -142,11 +160,17 @@ Convivo/
│ ├─ Dockerfile # Multi-stage: build → nginx │ ├─ Dockerfile # Multi-stage: build → nginx
│ ├─ nginx.conf.template # SPA + same-origin proxy to the Supabase core │ ├─ nginx.conf.template # SPA + same-origin proxy to the Supabase core
│ └─ src/ # screens, components, lib, context │ └─ src/ # screens, components, lib, context
├─ apps/admin/ # Admin console (React + Vite + TS, desktop-first)
│ ├─ Dockerfile # Multi-stage: build → nginx
│ ├─ nginx.conf.template # SPA + same-origin proxy to the Supabase core
│ └─ src/ # views, components, lib, context
├─ supabase/ ├─ supabase/
│ ├─ config.toml # Local stack config (ports, auth, RLS defaults) │ ├─ config.toml # Local stack config (ports, auth, RLS defaults)
│ ├─ migrations/ # 20260822000000_init.sql — schema, RLS, RPCs │ ├─ 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 │ └─ seed.sql # Slots, sessions, 13 demo users, Ana's demo state
├─ docker-compose.yml # Runs the app sidecar on the Supabase network ├─ docker-compose.yml # Runs both app sidecars on the Supabase network
├─ docs/ # ← this documentation ├─ docs/ # ← this documentation
└─ mockup/index.html # Original interactive mockup (design reference) └─ mockup/index.html # Original interactive mockup (design reference)
``` ```
+1
View File
@@ -34,5 +34,6 @@ Postgres 17 ── schema (9 tables)
## Source of truth ## Source of truth
- Schema + RPCs + RLS: [`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql) - 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)
- Seed: [`supabase/seed.sql`](../../supabase/seed.sql) - Seed: [`supabase/seed.sql`](../../supabase/seed.sql)
- Stack config: [`supabase/config.toml`](../../supabase/config.toml) - Stack config: [`supabase/config.toml`](../../supabase/config.toml)
+31 -21
View File
@@ -4,12 +4,14 @@ Docker is the backbone. Two pieces:
1. **The Supabase core** — a set of containers managed by the **Supabase CLI** 1. **The Supabase core** — a set of containers managed by the **Supabase CLI**
(not by a compose file in this repo). See [supabase-core.md](./supabase-core.md). (not by a compose file in this repo). See [supabase-core.md](./supabase-core.md).
2. **The app sidecar** — a single container built from 2. **The app sidecars** — two containers, the attendee app
[`apps/convivo/Dockerfile`](../../apps/convivo/Dockerfile) and orchestrated by ([`apps/convivo/Dockerfile`](../../apps/convivo/Dockerfile), `:3000`) and the
the root [`docker-compose.yml`](../../docker-compose.yml). admin console ([`apps/admin/Dockerfile`](../../apps/admin/Dockerfile), `:3001`),
orchestrated by the root [`docker-compose.yml`](../../docker-compose.yml).
The app container **joins the network the CLI created** for the core and proxies Each app container **joins the network the CLI created** for the core and proxies
the Supabase same-origin paths to the Kong container. the Supabase same-origin paths to the Kong container. Both use the identical
multi-stage build + nginx proxy pattern (only the port and build context differ).
## How the pieces fit ## How the pieces fit
@@ -21,10 +23,13 @@ flowchart LR
subgraph Net["supabase_network_Convivo (external)"] subgraph Net["supabase_network_Convivo (external)"]
K["supabase_kong_Convivo<br/>:8000 (internal)"] K["supabase_kong_Convivo<br/>:8000 (internal)"]
APP["convivo-app<br/>nginx :3000"] APP["convivo-app<br/>nginx :3000"]
ADM["convivo-admin<br/>nginx :3001"]
end end
CLI -.creates.-> Net CLI -.creates.-> Net
APP -->|"proxy /auth /rest /realtime /storage"| K APP -->|"proxy /auth /rest /realtime /storage"| K
ADM -->|"proxy /auth /rest /realtime /storage"| K
APP -->|"host port 3000"| U["Browser"] APP -->|"host port 3000"| U["Browser"]
ADM -->|"host port 3001"| U
``` ```
## The app image (`apps/convivo/Dockerfile`) ## The app image (`apps/convivo/Dockerfile`)
@@ -62,15 +67,17 @@ same-origin paths to the core:
## Root `docker-compose.yml` ## Root `docker-compose.yml`
Runs **only the app** (the core is CLI-managed). Key settings: Runs **only the apps** (the core is CLI-managed). There are two services —
`convivo-app` (`:3000`) and `convivo-admin` (`:3001`) — with identical settings
except the build context and port:
| Setting | Value | Why | | Setting | `convivo-app` | `convivo-admin` | Why |
|---|---|---| |---|---|---|---|
| `build.context` | `./apps/convivo` | Builds the app image | | `build.context` | `./apps/convivo` | `./apps/admin` | Builds the app image |
| `ports` | `3000:3000` | The app on the host | | `ports` | `3000:3000` | `3001:3001` | The app on the host |
| `environment.SUPABASE_PROXY_TARGET` | `supabase_kong_Convivo:8000` (default) | Where nginx proxies | | `environment.SUPABASE_PROXY_TARGET` | `supabase_kong_Convivo:8000` (default) | same | Where nginx proxies |
| `networks.supabase` | **external**, name `supabase_network_Convivo` | Joins the CLI-created network | | `networks.supabase` | **external**, name `supabase_network_Convivo` | same | Joins the CLI-created network |
| `healthcheck` | `wget http://127.0.0.1:3000/` | Container reports healthy | | `healthcheck` | `wget http://127.0.0.1:3000/` | `wget http://127.0.0.1:3001/` | Container reports healthy |
> If you change `project_id` in `supabase/config.toml`, update the external > If you change `project_id` in `supabase/config.toml`, update the external
> network name (`supabase_network_<project_id>`) and the default proxy target > network name (`supabase_network_<project_id>`) and the default proxy target
@@ -85,25 +92,28 @@ npm run db:start
# 2. (Optional) reset to clean seed data # 2. (Optional) reset to clean seed data
npm run db:reset npm run db:reset
# 3. Build + run the app sidecar on :3000 # 3. Build + run both app sidecars (:3000 + :3001)
docker compose up --build docker compose up --build
``` ```
Open **http://localhost:3000**. Open **http://localhost:3000** (attendee) and **http://localhost:3001** (admin).
### Alternative: dev server (no app container) ### Alternative: dev server (no app container)
For faster iteration you can skip the app container and use the Vite dev server, For faster iteration you can skip the app containers and use the Vite dev
which proxies the same paths to `127.0.0.1:54321` (host port): servers, which proxy the same paths to `127.0.0.1:54321` (host port):
```bash ```bash
npm run db:start npm run db:start
npm run app:dev # Vite on :3000 npm run app:dev # attendee Vite on :3000
npm run admin:dev # admin Vite on :3001
``` ```
## Verified behavior ## Verified behavior
- `docker compose build` → `npm ci` + `tsc` + `vite build` all pass in-container. - `docker compose build` → `npm ci` + `tsc` + `vite build` all pass in-container
- `GET /` → HTTP 200 (SPA served by nginx). (both `convivo-app` and `convivo-admin`).
- `GET /` → HTTP 200 (SPA served by nginx) on both `:3000` and `:3001`.
- `GET /auth/v1/health` through the proxy → GoTrue health JSON (proxy works). - `GET /auth/v1/health` through the proxy → GoTrue health JSON (proxy works).
- Full login (QR + email) works through the Docker-served app. - Full login (QR + email) works through the Docker-served apps, including the
admin console's admin-role guard.
+18 -6
View File
@@ -37,13 +37,18 @@ Two `security definer` functions drive role checks (see [rpcs.md](./rpcs.md#role
| `profiles` | own **or** admin | — | admin only | admin only | | `profiles` | own **or** admin | — | admin only | admin only |
| `slots` | all authenticated | admin only | admin only | admin only | | `slots` | all authenticated | admin only | admin only | admin only |
| `sessions` | all authenticated | admin only | admin only | admin only | | `sessions` | all authenticated | admin only | admin only | admin only |
| `preferences` | own (`profile_id = auth.uid()`) | — | — | — | | `preferences` | own **or** admin | — | — | — |
| `connections` | rows you're in (`from_id` or `to_id` = you) | — | — | — | | `connections` | rows you're in **or** admin | — | — | — |
| `checkins` | own **or** staff/admin | — | — | — | | `checkins` | own **or** staff/admin | — | — | — |
| `feedback` | own | — | — | — | | `feedback` | own **or** admin | — | — | — |
| `leaderboard` | all authenticated | — | — | — | | `leaderboard` | all authenticated | — | — | — |
| `points_log` | own **or** admin | — | — | — | | `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 **"—" (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 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 deliberate: a client cannot `UPDATE profiles SET points = 9999` or insert its own
@@ -89,6 +94,12 @@ create policy "leaderboard_select_all" on public.leaderboard for select to authe
-- points_log: read own or admin -- points_log: read own or admin
create policy "points_log_select_own_or_admin" on public.points_log for select to authenticated 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()); 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());
``` ```
## GRANTs ## GRANTs
@@ -113,9 +124,10 @@ full DML at the Postgres level, but **RLS narrows it** to the policies above.
internally, e.g. only staff can call `checkin_attendee`). internally, e.g. only staff can call `checkin_attendee`).
- **Staff** — everything an attendee can do, plus can read all `checkins` and call - **Staff** — everything an attendee can do, plus can read all `checkins` and call
the check-in RPC. the check-in RPC.
- **Admin** — full read on everything, and the only role with **direct** write - **Admin** — full read on everything (including all `preferences`,
access to `profiles` / `slots` / `sessions` (this is what the future Admin app `connections`, and `feedback`), and the only role with **direct** write access
in Phase 2 will use). to `profiles` / `slots` / `sessions`. This is exactly what the Admin console
(Phase 2, [`../frontend/admin-app.md`](../frontend/admin-app.md)) uses.
## Things to revisit later ## Things to revisit later
+22 -2
View File
@@ -104,8 +104,28 @@ Post-session feedback.
- Otherwise inserts and awards `earned` (category `feedback`). - Otherwise inserts and awards `earned` (category `feedback`).
### `adjust_points(p_profile_id, p_delta, p_reason)` → `void` ### `adjust_points(p_profile_id, p_delta, p_reason)` → `void`
**Admin-only** manual points adjustment (category `admin`). Used by the future **Admin-only** manual points adjustment (category `admin`). Used by the Admin
Admin app (Phase 2). console (Phase 2) 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.
- 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
> `extensions` schema (not `public`), so the function — whose `search_path` is
> pinned to `public` — must qualify them as `extensions.gen_salt(...)` /
> `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).
## Role helper functions ## Role helper functions
+14 -7
View File
@@ -1,15 +1,22 @@
# Frontend — Attendee PWA # Frontend
The frontend is a **mobile-first single-page React app** (PWA) in There are **two** React apps, both talking to the same Supabase core through
[`apps/convivo/`](../../apps/convivo/). It is the same app for attendees, staff, same-origin paths:
and admins — the user's `role` changes what they see (e.g. the Scan tab becomes a
Check-in tab for staff). - **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
[admin-app.md](./admin-app.md).
| File | What it covers | | File | What it covers |
|---|---| |---|---|
| [app-structure.md](./app-structure.md) | Entry, contexts, the event hook, the tab shell, the demo clock | | [app-structure.md](./app-structure.md) | Attendee app: entry, contexts, the event hook, the tab shell, the demo clock |
| [screens.md](./screens.md) | Every screen: Login, Home, Agenda, Scan/Check-in, Connections, Feedback, Leaderboard, Profile | | [screens.md](./screens.md) | Attendee app: Login, Home, Agenda, Scan/Check-in, Connections, Feedback, Leaderboard, Profile |
| [api-client.md](./api-client.md) | The typed API wrapper + how the app talks to Supabase (auth, REST, realtime) | | [api-client.md](./api-client.md) | The typed API wrapper + how the app talks to Supabase (auth, REST, realtime) |
| [admin-app.md](./admin-app.md) | Admin console: views, the admin auth guard, QR reset, points, schedule |
## Tech ## Tech
+90
View File
@@ -0,0 +1,90 @@
# Frontend — Admin console
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.
It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
(nginx). The attendee app stays on 3000.
## What it does
| 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. |
## 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:
- If `role === 'admin'` → 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.
The demo admin is `CVV-ADM-0001` / `[email protected]`.
## Source layout
```
apps/admin/src/
├─ main.tsx # ReactDOM entry
├─ 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
│ └─ ToastContext.tsx # transient toasts
├─ lib/
│ ├─ supabase.ts # createClient (same-origin)
│ ├─ api.ts # typed wrapper: reads + updateProfile / adjustPoints / resetQrToken
│ └─ types.ts # TS types mirroring the DB
├─ components/
│ └─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, RoleBadge
├─ 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
```
## Data access
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).
### 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.
### Adjusting points
`adjust_points(profile_id, 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.
## 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.
+23 -19
View File
@@ -8,10 +8,10 @@ interface → **4** Sessionize interface.
> sync), and the Pretix interface is **Phase 3**. (Originally the whiteboard had > sync), and the Pretix interface is **Phase 3**. (Originally the whiteboard had
> Pretix as Phase 2 and the admin app as Phase 3.) > Pretix as Phase 2 and the admin app as Phase 3.)
> **Current state:** Phase 0 + Phase 1 are **complete and verified** (browser- > **Current state:** Phase 0 + Phase 1 + Phase 2 are **complete and verified**
> tested end-to-end, Docker-verified, pushed to `git.lago.dev/Lago/Convivo.git`). > (browser-tested end-to-end, Docker-verified, pushed to
> Per the working agreement, we **stop here** and let the user evaluate before > `git.lago.dev/Lago/Convivo.git`). Per the working agreement, we **stop here**
> starting Phase 2. > and let the user evaluate before starting Phase 3 (Pretix).
## Done ## Done
@@ -29,22 +29,27 @@ interface → **4** Sessionize interface.
- All flows browser-tested; Docker build + proxy + login verified. - All flows browser-tested; Docker build + proxy + login verified.
- Details: [frontend/README.md](./frontend/README.md). - Details: [frontend/README.md](./frontend/README.md).
## Next ### Phase 2 — Admin app (admin.appe.at) ✅
A separate desktop-first web app for event organizers, using the **admin** role
### Phase 2 — Admin app (admin.appe.at) ⬜ (next) (which has direct write access to `profiles` / `slots` / `sessions` via RLS — see
A separate web app for event organizers, using the **admin** role (which already
has direct write access to `profiles` / `slots` / `sessions` via RLS — see
[backend/rls.md](./backend/rls.md)). [backend/rls.md](./backend/rls.md)).
Likely scope: - **Login** — same QR + email flow, but guarded: non-admin accounts are signed
- Manage **attendees** (view, edit role/company, reset QR, adjust points via out and rejected ("This account is not an admin").
`adjust_points`). - **Dashboard** — live stats (attendees, check-ins, connections, avg rating,
- Manage **schedule** (slots + sessions) — create/edit/delete. sessions) + top points + recent activity.
- **Live overview** — who's checked in, connection activity, leaderboard. - **Attendees** — searchable table; edit name/company/role, view + **reset QR
- Reuse the same Supabase core + anon/service key pattern; a new `apps/admin` token** (new `reset_qr_token` RPC), **adjust points** (via `adjust_points`).
PWA. - **Schedule** — manage slots + sessions (create/edit/delete).
- **Activity** — check-ins, connections, and feedback tables.
- Same-origin proxy to Supabase (Vite dev on :3001 / nginx in Docker).
- Docker: `convivo-admin` service on :3001, same network + proxy pattern.
- All views + flows browser-tested; Docker build + proxy + login verified.
- Details: [frontend/admin-app.md](./frontend/admin-app.md).
### Phase 3 — Pretix interface ⬜ ## Next
### Phase 3 — Pretix interface ⬜ (next)
Sync **tickets → attendees** from [Pretix](https://pretix.eu) (the ticketing Sync **tickets → attendees** from [Pretix](https://pretix.eu) (the ticketing
system). This replaces the hand-written seed with real ticket data. system). This replaces the hand-written seed with real ticket data.
@@ -96,8 +101,7 @@ Likely scope:
1. **Pretix role mapping** — which ticket type = staff/admin? 1. **Pretix role mapping** — which ticket type = staff/admin?
2. **Sync style** — webhook (push) vs scheduled (pull) for Pretix/Sessionize? 2. **Sync style** — webhook (push) vs scheduled (pull) for Pretix/Sessionize?
3. **Sync runtime** — Supabase Edge Functions vs separate containers? 3. **Sync runtime** — Supabase Edge Functions vs separate containers?
4. **Admin app scope** — which admin features are must-haves for the event? 4. **Deployment target** — stay on localhost, or plan for the `appe.at`
5. **Deployment target** — stay on localhost, or plan for the `appe.at`
subdomains now? subdomains now?
## How to pick up work ## How to pick up work
+4 -2
View File
@@ -6,10 +6,12 @@
"scripts": { "scripts": {
"db:start": "supabase start", "db:start": "supabase start",
"db:stop": "supabase stop", "db:stop": "supabase stop",
"db:reset": "supabase reset", "db:reset": "supabase db reset",
"db:types": "supabase gen types typescript --local > packages/shared/src/database.types.ts", "db:types": "supabase gen types typescript --local > packages/shared/src/database.types.ts",
"app:dev": "npm --prefix apps/convivo run dev", "app:dev": "npm --prefix apps/convivo run dev",
"app:build": "npm --prefix apps/convivo run build" "app:build": "npm --prefix apps/convivo run build",
"admin:dev": "npm --prefix apps/admin run dev",
"admin:build": "npm --prefix apps/admin run build"
}, },
"devDependencies": { "devDependencies": {
"supabase": "^2.28.1" "supabase": "^2.28.1"
@@ -0,0 +1,79 @@
-- =============================================================================
-- Convivo — Phase 2 (Admin app): admin read access + QR reset RPC
--
-- The admin app (apps/admin) needs to:
-- 1. Read ALL profiles, preferences, connections, feedback, checkins,
-- points_log (a full event overview), not just the admin's own rows.
-- 2. Reset an attendee's QR token (which doubles as their auth password),
-- forcing them to re-login with the new lanyard code.
--
-- This migration adds the missing admin SELECT policies and a single
-- admin-only RPC. It does NOT change any existing policy.
-- =============================================================================
-- -----------------------------------------------------------------------------
-- ADMIN READ POLICIES
-- (profiles, checkins, points_log, leaderboard already allow admin/all reads.)
-- -----------------------------------------------------------------------------
-- preferences: admin can read everyone's picks
create policy "prefs_select_admin" on public.preferences for select to authenticated
using (public.is_admin());
-- connections: admin can read all connections (event overview)
create policy "conn_select_admin" on public.connections for select to authenticated
using (public.is_admin());
-- feedback: admin can read all feedback
create policy "feedback_select_admin" on public.feedback for select to authenticated
using (public.is_admin());
-- -----------------------------------------------------------------------------
-- reset_qr_token(p_profile_id) — admin only
--
-- Regenerates the attendee's QR token, syncs it into auth.users as the new
-- bcrypt password (the QR token IS the login password), and clears their
-- existing sessions so they must re-login with the new code.
--
-- security definer: runs as the table owner (postgres), which has write access
-- to both public.profiles and auth.* (verified).
-- -----------------------------------------------------------------------------
create or replace function public.reset_qr_token(p_profile_id uuid)
returns table (profile_id uuid, qr_token text)
language plpgsql security definer set search_path = public as $$
declare
v_uid uuid := auth.uid();
v_token text;
v_salt text;
begin
if v_uid is null then raise exception 'not authenticated'; end if;
if not public.is_admin() then raise exception 'admin only'; end if;
if not exists (select 1 from public.profiles where id = p_profile_id) then
raise exception 'profile not found';
end if;
-- Generate a fresh, human-friendly token: CVV-XXX-NNNN
v_token := 'CVV-' || upper(substr(md5(random()::text), 1, 3)) || '-' ||
lpad((floor(random() * 10000))::int::text, 4, '0');
-- Update the profile (source of truth for the lanyard).
update public.profiles set qr_token = v_token where id = p_profile_id;
-- Sync the auth password so the new token works for login.
-- (pgcrypto's gen_salt/crypt live in the `extensions` schema — qualify them,
-- since this function's search_path is pinned to `public`.)
v_salt := extensions.gen_salt('bf');
update auth.users
set encrypted_password = extensions.crypt(v_token, v_salt),
updated_at = now()
where id = p_profile_id;
-- Force re-login: drop the user's existing sessions.
delete from auth.sessions where user_id = p_profile_id;
return query select p_profile_id, v_token;
end;
$$;
grant execute on function public.reset_qr_token(uuid) to authenticated;