docs: add /docs living documentation per AGENT.MD

- docs/README.md: navigation hub
- docs/architecture.md: system overview, tech stack, data flows, ports
- docs/backend/: supabase-core, schema, rpcs, rls, seed, docker
- docs/frontend/: app-structure, screens, api-client
- docs/next-steps.md: Phase 2/3/4 plan + open decisions
- Fix README demo-account emails to match the actual 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 17:10:50 +02:00
1 parent 63aa4ecfc8
commit 33c058b5ee
16 files changed
+1494 -7

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
# Frontend — Attendee PWA
The frontend is a **mobile-first single-page React app** (PWA) in
[`apps/convivo/`](../../apps/convivo/). It is the same app for attendees, staff,
and admins — the user's `role` changes what they see (e.g. the Scan tab becomes a
Check-in tab for staff).
| File | What it covers |
|---|---|
| [app-structure.md](./app-structure.md) | Entry, contexts, the event hook, the tab shell, the demo clock |
| [screens.md](./screens.md) | Every screen: Login, Home, Agenda, Scan/Check-in, Connections, Feedback, Leaderboard, Profile |
| [api-client.md](./api-client.md) | The typed API wrapper + how the app talks to Supabase (auth, REST, realtime) |
## Tech
| Concern | Choice |
|---|---|
| Framework | React 18 + TypeScript |
| Build | Vite 5 |
| Supabase client | `@supabase/supabase-js` |
| QR scan | `html5-qrcode` (camera) with manual-entry fallback |
| QR render | `qrcode.react` |
| Styling | Hand-rolled CSS ported from the mockup (`src/styles.css`) |
| PWA | `public/manifest.webmanifest` + icons |
## Source layout
```
apps/convivo/src/
├─ main.tsx # ReactDOM entry
├─ App.tsx # Providers + Shell (tab nav + Feedback takeover)
├─ styles.css # All styling (ported from mockup/index.html)
├─ context/
│ ├─ AuthContext.tsx # session + profile + signOut
│ └─ ToastContext.tsx # transient toasts
├─ lib/
│ ├─ supabase.ts # createClient (same-origin)
│ ├─ api.ts # typed wrapper over rpc/from
│ ├─ types.ts # TS types mirroring the DB
│ ├─ time.ts # event clock + slot status + formatting
│ └─ useEvent.ts # loads the agenda once, exposes it grouped
├─ components/
│ └─ ui.tsx # Avatar, Spinner, Empty, Sheet, QrImage, Scanner
└─ screens/
├─ Login.tsx Home.tsx Agenda.tsx Scan.tsx
├─ Connections.tsx Feedback.tsx Leaderboard.tsx Profile.tsx
```
## Data flow (high level)
- **Auth** — `AuthContext` holds the Supabase session + the current `Profile`.
See [app-structure.md](./app-structure.md#authcontext).
- **Event data** — `useEvent()` loads the agenda once via the `get_agenda()` RPC
and exposes it grouped by slot plus the event clock. See
[app-structure.md](./app-structure.md#the-event-hook-useevent).
- **Per-screen data** — each screen fetches what it needs through the typed
[api client](./api-client.md) (e.g. Home fetches preferences + check-ins).
- **Live updates** — the Leaderboard subscribes to Realtime on the `leaderboard`
table. See [screens.md#leaderboard](./screens.md#leaderboard).
The app only ever uses the **anon key + the user's session JWT**; all security is
enforced by RLS in the database. See [../backend/rls.md](../backend/rls.md).
+93
View File
@@ -0,0 +1,93 @@
# API Client
How the app talks to Supabase. Source:
[`apps/convivo/src/lib/supabase.ts`](../../apps/convivo/src/lib/supabase.ts) and
[`apps/convivo/src/lib/api.ts`](../../apps/convivo/src/lib/api.ts).
## The Supabase client (`lib/supabase.ts`)
```ts
const url = import.meta.env.VITE_SUPABASE_URL || window.location.origin;
const anonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
export const supabase = createClient(url, anonKey, {
auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: false },
realtime: { params: { eventsPerSecond: 10 } },
});
```
- **Same-origin by default.** `VITE_SUPABASE_URL` is intentionally left unset, so
the client uses `window.location.origin`. The app is served behind a proxy
(Vite dev server, or nginx in Docker) that forwards `/auth`, `/rest`,
`/realtime`, `/storage` to the Supabase core. This avoids CORS entirely. See
[../backend/docker.md](../backend/docker.md).
- **Anon key only.** The client is created with the **anon key** (public). The
user's identity comes from the session JWT, and RLS enforces access. See
[../backend/rls.md](../backend/rls.md).
- **Session persistence** — the session is stored in `localStorage` and
auto-refreshed, so a reload keeps you logged in.
## The typed wrapper (`lib/api.ts`)
A thin, typed layer over `supabase.rpc` and `supabase.from`. It centralizes error
handling (wraps Supabase errors in `ApiError`) and gives every screen a clean
async API.
### RPC calls (mutations + complex reads)
These map 1:1 to the Postgres RPCs documented in
[../backend/rpcs.md](../backend/rpcs.md):
| Client function | RPC | Purpose |
|---|---|---|
| `lanyardLookup(qrToken)` | `lanyard_lookup` | Resolve a scanned QR to a public profile |
| `getPublicProfiles()` | `get_public_profiles` | All public profiles (leaderboard, name lookups) |
| `getAgenda()` | `get_agenda` | Slots + sessions (flat rows) |
| `setPreference(sessionId)` | `set_preference` | Pick a session for its slot |
| `clearPreference(slotId)` | `clear_preference` | Remove a pick |
| `createConnectionRequest(targetQr)` | `create_connection_request` | Send a connection request |
| `acceptConnection(id)` | `accept_connection` | Accept (+5 to both) |
| `rejectConnection(id)` | `reject_connection` | Decline |
| `checkinAttendee(sessionId, attendeeQr)` | `checkin_attendee` | Staff check-in (+10) |
| `submitFeedback(sessionId, rating, comment)` | `submit_feedback` | Rate a session (+5/+10) |
### Direct table reads (RLS-scoped)
These read the caller's own rows (RLS returns only what the user may see):
| Client function | Table | Returns |
|---|---|---|
| `getMyPreferences()` | `preferences` | the caller's picks |
| `getMyConnections()` | `connections` | connections the caller is in |
| `getMyCheckins()` | `checkins` | the caller's checked-in session ids |
| `getMyFeedback()` | `feedback` | the caller's feedback |
| `getLeaderboard()` | `leaderboard` | all rows (public to authenticated) |
| `getMyPointsLog()` | `points_log` | the caller's points history |
### Helpers
- **`groupAgenda(rows)`** — turns the flat `get_agenda()` rows into
`{ slot, sessions[] }[]` ordered by slot id. Used by `useEvent()`.
## Types (`lib/types.ts`)
TypeScript interfaces mirroring the DB tables and RPC return shapes
(`Profile`, `PublicProfile`, `Slot`, `Session`, `AgendaRow`, `Preference`,
`Connection`, `Checkin`, `Feedback`, `LeaderboardRow`, `PointsLogRow`,
`CheckinResult`, `FeedbackResult`). `PublicProfile` is the safe projection
(no email / qr_token) returned by the public read functions.
## Error handling
- `rpc()` throws `ApiError` with the Postgres message on failure.
- Screens catch errors and surface them via toasts
(`useToast().toast(message, 'err')`). RPCs raise human-readable messages
(e.g. "staff or admin only", "you must be checked in to this session to give
feedback") — see [../backend/rpcs.md#error-handling](../backend/rpcs.md#error-handling).
## Realtime
The only realtime subscription is on the `leaderboard` table (see
[screens.md#leaderboard](./screens.md#leaderboard)). The `leaderboard` table is
the Realtime source and is kept in sync transactionally by the RPCs — see
[../backend/schema.md#leaderboard--realtime-mirror](../backend/schema.md#leaderboard--realtime-mirror).
+124
View File
@@ -0,0 +1,124 @@
# App Structure
Entry point, global state (contexts), the event hook, the tab shell, and the demo
clock. For individual screens see [screens.md](./screens.md); for the data layer
see [api-client.md](./api-client.md).
## Entry & providers (`main.tsx`, `App.tsx`)
`App` wraps everything in two providers, then renders the `Shell`:
```
<ToastProvider>
<AuthProvider>
<Shell />
</AuthProvider>
</ToastProvider>
```
- **`ToastProvider`** — outermost, so any component (including auth) can show a
toast.
- **`AuthProvider`** — holds the session + profile (below).
- **`Shell`** — decides what to render based on auth state (below).
## AuthContext (`context/AuthContext.tsx`)
Holds the Supabase **session**, the current **`Profile`**, and a `loading` flag.
- On mount, reads the persisted session (`supabase.auth.getSession()`) and loads
the profile for that user id.
- Subscribes to `onAuthStateChange` so login/logout anywhere updates the context.
- `loadProfile(userId)` fetches `profiles` where `id = userId` (RLS returns only
the caller's own row — see [../backend/rls.md](../backend/rls.md)).
- Exposes: `session`, `user`, `profile`, `loading`, `refreshProfile()`, `signOut()`.
> The profile is the app's source of truth for the current user's `role` and
> `points`. After any points-changing action, screens call `refreshProfile()` to
> re-fetch.
## ToastContext (`context/ToastContext.tsx`)
Transient, auto-dismissing toasts. `useToast().toast(message, 'ok' | 'err')`.
Used for login success, connection results, check-in results, and RPC errors.
## The event hook (`lib/useEvent.ts`)
Loads the agenda **once** and exposes it in a convenient shape:
```ts
interface EventData {
slots: { slot: Slot; sessions: Session[] }[]; // grouped, ordered by slot id
sessionById: Map<string, Session>;
slotById: Map<number, Slot>;
now: Date; // the (simulated) event clock
loading: boolean;
error: string | null;
}
```
- Calls `getAgenda()` (the `get_agenda()` RPC) and groups the flat rows with
`groupAgenda()` (see [api-client.md](./api-client.md)).
- Every screen that needs the schedule calls `useEvent()` — the agenda is fetched
per screen mount (cheap, and keeps each screen self-contained).
## The event clock (`lib/time.ts`)
The app uses a **simulated "now"** so the demo always looks mid-event:
```ts
export const EVENT_DATE = '2026-10-23';
export const DEFAULT_NOW = new Date(`${EVENT_DATE}T10:20:00`);
```
At `10:20`, **Slot 1 (09:00–09:45) is `done`** and **Slot 2 (10:00–10:45) is
`now`** — matching the mockup. Helpers:
| Function | Returns |
|---|---|
| `slotStatus(slot, now)` | `'done'` \| `'now'` \| `'next'` |
| `fmtTime(time)` | `"09:00"` from `"09:00:00"` |
| `fmtRange(slot)` | `"09:00–09:45"` |
| `greeting(now)` | "Good morning" / "afternoon" / "evening" |
> This is a **frontend-only** concern. The database stores real slot times; the
> clock just decides which slot is "live" for display. To use the real clock,
> replace `DEFAULT_NOW` with `new Date()`.
## The Shell (`App.tsx`)
The `Shell` is the navigation container. Render logic, in order:
1. **`loading`** → full-screen spinner.
2. **No session / no profile** → `<Login />` (full screen, no tab bar).
3. **`feedbackSession` set** → `<Feedback />` full-screen takeover (no tab bar).
4. **Otherwise** → the active tab + the bottom tab bar.
### Tabs
| Tab id | Label | Screen | Notes |
|---|---|---|---|
| `home` | 🏠 Home | `Home` | default tab |
| `agenda` | 📅 Agenda | `Agenda` | |
| `scan` | 📷 **Scan** / **Check-in** | `Scan` | label is role-aware (below) |
| `connections` | 🤝 Connect | `Connections` | |
| `profile` | 👤 Profile | `Profile` | |
- **Role-aware Scan tab:** if `profile.role` is `staff` or `admin`, the tab label
is **"Check-in"** and the `Scan` screen defaults to staff mode. Otherwise it's
**"Scan"**.
- **Leaderboard** is *not* a tab — it's reached from the Home points pill and the
Home quick-actions. It renders as a tab in the shell but is opened via
`go('leaderboard')`.
- **Feedback** is a full-screen takeover (no tab bar), opened from the Agenda
session sheet via `openFeedback(sessionId)`.
## Shared UI components (`components/ui.tsx`)
| Component | Purpose |
|---|---|
| `Avatar` | Colored initials circle (color derived from a hash of the id) |
| `Spinner` | Loading indicator |
| `Empty` | Empty-state placeholder (icon + text) |
| `Sheet` | Bottom-sheet modal (backdrop + grab handle) |
| `QrImage` | Renders a string (e.g. a QR token) as a scannable QR (`qrcode.react`) |
| `Scanner` | Camera QR scanner (`html5-qrcode`) with a **manual-entry fallback** and a `hasCamera` guard (headless/no-camera environments fall back to typing the code) |
+138
View File
@@ -0,0 +1,138 @@
# Screens
Every screen in [`apps/convivo/src/screens/`](../../apps/convivo/src/screens/).
All screens are mobile-first and use the shared UI components
([app-structure.md#shared-ui-components](./app-structure.md#shared-ui-components)).
Data comes from the typed [api client](./api-client.md); the current user comes
from `useAuth()`.
| Screen | File | Reach |
|---|---|---|
| Login | `Login.tsx` | shown when not authenticated |
| Home | `Home.tsx` | tab (default) |
| Agenda | `Agenda.tsx` | tab |
| Scan / Check-in | `Scan.tsx` | tab (role-aware label) |
| Connections | `Connections.tsx` | tab |
| Profile | `Profile.tsx` | tab |
| Leaderboard | `Leaderboard.tsx` | from Home (points pill / quick action) |
| Feedback | `Feedback.tsx` | full-screen takeover from Agenda |
## Login
A 3-step flow: **splash → scan → confirm**.
1. **Splash** — "Convivo / Break the ice. Earn the points." Tap anywhere to continue.
2. **Scan** — scan (or type) your lanyard QR. Calls `lanyardLookup(qrToken)` to
resolve the attendee (pre-login, public). Shows the resolved name/company.
3. **Confirm** — enter the **email used to buy the ticket**, then
`signInWithPassword({ email, password: qrToken })`. On success the
`AuthContext` updates and the Shell renders the app. On mismatch, an error is
shown ("Email and QR code do not match").
> This is the QR + email login — no email is ever sent. See
> [../architecture.md#6-authentication-model](../architecture.md#6-authentication-model)
> and [../backend/rls.md](../backend/rls.md).
## Home
The landing screen. Shows:
- **Greeting + points pill** — "Good morning, Ana 👋" and `⚡ {points}` (tapping
the pill opens the Leaderboard).
- **Now card** — the session the user picked for the current slot, with a
"✓ Checked in" or "Show your QR to staff to check in" pill.
- **Next card** — the pick for the next slot.
- **My picks today** — the user's pick per slot (tap to change → opens Agenda).
- **Quick actions** — Scan & connect, Agenda, Connections, Leaderboard.
Data: `useEvent()` (agenda + clock) + `getMyPreferences()` + `getMyCheckins()`.
Slot status comes from `slotStatus(slot, now)` ([app-structure.md#the-event-clock](./app-structure.md#the-event-clock)).
## Agenda
Lists all 6 slots, each with its 3 sessions and a status pill (**Done / ● Live /
Up next**). The user's pick per slot is highlighted (filled check).
- **Tap a session** → opens a bottom **sheet** with details (description, speaker,
room, capacity, checked-in state) and actions:
- **Give feedback ⭐** — only when the session is *done* **and** the user is
checked in. Opens the Feedback takeover (`openFeedback(sessionId)`).
- **Pick / Remove my pick** — `setPreference(sessionId)` / `clearPreference(slotId)`.
- Picking is "one per slot" — picking a new session in a slot replaces the old
pick (enforced by the `set_preference` RPC).
Data: `useEvent()` + `getMyPreferences()` + `getMyCheckins()`.
## Scan / Check-in
One screen, two modes (segmented control: **Attendee / Staff**). The default mode
and the tab label are role-aware: staff/admin default to **Staff** mode and the
tab reads **Check-in**.
- **Attendee mode (connect):** scan a peer's lanyard → `lanyardLookup` → a
"Connect with {name}?" sheet → `createConnectionRequest(qr)`. Guards: can't
connect with yourself. Result toast reflects the connection status (sent /
already connected).
- **Staff mode (check-in):** pick a session (dropdown grouped by slot), then scan
an attendee's lanyard → `checkinAttendee(sessionId, qr)`. Shows a result sheet:
"✓ {name} — Checked in — +10 pts · now {total}" or "⚠️ Already checked in — no
extra points" (the `already` flag from the RPC).
Data: `useEvent()` (for the session list) + the RPCs above.
## Connections
Two tabs: **My connections** and **Requests** (with a count badge).
- **My connections** — accepted connections (the other person's name/company).
- **Requests** — incoming (`to_id = me`, pending) with **Accept / Decline**
buttons (`acceptConnection` / `rejectConnection`), and outgoing (`from_id = me`,
pending) shown as "Sent".
- Accepting awards +5 to both (see [../backend/rpcs.md#accept_connectionp_connection_id--connections](../backend/rpcs.md#accept_connectionp_connection_id--connections)).
Data: `getMyConnections()` + `getPublicProfiles()` (to resolve names/companies).
## Feedback
A **full-screen takeover** (no tab bar), opened from the Agenda session sheet.
- Shows the session (slot · time · room · title).
- **1–5 star** rating + optional comment ("bonus points for details").
- If the user already rated this session, it pre-fills and the button reads
**"Update feedback"** (the RPC updates without re-awarding points).
- On submit: `submitFeedback(sessionId, rating, comment)` → `refreshProfile()` →
a success card ("+N pts earned!" or "Feedback updated!").
Data: `useEvent()` (session/slot) + `getMyFeedback()` (to detect existing) +
`submitFeedback`.
## Leaderboard
The live leaderboard.
- **Podium** for the top 3 (1st/2nd/3rd bars), then the rest as ranked rows.
- **Your row is highlighted** (`me`).
- **Live:** subscribes to Realtime `postgres_changes` on the `leaderboard` table
and re-fetches on any change — so it updates the moment points change anywhere.
```ts
supabase.channel('leaderboard-live')
.on('postgres_changes', { event: '*', schema: 'public', table: 'leaderboard' }, () => {
getLeaderboard().then(setRows);
})
.subscribe();
```
Data: `getLeaderboard()` (initial + on each realtime event). The `leaderboard`
table is kept in sync transactionally by the RPCs — see
[../backend/schema.md#leaderboard--realtime-mirror](../backend/schema.md#leaderboard--realtime-mirror).
## Profile
- **Header** — avatar, name, company, role pill, points pill.
- **My QR code** — renders `profile.qr_token` as a scannable QR (`QrImage`).
"Show this to staff for check-in and to peers to connect."
- **Points breakdown** — sums `points_log` by category
(Session check-ins / Connections / Feedback / Other) + Total.
- **Log out** — `signOut()`.
Data: `useAuth()` (profile) + `getMyPointsLog()`.