Post-event reporting + talk networking incentives
- Talk networking: per-event talk_networking_bonus awarded when two people who shared a checked-in talk accept a connection (accept_connection re-created, shared_talk flag, get_talk_cohort RPC, points_log category check widened); Convivo Networking sub-tab inside the Connect screen (Home quick action deep-links in; Connect button reflects existing connection state and is disabled for sent/connected/declined); admin Events view bonus input (0-10). - Reports: sidecar POST /export (CSV / multi-sheet XLSX / PDF report via new pdfkit dep); APPE Admin Reports view (any event: on-screen summary, session feedback summary, top-5, CSV/Excel/PDF downloads); Activity session-feedback per-session aggregate header. - Also carried: @appe.at admin trigger + default password, bulk contact delete, session level/area + event-level feedback, agenda level/area filters, admin password self-service, schedule level/area fields. - 18/18 RPC tests; both apps build; exports verified end-to-end.
This commit is contained in:
1 parent
08ab41898b
commit
3adc0fd58f
35 files changed
+3973
-54
No files matched your search
+101
-4
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { AuthProvider, useAuth } from './context/AuthContext';
|
||||
import { ToastProvider } from './context/ToastContext';
|
||||
import { ToastProvider, useToast } from './context/ToastContext';
|
||||
import { Login } from './screens/Login';
|
||||
import { Dashboard } from './views/Dashboard';
|
||||
import { Contacts } from './views/Contacts';
|
||||
@@ -10,7 +10,9 @@ import { Schedule } from './views/Schedule';
|
||||
import { Activity } from './views/Activity';
|
||||
import { Events } from './views/Events';
|
||||
import { Interfaces } from './views/Interfaces';
|
||||
import { Spinner } from './components/ui';
|
||||
import { Reports } from './views/Reports';
|
||||
import { Spinner, Modal } from './components/ui';
|
||||
import { DEFAULT_ADMIN_PASSWORD } from './lib/api';
|
||||
|
||||
export type View =
|
||||
| 'dashboard'
|
||||
@@ -20,7 +22,8 @@ export type View =
|
||||
| 'schedule'
|
||||
| 'activity'
|
||||
| 'events'
|
||||
| 'interfaces';
|
||||
| 'interfaces'
|
||||
| 'reports';
|
||||
|
||||
const NAV: { id: View; label: string; ico: string }[] = [
|
||||
{ id: 'dashboard', label: 'Dashboard', ico: '📊' },
|
||||
@@ -31,8 +34,100 @@ const NAV: { id: View; label: string; ico: string }[] = [
|
||||
{ id: 'activity', label: 'Activity', ico: '⚡' },
|
||||
{ id: 'events', label: 'Events', ico: '📅' },
|
||||
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
|
||||
{ id: 'reports', label: 'Reports', ico: '📤' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Shown once per session when an admin signs in with the default password
|
||||
* (`appe-admin-2026`). Prompts them to set a personal password. Dismissable
|
||||
* ("Not now"); the prompt re-appears on the next sign-in while the default is
|
||||
* in use.
|
||||
*/
|
||||
function ChangePasswordPrompt() {
|
||||
const { contact, changePassword } = useAuth();
|
||||
const { push } = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Open the prompt when the signed-in admin is using the default password.
|
||||
useEffect(() => {
|
||||
if (contact && contact.password === DEFAULT_ADMIN_PASSWORD) setOpen(true);
|
||||
}, [contact]);
|
||||
|
||||
async function onSubmit() {
|
||||
if (newPassword.length < 6) {
|
||||
setError('Password must be at least 6 characters.');
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await changePassword(newPassword);
|
||||
push('success', 'Password updated');
|
||||
setOpen(false);
|
||||
setNewPassword('');
|
||||
setConfirmPassword('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to change password');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
title="Change your password"
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost" onClick={() => setOpen(false)}>
|
||||
Not now
|
||||
</button>
|
||||
<button className="btn primary" onClick={onSubmit} disabled={busy}>
|
||||
{busy ? 'Saving…' : 'Save password'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p style={{ margin: 0, fontSize: 13.5, color: 'var(--muted)' }}>
|
||||
You signed in with the default admin password. Set a personal password
|
||||
so only you can access this account.
|
||||
</p>
|
||||
<div className="field">
|
||||
<label>New password</label>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
placeholder="••••••••••"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Confirm new password</label>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
placeholder="••••••••••"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
{error && <div className="login-err">{error}</div>}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { contact, loading, signOut } = useAuth();
|
||||
const [view, setView] = useState<View>('dashboard');
|
||||
@@ -49,6 +144,7 @@ function Shell() {
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<ChangePasswordPrompt />
|
||||
<aside className="sidebar">
|
||||
<div className="brand">
|
||||
<div className="logo"><img src="/icon-192.png" alt="APPE" /></div>
|
||||
@@ -99,6 +195,7 @@ function Shell() {
|
||||
{view === 'activity' && <Activity />}
|
||||
{view === 'events' && <Events />}
|
||||
{view === 'interfaces' && <Interfaces />}
|
||||
{view === 'reports' && <Reports />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { changeMyPassword } from '../lib/api';
|
||||
import type { Contact } from '../lib/types';
|
||||
|
||||
interface AuthState {
|
||||
@@ -8,6 +9,8 @@ interface AuthState {
|
||||
/** Sign in with the admin's email + password (event-independent). */
|
||||
signIn: (email: string, password: string) => Promise<void>;
|
||||
signOut: () => Promise<void>;
|
||||
/** Change the current admin's own login password (re-authenticates). */
|
||||
changePassword: (newPassword: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
@@ -100,8 +103,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setContact(null);
|
||||
}
|
||||
|
||||
async function changePassword(newPassword: string) {
|
||||
if (!contact) throw new Error('Not signed in');
|
||||
await changeMyPassword(contact.email, newPassword);
|
||||
// Re-load the contact so the (now changed) password is reflected.
|
||||
const c = await loadAdminContact(contact.email);
|
||||
if (c) setContact(c);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ contact, loading, signIn, signOut }}>
|
||||
<AuthContext.Provider value={{ contact, loading, signIn, signOut, changePassword }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
Connection,
|
||||
Contact,
|
||||
Event,
|
||||
EventFeedback,
|
||||
ExcelSyncResult,
|
||||
Feedback,
|
||||
LeaderboardRow,
|
||||
@@ -23,6 +24,9 @@ import type {
|
||||
|
||||
export class ApiError extends Error {}
|
||||
|
||||
/** The default admin password for @appe.at contacts (set by the DB trigger). */
|
||||
export const DEFAULT_ADMIN_PASSWORD = 'appe-admin-2026';
|
||||
|
||||
async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
|
||||
const { data, error } = await supabase.rpc(fn, args);
|
||||
if (error) throw new ApiError(error.message);
|
||||
@@ -61,6 +65,7 @@ export const getAllSessionSpeakers = () => all<SessionSpeaker>('session_speakers
|
||||
export const getAllConnections = () => all<Connection>('connections', { col: 'created_at', asc: false });
|
||||
export const getAllCheckins = () => all<Checkin>('checkins', { col: 'created_at', asc: false });
|
||||
export const getAllFeedback = () => all<Feedback>('feedback', { col: 'created_at', asc: false });
|
||||
export const getAllEventFeedback = () => all<EventFeedback>('event_feedback', { col: 'created_at', asc: false });
|
||||
export const getAllPointsLog = () => all<PointsLogRow>('points_log', { col: 'created_at', asc: false });
|
||||
export const getLeaderboard = () => all<LeaderboardRow>('leaderboard', { col: 'points', asc: false });
|
||||
|
||||
@@ -96,11 +101,34 @@ export async function deleteContact(email: string): Promise<void> {
|
||||
if (error) throw new ApiError(error.message);
|
||||
}
|
||||
|
||||
/** Delete many contacts at once (admin-only RLS). */
|
||||
/**
|
||||
* Delete many contacts at once (admin-only). Uses the `bulk_delete_contacts`
|
||||
* RPC, which bypasses the "a session must have at least one speaker" guard —
|
||||
* a direct PostgREST delete would fail (P0001) if the batch includes a contact
|
||||
* who is the sole speaker of a session.
|
||||
*/
|
||||
export async function deleteContacts(emails: string[]): Promise<void> {
|
||||
if (emails.length === 0) return;
|
||||
const { error } = await supabase.from('contacts').delete().in('email', emails);
|
||||
if (error) throw new ApiError(error.message);
|
||||
await rpc<number>('bulk_delete_contacts', { p_emails: emails });
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the current admin's own login password. Sets `contacts.password`
|
||||
* (the `trg_contact_password_sync` trigger re-hashes it into
|
||||
* `auth.users.encrypted_password`), then re-authenticates with the new
|
||||
* password so the session reflects the change.
|
||||
*/
|
||||
export async function changeMyPassword(email: string, newPassword: string): Promise<void> {
|
||||
const { error: updateError } = await supabase
|
||||
.from('contacts')
|
||||
.update({ password: newPassword })
|
||||
.eq('email', email);
|
||||
if (updateError) throw new ApiError(updateError.message);
|
||||
const { error: signInError } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password: newPassword,
|
||||
});
|
||||
if (signInError) throw new ApiError(signInError.message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,6 +199,7 @@ export async function upsertEvent(
|
||||
pretix_event_slug?: string | null;
|
||||
pretix_api_key?: string | null;
|
||||
use_realtime_clock?: boolean;
|
||||
talk_networking_bonus?: number;
|
||||
},
|
||||
): Promise<void> {
|
||||
if (id) {
|
||||
@@ -240,6 +269,34 @@ export async function importSessionizeExcel(eventId: string, file: File): Promis
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Request an event report from the sidecar (`POST /export`). Returns the
|
||||
* filename, mime type, and base64 content; the caller decodes and downloads.
|
||||
*/
|
||||
export const exportEventReport = (
|
||||
eventId: string,
|
||||
format: 'csv' | 'xlsx' | 'pdf',
|
||||
tables?: string[],
|
||||
) =>
|
||||
sidecarFetch<{ filename: string; mime: string; content_base64: string }>('/export', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ event_id: eventId, format, tables }),
|
||||
});
|
||||
|
||||
/** Decode a base64 report body and trigger a browser download. */
|
||||
export function downloadReport(res: { filename: string; mime: string; content_base64: string }): void {
|
||||
const bytes = Uint8Array.from(atob(res.content_base64), (c) => c.charCodeAt(0));
|
||||
const blob = new Blob([bytes], { type: res.mime });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = res.filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** Recent sync_runs rows for an event (newest first). */
|
||||
export const getSyncRuns = (eventId: string) =>
|
||||
all<SyncRun>('sync_runs', { col: 'started_at', asc: false }).then((rows) =>
|
||||
|
||||
@@ -43,6 +43,8 @@ export interface Event {
|
||||
pretix_api_key?: string | null;
|
||||
/** When the Sessionize sync last ran for this event. */
|
||||
last_synced_at: string | null;
|
||||
/** Bonus points each party earns for a connection when they shared a checked-in talk (0 = off). */
|
||||
talk_networking_bonus: number;
|
||||
avg_feedback: number | null;
|
||||
num_sessions: number;
|
||||
num_speakers: number;
|
||||
@@ -214,6 +216,20 @@ export interface Session {
|
||||
average_feedback: number | null;
|
||||
ai_generated_feedback: string | null;
|
||||
material_path: string | null;
|
||||
/** Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). */
|
||||
level: string | null;
|
||||
/** Free-text area/topic classification (e.g. Power Apps, Power Automate). */
|
||||
area: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** Event-level feedback (distinct from the per-session `feedback` table). */
|
||||
export interface EventFeedback {
|
||||
id: string;
|
||||
event_id: string;
|
||||
contact_email: string;
|
||||
rating: number;
|
||||
comment: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@@ -266,7 +282,7 @@ export interface PointsLogRow {
|
||||
event_id: string;
|
||||
contact_email: string;
|
||||
delta: number;
|
||||
category: 'checkin' | 'connection' | 'feedback' | 'admin';
|
||||
category: 'checkin' | 'connection' | 'feedback' | 'admin' | 'talk_networking';
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,14 +3,15 @@ import {
|
||||
getAllCheckins,
|
||||
getAllConnections,
|
||||
getAllContacts,
|
||||
getAllEventFeedback,
|
||||
getAllFeedback,
|
||||
getActiveEvent,
|
||||
getSessions,
|
||||
} from '../lib/api';
|
||||
import type { Checkin, Connection, Contact, Event, Feedback, Session } from '../lib/types';
|
||||
import type { Checkin, Connection, Contact, Event, EventFeedback, Feedback, Session } from '../lib/types';
|
||||
import { Avatar, Empty, Spinner } from '../components/ui';
|
||||
|
||||
type Tab = 'checkins' | 'connections' | 'feedback';
|
||||
type Tab = 'checkins' | 'connections' | 'feedback' | 'event_feedback';
|
||||
|
||||
export function Activity() {
|
||||
const [event, setEvent] = useState<Event | null>(null);
|
||||
@@ -21,17 +22,19 @@ export function Activity() {
|
||||
const [checkins, setCheckins] = useState<Checkin[]>([]);
|
||||
const [connections, setConnections] = useState<Connection[]>([]);
|
||||
const [feedback, setFeedback] = useState<Feedback[]>([]);
|
||||
const [eventFeedback, setEventFeedback] = useState<EventFeedback[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const ev = await getActiveEvent();
|
||||
setEvent(ev);
|
||||
const [c, ck, cn, fb] = await Promise.all([
|
||||
const [c, ck, cn, fb, efb] = await Promise.all([
|
||||
getAllContacts(),
|
||||
getAllCheckins(),
|
||||
getAllConnections(),
|
||||
getAllFeedback(),
|
||||
getAllEventFeedback(),
|
||||
]);
|
||||
setContacts(c);
|
||||
if (ev) {
|
||||
@@ -40,6 +43,7 @@ export function Activity() {
|
||||
setCheckins(ck.filter((x) => x.event_id === ev.id));
|
||||
setConnections(cn.filter((x) => x.event_id === ev.id));
|
||||
setFeedback(fb.filter((x) => x.event_id === ev.id));
|
||||
setEventFeedback(efb.filter((x) => x.event_id === ev.id));
|
||||
}
|
||||
setLoaded(true);
|
||||
} catch (e) {
|
||||
@@ -61,6 +65,26 @@ export function Activity() {
|
||||
return (id: string) => m.get(id) ?? id;
|
||||
}, [sessions]);
|
||||
|
||||
// Per-session feedback aggregate (avg rating + response count), for the
|
||||
// post-event session feedback summary.
|
||||
const sessionFeedbackSummary = useMemo(() => {
|
||||
const bySession = new Map<string, { count: number; sum: number }>();
|
||||
for (const f of feedback) {
|
||||
const e = bySession.get(f.session_id) ?? { count: 0, sum: 0 };
|
||||
e.count += 1;
|
||||
e.sum += f.rating;
|
||||
bySession.set(f.session_id, e);
|
||||
}
|
||||
return [...bySession.entries()]
|
||||
.map(([session_id, e]) => ({
|
||||
session_id,
|
||||
title: sessionTitle(session_id),
|
||||
avg: e.sum / e.count,
|
||||
count: e.count,
|
||||
}))
|
||||
.sort((a, b) => b.avg - a.avg);
|
||||
}, [feedback, sessionTitle]);
|
||||
|
||||
if (error) return <Empty icon="⚠️" text={error} />;
|
||||
if (!loaded)
|
||||
return (
|
||||
@@ -91,7 +115,7 @@ export function Activity() {
|
||||
<div>
|
||||
<h1>Activity</h1>
|
||||
<div className="sub">
|
||||
{event.name} · {checkins.length} check-ins · {connections.length} connections · {feedback.length} feedback.
|
||||
{event.name} · {checkins.length} check-ins · {connections.length} connections · {feedback.length} session feedback · {eventFeedback.length} event feedback.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -104,7 +128,10 @@ export function Activity() {
|
||||
Connections
|
||||
</button>
|
||||
<button className={tab === 'feedback' ? 'active' : ''} onClick={() => setTab('feedback')}>
|
||||
Feedback
|
||||
Session feedback
|
||||
</button>
|
||||
<button className={tab === 'event_feedback' ? 'active' : ''} onClick={() => setTab('event_feedback')}>
|
||||
Event feedback
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -185,6 +212,23 @@ export function Activity() {
|
||||
{feedback.length === 0 ? (
|
||||
<Empty icon="⭐" text="No feedback yet." />
|
||||
) : (
|
||||
<>
|
||||
{/* Per-session aggregate header (the post-event session feedback summary). */}
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>
|
||||
Per-session summary
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
{sessionFeedbackSummary.map((s) => (
|
||||
<span key={s.session_id} className="pill amber" title={s.title}>
|
||||
{s.title} · {s.avg.toFixed(1)}★ · {s.count}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{feedback.length > 0 && (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
@@ -216,6 +260,41 @@ export function Activity() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'event_feedback' && (
|
||||
<div className="card">
|
||||
{eventFeedback.length === 0 ? (
|
||||
<Empty icon="⭐" text="No event-level feedback yet." />
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>From</th>
|
||||
<th>Rating</th>
|
||||
<th>Comment</th>
|
||||
<th>When</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{eventFeedback.map((f) => (
|
||||
<tr key={f.id}>
|
||||
<td>
|
||||
<PersonCell name={nameOf(f.contact_email)} email={f.contact_email} />
|
||||
</td>
|
||||
<td>
|
||||
<span className="pill amber">{'★'.repeat(f.rating)}</span>
|
||||
</td>
|
||||
<td className="muted">{f.comment || '—'}</td>
|
||||
<td className="muted">{fmt(f.created_at)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -293,6 +293,7 @@ function EventModal({
|
||||
const [pretixLoading, setPretixLoading] = useState(false);
|
||||
const [pretixError, setPretixError] = useState<string | null>(null);
|
||||
const [realtimeClock, setRealtimeClock] = useState(event?.use_realtime_clock ?? false);
|
||||
const [talkBonus, setTalkBonus] = useState(event?.talk_networking_bonus ?? 2);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const lastFetchedKey = useRef<string | null>(null);
|
||||
|
||||
@@ -339,6 +340,7 @@ function EventModal({
|
||||
pretix_event_slug: pretixEventSlug.trim() || null,
|
||||
pretix_api_key: pretixApiKey.trim() || null,
|
||||
use_realtime_clock: realtimeClock,
|
||||
talk_networking_bonus: Math.max(0, Math.min(10, Math.round(talkBonus) || 0)),
|
||||
});
|
||||
onSaved(event ? 'Event updated' : 'Event created');
|
||||
} catch (e) {
|
||||
@@ -491,6 +493,27 @@ function EventModal({
|
||||
<Toggle checked={realtimeClock} onChange={setRealtimeClock} label={realtimeClock ? 'On' : 'Off'} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
<div className="row between" style={{ alignItems: 'center' }}>
|
||||
<div>
|
||||
<label>Talk networking bonus</label>
|
||||
<div className="muted small" style={{ marginTop: 2, maxWidth: 420 }}>
|
||||
Points each party earns when two people who were checked into the same talk accept a
|
||||
connection. <b>0 disables</b> the bonus (the +5 connection award still applies).
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
className="input mono"
|
||||
type="number"
|
||||
min={0}
|
||||
max={10}
|
||||
step={1}
|
||||
style={{ width: 84, textAlign: 'center' }}
|
||||
value={Number.isFinite(talkBonus) ? talkBonus : 0}
|
||||
onChange={(e) => setTalkBonus(parseInt(e.target.value, 10) || 0)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
downloadReport,
|
||||
exportEventReport,
|
||||
getAllCheckins,
|
||||
getAllConnections,
|
||||
getAllContacts,
|
||||
getAllEventFeedback,
|
||||
getAllEvents,
|
||||
getAllFeedback,
|
||||
getAllPointsLog,
|
||||
getLeaderboard,
|
||||
getRegistrations,
|
||||
getSessions,
|
||||
} from '../lib/api';
|
||||
import type {
|
||||
Checkin,
|
||||
Connection,
|
||||
Contact,
|
||||
Event,
|
||||
EventFeedback,
|
||||
Feedback,
|
||||
LeaderboardRow,
|
||||
PointsLogRow,
|
||||
Registration,
|
||||
Session,
|
||||
} from '../lib/types';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { Empty, Spinner } from '../components/ui';
|
||||
|
||||
const TABLES = [
|
||||
'registrations',
|
||||
'checkins',
|
||||
'connections',
|
||||
'session_feedback',
|
||||
'event_feedback',
|
||||
'leaderboard',
|
||||
'points_log',
|
||||
] as const;
|
||||
|
||||
const CATEGORY_LABEL: Record<string, string> = {
|
||||
checkin: 'Session check-ins',
|
||||
connection: 'Connections',
|
||||
feedback: 'Feedback',
|
||||
talk_networking: 'Talk networking',
|
||||
admin: 'Other',
|
||||
};
|
||||
|
||||
/**
|
||||
* Post-event reporting & export. For any event (active or past): an on-screen
|
||||
* summary (session-feedback summary + aggregates) and CSV / Excel / PDF report
|
||||
* downloads (served by the sidecar's `POST /export`).
|
||||
*/
|
||||
export function Reports() {
|
||||
const { push } = useToast();
|
||||
const [events, setEvents] = useState<Event[]>([]);
|
||||
const [selectedId, setSelectedId] = useState('');
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [contacts, setContacts] = useState<Contact[]>([]);
|
||||
const [registrations, setRegistrations] = useState<Registration[]>([]);
|
||||
const [checkins, setCheckins] = useState<Checkin[]>([]);
|
||||
const [connections, setConnections] = useState<Connection[]>([]);
|
||||
const [feedback, setFeedback] = useState<Feedback[]>([]);
|
||||
const [eventFeedback, setEventFeedback] = useState<EventFeedback[]>([]);
|
||||
const [leaderboard, setLeaderboard] = useState<LeaderboardRow[]>([]);
|
||||
const [pointsLog, setPointsLog] = useState<PointsLogRow[]>([]);
|
||||
const [sessions, setSessions] = useState<Session[]>([]);
|
||||
|
||||
const [tables, setTables] = useState<Set<string>>(new Set(TABLES));
|
||||
const [exporting, setExporting] = useState<'csv' | 'xlsx' | 'pdf' | null>(null);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const evs = await getAllEvents();
|
||||
setEvents(evs);
|
||||
const active = evs.find((e) => e.is_active);
|
||||
const first = active ?? evs[0];
|
||||
if (first) setSelectedId((cur) => cur || first.id);
|
||||
setLoaded(true);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load');
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
// Load the selected event's data (any event, not just the active one).
|
||||
useEffect(() => {
|
||||
if (!selectedId) return;
|
||||
let active = true;
|
||||
(async () => {
|
||||
try {
|
||||
const [c, reg, ck, cn, fb, efb, lb, pl, ss] = await Promise.all([
|
||||
getAllContacts(),
|
||||
getRegistrations(selectedId),
|
||||
getAllCheckins(),
|
||||
getAllConnections(),
|
||||
getAllFeedback(),
|
||||
getAllEventFeedback(),
|
||||
getLeaderboard(),
|
||||
getAllPointsLog(),
|
||||
getSessions(selectedId),
|
||||
]);
|
||||
if (!active) return;
|
||||
setContacts(c);
|
||||
setRegistrations(reg);
|
||||
setCheckins(ck.filter((x) => x.event_id === selectedId));
|
||||
setConnections(cn.filter((x) => x.event_id === selectedId));
|
||||
setFeedback(fb.filter((x) => x.event_id === selectedId));
|
||||
setEventFeedback(efb.filter((x) => x.event_id === selectedId));
|
||||
setLeaderboard(lb.filter((x) => x.event_id === selectedId));
|
||||
setPointsLog(pl.filter((x) => x.event_id === selectedId));
|
||||
setSessions(ss);
|
||||
} catch (e) {
|
||||
if (active) setError(e instanceof Error ? e.message : 'Failed to load event data');
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [selectedId]);
|
||||
|
||||
const nameOf = useMemo(() => {
|
||||
const m = new Map(contacts.map((c) => [c.email, c.full_name]));
|
||||
return (email: string) => m.get(email) ?? email;
|
||||
}, [contacts]);
|
||||
|
||||
// ---- Aggregates -----------------------------------------------------------
|
||||
const byType = useMemo(() => {
|
||||
const t: Record<string, number> = {};
|
||||
for (const r of registrations) t[r.type] = (t[r.type] ?? 0) + 1;
|
||||
return t;
|
||||
}, [registrations]);
|
||||
|
||||
const acceptedConnections = useMemo(
|
||||
() => connections.filter((c) => c.status === 'accepted').length,
|
||||
[connections],
|
||||
);
|
||||
|
||||
const sessionFeedbackAvg = useMemo(() => {
|
||||
if (feedback.length === 0) return null;
|
||||
return feedback.reduce((s, f) => s + f.rating, 0) / feedback.length;
|
||||
}, [feedback]);
|
||||
|
||||
const eventFeedbackAvg = useMemo(() => {
|
||||
if (eventFeedback.length === 0) return null;
|
||||
return eventFeedback.reduce((s, f) => s + f.rating, 0) / eventFeedback.length;
|
||||
}, [eventFeedback]);
|
||||
|
||||
// Per-session feedback summary (the "post-event session feedback summary").
|
||||
const sessionSummary = useMemo(() => {
|
||||
const bySession = new Map<string, { count: number; sum: number }>();
|
||||
for (const f of feedback) {
|
||||
const e = bySession.get(f.session_id) ?? { count: 0, sum: 0 };
|
||||
e.count += 1;
|
||||
e.sum += f.rating;
|
||||
bySession.set(f.session_id, e);
|
||||
}
|
||||
return sessions
|
||||
.map((s) => {
|
||||
const e = bySession.get(s.id);
|
||||
return {
|
||||
title: s.title,
|
||||
room: s.room,
|
||||
avg: e ? e.sum / e.count : null,
|
||||
count: e ? e.count : 0,
|
||||
};
|
||||
})
|
||||
.filter((s) => s.count > 0)
|
||||
.sort((a, b) => (b.avg ?? 0) - (a.avg ?? 0));
|
||||
}, [sessions, feedback]);
|
||||
|
||||
const topLeaderboard = useMemo(
|
||||
() => [...leaderboard].sort((a, b) => b.points - a.points).slice(0, 5),
|
||||
[leaderboard],
|
||||
);
|
||||
|
||||
const pointsByCategory = useMemo(() => {
|
||||
const t: Record<string, number> = {};
|
||||
for (const l of pointsLog) t[l.category] = (t[l.category] ?? 0) + l.delta;
|
||||
return t;
|
||||
}, [pointsLog]);
|
||||
|
||||
// ---- Export -------------------------------------------------------------
|
||||
async function doExport(format: 'csv' | 'xlsx' | 'pdf') {
|
||||
if (!selectedId) return;
|
||||
setExporting(format);
|
||||
try {
|
||||
const res = await exportEventReport(selectedId, format, format === 'pdf' ? undefined : [...tables]);
|
||||
downloadReport(res);
|
||||
push('success', `Downloaded ${format.toUpperCase()} report`);
|
||||
} catch (e) {
|
||||
push('error', e instanceof Error ? e.message : 'Export failed');
|
||||
} finally {
|
||||
setExporting(null);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTable(t: string) {
|
||||
setTables((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(t)) next.delete(t);
|
||||
else next.add(t);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
if (error) return <Empty icon="⚠️" text={error} />;
|
||||
if (!loaded)
|
||||
return (
|
||||
<div className="loading-screen">
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
|
||||
const selected = events.find((e) => e.id === selectedId);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-head">
|
||||
<div>
|
||||
<h1>Reports</h1>
|
||||
<div className="sub">Post-event summary + CSV / Excel / PDF export. Works for any event.</div>
|
||||
</div>
|
||||
<select
|
||||
className="input"
|
||||
style={{ maxWidth: 320 }}
|
||||
value={selectedId}
|
||||
onChange={(e) => setSelectedId(e.target.value)}
|
||||
>
|
||||
{events.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name} {e.is_active ? '(active)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{!selected ? (
|
||||
<div className="card">
|
||||
<Empty icon="📅" text="No events yet. Create one in the Events view first." />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* On-screen summary */}
|
||||
<div className="card" style={{ marginBottom: 18 }}>
|
||||
<h2 className="h2">📊 Summary — {selected.name}</h2>
|
||||
<div className="muted small" style={{ marginBottom: 12 }}>
|
||||
{selected.start_date} – {selected.end_date}
|
||||
{selected.location ? ` · ${selected.location}` : ''}
|
||||
</div>
|
||||
<div className="stat-grid">
|
||||
<Stat label="Registrations" value={registrations.length} />
|
||||
<Stat label="Check-ins" value={checkins.length} />
|
||||
<Stat label="Connections" value={connections.length} sub={`${acceptedConnections} accepted`} />
|
||||
<Stat label="Session feedback" value={feedback.length} sub={sessionFeedbackAvg != null ? `avg ${sessionFeedbackAvg.toFixed(1)}★` : undefined} />
|
||||
<Stat label="Event feedback" value={eventFeedback.length} sub={eventFeedbackAvg != null ? `avg ${eventFeedbackAvg.toFixed(1)}★` : undefined} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', marginTop: 14 }}>
|
||||
<div>
|
||||
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>Registrations by type</div>
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
{Object.entries(byType).map(([t, n]) => (
|
||||
<span key={t} className="pill">{t}: {n}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="muted small" style={{ fontWeight: 700, marginBottom: 6 }}>Points by category</div>
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
{Object.entries(pointsByCategory).map(([c, n]) => (
|
||||
<span key={c} className="pill">{CATEGORY_LABEL[c] ?? c}: +{n}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Session feedback summary */}
|
||||
<div className="card" style={{ marginBottom: 18 }}>
|
||||
<h2 className="h2">⭐ Session feedback summary</h2>
|
||||
{sessionSummary.length === 0 ? (
|
||||
<Empty icon="⭐" text="No session feedback yet." />
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Session</th>
|
||||
<th>Room</th>
|
||||
<th>Avg rating</th>
|
||||
<th>Responses</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sessionSummary.map((s) => (
|
||||
<tr key={s.title}>
|
||||
<td style={{ fontWeight: 600 }}>{s.title}</td>
|
||||
<td className="muted">{s.room ?? '—'}</td>
|
||||
<td>
|
||||
<span className="pill amber">
|
||||
{s.avg != null ? `${s.avg.toFixed(1)}★` : '—'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="muted">{s.count}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Top leaderboard */}
|
||||
<div className="card" style={{ marginBottom: 18 }}>
|
||||
<h2 className="h2">🏆 Top points</h2>
|
||||
{topLeaderboard.length === 0 ? (
|
||||
<Empty icon="🏆" text="No points yet." />
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Attendee</th>
|
||||
<th>Points</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{topLeaderboard.map((r, i) => (
|
||||
<tr key={r.contact_email}>
|
||||
<td className="muted">{i + 1}</td>
|
||||
<td style={{ fontWeight: 600 }}>{nameOf(r.contact_email)}</td>
|
||||
<td>
|
||||
<span className="pill amber">⚡ {r.points}</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Export */}
|
||||
<div className="card">
|
||||
<h2 className="h2">📤 Export</h2>
|
||||
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 14 }}>
|
||||
<button
|
||||
className="btn primary"
|
||||
disabled={exporting !== null || tables.size === 0}
|
||||
onClick={() => void doExport('csv')}
|
||||
>
|
||||
{exporting === 'csv' ? 'Preparing…' : 'Download CSV'}
|
||||
</button>
|
||||
<button
|
||||
className="btn primary"
|
||||
disabled={exporting !== null || tables.size === 0}
|
||||
onClick={() => void doExport('xlsx')}
|
||||
>
|
||||
{exporting === 'xlsx' ? 'Preparing…' : 'Download Excel'}
|
||||
</button>
|
||||
<button className="btn primary" disabled={exporting !== null} onClick={() => void doExport('pdf')}>
|
||||
{exporting === 'pdf' ? 'Preparing…' : 'Download PDF report'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="muted small" style={{ marginBottom: 8 }}>
|
||||
Tables included in CSV / Excel:
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
|
||||
{TABLES.map((t) => (
|
||||
<label key={t} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={tables.has(t)}
|
||||
onChange={() => toggleTable(t)}
|
||||
style={{ width: 16, height: 16, accentColor: 'var(--accent)' }}
|
||||
/>
|
||||
<span className="muted small">{t.replace('_', ' ')}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ label, value, sub }: { label: string; value: number; sub?: string }) {
|
||||
return (
|
||||
<div className="stat">
|
||||
<div className="val">{value}</div>
|
||||
<div className="lbl">
|
||||
{label}
|
||||
{sub ? ` · ${sub}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -193,7 +193,7 @@ export function Schedule() {
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 700, fontSize: 14 }}>{s.title}</div>
|
||||
<div className="muted small">
|
||||
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null].filter(Boolean).join(' · ')}
|
||||
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null, s.level ? `📶 ${s.level}` : null, s.area ? `🗂 ${s.area}` : null].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
<div className="muted small" style={{ marginTop: 4 }}>
|
||||
{s.average_feedback != null && <span>⭐ {s.average_feedback.toFixed(1)}</span>}
|
||||
@@ -364,6 +364,8 @@ function SessionModal({
|
||||
const [room, setRoom] = useState(session?.room ?? '');
|
||||
const [capacity, setCapacity] = useState(session?.capacity?.toString() ?? '');
|
||||
const [description, setDescription] = useState(session?.description ?? '');
|
||||
const [level, setLevel] = useState(session?.level ?? '');
|
||||
const [area, setArea] = useState(session?.area ?? '');
|
||||
const [speakerEmails, setSpeakerEmails] = useState<string[]>(currentSpeakers);
|
||||
const [material, setMaterial] = useState<File | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -377,6 +379,8 @@ function SessionModal({
|
||||
room: room.trim() || null,
|
||||
capacity: capacity ? parseInt(capacity, 10) : null,
|
||||
description: description.trim() || null,
|
||||
level: level.trim() || null,
|
||||
area: area.trim() || null,
|
||||
slot_id: slotId,
|
||||
event_id: eventId,
|
||||
};
|
||||
@@ -445,6 +449,16 @@ function SessionModal({
|
||||
<label>Description</label>
|
||||
<textarea className="input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="—" />
|
||||
</div>
|
||||
<div className="grid-2">
|
||||
<div className="field">
|
||||
<label>Level</label>
|
||||
<input className="input" value={level} onChange={(e) => setLevel(e.target.value)} placeholder="e.g. 100 / Beginner" />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Area / Topic</label>
|
||||
<input className="input" value={area} onChange={(e) => setArea(e.target.value)} placeholder="e.g. Power Apps" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label>Speakers ({speakerEmails.length})</label>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Connections } from './screens/Connections';
|
||||
import { Leaderboard } from './screens/Leaderboard';
|
||||
import { Profile } from './screens/Profile';
|
||||
import { Feedback } from './screens/Feedback';
|
||||
import { EventFeedback } from './screens/EventFeedback';
|
||||
import { QrImage, Spinner } from './components/ui';
|
||||
import { getMyConnections } from './lib/api';
|
||||
import { usePolling } from './lib/usePolling';
|
||||
@@ -26,7 +27,22 @@ function Shell() {
|
||||
const { session, contact, registration, loading, refresh, signOut } = useAuth();
|
||||
const [tab, setTab] = useState<Tab>('home');
|
||||
const [feedbackSession, setFeedbackSession] = useState<string | null>(null);
|
||||
const [eventFeedbackOpen, setEventFeedbackOpen] = useState(false);
|
||||
const [pendingIncoming, setPendingIncoming] = useState(0);
|
||||
// Which sub-tab the Connect screen opens on (default 'mine'; 'networking'
|
||||
// when reached via the Home "Networking" quick action).
|
||||
const [connectionsTab, setConnectionsTab] = useState<'mine' | 'req' | 'networking'>('mine');
|
||||
|
||||
// Home's `go` handles the tab ids; 'networking' routes into the Connect
|
||||
// screen's networking sub-tab.
|
||||
const go = (t: string) => {
|
||||
if (t === 'networking') {
|
||||
setConnectionsTab('networking');
|
||||
setTab('connections');
|
||||
return;
|
||||
}
|
||||
setTab(t as Tab);
|
||||
};
|
||||
|
||||
const email = contact?.email ?? '';
|
||||
|
||||
@@ -123,16 +139,25 @@ function Shell() {
|
||||
);
|
||||
}
|
||||
|
||||
// Event-level feedback is also a full-screen takeover (no tab bar).
|
||||
if (eventFeedbackOpen) {
|
||||
return (
|
||||
<div className="app">
|
||||
<EventFeedback onDone={() => { setEventFeedbackOpen(false); setTab('home'); }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// The home page (incl. the tab bar) is identical for every role. Staff keep
|
||||
// their check-in capability inside the Scan screen (Attendee/Staff toggle).
|
||||
const scanLabel = 'Scan';
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
{tab === 'home' && <Home go={(t) => setTab(t as Tab)} />}
|
||||
{tab === 'home' && <Home go={go} onEventFeedback={() => setEventFeedbackOpen(true)} />}
|
||||
{tab === 'agenda' && <Agenda openFeedback={(id) => setFeedbackSession(id)} />}
|
||||
{tab === 'scan' && <Scan />}
|
||||
{tab === 'connections' && <Connections />}
|
||||
{tab === 'connections' && <Connections initialTab={connectionsTab} />}
|
||||
{tab === 'profile' && <Profile />}
|
||||
{tab === 'leaderboard' && <Leaderboard />}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
Connection,
|
||||
Contact,
|
||||
Event,
|
||||
EventFeedback,
|
||||
Feedback,
|
||||
FeedbackResult,
|
||||
LeaderboardRow,
|
||||
@@ -15,6 +16,8 @@ import type {
|
||||
Session,
|
||||
Slot,
|
||||
WelcomeCheckinResult,
|
||||
AcceptConnectionResult,
|
||||
TalkCohortMember,
|
||||
} from './types';
|
||||
|
||||
export class ApiError extends Error {}
|
||||
@@ -74,6 +77,8 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
|
||||
ai_generated_feedback: r.ai_generated_feedback,
|
||||
material_path: r.material_path,
|
||||
speakers: r.speakers,
|
||||
level: r.level,
|
||||
area: r.area,
|
||||
created_at: '',
|
||||
});
|
||||
}
|
||||
@@ -81,6 +86,17 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
|
||||
return [...map.values()].sort((a, b) => a.slot.id - b.slot.id);
|
||||
}
|
||||
|
||||
/** Submit (or update) the current user's event-level feedback. */
|
||||
export async function submitEventFeedback(rating: number, comment: string): Promise<void> {
|
||||
await rpc('submit_event_feedback', { p_rating: rating, p_comment: comment });
|
||||
}
|
||||
|
||||
/** Read the current user's own event-level feedback (null if not yet submitted). */
|
||||
export async function getMyEventFeedback(): Promise<EventFeedback | null> {
|
||||
const rows = await rpc<EventFeedback[]>('get_my_event_feedback', {});
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
/** The signed-in contact's own row (filter by email — admins can see all rows). */
|
||||
export async function getMyContact(email: string): Promise<Contact | null> {
|
||||
const { data, error } = await supabase.from('contacts').select('*').eq('email', email).maybeSingle();
|
||||
@@ -139,8 +155,9 @@ export async function createConnectionRequest(targetQr: string): Promise<Connect
|
||||
return rpc<Connection>('create_connection_request', { p_target_qr: targetQr });
|
||||
}
|
||||
|
||||
export async function acceptConnection(id: string): Promise<Connection> {
|
||||
return rpc<Connection>('accept_connection', { p_connection_id: id });
|
||||
export async function acceptConnection(id: string): Promise<AcceptConnectionResult> {
|
||||
// accept_connection returns a single composite row (a JSON object).
|
||||
return rpc<AcceptConnectionResult>('accept_connection', { p_connection_id: id });
|
||||
}
|
||||
|
||||
export async function rejectConnection(id: string): Promise<Connection> {
|
||||
@@ -154,6 +171,11 @@ export async function getMyCheckins(email: string): Promise<string[]> {
|
||||
return (data as { session_id: string }[]).map((c) => c.session_id);
|
||||
}
|
||||
|
||||
/** Other attendees (staff excluded, self excluded) checked into the same talk. */
|
||||
export async function getTalkCohort(sessionId: string): Promise<TalkCohortMember[]> {
|
||||
return rpc<TalkCohortMember[]>('get_talk_cohort', { p_session_id: sessionId });
|
||||
}
|
||||
|
||||
export async function checkinAttendee(sessionId: string, attendeeQr: string): Promise<CheckinResult> {
|
||||
const rows = await rpc<CheckinResult[]>('checkin_attendee', { p_session_id: sessionId, p_attendee_qr: attendeeQr });
|
||||
return rows[0];
|
||||
|
||||
@@ -35,6 +35,8 @@ export interface Event {
|
||||
is_active: boolean;
|
||||
/** When true, the app uses the real system clock for slot status (Live/Next/Done). */
|
||||
use_realtime_clock: boolean;
|
||||
/** Bonus points each party earns for a connection when they shared a checked-in talk (0 = off). */
|
||||
talk_networking_bonus: number;
|
||||
avg_feedback: number | null;
|
||||
num_sessions: number;
|
||||
num_speakers: number;
|
||||
@@ -68,6 +70,10 @@ export interface Session {
|
||||
material_path: string | null;
|
||||
/** Comma-separated speaker names (from the get_agenda RPC). */
|
||||
speakers: string | null;
|
||||
/** Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). */
|
||||
level: string | null;
|
||||
/** Free-text area/topic classification (e.g. Power Apps, Power Automate). */
|
||||
area: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@@ -88,6 +94,18 @@ export interface AgendaRow {
|
||||
ai_generated_feedback: string | null;
|
||||
material_path: string | null;
|
||||
speakers: string | null;
|
||||
level: string | null;
|
||||
area: string | null;
|
||||
}
|
||||
|
||||
/** Event-level feedback (distinct from the per-session `feedback` table). */
|
||||
export interface EventFeedback {
|
||||
id: string;
|
||||
event_id: string;
|
||||
contact_email: string;
|
||||
rating: number;
|
||||
comment: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Preference {
|
||||
@@ -141,7 +159,7 @@ export interface PointsLogRow {
|
||||
event_id: string;
|
||||
contact_email: string;
|
||||
delta: number;
|
||||
category: 'checkin' | 'connection' | 'feedback' | 'admin';
|
||||
category: 'checkin' | 'connection' | 'feedback' | 'admin' | 'talk_networking';
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@@ -169,6 +187,20 @@ export interface WelcomeCheckinResult {
|
||||
already: boolean;
|
||||
}
|
||||
|
||||
/** Result of accepting a connection (the connection row + the shared-talk flag). */
|
||||
export interface AcceptConnectionResult extends Connection {
|
||||
/** True when both parties were checked into the same session (talk). */
|
||||
shared_talk: boolean;
|
||||
}
|
||||
|
||||
/** A person checked into the same talk (from get_talk_cohort). */
|
||||
export interface TalkCohortMember {
|
||||
email: string;
|
||||
full_name: string;
|
||||
registration_type: RegistrationType | null;
|
||||
qr_token: string | null;
|
||||
}
|
||||
|
||||
export interface FeedbackResult {
|
||||
feedback_id: string;
|
||||
points: number;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useEvent } from '../lib/useEvent';
|
||||
import {
|
||||
@@ -26,8 +26,29 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Agenda filters: level + area (free-text, dynamic — built from the distinct
|
||||
// values actually present in the agenda, so it works for numeric levels
|
||||
// (100/200/300) or text levels (Beginner/Intermediate) alike).
|
||||
const [levelFilter, setLevelFilter] = useState<string>('');
|
||||
const [areaFilter, setAreaFilter] = useState<string>('');
|
||||
|
||||
const email = contact?.email ?? '';
|
||||
|
||||
// Distinct level + area values present in the agenda (for the filter dropdowns).
|
||||
const levelOptions = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const { sessions } of slots) for (const s of sessions) if (s.level) set.add(s.level);
|
||||
return [...set].sort();
|
||||
}, [slots]);
|
||||
const areaOptions = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const { sessions } of slots) for (const s of sessions) if (s.area) set.add(s.area);
|
||||
return [...set].sort();
|
||||
}, [slots]);
|
||||
|
||||
const matchesFilter = (s: Session) =>
|
||||
(!levelFilter || s.level === levelFilter) && (!areaFilter || s.area === areaFilter);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
(async () => {
|
||||
@@ -144,9 +165,60 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
|
||||
Pick <b>one session per slot</b> — you can change until the slot starts.
|
||||
</div>
|
||||
|
||||
{/* Agenda filters: level + area (only shown if there are values to filter by). */}
|
||||
{(levelOptions.length > 0 || areaOptions.length > 0) && (
|
||||
<div className="row" style={{ gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
|
||||
{levelOptions.length > 0 && (
|
||||
<select
|
||||
className="input"
|
||||
style={{ flex: 1, minWidth: 120 }}
|
||||
value={levelFilter}
|
||||
onChange={(e) => setLevelFilter(e.target.value)}
|
||||
aria-label="Filter by level"
|
||||
>
|
||||
<option value="">All levels</option>
|
||||
{levelOptions.map((l) => (
|
||||
<option key={l} value={l}>{l}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{areaOptions.length > 0 && (
|
||||
<select
|
||||
className="input"
|
||||
style={{ flex: 1, minWidth: 120 }}
|
||||
value={areaFilter}
|
||||
onChange={(e) => setAreaFilter(e.target.value)}
|
||||
aria-label="Filter by area"
|
||||
>
|
||||
<option value="">All areas</option>
|
||||
{areaOptions.map((a) => (
|
||||
<option key={a} value={a}>{a}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{(levelFilter || areaFilter) && (
|
||||
<button
|
||||
className="btn ghost small"
|
||||
onClick={() => { setLevelFilter(''); setAreaFilter(''); }}
|
||||
aria-label="Clear filters"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{slots.map(({ slot, sessions }) => {
|
||||
const status = slotStatus(slot, now);
|
||||
const isServiceSlot = slot.type === 'service_session';
|
||||
// Apply the level/area filter to non-service sessions only (service
|
||||
// sessions have no level/area and are always shown).
|
||||
const visibleSessions = isServiceSlot
|
||||
? sessions
|
||||
: sessions.filter(matchesFilter);
|
||||
// Skip the slot if it's a talk slot and all its sessions are filtered out.
|
||||
if (!isServiceSlot && visibleSessions.length === 0) return null;
|
||||
return (
|
||||
<div className="slot-card" key={slot.id}>
|
||||
<div className="slot-head">
|
||||
@@ -160,7 +232,7 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
|
||||
{status === 'now' && <span className="pill violet">● Live</span>}
|
||||
{status === 'next' && <span className="pill cyan">Up next</span>}
|
||||
</div>
|
||||
{sessions.map((s) => {
|
||||
{visibleSessions.map((s) => {
|
||||
const picked = pickFor(slot.id) === s.id;
|
||||
const isMySession = mySpeakerSessions.includes(s.id);
|
||||
const isService = slot.type === 'service_session';
|
||||
@@ -204,6 +276,8 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
|
||||
</div>
|
||||
<div className="row" style={{ gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
|
||||
<span className="pill">{selIsService ? '' : '🎤 '}{selected.speakers}</span>
|
||||
{selected.level && <span className="pill violet">📶 {selected.level}</span>}
|
||||
{selected.area && <span className="pill cyan">🗂 {selected.area}</span>}
|
||||
{selected.capacity && <span className="pill">👥 {selected.capacity}</span>}
|
||||
{selCheckedIn && <span className="pill green">✓ Checked in</span>}
|
||||
</div>
|
||||
|
||||
@@ -6,10 +6,20 @@ import { capWords } from '../lib/time';
|
||||
import type { Connection, PublicContact } from '../lib/types';
|
||||
import { Avatar, Empty, Sheet, Spinner } from '../components/ui';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { NetworkingPanel } from './Networking';
|
||||
|
||||
export function Connections() {
|
||||
export function Connections({
|
||||
initialTab = 'mine',
|
||||
}: {
|
||||
initialTab?: 'mine' | 'req' | 'networking';
|
||||
}) {
|
||||
const { contact } = useAuth();
|
||||
const [tab, setTab] = useState<'mine' | 'req'>('mine');
|
||||
const [tab, setTab] = useState<'mine' | 'req' | 'networking'>(initialTab);
|
||||
|
||||
// A deep-link (e.g. the Home "Networking" quick action) re-targets the tab.
|
||||
useEffect(() => {
|
||||
setTab(initialTab);
|
||||
}, [initialTab]);
|
||||
const [conns, setConns] = useState<Connection[]>([]);
|
||||
const [people, setPeople] = useState<Map<string, PublicContact>>(new Map());
|
||||
const [points, setPoints] = useState<Map<string, number>>(new Map());
|
||||
@@ -71,12 +81,13 @@ export function Connections() {
|
||||
|
||||
return (
|
||||
<section className="screen">
|
||||
<div className="h1">Connections</div>
|
||||
<div className="h1">{tab === 'networking' ? 'Networking' : 'Connections'}</div>
|
||||
<div className="seg">
|
||||
<button className={tab === 'mine' ? 'active' : ''} data-testid="connections-tab-mine" onClick={() => setTab('mine')}>My connections</button>
|
||||
<button className={tab === 'req' ? 'active' : ''} data-testid="connections-tab-req" onClick={() => setTab('req')}>
|
||||
Requests {incoming.length + outgoing.length > 0 && <span className="pill violet" style={{ marginLeft: 4 }}>{incoming.length + outgoing.length}</span>}
|
||||
</button>
|
||||
<button className={tab === 'networking' ? 'active' : ''} data-testid="connections-tab-networking" onClick={() => setTab('networking')}>🗣 Networking</button>
|
||||
</div>
|
||||
|
||||
{tab === 'mine' &&
|
||||
@@ -146,6 +157,8 @@ export function Connections() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'networking' && <NetworkingPanel />}
|
||||
|
||||
{detail && (() => {
|
||||
const p = people.get(detail.email);
|
||||
const t = p?.registration_type ?? null;
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useEvent } from '../lib/useEvent';
|
||||
import { getMyEventFeedback, submitEventFeedback } from '../lib/api';
|
||||
import { Spinner } from '../components/ui';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
|
||||
/**
|
||||
* Event-level feedback (distinct from the per-session Feedback screen).
|
||||
* Any registered participant can rate the event overall (1–5) + leave a
|
||||
* comment. Idempotent: one row per (event, contact) — re-submitting updates
|
||||
* the existing row.
|
||||
*/
|
||||
export function EventFeedback({ onDone }: { onDone: () => void }) {
|
||||
const { contact } = useAuth();
|
||||
const { event, loading } = useEvent();
|
||||
const [rating, setRating] = useState(0);
|
||||
const [comment, setComment] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Pre-fill with the user's existing event feedback (if any).
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
(async () => {
|
||||
try {
|
||||
const existing = await getMyEventFeedback();
|
||||
if (!active || !existing) return;
|
||||
setRating(existing.rating);
|
||||
setComment(existing.comment ?? '');
|
||||
setSubmitted(true);
|
||||
} catch {
|
||||
/* non-fatal */
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (loading || !event) {
|
||||
return (
|
||||
<section className="screen no-tab">
|
||||
<div className="center" style={{ flex: 1 }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (rating === 0) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await submitEventFeedback(rating, comment.trim());
|
||||
toast('Thanks for your feedback! ⭐', 'ok');
|
||||
setSubmitted(true);
|
||||
onDone();
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : 'Could not submit feedback', 'err');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="screen no-tab">
|
||||
<div className="row" style={{ marginBottom: 14 }}>
|
||||
<button className="btn ghost small" onClick={onDone}>← Back</button>
|
||||
<div className="grow" style={{ textAlign: 'center' }}>
|
||||
<div className="h2">Rate this event</div>
|
||||
</div>
|
||||
<span style={{ width: 60 }} />
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ textAlign: 'center' }}>
|
||||
<div className="h2">{event.name}</div>
|
||||
<div className="muted small" style={{ marginTop: 4 }}>
|
||||
{event.location ? `${event.location} · ` : ''}
|
||||
{event.start_date}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="stars" style={{ justifyContent: 'center', margin: '20px 0' }}>
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
data-testid={`event-feedback-star-${n}`}
|
||||
className={`star ${n <= rating ? 'on' : ''}`}
|
||||
onClick={() => setRating(n)}
|
||||
aria-label={`${n} star${n > 1 ? 's' : ''}`}
|
||||
>
|
||||
★
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
className="input"
|
||||
data-testid="event-feedback-comment"
|
||||
placeholder="Share your thoughts about the event (optional)"
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
rows={4}
|
||||
/>
|
||||
|
||||
<button
|
||||
className="btn primary"
|
||||
data-testid="event-feedback-submit"
|
||||
disabled={busy || rating === 0}
|
||||
onClick={submit}
|
||||
>
|
||||
{busy ? 'Submitting…' : submitted ? 'Update feedback' : 'Submit feedback'}
|
||||
</button>
|
||||
<div className="muted small" style={{ textAlign: 'center', marginTop: 8 }}>
|
||||
{contact ? `Signing in as ${contact.full_name}` : ''}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -42,7 +42,7 @@ function ConcurrentList({ sessions }: { sessions: Session[] }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function Home({ go }: { go: (tab: string) => void }) {
|
||||
export function Home({ go, onEventFeedback }: { go: (tab: string) => void; onEventFeedback?: () => void }) {
|
||||
const { contact, registration } = useAuth();
|
||||
const { event, slots, sessionById, slotById, now, clockMode, loading } = useEvent();
|
||||
const [prefs, setPrefs] = useState<Preference[]>([]);
|
||||
@@ -236,11 +236,20 @@ export function Home({ go }: { go: (tab: string) => void }) {
|
||||
<span className="ico">🤝</span>
|
||||
<span className="lbl">Connections</span>
|
||||
</div>
|
||||
<div className="qa" onClick={() => go('networking')}>
|
||||
<span className="ico">🗣</span>
|
||||
<span className="lbl">Networking</span>
|
||||
</div>
|
||||
<div className="qa" onClick={() => go('leaderboard')}>
|
||||
<span className="ico">🏆</span>
|
||||
<span className="lbl">Leaderboard</span>
|
||||
</div>
|
||||
</div>
|
||||
{onEventFeedback && (
|
||||
<button className="btn ghost" style={{ width: '100%', marginTop: 10 }} onClick={onEventFeedback}>
|
||||
⭐ Rate this event
|
||||
</button>
|
||||
)}
|
||||
<div style={{ height: 8 }} />
|
||||
|
||||
{/* Pending material popup (speakers only, when a session is missing its attachment) */}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useEvent } from '../lib/useEvent';
|
||||
import {
|
||||
createConnectionRequest,
|
||||
getMyCheckins,
|
||||
getMyConnections,
|
||||
getTalkCohort,
|
||||
} from '../lib/api';
|
||||
import { capWords } from '../lib/time';
|
||||
import type { Connection, TalkCohortMember } from '../lib/types';
|
||||
import { Avatar, Empty, Spinner } from '../components/ui';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
|
||||
/**
|
||||
* Networking around talks (an embeddable panel, shown as a tab inside the
|
||||
* Connect screen). For every talk the user was checked into, list the other
|
||||
* attendees who were also in that talk (the "talk cohort") so the user can
|
||||
* make a connection. Accepting a connection with a shared talk earns the
|
||||
* per-event talk networking bonus (see `events.talk_networking_bonus`).
|
||||
*/
|
||||
export function NetworkingPanel() {
|
||||
const { contact } = useAuth();
|
||||
const { event, sessionById, loading } = useEvent();
|
||||
const [myCheckins, setMyCheckins] = useState<string[]>([]);
|
||||
const [cohorts, setCohorts] = useState<Record<string, TalkCohortMember[]>>({});
|
||||
const [loadingCohorts, setLoadingCohorts] = useState(false);
|
||||
const [connecting, setConnecting] = useState<string | null>(null);
|
||||
// The user's existing connections, so a Connect button can show the current
|
||||
// state ("Sent" / "Connected" / …) instead of allowing duplicate requests.
|
||||
const [conns, setConns] = useState<Connection[]>([]);
|
||||
const { toast } = useToast();
|
||||
|
||||
const email = contact?.email ?? '';
|
||||
|
||||
const loadConns = useCallback(async () => {
|
||||
try {
|
||||
setConns(await getMyConnections());
|
||||
} catch {
|
||||
/* non-fatal */
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (email) void loadConns();
|
||||
}, [email, loadConns]);
|
||||
|
||||
// Keep the connection states fresh (a peer may accept while the panel is open).
|
||||
useEffect(() => {
|
||||
window.addEventListener('connections-changed', loadConns);
|
||||
return () => window.removeEventListener('connections-changed', loadConns);
|
||||
}, [loadConns]);
|
||||
|
||||
/** The existing connection to a given person (any status), or null. */
|
||||
const connWith = (theirEmail: string) =>
|
||||
conns.find((c) => (c.from_email === email && c.to_email === theirEmail) ||
|
||||
(c.from_email === theirEmail && c.to_email === email)) ?? null;
|
||||
|
||||
// Load the sessions the user is checked into, then each talk's cohort.
|
||||
useEffect(() => {
|
||||
if (!email) return;
|
||||
let active = true;
|
||||
(async () => {
|
||||
try {
|
||||
const ids = await getMyCheckins(email);
|
||||
if (!active) return;
|
||||
setMyCheckins(ids);
|
||||
if (ids.length === 0) return;
|
||||
setLoadingCohorts(true);
|
||||
const results = await Promise.all(
|
||||
ids.map(async (sid): Promise<[string, TalkCohortMember[]]> => {
|
||||
try {
|
||||
return [sid, await getTalkCohort(sid)];
|
||||
} catch {
|
||||
return [sid, []];
|
||||
}
|
||||
}),
|
||||
);
|
||||
if (!active) return;
|
||||
const map: Record<string, TalkCohortMember[]> = {};
|
||||
for (const [sid, list] of results) map[sid] = list;
|
||||
setCohorts(map);
|
||||
} catch {
|
||||
/* non-fatal */
|
||||
} finally {
|
||||
if (active) setLoadingCohorts(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [email]);
|
||||
|
||||
// Only show talks that actually exist in the agenda (check-ins for a
|
||||
// service session or a removed session are skipped).
|
||||
const myTalks = useMemo(
|
||||
() => myCheckins.filter((sid) => sessionById.has(sid)).map((sid) => sessionById.get(sid)!),
|
||||
[myCheckins, sessionById],
|
||||
);
|
||||
|
||||
if (loading || !contact) {
|
||||
return (
|
||||
<div className="center" style={{ flex: 1 }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function connect(member: TalkCohortMember) {
|
||||
if (!member.qr_token) {
|
||||
toast('No QR token for this attendee', 'err');
|
||||
return;
|
||||
}
|
||||
// Never allow a duplicate request: if a connection already exists (any
|
||||
// status), the button is disabled — this is the backstop.
|
||||
if (connWith(member.email)) return;
|
||||
setConnecting(member.email);
|
||||
try {
|
||||
const conn = await createConnectionRequest(member.qr_token);
|
||||
if (conn.status === 'accepted') toast(`Connected with ${member.full_name}! 🤝`, 'ok');
|
||||
else if (conn.status === 'pending') toast(`Request sent to ${member.full_name}`, 'ok');
|
||||
else toast('Request already resolved');
|
||||
window.dispatchEvent(new Event('connections-changed'));
|
||||
await loadConns();
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : 'Could not send request', 'err');
|
||||
} finally {
|
||||
setConnecting(null);
|
||||
}
|
||||
}
|
||||
|
||||
/** The Connect button state for a person: 'connect' | 'sent' | 'connected' | 'requested' | 'declined'. */
|
||||
function connState(theirEmail: string): { label: string; kind: string } {
|
||||
const c = connWith(theirEmail);
|
||||
if (!c) return { label: 'Connect', kind: 'connect' };
|
||||
if (c.status === 'accepted') return { label: 'Connected', kind: 'connected' };
|
||||
if (c.status === 'pending') {
|
||||
return c.from_email === email
|
||||
? { label: 'Sent', kind: 'sent' }
|
||||
: { label: 'Requested', kind: 'requested' };
|
||||
}
|
||||
return { label: 'Declined', kind: 'declined' };
|
||||
}
|
||||
|
||||
const bonus = event?.talk_networking_bonus ?? 0;
|
||||
|
||||
return (
|
||||
<div data-testid="networking-panel">
|
||||
<div className="muted small" style={{ marginBottom: 14 }}>
|
||||
People who were in the same talk as you.
|
||||
{bonus > 0 ? (
|
||||
<> Connect with them to earn <b>+{bonus} pts</b> (shared talk).</>
|
||||
) : (
|
||||
<> Connect with people you met at a talk.</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{myTalks.length === 0 ? (
|
||||
<Empty icon="🗣" text="You haven’t been checked into a talk yet. Get checked in by staff to see who else was there." />
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
{myTalks.map((talk) => {
|
||||
const members = (cohorts[talk.id] ?? []).filter((m) => m.email !== email);
|
||||
return (
|
||||
<div className="card" key={talk.id} data-testid={`networking-talk-${talk.id}`}>
|
||||
<div className="h2" style={{ marginBottom: 2 }}>{talk.title}</div>
|
||||
<div className="muted small" style={{ marginBottom: 10 }}>
|
||||
{talk.room ? `${talk.room} · ` : ''}
|
||||
{talk.speakers ? `🎤 ${talk.speakers}` : ''}
|
||||
</div>
|
||||
{loadingCohorts && (
|
||||
<div className="center" style={{ padding: 8 }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{!loadingCohorts && members.length === 0 && (
|
||||
<div className="muted small">No one else was checked in here yet.</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{members.map((m) => (
|
||||
<div className="conn" key={m.email} data-testid={`networking-member-${m.email}`}>
|
||||
<Avatar name={m.full_name} id={m.email} size={40} />
|
||||
<div className="grow">
|
||||
<div className="name">{m.full_name}</div>
|
||||
{m.registration_type && (
|
||||
<div className="meta">{capWords(m.registration_type)}</div>
|
||||
)}
|
||||
</div>
|
||||
{(() => {
|
||||
const s = connState(m.email);
|
||||
const disabled = s.kind !== 'connect' || connecting === m.email;
|
||||
return (
|
||||
<button
|
||||
className={
|
||||
s.kind === 'connected'
|
||||
? 'btn small'
|
||||
: s.kind === 'connect'
|
||||
? 'btn primary small'
|
||||
: 'btn ghost small'
|
||||
}
|
||||
data-testid={`networking-connect-${m.email}`}
|
||||
disabled={disabled}
|
||||
onClick={() => void connect(m)}
|
||||
>
|
||||
{connecting === m.email ? '…' : s.label}
|
||||
</button>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ const CATEGORY_LABEL: Record<PointsLogRow['category'], string> = {
|
||||
checkin: 'Session check-ins',
|
||||
connection: 'Connections',
|
||||
feedback: 'Feedback',
|
||||
talk_networking: 'Talk networking',
|
||||
admin: 'Other',
|
||||
};
|
||||
|
||||
|
||||
Generated
+1188
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@
|
||||
"start": "node src/server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"pdfkit": "^0.15.0",
|
||||
"xlsx": "^0.18.5"
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@
|
||||
|
||||
const http = require('http');
|
||||
const XLSX = require('xlsx');
|
||||
const PDFDocument = require('pdfkit');
|
||||
|
||||
const SUPABASE_URL = (process.env.SUPABASE_URL || 'http://supabase_kong_Convivo:8000').replace(/\/$/, '');
|
||||
const SERVICE_ROLE_KEY =
|
||||
@@ -275,6 +276,11 @@ function transform(data) {
|
||||
// A service session is a break/lunch/closing (isServiceSession) OR a
|
||||
// plenum (isPlenumSession) — plenums are full-hall items with no pick.
|
||||
is_service_session: Boolean(s.isServiceSession || s.isPlenumSession),
|
||||
// Level + area (free-text classification for agenda filtering).
|
||||
// Sessionize's public /view/ endpoint may not expose these; if present
|
||||
// (e.g. via a custom field or a future API version) we capture them.
|
||||
level: (s.level || '').trim() || null,
|
||||
area: (s.area || s.topic || '').trim() || null,
|
||||
speakers: speakerEmails,
|
||||
});
|
||||
}
|
||||
@@ -351,6 +357,11 @@ function transformExcel(buffer) {
|
||||
start_time,
|
||||
end_time,
|
||||
is_service_session: /service|break|lunch|closing|plenum/i.test(String(r['Session Format'] ?? '')),
|
||||
// Level + area (free-text classification for agenda filtering).
|
||||
// The Sessionize "Sessions and speakers (advanced)" .xlsx may include
|
||||
// "Level" and "Area"/"Topic" columns; we read them if present.
|
||||
level: String(r['Level'] ?? '').trim() || null,
|
||||
area: String(r['Area'] ?? r['Topic'] ?? '').trim() || null,
|
||||
speakers: speakerEmails,
|
||||
});
|
||||
}
|
||||
@@ -584,6 +595,301 @@ async function runPretixLoop() {
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// POST /export — event reports (CSV / XLSX / PDF)
|
||||
//
|
||||
// Fetches an event's full dataset (service role) and renders it as:
|
||||
// * csv — one combined CSV (a `table` column distinguishes the rows)
|
||||
// * xlsx — one workbook, one sheet per table
|
||||
// * pdf — a structured post-event report (summary + per-session + top points)
|
||||
// Returns { filename, mime, content_base64 }.
|
||||
// =============================================================================
|
||||
|
||||
// The tables an export can include (CSV/XLSX). The PDF always uses all of them.
|
||||
const EXPORT_TABLES = [
|
||||
'registrations',
|
||||
'checkins',
|
||||
'connections',
|
||||
'session_feedback',
|
||||
'event_feedback',
|
||||
'leaderboard',
|
||||
'points_log',
|
||||
];
|
||||
|
||||
// Escape a single CSV cell (RFC 4180).
|
||||
function csvCell(v) {
|
||||
const s = v == null ? '' : String(v);
|
||||
return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
|
||||
}
|
||||
|
||||
// Render an array of flat row objects as a single CSV string.
|
||||
function rowsToCsv(rows) {
|
||||
if (rows.length === 0) return '';
|
||||
const headers = Object.keys(rows[0]);
|
||||
const lines = [headers.map(csvCell).join(',')];
|
||||
for (const r of rows) lines.push(headers.map((h) => csvCell(r[h])).join(','));
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
// Fetch the event's full dataset (service role), joined for readability.
|
||||
async function fetchEventDataset(eventId) {
|
||||
const events = await supabaseFetch(
|
||||
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=*`,
|
||||
);
|
||||
const event = Array.isArray(events) ? events[0] : null;
|
||||
if (!event) throw new Error('event not found');
|
||||
|
||||
const [contacts, regs, checkins, connections, feedback, eventFeedback, leaderboard, pointsLog, sessions] =
|
||||
await Promise.all([
|
||||
supabaseFetch('/rest/v1/contacts?select=email,full_name'),
|
||||
supabaseFetch(`/rest/v1/registrations?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
supabaseFetch(`/rest/v1/checkins?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
supabaseFetch(`/rest/v1/connections?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
supabaseFetch(`/rest/v1/feedback?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
supabaseFetch(`/rest/v1/event_feedback?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
supabaseFetch(`/rest/v1/leaderboard?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
supabaseFetch(`/rest/v1/points_log?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
supabaseFetch(`/rest/v1/sessions?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
|
||||
]);
|
||||
|
||||
const nameOf = new Map((Array.isArray(contacts) ? contacts : []).map((c) => [c.email, c.full_name]));
|
||||
const sessionTitle = new Map((Array.isArray(sessions) ? sessions : []).map((s) => [s.id, s.title]));
|
||||
const titleOf = (id) => sessionTitle.get(id) ?? id ?? '';
|
||||
const name = (email) => nameOf.get(email) ?? email ?? '';
|
||||
|
||||
return {
|
||||
event,
|
||||
registrations: (Array.isArray(regs) ? regs : []).map((r) => ({
|
||||
email: r.contact_email,
|
||||
name: name(r.contact_email),
|
||||
type: r.type,
|
||||
checked_in: r.checked_in,
|
||||
points: r.points,
|
||||
qr_token: r.qr_token,
|
||||
})),
|
||||
checkins: (Array.isArray(checkins) ? checkins : []).map((c) => ({
|
||||
email: c.contact_email,
|
||||
name: name(c.contact_email),
|
||||
session: titleOf(c.session_id),
|
||||
checked_in_by: name(c.staff_email),
|
||||
when: c.created_at,
|
||||
})),
|
||||
connections: (Array.isArray(connections) ? connections : []).map((c) => ({
|
||||
from: name(c.from_email),
|
||||
to: name(c.to_email),
|
||||
status: c.status,
|
||||
when: c.created_at,
|
||||
})),
|
||||
sessionFeedback: (Array.isArray(feedback) ? feedback : []).map((f) => ({
|
||||
email: f.contact_email,
|
||||
name: name(f.contact_email),
|
||||
session: titleOf(f.session_id),
|
||||
rating: f.rating,
|
||||
comment: f.comment,
|
||||
when: f.created_at,
|
||||
})),
|
||||
eventFeedback: (Array.isArray(eventFeedback) ? eventFeedback : []).map((f) => ({
|
||||
email: f.contact_email,
|
||||
name: name(f.contact_email),
|
||||
rating: f.rating,
|
||||
comment: f.comment,
|
||||
when: f.created_at,
|
||||
})),
|
||||
leaderboard: (Array.isArray(leaderboard) ? leaderboard : [])
|
||||
.sort((a, b) => (b.points ?? 0) - (a.points ?? 0))
|
||||
.map((l) => ({ name: l.full_name ?? name(l.contact_email), points: l.points })),
|
||||
pointsLog: (Array.isArray(pointsLog) ? pointsLog : []).map((l) => ({
|
||||
email: l.contact_email,
|
||||
name: name(l.contact_email),
|
||||
delta: l.delta,
|
||||
category: l.category,
|
||||
when: l.created_at,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// Build the combined CSV (a `table` column distinguishes the rows).
|
||||
function buildCsv(ds, tables) {
|
||||
const source = {
|
||||
registrations: ds.registrations,
|
||||
checkins: ds.checkins,
|
||||
connections: ds.connections,
|
||||
session_feedback: ds.sessionFeedback,
|
||||
event_feedback: ds.eventFeedback,
|
||||
leaderboard: ds.leaderboard,
|
||||
points_log: ds.pointsLog,
|
||||
};
|
||||
const chunks = [];
|
||||
for (const t of tables) {
|
||||
const rows = source[t] || [];
|
||||
if (rows.length === 0) continue;
|
||||
const withTable = rows.map((r) => ({ table: t, ...r }));
|
||||
chunks.push(rowsToCsv(withTable));
|
||||
}
|
||||
return chunks.join('\n');
|
||||
}
|
||||
|
||||
// Build the multi-sheet XLSX workbook (one sheet per table).
|
||||
function buildXlsx(ds, tables) {
|
||||
const source = {
|
||||
registrations: ds.registrations,
|
||||
checkins: ds.checkins,
|
||||
connections: ds.connections,
|
||||
session_feedback: ds.sessionFeedback,
|
||||
event_feedback: ds.eventFeedback,
|
||||
leaderboard: ds.leaderboard,
|
||||
points_log: ds.pointsLog,
|
||||
};
|
||||
const wb = XLSX.utils.book_new();
|
||||
for (const t of tables) {
|
||||
const rows = source[t] || [];
|
||||
const ws = XLSX.utils.json_to_sheet(rows.length > 0 ? rows : [{ note: 'no data' }]);
|
||||
XLSX.utils.book_append_sheet(wb, ws, t.slice(0, 31));
|
||||
}
|
||||
const out = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });
|
||||
return out;
|
||||
}
|
||||
|
||||
// Build the PDF post-event report.
|
||||
function buildPdf(ds) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const doc = new PDFDocument({ size: 'A4', margin: 48 });
|
||||
const buf = [];
|
||||
doc.on('data', (c) => buf.push(c));
|
||||
doc.on('end', () => resolve(Buffer.concat(buf)));
|
||||
doc.on('error', reject);
|
||||
|
||||
const ev = ds.event;
|
||||
const h2 = (t) => {
|
||||
doc.font('Helvetica-Bold').fontSize(13);
|
||||
doc.text(t, { continued: false });
|
||||
doc.moveDown(0.4);
|
||||
};
|
||||
const line = (label, value) => {
|
||||
doc.font('Helvetica').fontSize(10);
|
||||
doc.text(`${label}: `, { continued: true });
|
||||
doc.font('Helvetica-Bold').text(String(value), { continued: false });
|
||||
doc.moveDown(0.15);
|
||||
};
|
||||
|
||||
// Header.
|
||||
doc.font('Helvetica-Bold').fontSize(18).text(ev.name || 'Event report');
|
||||
doc.font('Helvetica').fontSize(10).fillColor('#555');
|
||||
const dates = `${ev.start_date} – ${ev.end_date}${ev.location ? ` · ${ev.location}` : ''}`;
|
||||
doc.text(dates);
|
||||
doc.moveDown(0.3);
|
||||
doc.text(`Generated ${new Date().toISOString()}`);
|
||||
doc.moveDown(0.8);
|
||||
doc.fillColor('#000');
|
||||
|
||||
// Summary.
|
||||
h2('Summary');
|
||||
const byType = {};
|
||||
for (const r of ds.registrations) byType[r.type] = (byType[r.type] || 0) + 1;
|
||||
line('Registrations', ds.registrations.length);
|
||||
line('By type', Object.keys(byType).length ? Object.entries(byType).map(([t, n]) => `${t} ${n}`).join(', ') : '—');
|
||||
line('Check-ins', ds.checkins.length);
|
||||
const accepted = ds.connections.filter((c) => c.status === 'accepted').length;
|
||||
line('Connections', `${ds.connections.length} (${accepted} accepted)`);
|
||||
const sf = ds.sessionFeedback;
|
||||
line('Session feedback', sf.length ? `${sf.length} (avg ${(sf.reduce((s, f) => s + f.rating, 0) / sf.length).toFixed(2)}★)` : '—');
|
||||
const ef = ds.eventFeedback;
|
||||
line('Event feedback', ef.length ? `${ef.length} (avg ${(ef.reduce((s, f) => s + f.rating, 0) / ef.length).toFixed(2)}★)` : '—');
|
||||
const catTotals = {};
|
||||
for (const l of ds.pointsLog) catTotals[l.category] = (catTotals[l.category] || 0) + l.delta;
|
||||
line('Points by category', Object.keys(catTotals).length ? Object.entries(catTotals).map(([c, n]) => `${c} +${n}`).join(', ') : '—');
|
||||
doc.moveDown(0.6);
|
||||
|
||||
// Per-session feedback.
|
||||
h2('Session feedback');
|
||||
if (sf.length === 0) {
|
||||
doc.font('Helvetica').fontSize(10).text('No session feedback.');
|
||||
} else {
|
||||
const bySession = {};
|
||||
for (const f of sf) {
|
||||
const e = (bySession[f.session] ||= { count: 0, sum: 0 });
|
||||
e.count += 1;
|
||||
e.sum += f.rating;
|
||||
}
|
||||
const rows = Object.entries(bySession)
|
||||
.map(([title, e]) => ({ title, avg: e.sum / e.count, count: e.count }))
|
||||
.sort((a, b) => b.avg - a.avg);
|
||||
doc.font('Helvetica-Bold').fontSize(9).text('Session', { continued: true }).text(' ', { continued: true });
|
||||
doc.text('Avg', { continued: true }).text(' ', { continued: true }).text('Responses');
|
||||
doc.moveDown(0.2);
|
||||
doc.font('Helvetica').fontSize(9);
|
||||
for (const r of rows) {
|
||||
doc.text(`${r.title} · ${r.avg.toFixed(2)}★ · ${r.count}`, { lineBreak: true });
|
||||
}
|
||||
}
|
||||
doc.moveDown(0.6);
|
||||
|
||||
// Top points.
|
||||
h2('Top points');
|
||||
if (ds.leaderboard.length === 0) {
|
||||
doc.font('Helvetica').fontSize(10).text('No points yet.');
|
||||
} else {
|
||||
doc.font('Helvetica').fontSize(9);
|
||||
ds.leaderboard.slice(0, 10).forEach((l, i) => {
|
||||
doc.text(`${i + 1}. ${l.name} · ${l.points} pts`, { lineBreak: true });
|
||||
});
|
||||
}
|
||||
doc.moveDown(0.6);
|
||||
|
||||
// Event-level feedback comments.
|
||||
h2('Event-level feedback');
|
||||
const comments = ef.filter((f) => f.comment).slice(0, 50);
|
||||
if (comments.length === 0) {
|
||||
doc.font('Helvetica').fontSize(10).text('No event-level comments.');
|
||||
} else {
|
||||
doc.font('Helvetica').fontSize(9);
|
||||
for (const c of comments) {
|
||||
const body = (c.comment || '').replace(/\s+/g, ' ').trim().slice(0, 200);
|
||||
doc.text(`• [${c.rating}★] ${c.name}: ${body}`, { lineBreak: true });
|
||||
doc.moveDown(0.15);
|
||||
}
|
||||
}
|
||||
|
||||
doc.end();
|
||||
});
|
||||
}
|
||||
|
||||
// The POST /export handler.
|
||||
async function handleExport(body) {
|
||||
const { event_id: eventId, format, tables } = body || {};
|
||||
if (!eventId) throw new Error('event_id is required');
|
||||
if (!['csv', 'xlsx', 'pdf'].includes(format)) throw new Error('format must be csv, xlsx, or pdf');
|
||||
|
||||
const ds = await fetchEventDataset(eventId);
|
||||
const slug = (ds.event.name || eventId).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'event';
|
||||
|
||||
if (format === 'pdf') {
|
||||
const buf = await buildPdf(ds);
|
||||
return { filename: `${slug}-report.pdf`, mime: 'application/pdf', content_base64: buf.toString('base64') };
|
||||
}
|
||||
|
||||
const selected = (Array.isArray(tables) && tables.length > 0 ? tables : EXPORT_TABLES).filter((t) =>
|
||||
EXPORT_TABLES.includes(t),
|
||||
);
|
||||
if (selected.length === 0) throw new Error('no valid tables selected');
|
||||
|
||||
if (format === 'csv') {
|
||||
const csv = buildCsv(ds, selected);
|
||||
return {
|
||||
filename: `${slug}-report.csv`,
|
||||
mime: 'text/csv;charset=utf-8',
|
||||
content_base64: Buffer.from(csv, 'utf8').toString('base64'),
|
||||
};
|
||||
}
|
||||
// xlsx
|
||||
const buf = buildXlsx(ds, selected);
|
||||
return {
|
||||
filename: `${slug}-report.xlsx`,
|
||||
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
content_base64: Buffer.from(buf).toString('base64'),
|
||||
};
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
||||
const path = url.pathname;
|
||||
@@ -632,6 +938,11 @@ const server = http.createServer(async (req, res) => {
|
||||
const organizers = await fetchPretixOptions(apiKey);
|
||||
return json(res, 200, { organizers });
|
||||
}
|
||||
if (req.method === 'POST' && path === '/export') {
|
||||
const body = await readBody(req);
|
||||
const result = await handleExport(body);
|
||||
return json(res, 200, result);
|
||||
}
|
||||
return json(res, 404, { error: 'not found' });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: e.message });
|
||||
|
||||
Reference in new issue
Block a user