Files
Convivo/docs/frontend/admin-app.md
T
8e38052f4c feat(admin): per-row badge preview with unconfigured tooltip, Excel-style column filters and search in Contacts/Registrations
- New shared BadgeRender module (resolveText/resolveQr/BadgeElementBody/BadgePagePreview/fitScale) reused by the badge editor and the new read-only preview modal
- Registrations: Badge button on every row opens a live preview of that attendee's badge; grayed out with a Uiverse-style APPE-red tooltip when the event has no badge configured
- Contacts + Registrations: per-column multi-select filters (LinkedIn/Visibility/Admin; Type/Ticket/Checked in) with Excel-style live counts, plus general search (contacts: first/last/email; registrations: +type)
- New Tooltip and ColumnFilter primitives in ui.tsx (portal-based, escape/outside-click close)
- e2e: registration-badge-preview.spec.ts (13) + table-filters.spec.ts (13), all green; docs synced

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]>
2026-10-16 08:53:46 +02:00

276 lines
19 KiB
Markdown

# Frontend — APPE Admin
The admin console is a **desktop-first single-page React app** in
[`apps/admin/`](../../apps/admin/), branded **APPE Admin**. It is a separate app
from the attendee PWA (same stack, same Supabase core, same same-origin proxy
pattern). Its admin gate accepts an existing contact with **`is_admin = true`
or an `@appe.at` email**, matching the database admin rule; other accounts are
signed out. Backend RLS remains the authorization boundary.
It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
(nginx). The attendee app stays on 3000.
## What it does
| View | Purpose |
|---|---|
| **Dashboard** | Active event card (name, dates, location, aggregates: avg feedback, #sessions, #speakers, #registrations, #checked-in) + top points + recent activity. |
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) A general search matches **first name, last name or email address**; the **LinkedIn**, **Visibility** and **Admin** columns each have an Excel-style **multi-select filter** with live counts. |
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. |
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). |
| **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. |
| **Activity** | Tables of check-ins, connections, and feedback (per active event), with manual **Generate AI Summary** controls for the event and individual sessions. |
| **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). |
| **Badges** | A **per-event WYSIWYG badge / PDF layout editor** (modelled on pretix's PDF Editor). Pick the event, then design one or more named **layouts** (a **Default** per event, switchable / creatable / deletable). Add **text boxes**, **QR codes** and **images** to a millimetre canvas; drag to move, use the 8 resize handles + rotation handle, **Shift-click to multi-select**, and **press `Del`** to remove. While dragging, **PowerPoint-style smart guides** appear — dashed alignment lines (edges / centres, page and neighbouring items) plus equal-spacing lines — and the element **snaps** to them. A **Word-style align** toolbar (left / center / right, top / middle / bottom) plus **PowerPoint-style** object alignment — align to the **page** or to the **selection**, and **distribute** horizontally / vertically — with the same controls in the properties panel. Text binds to attendee fields (name, email, ticket type, QR token, event name, **company / organizer**, or static) with font, size, line-height, colour, bold/italic, a labelled **Align text in box** section (horizontal left / center / right and vertical top / middle / bottom, inside the element's own frame) and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo** (`Ctrl`+`Z` / `Ctrl`+`Y`, also `Ctrl`+`Shift`+`Z`), a **Preview** mode (no handles), a **JSON** view of the layout, and **Save**. Previewed against a real sample registration. See [../backend/rpcs.md#badge-editor](../backend/rpcs.md#badge-editor). |
| **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. |
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
| **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). |
## Sessionize Source Editing
The Events editor accepts a Sessionize `All` or `GridSmart` URL, or the full
Sessionize `<script src="...">` tag, in the same multiline source field. Save
extracts and validates the HTTPS Sessionize URL and stores it as
`sessionize_endpoint`; the script is never executed. Invalid sources produce an
in-place error and are not saved. Active configured events sync at startup and
every 15 minutes by default; the existing Sync button still runs immediately.
See [source parsing and polling](../backend/sidecar.md#gridsmart-sources-and-polling).
## Auth guard
Login uses **email-only magic links**, with no password field, sign-in method
selector, password fallback, or password-change prompt. `AuthContext` checks
the contact after signing in:
- If `is_admin === true` or the contact email ends in `@appe.at` → the session
is accepted and the console is shown.
- Otherwise → the app calls `signOut()` and shows **"This account is not an
admin."** The same check runs on session restore (page reload) and on every
`onAuthStateChange`, so a non-admin can never see the console.
### Magic links
The email-only form calls `signInWithOtp` with `shouldCreateUser: false` and
`emailRedirectTo: <current Admin origin>/auth/callback`. It does not create
accounts or grant admin privileges. Eligible accounts must already exist in
Supabase Auth and have a matching contact. Account-related send failures show
the same generic confirmation as success; rate limits, network failures and
server failures show a generic retry error instead of server details. The
recipient is locked while sending, and resend has a 60-second UI
cooldown. A failed resend clears the previous confirmation.
`/auth/callback` accepts implicit-flow access/refresh tokens in the fragment,
or a PKCE `code` query parameter when a verifier exists in the same browser.
The callback is consumed once even under React StrictMode. It removes query
parameters and fragments from browser history before exchanging credentials,
ignores supplied `next`/`redirect_to` destinations, and always returns to `/`.
Invalid, expired or rejected links clear the local Auth session and allow a new
link request. The default client uses implicit flow and
`detectSessionInUrl: false`; the callback performs session handling explicitly.
A token-hash `/auth/confirm` email template is not supported by this handler.
Auth-state listeners defer Supabase calls with `setTimeout` rather than awaiting
them inside `onAuthStateChange`, avoiding Auth lock deadlocks. Revision checks
discard outdated listener/session-restore lookups after later auth events.
Vite proxies only `/auth/v1` so the SPA owns `/auth/callback`; nginx serves the
callback with `Cache-Control: no-store` and `Referrer-Policy: no-referrer`.
Local redirect allowlisting, Mailpit, and explicit production SMTP/URL setup are
documented in [Supabase Core](../backend/supabase-core.md#magic-link-configuration).
`admin.appe.at` is an intended production domain, not a verified deployment.
Focused browser coverage (mocked Auth/REST; no real email or database writes):
```bash
npm --prefix apps/admin run build
npm --prefix e2e test -- admin-magic-link.spec.ts
```
The spec defaults to `http://localhost:3001`; set `CONVIVO_ADMIN_URL` to test an
alternate local server. Real delivery and Supabase redirect enforcement require
a separate local Mailpit smoke test after restarting the local Auth service.
This is an **Admin frontend-only** change. Existing database passwords, password
sync triggers, shared password operations and Supabase Auth's password endpoint
remain unchanged because attendee/staff login still uses them. Admin sessions
remain event-independent, and contacts with existing default passwords do not
receive a password-change prompt. See [demo accounts](../backend/seed.md#demo-accounts)
for seeded staff credentials used by the Convivo app.
## Source layout
```
apps/admin/src/
├─ main.tsx # ReactDOM entry
├─ App.tsx # Providers + Shell (sidebar nav + view switch)
├─ styles.css # Desktop-first styling (same design tokens as the PWA)
├─ context/
│ ├─ AuthContext.tsx # session + contact + is_admin guard
│ └─ ToastContext.tsx # transient toasts
├─ lib/
│ ├─ supabase.ts # createClient (same-origin)
│ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points)
│ └─ types.ts # TS types mirroring the DB
├─ components/
│ ├─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, TypeBadge, Toggle, Tooltip, ColumnFilter
│ └─ BadgeRender.tsx # shared badge renderer: resolveText/resolveQr, BadgeElementBody, BadgePagePreview, fitScale
├─ screens/
│ └─ Login.tsx # email-only magic-link login (admin-only)
└─ views/
├─ Dashboard.tsx # active event + aggregates + top points + activity
├─ Contacts.tsx # table + edit / is_admin / visibility / points
├─ Registrations.tsx# per-event list + type / QR token (view) / badge preview / checked-in + sponsor lookup
├─ Sponsors.tsx # sponsor CRUD
├─ Schedule.tsx # slots + sessions + speakers + material
├─ Activity.tsx # check-ins / connections / feedback tables
├─ Events.tsx # event management (+ sessionize_endpoint + per-row Sync + talk networking bonus)
├─ Interfaces.tsx # sidecar status / run / recent runs
├─ Reports.tsx # post-event summary + CSV / Excel / PDF export (sidecar /export)
└─ Settings.tsx # server-only LLM configuration (redacted key)
```
## Data access
The admin app uses the **anon key + the admin's session JWT** — no service-role
key. Everything it can do is allowed by RLS:
- **Reads** — admin-only `select` policies on `contacts`, `registrations`,
`sponsors`, `connections`, `feedback`, `checkins`, `points_log`, plus the public
`events` / `slots` / `sessions` / `session_speakers` / `leaderboard`. See
[../backend/rls.md](../backend/rls.md).
- **Writes** — direct `insert` / `update` / `delete` on `contacts`, `events`,
`registrations`, `sponsors`, `slots`, `sessions`, and `session_speakers`
(admin-only policies).
- **RPCs** — `adjust_points` (manual, audited as `admin`), `upsert_contact`,
`create_registration`, `set_registration_type`,
`set_session_material` (attach uploaded material), and
`delete_event_schedule` (clear the active event's slots/sessions). The
`reset_registration_qr_token` RPC still exists but the admin UI no longer
exposes a token reset. See
[../backend/rpcs.md](../backend/rpcs.md).
### Viewing a QR token
The QR token lives on the **registration** (per event), not the contact. The
**Registrations** view shows each registration's token and a **QR** button that
opens a modal with the scannable code. The token is **final** — it is generated
per event and can't be reset from the UI (the `reset_registration_qr_token` RPC
still exists, but the admin UI no longer exposes a reset action).
### Previewing a badge
Every registration row also has a **Badge** button. It opens a modal that renders
the event's **badge layout** for that specific attendee — the same millimetre
markup the Badges editor draws, minus the editing chrome — so the bound fields
resolve against that row's own **name**, **ticket type**, **QR token**, plus the
event's **name** and **company / organizer**. The event's layouts are loaded with
the list (one request per event, reused by every preview); when an event has
several layouts a **Layout** dropdown picks between them (the default is
preselected), and the badge is scaled to fit the dialog on any viewport.
A badge counts as **configured** only when a layout for the event actually has
elements — an empty layout would render a blank white badge. When nothing is
configured, the **Badge** button is still shown on every row but **disabled**
(grayed out, not clickable), and hovering or focusing it reveals a tooltip —
*“A badge needs to be configured for this event first. Design one in the Badges
view.”* — pointing the admin to the **Badges** view. The tooltip is the shared
`Tooltip` component in `components/ui.tsx`: the Uiverse dark-glass card already
used in Interfaces, re-themed to the APPE red accent and rendered through a
portal so it is never clipped by the table's `overflow: hidden`. The shared badge
renderer lives in `components/BadgeRender.tsx`, used by both the editor and this
preview.
### Sponsor lookup (in-place)
Setting a registration's type to **Sponsor** requires a sponsor lookup. If none
exists for that contact, the change fails with `a sponsor registration requires a
sponsor lookup` and the UI opens an **in-place sponsor popup** (instead of just
erroring). The popup lets the admin either **link an existing sponsor** (a
dropdown lists the event's sponsors; picking one pre-fills the form) or **create
a new one** (type, name, email, phone, amount, paid). On save it upserts the
sponsor linked to that contact's email, then sets the registration type to
`sponsor` in one step.
### Adjusting points
`adjust_points(contact_email, delta, reason)` is the same transactional RPC the
event uses, but the `category` is `admin` so manual adjustments are auditable in
`points_log`. It keeps `registrations.points` and the `leaderboard` mirror in sync.
### Session material
The Schedule view uploads a session's material to the `materials` bucket and sets
`sessions.material_path` (admins can write `sessions` directly).
### Feedback AI Summaries
Configure the complete OpenAI-compatible HTTPS endpoint, model and optional key
in **Settings > Feedback AI**. The key is never returned to the browser. In
**Activity**, the event feedback tab has one **Generate AI Summary** button;
the session feedback tab has one per session with responses. Generation is manual,
disabled without feedback or configuration, and shows loading and recoverable
error states. Saved plain-text summaries include their model, response count and
generation time. Regeneration replaces a result only after success.
The obsolete Schedule evaluation stub has been removed and its RPC is no longer
client-callable. See the [backend contract](../backend/feedback-ai.md) for provider
compatibility, data privacy, permissions and deployment requirements.
### Registration Tickets
Registration totals and check-in totals exclude blank/missing QR tokens. Unticketed
rows remain listed separately. Check-in toggles update immediately, disable during
the request and restore their previous value on failure, without a page refresh.
**Merge tickets** appears only on QR-less Sessionize-imported registration rows.
Its modal ranks purchased tickets from the same event by matching name words,
including accent normalization, and allows searching/selecting any purchased
ticket regardless of whether its name matches. Nothing merges until confirmation.
The destination keeps its QR/email, attendance and points; session assignments and
the speaker/staff role transfer before deleting the imported registration. Contact
and Auth records and other events are preserved. Source attendee activity requires
manual reconciliation before merging. See [the RPC contract](../backend/rpcs.md).
### Delete current schedule
The Schedule view keeps the existing active-event selection pattern: it loads
`getActiveEvent()`, then reads slots/sessions for that event. **Delete current
schedule** captures the active event ID/name when the confirmation modal opens
and calls `delete_event_schedule(p_event_id)`. Success refreshes only that same
event view and reports deleted slot/session counts; if the admin navigates away
or changes the active event while the RPC is pending, the stale completion does
not clear the newly selected event's UI.
The confirmation spells out the irreversible data loss: slots, sessions,
speaker links, preferences, check-ins and feedback are deleted; registrations
are preserved; material paths are removed with session rows, but Storage objects
are not physically purged. The UI disables schedule mutation controls while the
delete is pending. A later or concurrent Sessionize/Pretix sync can recreate
schedule rows because the admin delete does not lock the import sidecar.
### Reports (post-event summary + export)
The **Reports** view is the post-event reporting surface. It works for **any**
event (active or past) — the event selector defaults to the active event but can
pick a past one.
- **On-screen summary** — computed client-side from the same reads the export
uses: registrations (by type), check-ins, connections (total / accepted),
session feedback (count + average), event feedback (count + average), points by
category, and a top-5 leaderboard.
- **Session feedback summary** — a per-session table (title, room, average
rating, response count) sorted by average; this is the post-event session
feedback summary.
- **Export** — three buttons call the sidecar's [`POST /export`](../backend/sidecar.md#http-api):
**Download CSV**, **Download Excel**, **Download PDF report**. CSV/XLSX include
the tables ticked in the checkbox list (default: all); the PDF always uses the
full dataset. The response's base64 body is decoded and downloaded in the
browser (`downloadReport` in `lib/api.ts`).
## Styling
The admin app reuses the attendee app's **design tokens** (colors, Poppins font,
card/pill/button styles) but is laid out **desktop-first**: a dark sidebar with
the **APPE / Admin** brand + nav + admin identity, and a wide content area with
stat cards and data tables. Below ~760px the sidebar collapses to a top bar so it
still works on a phone.