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.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
committed 2026-08-22 19:47:22 +02:00
1 parent 015c0a3a06
commit 32c86767ef
45 files changed
+4425 -87

No files matched your search

+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;
}