diff --git a/AGENT.MD b/AGENT.MD new file mode 100644 index 0000000..282a0dd --- /dev/null +++ b/AGENT.MD @@ -0,0 +1,40 @@ +# ORCHESTRATION & AGENT SYSTEM INSTRUCTIONS + +## 1. Operating Mindset & Clarification Policy +- **Uncertainty Rule:** If any instruction, context, or technical approach is ambiguous or uncertain, you MUST ask for clarification before proceeding with implementation. +- **Web Search Integration:** Use web search capabilities immediately whenever you encounter unknown APIs, library updates, or uncertain technical patterns. Never guess implementation details. +- **Role Boundary:** You act strictly as the **Supervisor / Orchestrator Agent**. You supervise, coordinate, and maintain project state. You DO NOT write or edit production code directly unless explicitly requested for trivial inline fixes. + +## 2. Multi-Agent Delegation Model +- **Sub-Agent Engine:** Delegate all code implementation, refactoring, and file generation tasks to sub-agents powered by the `qwen3.6-27b` family. +- **Task Delegation Prompting:** When issuing tasks to sub-agents, provide explicit, isolated, and highly detailed prompts containing: + 1. **Context & Objective:** Precise scope of what needs to be built. + 2. **Inputs:** Exact file paths, interfaces, or schemas required. + 3. **Desired Output:** Expected code structure, exported functions, tests, or documentation artifacts. + 4. **Constraints:** Styling rules, error handling guidelines, and prohibited patterns. +- **Supervisor Role:** Verify the outputs from sub-agents against project requirements before accepting changes. + +## 3. Mandatory Documentation Architecture (`/docs`) +You are responsible for keeping living documentation updated from day zero. Every project MUST maintain and enforce the following structure inside the root `/docs` folder: + +docs/ +├── README.md +├── architecture.md +├── backend/ +│ ├── README.md +│ └── [component-files].md +└── frontend/ + ├── README.md + └── [component-files].md + +### Documentation Standards & Rules: +1. **`docs/README.md`**: Serves as the central navigation hub, summarizing the project setup and mapping where specific information lives. +2. **`docs/architecture.md`**: High-level system overview, global tech stack, environment setups, and system-wide data flows. +3. **`docs/backend/`**: + - `README.md`: Overview of the backend service architecture, runtime, and folder map. + - Individual component markdown files documenting endpoints, data models, Docker services, and logic. +4. **`docs/frontend/`**: + - `README.md`: Overview of UI/UX layers, state management, and component hierarchy. + - Individual component markdown files documenting pages, hooks, state slices, and UI modules. +5. **Cross-Referencing Rule:** Avoid duplicate documentation. Use relative Markdown links across files. + - *Example:* If Frontend consumes a Backend API port, `docs/frontend/api-client.md` states the integration and links directly to `docs/backend/docker.md#exposed-ports` or `docs/backend/api-routes.md`. \ No newline at end of file diff --git a/README.md b/README.md index c838d46..9b7f3d3 100644 --- a/README.md +++ b/README.md @@ -233,16 +233,16 @@ Login = **QR code** (typed or scanned) + **email**. The QR token is the password | **Ana Silva** | attendee | `CVV-ANA-4821` | ana.silva@nubank.com | | **Bruno Costa** | staff | `CVV-BRU-1177` | bruno.costa@acme.com | | **Rita Lopes** | staff | `CVV-RIT-9034` | rita.lopes@globant.com | -| **Admin** | admin | `CVV-ADM-0001` | admin@appe.at | +| **Convivo Admin** | admin | `CVV-ADM-0001` | admin@appe.at | | Tomás Ribeiro | attendee | `CVV-TOM-5566` | tomas.ribeiro@dataprev.com | | Sofia Almeida | attendee | `CVV-SOF-2299` | sofia.almeida@loop.com | | Marco Chen | attendee | `CVV-MRC-7712` | marco.chen@deepmind.com | -| Julia Santos | attendee | `CVV-JUL-3345` | julia.santos@acme.com | -| Pedro Nunes | attendee | `CVV-PED-8801` | pedro.nunes@globant.com | -| Carla Mendes | attendee | `CVV-CAR-6623` | carla.mendes@nubank.com | -| Diego Ferreira | attendee | `CVV-DIE-4458` | diego.ferreira@loop.com | -| Marina Costa | attendee | `CVV-MNA-2210` | marina.costa@dataprev.com | -| Lucas Oliveira | attendee | `CVV-LUC-9987` | lucas.oliveira@deepmind.com | +| Julia Santos | attendee | `CVV-JUL-3345` | julia.santos@ifood.com | +| Pedro Nunes | attendee | `CVV-PED-8801` | pedro.nunes@microsoft.com | +| Carla Mendes | attendee | `CVV-CAR-6623` | carla.mendes@quintoessencial.com | +| Diego Ferreira | attendee | `CVV-DIE-4458` | diego.ferreira@stone.com | +| Marina Costa | attendee | `CVV-MNA-2210` | marina.costa@olx.com | +| Lucas Oliveira | attendee | `CVV-LUC-9987` | lucas.oliveira@usp.br | **Suggested demo flow:** 1. Log in as **Ana** (attendee) → see Home, Agenda, Leaderboard. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..68a921e --- /dev/null +++ b/docs/README.md @@ -0,0 +1,51 @@ +# Convivo — Documentation + +Living documentation for **Convivo** — a conference networking app that turns a +conference into a game. This folder is the single source of truth for *how the +system works*; the root [`README.md`](../README.md) is the quick-start. + +> **Status:** Phase 0 (Dockerized Supabase core) + Phase 1 (attendee web PWA) +> are complete and verified. Phases 2–4 are planned — see +> [next-steps.md](./next-steps.md). + +## Where things live + +| Topic | Read this | +|---|---| +| **System overview, tech stack, data flows, ports** | [architecture.md](./architecture.md) | +| **Backend (Supabase core) — overview** | [backend/README.md](./backend/README.md) | +| Supabase local stack, ports, how it runs | [backend/supabase-core.md](./backend/supabase-core.md) | +| Database schema (all tables) | [backend/schema.md](./backend/schema.md) | +| Transactional points RPCs (the business logic) | [backend/rpcs.md](./backend/rpcs.md) | +| Row Level Security policies | [backend/rls.md](./backend/rls.md) | +| Seed data + demo accounts | [backend/seed.md](./backend/seed.md) | +| Docker (app image + compose) | [backend/docker.md](./backend/docker.md) | +| **Frontend (attendee PWA) — overview** | [frontend/README.md](./frontend/README.md) | +| App structure, state, contexts, routing | [frontend/app-structure.md](./frontend/app-structure.md) | +| Every screen (Login, Home, Agenda, Scan, …) | [frontend/screens.md](./frontend/screens.md) | +| API client (how the app talks to Supabase) | [frontend/api-client.md](./frontend/api-client.md) | +| **What's next (Phase 2/3/4 + open items)** | [next-steps.md](./next-steps.md) | + +## Reading order + +1. **New to the project?** Start with [architecture.md](./architecture.md), then + [backend/README.md](./backend/README.md) and [frontend/README.md](./frontend/README.md). +2. **Working on the database / points logic?** Go to + [backend/schema.md](./backend/schema.md) → [backend/rpcs.md](./backend/rpcs.md) → + [backend/rls.md](./backend/rls.md). +3. **Working on the UI?** Go to [frontend/app-structure.md](./frontend/app-structure.md) + → [frontend/screens.md](./frontend/screens.md) → [frontend/api-client.md](./frontend/api-client.md). +4. **Planning the next phase?** Read [next-steps.md](./next-steps.md). + +## Conventions + +- **No duplication.** Each fact lives in exactly one file; other files link to it + with relative Markdown links. (e.g. the frontend API client links to the backend + RPC reference instead of re-describing the RPCs.) +- **Code is the source of truth.** If a doc and the code disagree, the code wins — + fix the doc. Key files: + - Schema + RPCs + RLS: [`supabase/migrations/20260822000000_init.sql`](../supabase/migrations/20260822000000_init.sql) + - Seed: [`supabase/seed.sql`](../supabase/seed.sql) + - App source: [`apps/convivo/src/`](../apps/convivo/src/) +- **Keep it current.** Update the relevant doc in the same change that changes the + behavior it describes. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..3730040 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,152 @@ +# Convivo — Architecture + +High-level system overview, tech stack, environment setup, and system-wide data +flows. For component-level detail, see [backend/README.md](./backend/README.md) +and [frontend/README.md](./frontend/README.md). + +## 1. The product in one paragraph + +Convivo is a mobile-first web app (PWA) for conference attendees. People log in +with the **QR code on their lanyard + the email they used to buy their ticket** +(no email is ever sent). They pick one session per slot, scan peers' lanyards to +make connections, get checked in by staff, and rate sessions. Every action earns +**points**, and a **live leaderboard** turns networking into a game. + +## 2. System diagram + +```mermaid +flowchart LR + subgraph Browser["Browser (attendee / staff phone)"] + A["Convivo PWA
React 18 + Vite 5 + TS
mobile-first, installable"] + end + + subgraph Docker["Docker (local)"] + subgraph AppC["convivo-app container (:3000)"] + N["nginx
serves SPA + proxies Supabase paths"] + end + subgraph Core["Supabase core (Supabase CLI)"] + K["Kong API gateway
:54321"] + K --> G["GoTrue (Auth)"] + K --> R["PostgREST"] + K --> RT["Realtime"] + K --> S["Storage"] + R --> P[("Postgres 17
schema · RLS · points RPCs")] + RT --> P + G --> P + end + end + + A -->|"same-origin /auth /rest /realtime /storage"| N + N -->|"proxy (supabase_kong_Convivo:8000)"| K +``` + +**Key idea:** there is **no custom backend**. Supabase provides auth, data, +business logic (as Postgres RPCs), and realtime. The app is a thin client that +talks to Supabase through **same-origin paths**, so there is no CORS to manage. + +## 3. Tech stack + +| Layer | Choice | Why | +|---|---|---| +| Core | **Supabase (local, Docker)** via the Supabase CLI | Postgres + Auth + REST + Realtime + Storage in one managed stack; RLS + RPCs keep all logic in the DB | +| App | **React 18 + Vite 5 + TypeScript** (PWA) | Fast, mobile-first, installable; same-origin proxy avoids CORS | +| QR | `html5-qrcode` (scan) + `qrcode.react` (render) | Camera scan with manual-entry fallback | +| Client | `@supabase/supabase-js` | Auth + REST + Realtime in one client | +| Packaging | **Docker** (multi-stage build → nginx) | The app is a sidecar that joins the Supabase network | + +## 4. The two halves + +### Backend — the Supabase core +Everything server-side lives in Postgres. See [backend/README.md](./backend/README.md): +- **Schema** — 9 tables (people, schedule, and the event's activity). → [backend/schema.md](./backend/schema.md) +- **Business logic** — transactional `security definer` RPCs that award points and + keep the leaderboard consistent. → [backend/rpcs.md](./backend/rpcs.md) +- **Security** — Row Level Security on every table; the app only ever uses the + **anon key + the user's session JWT**. → [backend/rls.md](./backend/rls.md) +- **Data** — seed with 6 slots, 18 sessions, 13 demo users. → [backend/seed.md](./backend/seed.md) + +### Frontend — the attendee PWA +A single-page React app with a tab shell and a few full-screen takeovers. See +[frontend/README.md](./frontend/README.md): +- **Structure** — contexts (auth, toast), the event hook, the tab shell. → [frontend/app-structure.md](./frontend/app-structure.md) +- **Screens** — Login, Home, Agenda, Scan/Check-in, Connections, Feedback, Leaderboard, Profile. → [frontend/screens.md](./frontend/screens.md) +- **API client** — a thin typed wrapper over `supabase.rpc` / `supabase.from`. → [frontend/api-client.md](./frontend/api-client.md) + +## 5. How a request flows (example: staff check-in) + +```mermaid +sequenceDiagram + participant U as Staff (PWA) + participant N as nginx (app container) + participant K as Kong + participant R as PostgREST + participant DB as Postgres (RPC) + + U->>N: POST /rest/v1/rpc/checkin_attendee {session, attendeeQr} + N->>K: proxy (same-origin) + K->>R: route /rest + R->>DB: execute checkin_attendee() as `authenticated` + Note over DB: security definer → bypasses RLS
1. insert checkin (ON CONFLICT do nothing)
2. _award_points(+10) → profiles.points + points_log
3. _sync_leaderboard() + DB-->>R: {checkin_id, attendee_name, points, already} + R-->>K: JSON + K-->>N: JSON + N-->>U: result sheet ("+10 pts · now 62") + Note over DB: leaderboard row changed → Realtime broadcasts to all open apps +``` + +The same pattern applies to every mutation: the app calls an RPC, Postgres does +the work atomically, and the `leaderboard` table change fans out over Realtime. + +## 6. Authentication model + +- The **QR token is the Supabase Auth password**; the **email is the identifier**. + Login is a standard `signInWithPassword({ email, password: qrToken })`. +- `enable_confirmations = false`, so **no email is sent** — the email is only a + "confirm it's you" check against the ticket purchase. +- After login, the app holds a short-lived **session JWT** (in `localStorage`). + Every request sends the **anon key** (public) + the **session JWT** (identity). +- The **service-role key is never in the app** — it bypasses RLS and stays + server-side. See [backend/rls.md](./backend/rls.md) for what each role can do. + +## 7. Environment & ports + +| Service | Port | Notes | +|---|---|---| +| **Convivo app** | **3000** | Vite dev server (dev) or nginx (Docker) | +| Supabase API (Kong) | 54321 | The single gateway the app proxies to | +| Supabase Studio | 54323 | UI — login `postgres` / `postgres` | +| Postgres | 54322 | Direct DB access (`postgres` / `postgres`) | +| SMTP (Mailpit) | 54324 | Captures emails (none are sent in this flow) | + +**Run it** (full instructions in the root [`README.md`](../README.md)): +```bash +npm run db:start # start the Supabase core (Docker) +npm run db:reset # (re)apply migrations + seed +npm run app:dev # dev server on :3000 +# — or — +docker compose up --build # app as a Docker sidecar on :3000 +``` + +## 8. The demo clock + +The app uses a **simulated "now"** of `2026-10-23 10:20` (see +[frontend/app-structure.md](./frontend/app-structure.md#the-event-clock)) so that +Slot 1 is *done* and Slot 2 is *live* — matching the mockup. This is a frontend +concern only; the database stores real slot times. + +## 9. Repository layout + +``` +Convivo/ +├─ apps/convivo/ # Attendee web PWA (React + Vite + TS) +│ ├─ Dockerfile # Multi-stage: build → nginx +│ ├─ nginx.conf.template # SPA + same-origin proxy to the Supabase core +│ └─ src/ # screens, components, lib, context +├─ supabase/ +│ ├─ config.toml # Local stack config (ports, auth, RLS defaults) +│ ├─ migrations/ # 20260822000000_init.sql — schema, RLS, RPCs +│ └─ seed.sql # Slots, sessions, 13 demo users, Ana's demo state +├─ docker-compose.yml # Runs the app sidecar on the Supabase network +├─ docs/ # ← this documentation +└─ mockup/index.html # Original interactive mockup (design reference) +``` diff --git a/docs/backend/README.md b/docs/backend/README.md new file mode 100644 index 0000000..0fdde63 --- /dev/null +++ b/docs/backend/README.md @@ -0,0 +1,38 @@ +# Backend — Supabase Core + +Convivo has **no custom backend**. The entire server side is a **local Supabase +stack** (run with the Supabase CLI) plus the schema, RPCs, and RLS that live in +Postgres. This folder documents that core. + +| File | What it covers | +|---|---| +| [supabase-core.md](./supabase-core.md) | The local stack: containers, ports, how to start/reset, config | +| [schema.md](./schema.md) | All 9 tables, columns, constraints, indexes | +| [rpcs.md](./rpcs.md) | The transactional points RPCs (the business logic) | +| [rls.md](./rls.md) | Row Level Security policies + which key the app uses | +| [seed.md](./seed.md) | Seed data + the 13 demo accounts | +| [docker.md](./docker.md) | Docker: the app image + root compose (how the core + app run together) | + +## The big picture + +``` +Postgres 17 ── schema (9 tables) + ── RLS (who can read/write what) + ── RPCs (security definer, transactional points logic) + ── seed (demo data) +``` + +- **Data + logic live in the database.** The app never computes points or writes + to `profiles.points` directly — it calls RPCs, and Postgres enforces the rules. +- **RLS is the security boundary.** The app uses the **anon key + the user's + session JWT**; RLS decides what that user may see and do. The service-role key + is never shipped to the app. See [rls.md](./rls.md). +- **Points are transactional.** Each RPC updates points, inserts the related row, + and re-syncs the `leaderboard` mirror in **one transaction**, so the leaderboard + is always consistent and duplicate actions never double-award. See [rpcs.md](./rpcs.md). + +## Source of truth + +- Schema + RPCs + RLS: [`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql) +- Seed: [`supabase/seed.sql`](../../supabase/seed.sql) +- Stack config: [`supabase/config.toml`](../../supabase/config.toml) diff --git a/docs/backend/docker.md b/docs/backend/docker.md new file mode 100644 index 0000000..1359ed8 --- /dev/null +++ b/docs/backend/docker.md @@ -0,0 +1,109 @@ +# Docker + +Docker is the backbone. Two pieces: + +1. **The Supabase core** — a set of containers managed by the **Supabase CLI** + (not by a compose file in this repo). See [supabase-core.md](./supabase-core.md). +2. **The app sidecar** — a single container built from + [`apps/convivo/Dockerfile`](../../apps/convivo/Dockerfile) and orchestrated by + the root [`docker-compose.yml`](../../docker-compose.yml). + +The app container **joins the network the CLI created** for the core and proxies +the Supabase same-origin paths to the Kong container. + +## How the pieces fit + +```mermaid +flowchart LR + subgraph Host + CLI["supabase start
(Supabase CLI)"] + end + subgraph Net["supabase_network_Convivo (external)"] + K["supabase_kong_Convivo
:8000 (internal)"] + APP["convivo-app
nginx :3000"] + end + CLI -.creates.-> Net + APP -->|"proxy /auth /rest /realtime /storage"| K + APP -->|"host port 3000"| U["Browser"] +``` + +## The app image (`apps/convivo/Dockerfile`) + +Multi-stage build: + +- **Stage 1 — `build`** (`node:20-alpine`): `npm ci` (reproducible via + `package-lock.json`), then `npm run build` (tsc + vite). The anon key is baked + in at build time via `ARG VITE_SUPABASE_ANON_KEY` (it's not a secret — it's the + standard local anon key). +- **Stage 2 — `serve`** (`nginx:1.27-alpine`): copies the built `dist/` and an + nginx config **template**. The entrypoint + ([`docker-entrypoint.sh`](../../apps/convivo/docker-entrypoint.sh)) injects the + proxy target at container start, then runs nginx. + +### nginx config + +[`nginx.conf.template`](../../apps/convivo/nginx.conf.template) serves the SPA +(`try_files ... /index.html` for client-side routing) and proxies the Supabase +same-origin paths to the core: + +| Location | Proxied to | Notes | +|---|---|---| +| `/auth/` | `__SUPABASE_PROXY_TARGET__` | GoTrue | +| `/rest/` | `__SUPABASE_PROXY_TARGET__` | PostgREST (tables + RPCs) | +| `/realtime/` | `__SUPABASE_PROXY_TARGET__` | WebSocket — `Upgrade`/`Connection` headers + long timeouts | +| `/storage/` | `__SUPABASE_PROXY_TARGET__` | Storage (unused in v1) | + +`__SUPABASE_PROXY_TARGET__` is replaced at start with the value of the +`SUPABASE_PROXY_TARGET` env var (default `supabase_kong_Convivo:8000`). + +> **Why `:8000` and not `:54321`?** Kong listens on **8000 inside** the container; +> the `54321→8000` mapping is host-only. From inside the shared network you must +> target the internal port. See [supabase-core.md#ports](./supabase-core.md#ports). + +## Root `docker-compose.yml` + +Runs **only the app** (the core is CLI-managed). Key settings: + +| Setting | Value | Why | +|---|---|---| +| `build.context` | `./apps/convivo` | Builds the app image | +| `ports` | `3000:3000` | The app on the host | +| `environment.SUPABASE_PROXY_TARGET` | `supabase_kong_Convivo:8000` (default) | Where nginx proxies | +| `networks.supabase` | **external**, name `supabase_network_Convivo` | Joins the CLI-created network | +| `healthcheck` | `wget http://127.0.0.1:3000/` | Container reports healthy | + +> If you change `project_id` in `supabase/config.toml`, update the external +> network name (`supabase_network_`) and the default proxy target +> (`supabase_kong_:8000`) to match. + +## Running + +```bash +# 1. Start the Supabase core (creates containers + supabase_network_Convivo) +npm run db:start + +# 2. (Optional) reset to clean seed data +npm run db:reset + +# 3. Build + run the app sidecar on :3000 +docker compose up --build +``` + +Open **http://localhost:3000**. + +### Alternative: dev server (no app container) + +For faster iteration you can skip the app container and use the Vite dev server, +which proxies the same paths to `127.0.0.1:54321` (host port): + +```bash +npm run db:start +npm run app:dev # Vite on :3000 +``` + +## Verified behavior + +- `docker compose build` → `npm ci` + `tsc` + `vite build` all pass in-container. +- `GET /` → HTTP 200 (SPA served by nginx). +- `GET /auth/v1/health` through the proxy → GoTrue health JSON (proxy works). +- Full login (QR + email) works through the Docker-served app. diff --git a/docs/backend/rls.md b/docs/backend/rls.md new file mode 100644 index 0000000..107efa7 --- /dev/null +++ b/docs/backend/rls.md @@ -0,0 +1,126 @@ +# Row Level Security (RLS) + +RLS is the security boundary. It is **enabled on all 9 tables**, and every policy +is scoped to the `authenticated` role. The `anon` role has `GRANT select` at the +Postgres level, but RLS blocks it from reading anything — so an unauthenticated +request sees no rows. + +Source of truth: +[`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql) +(RLS section). + +## Which key does the app use? + +**The anon key — never the service-role (admin) key.** + +- The app ships only `VITE_SUPABASE_ANON_KEY` (baked in at build time). It's the + standard local anon JWT, **public by design** — safe to be in the bundle. +- Every request carries the **anon key + the user's session JWT** (from the + QR+email login). PostgREST then runs as the `authenticated` role, and **RLS + decides what that user can see/do**. +- The **service-role key is never in the app**. It bypasses RLS entirely, so it + must stay server-side (used only for admin ops / verification). + +> Model: *the anon key gets you to the door, the session JWT says who you are, +> RLS says what you may touch.* + +## Role helpers + +Two `security definer` functions drive role checks (see [rpcs.md](./rpcs.md#role-helper-functions)): +- `is_admin()` — current user's profile has `role = 'admin'` +- `is_staff_or_admin()` — current user's profile has `role in ('staff','admin')` + +## Policies by table + +| Table | SELECT | INSERT | UPDATE | DELETE | +|---|---|---|---|---| +| `profiles` | own **or** admin | — | admin only | admin only | +| `slots` | all authenticated | admin only | admin only | admin only | +| `sessions` | all authenticated | admin only | admin only | admin only | +| `preferences` | own (`profile_id = auth.uid()`) | — | — | — | +| `connections` | rows you're in (`from_id` or `to_id` = you) | — | — | — | +| `checkins` | own **or** staff/admin | — | — | — | +| `feedback` | own | — | — | — | +| `leaderboard` | all authenticated | — | — | — | +| `points_log` | own **or** admin | — | — | — | + +**"—" (no policy)** means normal users have **no direct write access** — those +tables are written only by the `security definer` RPCs, which bypass RLS. This is +deliberate: a client cannot `UPDATE profiles SET points = 9999` or insert its own +check-in. See [rpcs.md](./rpcs.md). + +### The exact policies + +```sql +-- profiles: read own or admin; write admin only +create policy "profiles_select_own_or_admin" on public.profiles for select to authenticated + using (id = auth.uid() or public.is_admin()); +create policy "profiles_update_admin" on public.profiles for update to authenticated + using (public.is_admin()) with check (public.is_admin()); +create policy "profiles_delete_admin" on public.profiles for delete to authenticated + using (public.is_admin()); + +-- slots / sessions: readable by any authenticated user (public agenda); admin writes +create policy "slots_select_all" on public.slots for select to authenticated using (true); +create policy "slots_admin_insert" on public.slots for insert to authenticated with check (public.is_admin()); +create policy "slots_admin_update" on public.slots for update to authenticated using (public.is_admin()) with check (public.is_admin()); +create policy "slots_admin_delete" on public.slots for delete to authenticated using (public.is_admin()); +-- (sessions: identical four policies) + +-- preferences: read own +create policy "prefs_select_own" on public.preferences for select to authenticated + using (profile_id = auth.uid()); + +-- connections: read rows you're involved in +create policy "conn_select_involved" on public.connections for select to authenticated + using (from_id = auth.uid() or to_id = auth.uid()); + +-- checkins: read own or staff/admin +create policy "checkins_select_own_or_staff" on public.checkins for select to authenticated + using (profile_id = auth.uid() or public.is_staff_or_admin()); + +-- feedback: read own +create policy "feedback_select_own" on public.feedback for select to authenticated + using (profile_id = auth.uid()); + +-- leaderboard: readable by any authenticated user +create policy "leaderboard_select_all" on public.leaderboard for select to authenticated using (true); + +-- points_log: read own or admin +create policy "points_log_select_own_or_admin" on public.points_log for select to authenticated + using (profile_id = auth.uid() or public.is_admin()); +``` + +## GRANTs + +The new Supabase CLI does **not** auto-expose new tables to the Data API roles, so +the migration grants explicitly (RLS still governs what each role can actually see): + +```sql +grant usage on schema public to anon, authenticated, service_role; +grant select on to anon, authenticated, service_role; +grant insert, update, delete on to authenticated, service_role; +grant execute on function to authenticated; +``` + +Note `anon` gets `select` but **no** `insert/update/delete`; `authenticated` gets +full DML at the Postgres level, but **RLS narrows it** to the policies above. + +## Net effect by role + +- **Attendee** — sees their own profile/prefs/connections/feedback, the full + agenda, and the leaderboard; can only act through the RPCs (which re-check role + internally, e.g. only staff can call `checkin_attendee`). +- **Staff** — everything an attendee can do, plus can read all `checkins` and call + the check-in RPC. +- **Admin** — full read on everything, and the only role with **direct** write + access to `profiles` / `slots` / `sessions` (this is what the future Admin app + in Phase 3 will use). + +## Things to revisit later + +- `slots` / `sessions` are readable by *any* authenticated user (fine — it's a + public agenda). If you ever want the agenda hidden until the event, that's a + one-line policy change. +- `leaderboard` exposes every attendee's name + points to any authenticated user. + That's the intended product behavior (a public leaderboard). diff --git a/docs/backend/rpcs.md b/docs/backend/rpcs.md new file mode 100644 index 0000000..004895d --- /dev/null +++ b/docs/backend/rpcs.md @@ -0,0 +1,125 @@ +# Points RPCs (Business Logic) + +All mutations go through **Postgres RPCs** (`security definer`, transactional). +The app never writes to `profiles.points`, `connections`, `checkins`, `feedback`, +or `leaderboard` directly — it calls these functions. This is what makes the +points system race-free and prevents a client from, e.g., setting its own points. + +Source of truth: +[`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql). + +## Why RPCs? + +- **`security definer`** → the function runs as the table owner and **bypasses + RLS**, so it can update points and sync the leaderboard even though the calling + user can't write those tables directly. +- **Transactional** → each RPC does *update points + insert the related row + + re-sync the leaderboard* in **one transaction**. Either all happen or none do. +- **Idempotent where it matters** → re-check-in and re-feedback are detected and + never double-award. + +## Points rules + +| Action | Points | Awarded to | +|---|---|---| +| Checked into a session (by staff) | **+10** | the attendee | +| Connection accepted | **+5 each** | both people | +| Feedback — rating only | **+5** | the attendee | +| Feedback — rating + comment | **+10** | the attendee | +| Admin adjustment | any | the target (audited as `admin`) | + +## Internal helpers + +### `_award_points(p_profile_id, p_delta, p_category)` +The single place points change. In one transaction it: +1. `update profiles set points = greatest(0, points + p_delta)` (floored at 0), +2. `insert into points_log (profile_id, delta, category)`, +3. calls `_sync_leaderboard(p_profile_id)`. + +### `_sync_leaderboard(p_profile_id)` +Upserts the `leaderboard` row for that profile from `profiles` +(`on conflict (profile_id) do update ...`). This is what makes the leaderboard a +consistent, Realtime-friendly mirror. + +## Public read functions + +| Function | Returns | Used for | +|---|---|---| +| `get_public_profiles()` | `id, full_name, company, role, points` (ordered by points) | Leaderboard initial load, id→name lookups | +| `lanyard_lookup(p_qr_token)` | `id, full_name, company, role` | Resolve a scanned QR (pre-login + connect) | +| `get_agenda()` | slots with their sessions (flat rows) | Agenda + Home | + +All three are `security definer` and expose **only public columns** (no email, no +`qr_token`). + +## Mutation RPCs + +### `set_preference(p_session_id)` → `preferences` +Sets (or changes) the preferred session for the slot that `p_session_id` belongs +to. Deletes the caller's existing pick for that slot, then inserts the new one. +Enforces "one pick per slot". + +### `clear_preference(p_slot_id)` → `void` +Removes the caller's pick for a slot. + +### `create_connection_request(p_target_qr)` → `connections` +Creates a **pending** connection to the attendee whose QR was scanned. +- Resolves the target by `qr_token`; errors if not found or if it's yourself. +- **Idempotent:** if the pair already has a connection (either direction), returns + the existing one instead of creating a duplicate. + +### `accept_connection(p_connection_id)` → `connections` +Accepts an **incoming** request. +- Locks the row (`for update`), verifies the caller is the recipient + (`to_id = auth.uid()`) and the status is still `pending`. +- Sets `status = 'accepted'`, `resolved_at = now()`. +- **Awards +5 to both** `from_id` and `to_id` (category `connection`). + +### `reject_connection(p_connection_id)` → `connections` +Same guards as accept, but sets `status = 'rejected'`. No points. + +### `checkin_attendee(p_session_id, p_attendee_qr)` → `(checkin_id, attendee_id, attendee_name, points, already)` +Staff checks an attendee into a session. +- **Role check:** `is_staff_or_admin()` or it raises `staff or admin only`. +- Resolves the attendee by `qr_token`. +- `insert into checkins ... on conflict (profile_id, session_id) do nothing + returning id` — if no row was inserted, the attendee was **already checked in**: + sets `already = true` and awards **no points**. +- Otherwise awards **+10** to the attendee (category `checkin`). +- Returns the attendee's current total points. + +> **Implementation note:** the "already checked in" case is detected via the +> `ON CONFLICT ... DO NOTHING returning id` (a `NULL` id means no-op), and the +> function uses a **single final `return query`** with flag variables — a +> `return query` inside an `if` block would *not* terminate the function and would +> double-award. + +### `submit_feedback(p_session_id, p_rating, p_comment)` → `(feedback_id, points, earned)` +Post-session feedback. +- **Requires the caller to be checked in** to that session (else raises). +- Validates `rating` is 1–5. +- `earned` = 10 if a non-empty comment, else 5. +- **Idempotent:** if feedback already exists for (caller, session), it **updates** + the rating/comment and awards **0** (already rewarded on first submission). +- Otherwise inserts and awards `earned` (category `feedback`). + +### `adjust_points(p_profile_id, p_delta, p_reason)` → `void` +**Admin-only** manual points adjustment (category `admin`). Used by the future +Admin app (Phase 3). + +## Role helper functions + +| Function | Returns | Meaning | +|---|---|---| +| `is_admin()` | `boolean` | current user's profile has `role = 'admin'` | +| `is_staff_or_admin()` | `boolean` | current user's profile has `role in ('staff','admin')` | + +Both are `security definer` so they can read `profiles` inside RLS checks and RPC +guards. + +## Error handling + +RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot +connect with yourself`, `staff or admin only`, `you must be checked in to this +session to give feedback`). The frontend surfaces these via toasts — see +[../frontend/api-client.md](../frontend/api-client.md). diff --git a/docs/backend/schema.md b/docs/backend/schema.md new file mode 100644 index 0000000..ef7ad21 --- /dev/null +++ b/docs/backend/schema.md @@ -0,0 +1,152 @@ +# Database Schema + +All tables live in the `public` schema. Source of truth: +[`supabase/migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql). + +There are **9 tables**: people, schedule, and the event's activity. + +```mermaid +erDiagram + profiles ||--o{ preferences : "picks" + profiles ||--o{ connections : "from/to" + profiles ||--o{ checkins : "checked in" + profiles ||--o{ feedback : "rates" + profiles ||--o{ leaderboard : "mirrored" + profiles ||--o{ points_log : "audited" + slots ||--o{ sessions : "contains" + sessions ||--o{ preferences : "picked" + sessions ||--o{ checkins : "checked into" + sessions ||--o{ feedback : "rated" +``` + +## `profiles` — people (source of truth) + +One row per attendee. `id` **is** the Supabase Auth user id. + +| Column | Type | Notes | +|---|---|---| +| `id` | `uuid` PK | = `auth.users(id)`; `on delete cascade` | +| `email` | `text` **unique** | The ticket-purchase email (login identifier) | +| `full_name` | `text` | | +| `company` | `text` | nullable | +| `role` | `text` | `attendee` \| `staff` \| `admin` (default `attendee`) | +| `qr_token` | `text` **unique** | The lanyard token; **doubles as the Auth password** | +| `points` | `integer` | `>= 0`, default 0 | +| `created_at` | `timestamptz` | | + +## `slots` — schedule blocks + +| Column | Type | Notes | +|---|---|---| +| `id` | `integer` PK | 1–6 | +| `name` | `text` | e.g. "Slot 1" | +| `slot_date` | `date` | `2026-10-23` | +| `start_time` | `time` | | +| `end_time` | `time` | | + +## `sessions` — one per (slot, room) + +| Column | Type | Notes | +|---|---|---| +| `id` | `uuid` PK | `gen_random_uuid()` | +| `title` | `text` | | +| `description` | `text` | nullable | +| `slot_id` | `integer` FK → `slots` | `on delete cascade` | +| `room` | `text` | "Main Stage" / "Room A" / "Room B" | +| `capacity` | `integer` | nullable (not enforced in v1) | +| `speakers` | `text` | | +| `created_at` | `timestamptz` | | + +Index: `sessions_slot_id_idx (slot_id)`. + +## `preferences` — one pick per slot + +| Column | Type | Notes | +|---|---|---| +| `id` | `uuid` PK | | +| `profile_id` | `uuid` FK → `profiles` | | +| `session_id` | `uuid` FK → `sessions` | | +| `slot_id` | `integer` | denormalized for easy "one per slot" | +| `created_at` | `timestamptz` | | + +**Constraint:** `unique (profile_id, slot_id)` — an attendee can pick at most one +session per slot. Enforced in the DB *and* by the `set_preference` RPC (which +deletes the old pick for the slot before inserting). + +## `connections` — the networking relationship + +| Column | Type | Notes | +|---|---|---| +| `id` | `uuid` PK | | +| `from_id` | `uuid` FK → `profiles` | the requester | +| `to_id` | `uuid` FK → `profiles` | the recipient | +| `status` | `text` | `pending` \| `accepted` \| `rejected` (default `pending`) | +| `created_at` | `timestamptz` | | +| `resolved_at` | `timestamptz` | set when accepted/rejected | + +**Constraint:** unique per **unordered pair** via +`unique index connections_pair_uniq on (least(from_id, to_id), greatest(from_id, to_id))`. +So Ana→Bruno and Bruno→Ana are the *same* connection — a pair can only ever have +one. + +## `checkins` — staff check-in of an attendee + +| Column | Type | Notes | +|---|---|---| +| `id` | `uuid` PK | | +| `profile_id` | `uuid` FK → `profiles` | the attendee being checked in | +| `session_id` | `uuid` FK → `sessions` | | +| `staff_id` | `uuid` FK → `profiles` | the staff member who scanned | +| `created_at` | `timestamptz` | | + +**Constraint:** `unique (profile_id, session_id)` — one check-in per attendee per +session (prevents double points). + +## `feedback` — post-session rating + +| Column | Type | Notes | +|---|---|---| +| `id` | `uuid` PK | | +| `profile_id` | `uuid` FK → `profiles` | | +| `session_id` | `uuid` FK → `sessions` | | +| `rating` | `integer` | `1–5` | +| `comment` | `text` | nullable (bonus points if present) | +| `created_at` | `timestamptz` | | + +**Constraint:** `unique (profile_id, session_id)` — one feedback per attendee per +session. + +## `leaderboard` — Realtime mirror + +A public, Realtime-friendly mirror of points. **Not** the source of truth — it is +kept in sync transactionally by the RPCs (see [rpcs.md](./rpcs.md#_sync_leaderboard)). + +| Column | Type | Notes | +|---|---|---| +| `profile_id` | `uuid` PK FK → `profiles` | | +| `full_name` | `text` | denormalized for display | +| `company` | `text` | denormalized | +| `points` | `integer` | | +| `updated_at` | `timestamptz` | | + +The app subscribes to `postgres_changes` on this table to update the leaderboard +live. See [../frontend/screens.md#leaderboard](../frontend/screens.md#leaderboard). + +## `points_log` — audit trail + +Powers the per-category points breakdown on the Profile screen. + +| Column | Type | Notes | +|---|---|---| +| `id` | `uuid` PK | | +| `profile_id` | `uuid` FK → `profiles` | | +| `delta` | `integer` | points added (can be negative for admin adjustments) | +| `category` | `text` | `checkin` \| `connection` \| `feedback` \| `admin` | +| `created_at` | `timestamptz` | | + +Index: `points_log_profile_id_idx (profile_id)`. + +## Other indexes + +- `profiles_qr_token_idx (qr_token)` — fast lanyard lookups. +- `checkins_session_id_idx (session_id)`. diff --git a/docs/backend/seed.md b/docs/backend/seed.md new file mode 100644 index 0000000..02eead8 --- /dev/null +++ b/docs/backend/seed.md @@ -0,0 +1,84 @@ +# Seed Data & Demo Accounts + +Source of truth: [`supabase/seed.sql`](../../supabase/seed.sql). The seed runs on +`npm run db:reset` and is **idempotent** (`on conflict ... do nothing`). + +## What it creates + +| Data | Count | Notes | +|---|---|---| +| `slots` | 6 | 23 Oct, 09:00–15:45 (see table below) | +| `sessions` | 18 | 3 per slot (Main Stage / Room A / Room B) | +| `auth.users` + `auth.identities` | 13 | 12 attendees + 1 admin; **QR token = bcrypt password** | +| `profiles` | 13 | one per user, with role + starting points | +| `leaderboard` | 13 | mirrored from `profiles` | +| `points_log` | 21 | Ana's coherent breakdown + one `admin` entry per other user | +| Ana's demo state | — | 6 preferences, 2 check-ins, 4 connections, 1 feedback | + +> **GoTrue gotcha:** manually-inserted `auth.users` must have +> `confirmation_token`, `recovery_token`, `email_change_token_new`, and +> `email_change` set to `''` (empty string), **not NULL** — GoTrue's password +> grant can't scan a NULL `confirmation_token`. `phone` is left NULL (unique +> constraint). + +## Slots + +| id | Time | +|---|---| +| 1 | 09:00–09:45 | +| 2 | 10:00–10:45 | +| 3 | 11:30–12:15 | +| 4 | 13:15–14:00 | +| 5 | 14:00–14:45 | +| 6 | 15:00–15:45 | + +## Demo accounts + +Login = **QR code** (typed or scanned) + **email**. The QR token is the password. + +| Person | Role | QR code | Email | Company | Start pts | +|---|---|---|---|---|---| +| **Ana Silva** | attendee | `CVV-ANA-4821` | ana.silva@nubank.com | Nubank | 40 | +| **Bruno Costa** | staff | `CVV-BRU-1177` | bruno.costa@acme.com | Acme Corp | 140 | +| **Rita Lopes** | staff | `CVV-RIT-9034` | rita.lopes@globant.com | Globant | 95 | +| **Convivo Admin** | admin | `CVV-ADM-0001` | admin@appe.at | Convivo | 0 | +| Tomás Ribeiro | attendee | `CVV-TOM-5566` | tomas.ribeiro@dataprev.com | Dataprev | 88 | +| Sofia Almeida | attendee | `CVV-SOF-2299` | sofia.almeida@loop.com | Loop | 76 | +| Marco Chen | attendee | `CVV-MRC-7712` | marco.chen@deepmind.com | DeepMind | 70 | +| Julia Santos | attendee | `CVV-JUL-3345` | julia.santos@ifood.com | iFood | 64 | +| Pedro Nunes | attendee | `CVV-PED-8801` | pedro.nunes@microsoft.com | Microsoft | 58 | +| Carla Mendes | attendee | `CVV-CAR-6623` | carla.mendes@quintoessencial.com | QuintoEssencial | 52 | +| Diego Ferreira | attendee | `CVV-DIE-4458` | diego.ferreira@stone.com | Stone | 35 | +| Marina Costa | attendee | `CVV-MNA-2210` | marina.costa@olx.com | OLX | 28 | +| Lucas Oliveira | attendee | `CVV-LUC-9987` | lucas.oliveira@usp.br | USP | 15 | + +## Ana's demo state (so the app looks alive on first login) + +Ana (id `11111111-…`) is seeded with a coherent 40-point history: + +- **Points breakdown** (`points_log`): 2× check-in (+10 each), 2× connection + (+5 each), 1× feedback (+10) = **40**. +- **Preferences** — one pick per slot (matches the mockup): + - Slot 1 → *Designing for Trust in AI Products* + - Slot 2 → *AI in Practice: Lessons from Production* + - Slot 3 → *Data Storytelling* + - Slot 4 → *Prototyping with AI* + - Slot 5 → *Community-Led Growth* + - Slot 6 → *Closing Panel: What's Next* +- **Check-ins** — checked into Slot 1 and Slot 2 (by staff Bruno). +- **Connections**: + - accepted with **Bruno** and **Rita** + - incoming (pending) from **Sofia** + - outgoing (pending) to **Julia** +- **Feedback** — rated Slot 1's *Designing for Trust in AI Products* 5★ with a comment. + +> Everyone else gets a single `admin` `points_log` entry for their starting points +> (so the Profile breakdown shows "Other"), and no other activity. + +## Suggested demo flow + +1. Log in as **Ana** (attendee) → Home, Agenda, Leaderboard all populated. +2. Scan **Marco** (`CVV-MRC-7712`) → send a connection request. +3. Log in as **Bruno** (staff) → the Scan tab becomes **Check-in** → pick a + session → scan **Carla** (`CVV-CAR-6623`) → she gets +10. +4. Watch the **Leaderboard** update live (Realtime). diff --git a/docs/backend/supabase-core.md b/docs/backend/supabase-core.md new file mode 100644 index 0000000..3b92c51 --- /dev/null +++ b/docs/backend/supabase-core.md @@ -0,0 +1,88 @@ +# Supabase Core — Local Stack + +The Supabase core is a set of Docker containers managed by the **Supabase CLI** +(installed as a root devDependency — `npx supabase` works out of the box). It is +the "main docker" of the project. + +## Containers + +`supabase start` brings up the full local stack (project id `Convivo`): + +| Container | Image | Role | +|---|---|---| +| `supabase_db_Convivo` | `supabase/postgres:17` | Postgres 17 — schema, RLS, RPCs, data | +| `supabase_auth_Convivo` | `supabase/gotrue` | Auth (QR + email login) | +| `supabase_rest_Convivo` | `supabase/postgrest` | REST API over Postgres (tables + RPCs) | +| `supabase_realtime_Convivo` | `supabase/realtime` | WebSocket realtime (leaderboard) | +| `supabase_storage_Convivo` | `supabase/storage-api` | Storage (unused in v1) | +| `supabase_kong_Convivo` | `supabase/kong` | **API gateway** — fronts everything on one port | +| `supabase_studio_Convivo` | `supabase/studio` | Web UI (Studio) | +| `supabase_inbucket_Convivo` | `supabase/mailpit` | Captures emails (none sent in this flow) | +| `supabase_pg_meta_Convivo` | `supabase/postgres-meta` | Metadata API (used by Studio) | +| `supabase_edge_runtime_Convivo` | `supabase/edge-runtime` | Edge functions (unused in v1) | +| `supabase_vector_Convivo` | `supabase/vector` | Log shipping | +| `supabase_analytics_Convivo` | `supabase/logflare` | Analytics | + +All containers share the external Docker network **`supabase_network_Convivo`** +(named `supabase_network_`). The app sidecar joins this network — see +[docker.md](./docker.md). + +## Ports + +| Service | Host port | Container port | Notes | +|---|---|---|---| +| **API (Kong)** | **54321** | 8000 | The single gateway the app proxies to. **Inside the network, Kong is on 8000** — the `54321→8000` mapping is host-only. | +| Studio | 54323 | 3000 | UI — login `postgres` / `postgres` | +| Postgres | 54322 | 5432 | Direct DB — `postgres` / `postgres` | +| SMTP (Mailpit) | 54324 | 8025 | Captures emails | +| Analytics | 54327 | 4000 | Logflare | + +> **Gotcha:** from *inside* the shared network (e.g. the app container), reach +> Kong at `supabase_kong_Convivo:8000`, **not** `:54321`. The `54321` port only +> exists on the host. This is why the app's nginx proxies to +> `supabase_kong_Convivo:8000` by default. + +## How to run + +```bash +# Start the core (creates containers + the supabase_network_Convivo network) +npm run db:start # = supabase start + +# (Re)apply migrations + seed, then restart the stack +npm run db:reset # = supabase db reset (NOT `supabase reset`) + +# Stop the core +npm run db:stop # = supabase stop + +# Show status / URLs / keys +npx supabase status +``` + +- `db:reset` drops and recreates the database, applies + [`migrations/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql), + then runs [`seed.sql`](../../supabase/seed.sql). Use it any time you want a + clean demo state. +- Migrations and seed are **idempotent** (`on conflict ... do nothing`), so a + reset is safe to repeat. + +## Config highlights (`supabase/config.toml`) + +| Setting | Value | Why | +|---|---|---| +| `project_id` | `Convivo` | Names the Docker network + containers | +| `[api] port` | `54321` | Kong gateway port | +| `[db] port` | `54322` | Postgres port | +| `[studio] port` | `54323` | Studio port | +| `[auth.email] enable_confirmations` | `false` | **No email is sent** — the QR+email login never emails the user | +| `[auth] site_url` | `http://127.0.0.1:3000` | The app origin | +| `[db.seed] sql_paths` | `["./seed.sql"]` | Seed runs on reset | + +## Keys + +| Key | Value | Where it's used | +|---|---|---| +| **Anon key** | standard local anon JWT (see `apps/convivo/.env.example`) | **Ships in the app** (public by design) | +| **Service-role key** | standard local service-role JWT | **Never in the app** — server-side only (used for admin ops / verification) | + +The app's security model (anon key + session JWT + RLS) is documented in +[rls.md](./rls.md). diff --git a/docs/frontend/README.md b/docs/frontend/README.md new file mode 100644 index 0000000..cb1dac5 --- /dev/null +++ b/docs/frontend/README.md @@ -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). diff --git a/docs/frontend/api-client.md b/docs/frontend/api-client.md new file mode 100644 index 0000000..dc1168e --- /dev/null +++ b/docs/frontend/api-client.md @@ -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). diff --git a/docs/frontend/app-structure.md b/docs/frontend/app-structure.md new file mode 100644 index 0000000..996df8b --- /dev/null +++ b/docs/frontend/app-structure.md @@ -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`** — 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; + slotById: Map; + 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** → `` (full screen, no tab bar). +3. **`feedbackSession` set** → `` 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) | diff --git a/docs/frontend/screens.md b/docs/frontend/screens.md new file mode 100644 index 0000000..63273ff --- /dev/null +++ b/docs/frontend/screens.md @@ -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()`. diff --git a/docs/next-steps.md b/docs/next-steps.md new file mode 100644 index 0000000..68ba330 --- /dev/null +++ b/docs/next-steps.md @@ -0,0 +1,105 @@ +# Next Steps + +What's done, what's next, and the open decisions. Phases follow the original +whiteboard: **0** Supabase core → **1** attendee app → **2** Pretix interface → +**3** admin app → **4** Sessionize interface. + +> **Current state:** Phase 0 + Phase 1 are **complete and verified** (browser- +> tested end-to-end, Docker-verified, pushed to `git.lago.dev/Lago/Convivo.git`). +> Per the working agreement, we **stop here** and let the user evaluate before +> starting Phase 2. + +## Done + +### Phase 0 — Dockerized Supabase core ✅ +- Full schema (9 tables), RLS on every table, transactional points RPCs. +- Seed: 6 slots, 18 sessions, 13 demo users (QR token = auth password). +- Runs via the Supabase CLI (`supabase start` / `supabase db reset`). +- Details: [backend/README.md](./backend/README.md). + +### Phase 1 — Attendee web PWA ✅ +- Login (QR + email, no email sent), Home, Agenda, Scan/Connect, staff Check-in, + Feedback, live Leaderboard, Profile. +- Same-origin proxy to Supabase (Vite dev / nginx in Docker). +- Docker: multi-stage build → nginx sidecar on the Supabase network. +- All flows browser-tested; Docker build + proxy + login verified. +- Details: [frontend/README.md](./frontend/README.md). + +## Next + +### Phase 2 — Pretix interface ⬜ (next) +Sync **tickets → attendees** from [Pretix](https://pretix.eu) (the ticketing +system). This replaces the hand-written seed with real ticket data. + +**Goal:** when someone buys a ticket in Pretix, a Convivo attendee is created +with a QR token and the right role/company. + +Likely scope: +- A **sync job / edge function** (or a small service) that pulls orders/attendees + from the Pretix API and upserts `profiles` + `auth.users`. +- **QR token generation** for each attendee (the token that goes on the lanyard). +- **Role mapping** — which Pretix ticket type maps to `attendee` / `staff` / + `admin` (open question, see below). +- **Idempotency** — re-running the sync must not duplicate attendees (key on the + Pretix order/attendee id). +- A way to **print/export lanyard QR codes** for the event. + +**Open questions:** +1. Which Pretix fields map to `role` and `company`? +2. Push (webhook on new order) vs pull (scheduled sync)? +3. Where does the sync job run (Supabase Edge Function vs a separate container)? + +### Phase 3 — Admin app (admin.appe.at) ⬜ +A separate web app for event organizers, using the **admin** role (which already +has direct write access to `profiles` / `slots` / `sessions` via RLS — see +[backend/rls.md](./backend/rls.md)). + +Likely scope: +- Manage **attendees** (view, edit role/company, reset QR, adjust points via + `adjust_points`). +- Manage **schedule** (slots + sessions) — create/edit/delete. +- **Live overview** — who's checked in, connection activity, leaderboard. +- Reuse the same Supabase core + anon/service key pattern; a new `apps/admin` + PWA. + +### Phase 4 — Sessionize interface ⬜ +Sync the **real agenda** (slots, sessions, speakers, rooms) from +[Sessionize](https://sessionize.com) instead of the hand-written seed. + +Likely scope: +- A sync job that pulls the event schedule from the Sessionize API and upserts + `slots` + `sessions`. +- Map Sessionize track/room/time → our `slots` / `sessions` shape. +- This makes the agenda **data-driven** from the real event (the schedule is + already stored in Postgres, so the app needs no changes). + +## Cross-cutting / later + +- **Real event clock** — replace the simulated `DEFAULT_NOW` + ([frontend/app-structure.md#the-event-clock](./frontend/app-structure.md#the-event-clock)) + with `new Date()` for the live event. +- **Subdomains** — `convivo.appe.at`, `admin.appe.at`, `db.appe.at` don't exist + yet; everything is on localhost. DNS + TLS + a reverse proxy in front of the + Supabase core will be needed for a real deployment. +- **Push notifications** — connection requests are currently seen when the app + is opened. (Out of scope for v1.) +- **Testing** — no automated tests yet. Candidates: RPC unit tests (points + idempotency, role guards), and an E2E smoke test (login → check-in → + leaderboard). + +## Open decisions (need user input) + +1. **Pretix role mapping** — which ticket type = staff/admin? +2. **Sync style** — webhook (push) vs scheduled (pull) for Pretix/Sessionize? +3. **Sync runtime** — Supabase Edge Functions vs separate containers? +4. **Admin app scope** — which admin features are must-haves for the event? +5. **Deployment target** — stay on localhost, or plan for the `appe.at` + subdomains now? + +## How to pick up work + +1. Read [architecture.md](./architecture.md) for the system overview. +2. For a phase, read the relevant component docs (backend or frontend) and the + source of truth files they link to. +3. Keep the docs updated in the same change that changes behavior (see the + conventions in [README.md](./README.md)).