Add Playwright E2E suite (46 tests) + app testids + test_cases.md

- e2e/: full Playwright suite covering every spec case (staff auth/UI,
  welcome + session check-in, attendee access/gating, connections,
  profile visibility, speaker material, sponsor, feedback, E2E journeys,
  role security matrix). 46/46 passing.
- apps/convivo: add data-testid attributes (gate, tabs, scanner, toggles)
  to support the E2E suite.
- test_cases.md: spec-case-to-test coverage map (all cases fully covered).
- .gitignore: ignore e2e node_modules/reports/test-results.
This commit is contained in:
Lago committed 2026-09-09 10:13:26 +02:00
1 parent e4c8815e52
commit 692df23149
44 files changed
+3715 -26

No files matched your search

+6
View File
@@ -30,3 +30,9 @@ Thumbs.db
# Browser test artifacts
.playwright-mcp/
# Playwright E2E artifacts
e2e/node_modules/
e2e/reports/
e2e/test-results/
test-results/
+2 -1
View File
@@ -84,7 +84,7 @@ function Shell() {
if (isGated) {
return (
<div className="app">
<div className="center" style={{ flex: 1, flexDirection: 'column', gap: 14, padding: 24, textAlign: 'center' }}>
<div className="center" data-testid="checkin-required-gate" style={{ flex: 1, flexDirection: 'column', gap: 14, padding: 24, textAlign: 'center' }}>
<div style={{ fontSize: 56 }}>🏷️</div>
<div className="h1" style={{ textAlign: 'center' }}>Please see a staff member</div>
<div className="muted" style={{ textAlign: 'center', maxWidth: 320 }}>
@@ -140,6 +140,7 @@ function Shell() {
{TABS.map((t) => (
<button
key={t.id}
data-testid={`tab-${t.id}`}
className={`tab ${t.id === 'scan' ? 'tab-scan' : ''} ${tab === t.id ? 'active' : ''}`}
onClick={() => setTab(t.id)}
>
+5 -2
View File
@@ -53,14 +53,16 @@ export function Toggle({
checked,
onChange,
label,
testId,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label: string;
testId?: string;
}) {
return (
<label className="toggle">
<input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
<input type="checkbox" data-testid={testId} checked={checked} onChange={(e) => onChange(e.target.checked)} />
<span className="track">
<span className="knob" />
</span>
@@ -160,11 +162,12 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
<div className="row" style={{ gap: 8 }}>
<input
className="input mono"
data-testid="scanner-manual-code"
placeholder="…or type the code (e.g. CVV-XXX-NNNN)"
value={manual}
onChange={(e) => setManual(e.target.value)}
/>
<button className="btn primary small" disabled={!manual.trim()} onClick={() => onResult(manual.trim())}>
<button className="btn primary small" data-testid="scanner-manual-go" disabled={!manual.trim()} onClick={() => onResult(manual.trim())}>
Go
</button>
</div>
+3 -3
View File
@@ -210,12 +210,12 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
{/* Speaker material: non-dismissible notification until uploaded. */}
{selNeedsMaterial && (
<div className="material-notice">
<div className="material-notice" data-testid="material-upload-notice">
<div className="mn-title">📎 Upload your session material</div>
<div className="muted small" style={{ marginBottom: 10 }}>
Attendees can download your slides/notes from this session.
</div>
<input ref={fileRef} type="file" className="input" onChange={handleUpload} />
<input ref={fileRef} type="file" data-testid="material-upload" className="input" onChange={handleUpload} />
</div>
)}
@@ -246,7 +246,7 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{selStatus === 'done' && selCheckedIn && (
<button className="btn primary" onClick={() => openFeedback(selected.id)}>
<button className="btn primary" data-testid="give-feedback" onClick={() => openFeedback(selected.id)}>
Give feedback ⭐
</button>
)}
+4 -4
View File
@@ -73,8 +73,8 @@ export function Connections() {
<section className="screen">
<div className="h1">Connections</div>
<div className="seg">
<button className={tab === 'mine' ? 'active' : ''} onClick={() => setTab('mine')}>My connections</button>
<button className={tab === 'req' ? 'active' : ''} onClick={() => setTab('req')}>
<button className={tab === 'mine' ? 'active' : ''} data-testid="connections-tab-mine" onClick={() => setTab('mine')}>My connections</button>
<button className={tab === 'req' ? 'active' : ''} data-testid="connections-tab-req" onClick={() => setTab('req')}>
Requests {incoming.length + outgoing.length > 0 && <span className="pill violet" style={{ marginLeft: 4 }}>{incoming.length + outgoing.length}</span>}
</button>
</div>
@@ -120,8 +120,8 @@ export function Connections() {
)}
</div>
</div>
<button className="btn primary small" onClick={() => resolve(c.id, true)}>Accept</button>
<button className="btn small" onClick={() => resolve(c.id, false)}>Decline</button>
<button className="btn primary small" data-testid="connection-accept" onClick={() => resolve(c.id, true)}>Accept</button>
<button className="btn small" data-testid="connection-decline" onClick={() => resolve(c.id, false)}>Decline</button>
</div>
))}
</div>
+3 -1
View File
@@ -58,6 +58,7 @@ export function Feedback({ sessionId, onDone }: { sessionId: string; onDone: ()
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
data-testid={`feedback-star-${n}`}
className={`star ${n <= rating ? 'on' : ''}`}
onClick={() => setRating(n)}
aria-label={`${n} star${n > 1 ? 's' : ''}`}
@@ -69,13 +70,14 @@ export function Feedback({ sessionId, onDone }: { sessionId: string; onDone: ()
<textarea
className="input"
data-testid="feedback-comment"
placeholder="Add a comment (optional) — comments earn bonus points"
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
/>
<button className="btn primary" disabled={busy || rating === 0} onClick={submit}>
<button className="btn primary" data-testid="feedback-submit" disabled={busy || rating === 0} onClick={submit}>
{busy ? 'Submitting…' : 'Submit feedback'}
</button>
<div className="muted small" style={{ textAlign: 'center', marginTop: 8 }}>
+2 -2
View File
@@ -149,7 +149,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
</div>
<div className="row" style={{ gap: 8 }}>
{pendingMaterial.length > 0 && (
<div className="material-pill" onClick={() => setMaterialSheetOpen(true)}>
<div className="material-pill" data-testid="material-pill" onClick={() => setMaterialSheetOpen(true)}>
📎 {pendingMaterial.length}
</div>
)}
@@ -159,7 +159,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
{/* Pending feedback: nudge to rate a session they attended. */}
{feedbackPending.length > 0 && (
<button className="feedback-pill" onClick={() => go('agenda')}>
<button className="feedback-pill" data-testid="feedback-pill" onClick={() => go('agenda')}>
⭐ {feedbackPending.length === 1 ? 'Rate your last session' : `Rate ${feedbackPending.length} sessions`}
</button>
)}
+5 -2
View File
@@ -68,7 +68,7 @@ export function Login() {
if (step === 'splash') {
return (
<section className="screen no-tab splash" onClick={() => setStep('scan')}>
<section className="screen no-tab splash" data-testid="login-splash" onClick={() => setStep('scan')}>
<div className="logo"><img src="/icon-192.png" alt="APPE" /></div>
<div className="splash-title">APPE</div>
<div className="splash-tag">Break the ice. Earn the points.</div>
@@ -112,6 +112,7 @@ export function Login() {
<input
className="input"
type="password"
data-testid="staff-login-password"
placeholder="••••••••••"
value={staffPassword}
onChange={(e) => setStaffPassword(e.target.value)}
@@ -128,6 +129,7 @@ export function Login() {
<input
className="input"
type="email"
data-testid="attendee-login-email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
@@ -137,9 +139,10 @@ export function Login() {
</>
)}
</div>
{error && <div className="muted small" style={{ color: 'var(--red)' }}>{error}</div>}
{error && <div className="muted small" data-testid="login-error" style={{ color: 'var(--red)' }}>{error}</div>}
<button
className="btn primary"
data-testid="login-confirm"
disabled={busy || (isStaff ? !staffPassword : !email.trim())}
onClick={confirm}
>
+5 -4
View File
@@ -103,16 +103,17 @@ export function Profile() {
<input
className="input"
type="url"
data-testid="profile-linkedin-url"
placeholder="https://linkedin.com/in/you"
value={linkedin}
onChange={(e) => setLinkedin(e.target.value)}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 14 }}>
<Toggle checked={showEmail} onChange={setShowEmail} label="Show my email" />
<Toggle checked={showLinkedin} onChange={setShowLinkedin} label="Show my LinkedIn" />
<Toggle checked={showEmail} onChange={setShowEmail} label="Show my email" testId="profile-show-email" />
<Toggle checked={showLinkedin} onChange={setShowLinkedin} label="Show my LinkedIn" testId="profile-show-linkedin" />
</div>
<button className="btn primary" disabled={saving} onClick={() => void saveProfile()}>
<button className="btn primary" data-testid="profile-save" disabled={saving} onClick={() => void saveProfile()}>
{saving ? 'Saving…' : 'Save profile'}
</button>
</div>
@@ -139,7 +140,7 @@ export function Profile() {
)}
</div>
<button className="btn danger" onClick={() => void signOut()}>Log out</button>
<button className="btn danger" data-testid="profile-logout" onClick={() => void signOut()}>Log out</button>
</section>
);
}
+7 -7
View File
@@ -109,8 +109,8 @@ export function Scan() {
</div>
{isStaff && (
<div className="seg" style={{ width: 170 }}>
<button className={mode === 'attendee' ? 'active' : ''} onClick={() => setMode('attendee')}>Attendee</button>
<button className={mode === 'staff' ? 'active' : ''} onClick={() => setMode('staff')}>Staff</button>
<button className={mode === 'attendee' ? 'active' : ''} data-testid="scan-mode-attendee" onClick={() => setMode('attendee')}>Attendee</button>
<button className={mode === 'staff' ? 'active' : ''} data-testid="scan-mode-staff" onClick={() => setMode('staff')}>Staff</button>
</div>
)}
</div>
@@ -119,7 +119,7 @@ export function Scan() {
<div>
<div className="row between" style={{ marginBottom: 10 }}>
<span className="muted small" style={{ fontWeight: 700 }}>Check-in type</span>
<label className="uiverse-toggle" title={welcomeMode ? 'Welcome check-in' : 'Session check-in'}>
<label className="uiverse-toggle" data-testid="welcome-checkin-toggle" title={welcomeMode ? 'Welcome check-in' : 'Session check-in'}>
<input
type="checkbox"
checked={welcomeMode}
@@ -134,7 +134,7 @@ export function Scan() {
) : (
<>
<div className="muted small" style={{ marginBottom: 7 }}>Checking in to session</div>
<select className="input" value={sessionId} onChange={(e) => setSessionId(e.target.value)}>
<select className="input" data-testid="session-selector" value={sessionId} onChange={(e) => setSessionId(e.target.value)}>
{slots
.filter(({ slot }) => slot.type !== 'service_session')
.map(({ slot, sessions }) => (
@@ -175,7 +175,7 @@ export function Scan() {
</div>
)}
<div style={{ marginTop: 16 }}>
<button className="btn primary" disabled={busy} onClick={confirmConnect}>
<button className="btn primary" data-testid="connection-send" disabled={busy} onClick={confirmConnect}>
{busy ? 'Sending…' : 'Connect 🤝'}
</button>
<button className="btn ghost" style={{ marginTop: 8 }} onClick={() => setConnectTarget(null)}>
@@ -189,7 +189,7 @@ export function Scan() {
{/* Check-in result sheet */}
<Sheet open={!!checkin} onClose={() => setCheckin(null)}>
{checkin && (
<div style={{ textAlign: 'center' }}>
<div style={{ textAlign: 'center' }} data-testid="session-checkin-result">
<div style={{ fontSize: 52 }}>{checkin.already ? '⚠️' : '✅'}</div>
<h3 style={{ marginTop: 10 }}>{checkin.attendee_name}</h3>
<div className="sub">{checkin.already ? 'Already checked in' : 'Checked in'}</div>
@@ -210,7 +210,7 @@ export function Scan() {
{/* Welcome check-in result sheet */}
<Sheet open={!!welcome} onClose={() => setWelcome(null)}>
{welcome && (
<div style={{ textAlign: 'center' }}>
<div style={{ textAlign: 'center' }} data-testid="welcome-checkin-result">
<div style={{ fontSize: 52 }}>{welcome.already ? '⚠️' : '👋'}</div>
<h3 style={{ marginTop: 10 }}>{welcome.attendee_name}</h3>
<div className="sub">{welcome.already ? 'Already checked in to the event' : 'Welcome to the event!'}</div>
+83
View File
@@ -0,0 +1,83 @@
# Convivo E2E Acceptance Suite
Playwright-based end-to-end acceptance tests for the Convivo application, covering
all four roles (Staff, Attendee, Speaker, Sponsor) across the full spec
(CONV-STAFF-AUTH-001 → CONV-E2E-002).
## Running
```bash
cd e2e
npm install # first time
npx playwright install chromium # first time
npx playwright test # full suite
npx playwright test <name> # a subset (e.g. `feedback`, `sponsor`)
npx playwright show-report reports/html
```
The suite runs against the live local stack (app :3000, Kong :54321, Postgres
container `supabase_db_Convivo`). Every test resets the relevant backend state
first (see `src/helpers/reset.ts`), so the suite is self-contained and
re-runnable.
## Layout
- `playwright.config.ts` — workers=1, 90s timeout, trace/screenshot/video on
failure, HTML report to `reports/html`.
- `src/helpers/` — `config` (identities, session ids), `db` (psql assertions),
`api` (PostgREST/Auth client for backend authorization checks), `reset`
(state reset + temporary-identity setup), `auth` (login flows), `multi`
(isolated per-user browser contexts).
- `src/pages/` — page objects (App, Home, Agenda, Scan, Connections, Profile,
Feedback).
- `tests/` — the spec cases, grouped by feature.
## Design decisions
- **Isolated BrowserContext per user** — multi-user tests (real-time gate lift,
connections, E2E journeys) create one context per participant so sessions never
leak and real-time behaviour is observed naturally.
- **Backend state validation** — assertions read the resulting persisted state
through a psql helper (spec §40), not just UI toasts. Authorization cases call
the RPC *as* a specific user (via their JWT) to prove the backend enforces the
rule, not just the frontend (spec §30/§39).
- **Stable `data-testid` selectors** — the app was instrumented with testids so
the suite is resilient to copy/label changes.
- **Real-time = 4s polling** — the app lifts the check-in gate via a 4s poll
(not Supabase Realtime); the real-time tests wait for that poll to fire.
## Results
**44/44 passing** (3.3 min, single worker).
| Area | Cases | Status |
|------|-------|--------|
| Staff auth | CONV-STAFF-AUTH-001..005 | ✅ |
| Staff UI | CONV-STAFF-UI-001 | ✅ |
| Welcome check-in + attendee access | CONV-CHECKIN-001..002, CONV-ATT-AUTH-001..003 | ✅ |
| Connections | CONV-CONN-001..008 | ✅ |
| Session check-in | CONV-SESSION-001..003 | ✅ |
| Profile visibility | CONV-PROFILE-001..005 | ✅ |
| Speaker + material | CONV-SPEAKER-001, CONV-MATERIAL-001..004 | ✅ |
| Sponsor | CONV-SPONSOR-001 | ✅ |
| Feedback | CONV-FEEDBACK-001..005 | ✅ |
| E2E journeys | CONV-E2E-001..002 | ✅ |
| Role security matrix | §39 (welcome/session check-in, material, feedback) | ✅ |
## Findings
- **Speakers have NULL `qr_token` in the seed** — the reset helper assigns
`CVV-SPK-9001` and re-hashes the auth password so the speaker can log in.
- **No sponsors exist in the seed** — the reset helper creates one
(`[email protected]` / `CVV-SPO-9001`).
- **Real-time is 4s polling, not Supabase Realtime** — the gate lift and
check-in activation are driven by a 4s poll in `App.tsx`.
- **`create_connection_request` is idempotent** — re-requesting an existing
connection returns the existing row rather than erroring.
- **GoTrue 500s on NULL `auth.users` token columns** — newly created auth users
must set `confirmation_token`, `email_change_token_new`, `email_change`,
`recovery_token`, `reauthentication_token`, `phone_change_token` to `''`
(empty string, not NULL) or the login endpoint returns a 500.
- **The speaker has 2 sessions** — so the pending-material pill shows a count
(not 0) even after uploading one session's material; tests assert the count
decreases by exactly 1.
+8
View File
@@ -0,0 +1,8 @@
Convivo demo session material
============================
This is a small, valid test file used by the speaker material-upload
acceptance tests (CONV-MATERIAL-002 / CONV-MATERIAL-003).
It stands in for a real slide deck / notes attachment that a speaker
uploads for their session so attendees can download it.
+93
View File
@@ -0,0 +1,93 @@
{
"name": "convivo-e2e",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "convivo-e2e",
"version": "1.0.0",
"devDependencies": {
"@playwright/test": "^1.48.0",
"@types/node": "^22.0.0",
"typescript": "^5.6.0"
}
},
"node_modules/@playwright/test": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.63.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@types/node": {
"version": "22.20.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",
"integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/playwright": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.63.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
}
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"name": "convivo-e2e",
"version": "1.0.0",
"private": true,
"description": "Convivo acceptance test suite (Playwright).",
"scripts": {
"test": "playwright test",
"test:headed": "playwright test --headed",
"test:report": "playwright show-report",
"reset": "node src/helpers/reset-cli.js"
},
"devDependencies": {
"@playwright/test": "^1.48.0",
"typescript": "^5.6.0",
"@types/node": "^22.0.0"
}
}
+44
View File
@@ -0,0 +1,44 @@
import { defineConfig, devices } from '@playwright/test';
/**
* Convivo acceptance test suite.
*
* Runs against the locally-running stack:
* - Convivo app (Vite dev) -> http://localhost:3000
* - Supabase (Kong) -> http://127.0.0.1:54321
* - Postgres container -> supabase_db_Convivo
*
* Start the stack first:
* npm run db:start && npm run app:dev
*
* Tests run serially (workers: 1) because they share the demo database and
* reset state between tests. Each test is self-contained: it resets the
* relevant rows in `beforeEach` so execution order never matters.
*/
export default defineConfig({
testDir: './tests',
timeout: 90_000,
expect: { timeout: 15_000 },
fullyParallel: false,
workers: 1,
retries: 0,
reporter: [
['list'],
['html', { open: 'never', outputFolder: 'reports/html' }],
],
use: {
baseURL: process.env.CONVIVO_BASE_URL || 'http://localhost:3000',
// Capture evidence for every failed test (spec §40).
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
actionTimeout: 15_000,
navigationTimeout: 30_000,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});
+113
View File
@@ -0,0 +1,113 @@
import { ANON_KEY, SERVICE_ROLE_KEY, SUPABASE_URL } from './config';
/**
* A thin PostgREST/Auth client for backend assertions and authorization checks.
*
* - `svc` : service-role calls (bypass RLS) — used to read persisted state.
* - `auth` : sign in a user and return their JWT — used to call an RPC *as*
* that user, so we can verify backend authorization (spec §30:
* "Authorization must be enforced by the backend as well as the
* frontend. Hiding a button is not sufficient security.").
*/
async function postgrest<T>(path: string, opts: { method?: string; body?: unknown; key?: string } = {}): Promise<T> {
const key = opts.key ?? SERVICE_ROLE_KEY;
const res = await fetch(SUPABASE_URL + path, {
method: opts.method ?? 'GET',
headers: {
apikey: key,
Authorization: `Bearer ${key}`,
'Content-Type': 'application/json',
},
body: opts.body ? JSON.stringify(opts.body) : undefined,
});
const text = await res.text();
let parsed: unknown = null;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
parsed = text;
}
if (!res.ok) {
const msg = (parsed as { message?: string } | null)?.message || text || res.statusText;
throw new Error(`PostgREST ${opts.method ?? 'GET'} ${path} -> ${res.status}: ${msg}`);
}
return parsed as T;
}
/** Service-role (bypasses RLS) read of a table. */
export function svcSelect<T>(table: string, query = ''): Promise<T> {
return postgrest<T>(`/rest/v1/${table}${query}`);
}
/** Service-role call to an RPC. */
export function svcRpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
return postgrest<T>(`/rest/v1/rpc/${fn}`, { method: 'POST', body: args });
}
/**
* Sign in a user (email + password) and return their access token (JWT).
* Uses the anon key + the user's session JWT, exactly like the app does.
*/
export async function signInJwt(email: string, password: string): Promise<string> {
const res = await fetch(`${SUPABASE_URL}/auth/v1/token?grant_type=password`, {
method: 'POST',
headers: { apikey: ANON_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const text = await res.text();
if (!res.ok) throw new Error(`signInJwt ${email} -> ${res.status}: ${text}`);
const parsed = JSON.parse(text) as { access_token: string };
return parsed.access_token;
}
/** Call an RPC as a specific user (using their JWT). Throws on error. */
export async function userRpc<T>(jwt: string, fn: string, args: Record<string, unknown>): Promise<T> {
const res = await fetch(`${SUPABASE_URL}/rest/v1/rpc/${fn}`, {
method: 'POST',
headers: {
apikey: ANON_KEY,
Authorization: `Bearer ${jwt}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(args),
});
const text = await res.text();
let parsed: unknown = null;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
parsed = text;
}
if (!res.ok) {
const msg = (parsed as { message?: string } | null)?.message || text || res.statusText;
throw new Error(`userRpc ${fn} -> ${res.status}: ${msg}`);
}
return parsed as T;
}
/** Call an RPC as a user and return { ok, status, message } (no throw). */
export async function userRpcResult(
jwt: string,
fn: string,
args: Record<string, unknown>,
): Promise<{ ok: boolean; status: number; message: string }> {
const res = await fetch(`${SUPABASE_URL}/rest/v1/rpc/${fn}`, {
method: 'POST',
headers: {
apikey: ANON_KEY,
Authorization: `Bearer ${jwt}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(args),
});
const text = await res.text();
let parsed: unknown = null;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
parsed = text;
}
const message = (parsed as { message?: string } | null)?.message || text || res.statusText;
return { ok: res.ok, status: res.status, message };
}
+69
View File
@@ -0,0 +1,69 @@
import type { Page } from '@playwright/test';
import type { Identity } from './config';
/**
* Login flows. The app's login is: splash → scan (QR or manual code) → confirm
* (staff: +password / non-staff: +email). We drive the manual-code path so the
* tests don't depend on a camera (spec §2: "use the application's QR/manual-code
* entry path").
*/
/** Navigate to the app and reach the scan step. */
export async function toScanStep(page: Page, appUrl: string): Promise<void> {
await page.goto(appUrl, { waitUntil: 'domcontentloaded' });
const splash = page.getByTestId('login-splash');
// The splash is only present when logged out. If we land on the app (a
// persisted session), just proceed.
if (await splash.isVisible().catch(() => false)) {
await splash.click();
}
await page.getByTestId('scanner-manual-code').waitFor({ state: 'visible' });
}
/**
* Log in a user via the manual-code path.
* @param identity the identity (email + qrToken + optional staff password)
* @param passwordOverride override the password (for wrong-password tests)
* @param emailOverride override the confirm email (for mismatch tests)
*/
export async function login(
page: Page,
appUrl: string,
identity: Identity,
opts: { passwordOverride?: string; emailOverride?: string; skipConfirm?: boolean } = {},
): Promise<void> {
await toScanStep(page, appUrl);
// Step 1: provide the QR (manual code).
await page.getByTestId('scanner-manual-code').fill(identity.qrToken);
await page.getByTestId('scanner-manual-go').click();
// Step 2: the confirm screen. Staff → password; non-staff → email.
const isStaff = identity.type === 'staff';
const confirmField = isStaff
? page.getByTestId('staff-login-password')
: page.getByTestId('attendee-login-email');
await confirmField.waitFor({ state: 'visible' });
if (opts.skipConfirm) return; // e.g. QR-without-password tests
if (isStaff) {
await confirmField.fill(opts.passwordOverride ?? identity.password ?? '');
} else {
await confirmField.fill(opts.emailOverride ?? identity.email);
}
await page.getByTestId('login-confirm').click();
// Wait for the app to settle: either the tab bar (admitted) or the gate.
await page
.locator('[data-testid="tab-home"], [data-testid="checkin-required-gate"]')
.first()
.waitFor({ state: 'visible' });
}
/** Log out via the Profile screen. */
export async function logout(page: Page): Promise<void> {
await page.getByTestId('tab-profile').click();
await page.getByTestId('profile-logout').click();
await page.getByTestId('login-splash').waitFor({ state: 'visible' });
}
+117
View File
@@ -0,0 +1,117 @@
/**
* Central configuration for the Convivo acceptance suite.
*
* All identities map to real demo data in the local Supabase stack. The
* "temporary" identities (sponsor, extra attendees, the speaker's QR token)
* are created/reset by the reset helper so tests are self-contained.
*/
export const APP_URL = process.env.CONVIVO_BASE_URL || 'http://localhost:3000';
export const SUPABASE_URL = process.env.SUPABASE_URL || 'http://127.0.0.1:54321';
export const DB_CONTAINER = process.env.SUPABASE_DB_CONTAINER || 'supabase_db_Convivo';
/** Standard local Supabase keys (public by design — not secrets). */
export const ANON_KEY =
process.env.VITE_SUPABASE_ANON_KEY ||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0';
export const SERVICE_ROLE_KEY =
process.env.SUPABASE_SERVICE_ROLE_KEY ||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';
/** The single active demo event. */
export const EVENT_ID = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee';
export interface Identity {
/** Supabase auth email (the login identifier). */
email: string;
/** The lanyard QR token (doubles as the auth password for non-staff). */
qrToken: string;
/** The staff/admin login password (only for staff). */
password?: string;
/** The registration type. */
type: 'attendee' | 'speaker' | 'staff' | 'sponsor';
/** Human label for reports. */
label: string;
}
/** Standard test identities (spec §4). */
export const ID = {
/** STAFF_01 — the privileged operational role. */
staff: {
email: '[email protected]',
qrToken: 'CVV-STF-2002',
password: 'appe-admin-2026',
type: 'staff',
label: 'STAFF_01',
} as Identity,
/** ATTENDEE_NEW — never welcome-checked-in (reset to false before use). */
attendeeNew: {
email: '[email protected]',
qrToken: 'CVV-ATT-1000',
type: 'attendee',
label: 'ATTENDEE_NEW',
} as Identity,
/** ATTENDEE_RETURNING — previously welcome-checked-in (reset to true). */
attendeeReturning: {
email: '[email protected]',
qrToken: 'CVV-ATT-1001',
type: 'attendee',
label: 'ATTENDEE_RETURNING',
} as Identity,
/** ATTENDEE_A — a normal attendee. */
attendeeA: {
email: '[email protected]',
qrToken: 'CVV-ATT-1002',
type: 'attendee',
label: 'ATTENDEE_A',
} as Identity,
/** ATTENDEE_B — a normal attendee. */
attendeeB: {
email: '[email protected]',
qrToken: 'CVV-ATT-1003',
type: 'attendee',
label: 'ATTENDEE_B',
} as Identity,
/** Extra attendees for independent connection/privacy tests. */
attendeeC: {
email: '[email protected]',
qrToken: 'CVV-ATT-1004',
type: 'attendee',
label: 'ATTENDEE_C',
} as Identity,
attendeeD: {
email: '[email protected]',
qrToken: 'CVV-ATT-1005',
type: 'attendee',
label: 'ATTENDEE_D',
} as Identity,
/** SPEAKER_01 — assigned to SESSION_A (slot 1, "done"). */
speaker: {
email: '[email protected]',
qrToken: 'CVV-SPK-9001', // assigned by the reset helper (seed leaves it NULL)
type: 'speaker',
label: 'SPEAKER_01',
} as Identity,
/** SPONSOR_01 — created by the reset helper (no sponsor exists in the seed). */
sponsor: {
email: '[email protected]',
qrToken: 'CVV-SPO-9001',
type: 'sponsor',
label: 'SPONSOR_01',
} as Identity,
} as const;
/** SESSION_A — slot 1 (a "done" slot at the simulated 10:20 clock). */
export const SESSION_A = '37ab7060-3d81-4221-9322-6971e97d1175';
/** SESSION_B — slot 2 (a "now" slot). */
export const SESSION_B = '5146388a-7f8b-4c70-b3d3-635ebdf713d4';
/** The speaker's session (slot 1) — used for material upload tests. */
export const SPEAKER_SESSION = SESSION_A;
+157
View File
@@ -0,0 +1,157 @@
import { execFileSync } from 'node:child_process';
import { DB_CONTAINER } from './config';
/**
* Run a SQL statement against the local Supabase Postgres container and return
* the raw psql output. Used for backend-state assertions and resets (spec §40:
* "validate the resulting persisted state through a database-facing test helper").
*/
export function psql(sql: string): string {
const out = execFileSync('docker', ['exec', '-i', DB_CONTAINER, 'psql', '-U', 'postgres', '-t', '-A'], {
input: sql,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
});
return out.trim();
}
/** Sleep helper (ms). */
export function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
/** Normalize a Postgres boolean rendered as `t`/`f` or `true`/`false`. */
export function isTrue(s: string): boolean {
return s === 't' || s === 'true' || s === '1';
}
/**
* Poll a boolean SQL predicate until it is true (or timeout). Used to make
* backend-state assertions robust against the small gap between a UI action
* completing and the committed row being read by a fresh psql connection.
*/
export async function psqlUntil(
sql: string,
{ timeoutMs = 5000, intervalMs = 150 } = {},
): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (isTrue(psqlScalar(sql))) return true;
if (Date.now() > deadline) return isTrue(psqlScalar(sql));
await sleep(intervalMs);
}
}
/** Run a SQL statement and return the first column of the first row as a string. */
export function psqlScalar(sql: string): string {
return psql(sql).split('\n')[0]?.trim() ?? '';
}
/** Run a SQL statement and return all rows as an array of strings (one per row). */
export function psqlRows(sql: string): string[] {
const out = psql(sql);
return out ? out.split('\n').map((r) => r.trim()).filter(Boolean) : [];
}
/** Escape a string for safe interpolation into a SQL literal. */
export function sqlQuote(s: string): string {
return `'${s.replace(/'/g, "''")}'`;
}
/**
* A small, typed view over the demo data for the most common assertions.
* Every method returns raw values; tests assert on them explicitly.
*/
export const db = {
/** The registration row for a contact (or null). */
registration(contactEmail: string) {
const row = psql(
`select type || '|' || checked_in || '|' || coalesce(qr_token, '') || '|' || points
from public.registrations where contact_email = ${sqlQuote(contactEmail)} limit 1`,
);
if (!row) return null;
const [type, checkedIn, qrToken, points] = row.split('|');
return { type, checkedIn: isTrue(checkedIn), qrToken, points: Number(points) };
},
/** Whether a contact is welcome-checked-in. */
isWelcomeCheckedIn(contactEmail: string): boolean {
return this.registration(contactEmail)?.checkedIn ?? false;
},
/** Poll until a contact is welcome-checked-in (robust against commit timing). */
async waitForWelcomeCheckedIn(contactEmail: string, timeoutMs = 5000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (this.isWelcomeCheckedIn(contactEmail)) return true;
if (Date.now() > deadline) return this.isWelcomeCheckedIn(contactEmail);
await sleep(150);
}
},
/** Poll until a contact has a session check-in for the given session. */
async waitForSessionCheckin(contactEmail: string, sessionId: string, timeoutMs = 5000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (this.sessionCheckins(contactEmail).includes(sessionId)) return true;
if (Date.now() > deadline) return this.sessionCheckins(contactEmail).includes(sessionId);
await sleep(150);
}
},
/** The session ids a contact is session-checked-in to. */
sessionCheckins(contactEmail: string): string[] {
return psqlRows(
`select session_id from public.checkins where contact_email = ${sqlQuote(contactEmail)} order by created_at`,
);
},
/** The connection rows involving a contact (status|from|to). */
connections(contactEmail: string): { status: string; from: string; to: string }[] {
return psqlRows(
`select status || '|' || from_email || '|' || to_email
from public.connections where from_email = ${sqlQuote(contactEmail)} or to_email = ${sqlQuote(contactEmail)}
order by created_at`,
).map((r) => {
const [status, from, to] = r.split('|');
return { status, from, to };
});
},
/** The feedback rows for a contact (session_id|rating). */
feedback(contactEmail: string): { sessionId: string; rating: number }[] {
return psqlRows(
`select session_id || '|' || rating from public.feedback where contact_email = ${sqlQuote(contactEmail)} order by created_at`,
).map((r) => {
const [sessionId, rating] = r.split('|');
return { sessionId, rating: Number(rating) };
});
},
/** The contact's visibility settings (show_email|show_linkedin|linkedin_url). */
contact(contactEmail: string) {
const row = psql(
`select show_email || '|' || show_linkedin || '|' || coalesce(linkedin_url, '')
from public.contacts where email = ${sqlQuote(contactEmail)} limit 1`,
);
if (!row) return null;
const [showEmail, showLinkedin, linkedinUrl] = row.split('|');
return { showEmail: isTrue(showEmail), showLinkedin: isTrue(showLinkedin), linkedinUrl };
},
/** Whether a session has material uploaded. */
sessionHasMaterial(sessionId: string): boolean {
return isTrue(
psqlScalar(
`select material_path is not null from public.sessions where id = ${sqlQuote(sessionId)}`,
),
);
},
/** The session_speakers rows for a contact. */
speakerSessions(contactEmail: string): string[] {
return psqlRows(
`select session_id from public.session_speakers where contact_email = ${sqlQuote(contactEmail)} order by session_id`,
);
},
};
+46
View File
@@ -0,0 +1,46 @@
import type { Browser, BrowserContext, Page } from '@playwright/test';
/**
* A named, isolated browser context for one user. Multi-user tests create one
* of these per participant so real-time behaviour is observed naturally
* (spec §2, §40). Each context has its own storage state (cookies/localStorage),
* so sessions never leak between users.
*/
export class UserSession {
constructor(
readonly name: string,
readonly context: BrowserContext,
readonly page: Page,
) {}
/** Close the context (and its page). */
async close(): Promise<void> {
await this.context.close();
}
}
/**
* Create an isolated browser context + page for a user.
* @param browser the shared browser (from the `browser` fixture)
* @param name a label for the user (e.g. "staff", "attendeeA")
*/
export async function createUser(browser: Browser, name: string): Promise<UserSession> {
const context = await browser.newContext();
const page = await context.newPage();
return new UserSession(name, context, page);
}
/**
* Create several isolated contexts at once.
* @returns a map of name -> UserSession
*/
export async function createUsers(
browser: Browser,
names: string[],
): Promise<Map<string, UserSession>> {
const map = new Map<string, UserSession>();
for (const name of names) {
map.set(name, await createUser(browser, name));
}
return map;
}
+64
View File
@@ -0,0 +1,64 @@
import type { Page } from '@playwright/test';
/**
* Evidence capture for failure reports (spec §42). Attach to a page to collect
* console errors and failed network requests; `summary()` returns them for the
* failure report.
*/
export class PageEvidence {
consoleErrors: string[] = [];
failedRequests: string[] = [];
constructor(private page: Page) {
page.on('console', (msg) => {
if (msg.type() === 'error') this.consoleErrors.push(msg.text());
});
page.on('pageerror', (err) => this.consoleErrors.push(`pageerror: ${err.message}`));
page.on('requestfailed', (req) => {
this.failedRequests.push(`${req.method()} ${req.url()} -> ${req.failure()?.errorText ?? 'failed'}`);
});
page.on('response', (res) => {
if (res.status() >= 400) this.failedRequests.push(`${res.request().method()} ${res.url()} -> ${res.status()}`);
});
}
/** A compact evidence block for the failure report. */
summary(): string {
const parts: string[] = [];
if (this.consoleErrors.length) parts.push(`Console errors:\n ${this.consoleErrors.join('\n ')}`);
if (this.failedRequests.length) parts.push(`Failed requests:\n ${this.failedRequests.join('\n ')}`);
return parts.length ? parts.join('\n\n') : '(no console errors or failed requests captured)';
}
}
/**
* Build a spec §42 failure-report block. Call inside a test's catch or via a
* custom expect message.
*/
export function failureReport(opts: {
testId: string;
testName: string;
roles: string;
preconditions: string;
expected: string;
actual: string;
repro: string;
evidence?: string;
probableArea?: string;
severity?: string;
}): string {
return [
`Test ID: ${opts.testId}`,
`Test name: ${opts.testName}`,
`Role(s): ${opts.roles}`,
`Preconditions: ${opts.preconditions}`,
`Expected: ${opts.expected}`,
`Actual: ${opts.actual}`,
`Reproduction: ${opts.repro}`,
opts.evidence ? `Evidence:\n${opts.evidence}` : '',
opts.probableArea ? `Probable implementation area: ${opts.probableArea}` : '',
opts.severity ? `Severity: ${opts.severity}` : '',
]
.filter(Boolean)
.join('\n');
}
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env node
// Convivo e2e — standalone state reset.
//
// node src/helpers/reset-cli.js
//
// Resets the demo rows the acceptance suite touches and (re)creates the
// temporary identities (speaker QR token, sponsor). Safe to run any time.
const { execFileSync } = require('node:child_process');
const DB_CONTAINER = process.env.SUPABASE_DB_CONTAINER || 'supabase_db_Convivo';
const EVENT_ID = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee';
function psql(sql) {
execFileSync('docker', ['exec', '-i', DB_CONTAINER, 'psql', '-U', 'postgres', '-t', '-A'], {
input: sql,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
});
}
const q = (s) => `'${s.replace(/'/g, "''")}'`;
const CONTACTS = [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
];
// Welcome check-in baseline: everyone checked in EXCEPT ATTENDEE_NEW (lena).
const CHECKED_IN = CONTACTS.filter((c) => c !== '[email protected]');
psql(`update public.registrations set checked_in = true where contact_email in (${CHECKED_IN.map(q).join(',')}) and event_id = ${q(EVENT_ID)}`);
psql(`update public.registrations set checked_in = false where contact_email = ${q('[email protected]')} and event_id = ${q(EVENT_ID)}`);
// Clear per-contact state.
for (const c of CONTACTS) {
psql(`delete from public.checkins where contact_email = ${q(c)}`);
psql(`delete from public.connections where from_email = ${q(c)} or to_email = ${q(c)}`);
psql(`delete from public.feedback where contact_email = ${q(c)}`);
psql(`update public.registrations set points = 0 where contact_email = ${q(c)}`);
psql(`delete from public.points_log where contact_email = ${q(c)}`);
psql(`delete from public.leaderboard where contact_email = ${q(c)}`);
psql(`update public.contacts set show_email = false, show_linkedin = false, linkedin_url = null where email = ${q(c)}`);
}
// Clear material on the speaker's session (SESSION_A).
psql(`update public.sessions set material_path = null where id = ${q('37ab7060-3d81-4221-9322-6971e97d1175')}`);
// Speaker QR token (seed leaves it NULL).
psql(`update public.registrations set qr_token = ${q('CVV-SPK-9001')} where contact_email = ${q('[email protected]')} and event_id = ${q(EVENT_ID)}`);
psql(`update auth.users set encrypted_password = extensions.crypt(${q('CVV-SPK-9001')}, extensions.gen_salt('bf')) where email = ${q('[email protected]')}`);
// Sponsor (created; no sponsor exists in the seed).
psql(`insert into auth.users (instance_id, id, aud, role, email, encrypted_password, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at)
values ('00000000-0000-0000-0000-000000000000', gen_random_uuid(), 'authenticated', 'authenticated', ${q('[email protected]')},
extensions.crypt(${q('CVV-SPO-9001')}, extensions.gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}', '{"full_name":"Demo Sponsor"}', now(), now())
on conflict (id) do nothing`);
psql(`insert into public.contacts (email, full_name, linkedin_url, show_email, show_linkedin, is_admin, password)
values (${q('[email protected]')}, 'Demo Sponsor', null, false, false, false, null)
on conflict (email) do nothing`);
psql(`insert into public.registrations (event_id, contact_email, type, checked_in, points, qr_token)
values (${q(EVENT_ID)}, ${q('[email protected]')}, 'sponsor', true, 0, ${q('CVV-SPO-9001')})
on conflict (event_id, contact_email) do update set type = 'sponsor', qr_token = ${q('CVV-SPO-9001')}, checked_in = true`);
console.log('Convivo e2e state reset complete.');
+178
View File
@@ -0,0 +1,178 @@
import { psql, sqlQuote } from './db';
import { EVENT_ID, ID } from './config';
/**
* Test-state reset. The suite shares the demo database, so every test resets
* the rows it touches in `beforeEach`. These resets are idempotent and
* targeted (they only touch the identities the suite uses), so they never
* disturb the rest of the demo data.
*
* `resetAll()` is the full reset used by most tests. Individual helpers are
* available for tests that only need a slice of it.
*/
const RESET_CONTACTS = [
ID.attendeeNew.email,
ID.attendeeReturning.email,
ID.attendeeA.email,
ID.attendeeB.email,
ID.attendeeC.email,
ID.attendeeD.email,
ID.speaker.email,
ID.sponsor.email,
];
/** Reset the welcome-check-in flag for a contact. */
export function setWelcomeCheckedIn(contactEmail: string, checkedIn: boolean): void {
psql(
`update public.registrations set checked_in = ${checkedIn}
where contact_email = ${sqlQuote(contactEmail)} and event_id = ${sqlQuote(EVENT_ID)}`,
);
}
/** Reset session check-ins for a contact. */
export function clearSessionCheckins(contactEmail: string): void {
psql(
`delete from public.checkins where contact_email = ${sqlQuote(contactEmail)}`,
);
}
/**
* Set a session check-in for a contact (direct DB). Used by tests that need a
* specific session check-in without driving the full staff-scan flow (e.g. the
* feedback tests, where check-in is a precondition, not the subject).
*/
export function setSessionCheckin(contactEmail: string, sessionId: string, staffEmail: string): void {
psql(
`insert into public.checkins (event_id, contact_email, session_id, staff_email)
values (${sqlQuote(EVENT_ID)}, ${sqlQuote(contactEmail)}, ${sqlQuote(sessionId)}, ${sqlQuote(staffEmail)})
on conflict (event_id, contact_email, session_id) do nothing`,
);
}
/** Reset all connections involving a contact. */
export function clearConnections(contactEmail: string): void {
psql(
`delete from public.connections where from_email = ${sqlQuote(contactEmail)} or to_email = ${sqlQuote(contactEmail)}`,
);
}
/** Reset feedback for a contact. */
export function clearFeedback(contactEmail: string): void {
psql(
`delete from public.feedback where contact_email = ${sqlQuote(contactEmail)}`,
);
}
/** Reset a contact's points + audit trail + leaderboard mirror. */
export function resetPoints(contactEmail: string): void {
psql(
`update public.registrations set points = 0 where contact_email = ${sqlQuote(contactEmail)}`,
);
psql(
`delete from public.points_log where contact_email = ${sqlQuote(contactEmail)}`,
);
psql(
`delete from public.leaderboard where contact_email = ${sqlQuote(contactEmail)}`,
);
}
/** Reset a contact's profile visibility settings. */
export function resetProfile(contactEmail: string): void {
psql(
`update public.contacts set show_email = false, show_linkedin = false, linkedin_url = null
where email = ${sqlQuote(contactEmail)}`,
);
}
/** Clear a session's material (storage object + material_path). */
export function clearSessionMaterial(sessionId: string): void {
psql(
`update public.sessions set material_path = null where id = ${sqlQuote(sessionId)}`,
);
}
/**
* Ensure the speaker can log in via the normal QR flow. The seed leaves the
* speaker's `qr_token` NULL (a real gap — see findings), so we assign a token
* and re-hash it as the auth password.
*/
export function ensureSpeakerQrToken(): void {
psql(
`update public.registrations set qr_token = ${sqlQuote(ID.speaker.qrToken)}
where contact_email = ${sqlQuote(ID.speaker.email)} and event_id = ${sqlQuote(EVENT_ID)}`,
);
psql(
`update auth.users set encrypted_password = extensions.crypt(${sqlQuote(ID.speaker.qrToken)}, extensions.gen_salt('bf'))
where email = ${sqlQuote(ID.speaker.email)}`,
);
}
/**
* Ensure the sponsor identity exists (contact + registration + auth user).
* No sponsor exists in the seed, so we create one. Idempotent.
*/
export function ensureSponsor(): void {
const { email, qrToken } = ID.sponsor;
// Auth user (QR token = password). Upsert by email so the password hash is
// always re-synced to the current QR token on every reset (idempotent).
// NOTE: GoTrue's user query fails to scan a NULL in any of the token columns
// (confirmation_token, email_change_token_new, recovery_token, email_change,
// reauthentication_token, phone_change_token) → 500 "Database error querying
// schema". So we set them all to '' (matching how seed users are stored).
psql(
`insert into auth.users (instance_id, id, aud, role, email, encrypted_password, email_confirmed_at, confirmation_token, email_change_token_new, email_change, recovery_token, reauthentication_token, phone_change_token, raw_app_meta_data, raw_user_meta_data, created_at, updated_at)
values ('00000000-0000-0000-0000-000000000000', gen_random_uuid(), 'authenticated', 'authenticated', ${sqlQuote(email)},
extensions.crypt(${sqlQuote(qrToken)}, extensions.gen_salt('bf')), now(), '', '', '', '', '', '',
'{"provider":"email","providers":["email"]}', '{"full_name":"Demo Sponsor"}', now(), now())
on conflict (email) where is_sso_user = false do update set encrypted_password = extensions.crypt(${sqlQuote(qrToken)}, extensions.gen_salt('bf')), confirmation_token = '', email_change_token_new = '', email_change = '', recovery_token = '', reauthentication_token = '', phone_change_token = '', updated_at = now()`,
);
// Contact.
psql(
`insert into public.contacts (email, full_name, linkedin_url, show_email, show_linkedin, is_admin, password)
values (${sqlQuote(email)}, 'Demo Sponsor', null, false, false, false, null)
on conflict (email) do nothing`,
);
// Registration (sponsor type).
psql(
`insert into public.registrations (event_id, contact_email, type, checked_in, points, qr_token)
values (${sqlQuote(EVENT_ID)}, ${sqlQuote(email)}, 'sponsor', false, 0, ${sqlQuote(qrToken)})
on conflict (event_id, contact_email) do update set type = 'sponsor', qr_token = ${sqlQuote(qrToken)}`,
);
}
/**
* The full reset. Sets the known baseline the tests expect:
* - ATTENDEE_NEW: not welcome-checked-in
* - ATTENDEE_RETURNING: welcome-checked-in
* - all: no session check-ins, no connections, no feedback, 0 points, profile reset
* - speaker: QR token assigned
* - sponsor: created
*/
export function resetAll(): void {
// Welcome check-in baseline.
setWelcomeCheckedIn(ID.attendeeNew.email, false);
setWelcomeCheckedIn(ID.attendeeReturning.email, true);
setWelcomeCheckedIn(ID.attendeeA.email, true);
setWelcomeCheckedIn(ID.attendeeB.email, true);
setWelcomeCheckedIn(ID.attendeeC.email, true);
setWelcomeCheckedIn(ID.attendeeD.email, true);
setWelcomeCheckedIn(ID.speaker.email, true);
setWelcomeCheckedIn(ID.sponsor.email, true);
// Clear per-contact state.
for (const c of RESET_CONTACTS) {
clearSessionCheckins(c);
clearConnections(c);
clearFeedback(c);
resetPoints(c);
resetProfile(c);
}
// Clear material on the speaker's session.
clearSessionMaterial('37ab7060-3d81-4221-9322-6971e97d1175');
// Temporary identities.
ensureSpeakerQrToken();
ensureSponsor();
}
+43
View File
@@ -0,0 +1,43 @@
import type { Page } from '@playwright/test';
/**
* The Agenda screen — the schedule (slots + sessions). Tapping a session opens
* a detail sheet with: pick/clear, the speaker material upload (for the
* session's speaker), the material download, and "Give feedback" (when the
* session is done and the user was checked in).
*/
export class AgendaPage {
constructor(
readonly page: Page,
) {}
/** Open a session's detail sheet by its title. */
async openSession(title: string): Promise<void> {
await this.page.getByRole('button', { name: title, exact: false }).first().click();
}
/** The material upload file input (visible only for the session's speaker, when pending). */
materialUploadInput(): ReturnType<Page['locator']> {
return this.page.getByTestId('material-upload');
}
/** Upload a material file (Playwright file-upload, spec §28). */
async uploadMaterial(filePath: string): Promise<void> {
await this.materialUploadInput().setInputFiles(filePath);
}
/** The "Give feedback" button (done + checked-in). */
giveFeedbackButton(): ReturnType<Page['locator']> {
return this.page.getByTestId('give-feedback');
}
/** The "You weren't checked in to this session" notice. */
notCheckedInNotice(): ReturnType<Page['locator']> {
return this.page.getByText(/You weren’t checked in to this session/);
}
/** The "📎 you" speaker tag on a session (marks the user's own session). */
speakerTag(): ReturnType<Page['locator']> {
return this.page.getByText('🎤 you').first();
}
}
+46
View File
@@ -0,0 +1,46 @@
import type { Page } from '@playwright/test';
/**
* Base page object for the authenticated Convivo app shell.
*
* The app is a single-page shell with a bottom tab bar (Home / Agenda / Scan /
* Connect / Profile) plus a full-screen Feedback takeover. This object wraps
* tab navigation and the shared "am I admitted?" checks. Keep business
* workflows in the tests themselves (spec §40).
*/
export class AppPage {
constructor(
readonly page: Page,
readonly appUrl: string,
) {}
/** Navigate to a tab by its testid suffix (home, agenda, scan, connections, profile). */
async gotoTab(tab: 'home' | 'agenda' | 'scan' | 'connections' | 'profile'): Promise<void> {
await this.page.getByTestId(`tab-${tab}`).click();
}
/** True when the user is admitted (tab bar visible). */
isAdmitted(): Promise<boolean> {
return this.page.getByTestId('tab-home').isVisible().catch(() => false);
}
/** True when the user is on the "please see a staff member" gate. */
isGated(): Promise<boolean> {
return this.page.getByTestId('checkin-required-gate').isVisible().catch(() => false);
}
/** Wait until the user is admitted (tab bar visible). */
async waitForAdmitted(): Promise<void> {
await this.page.getByTestId('tab-home').waitFor({ state: 'visible' });
}
/** Wait until the user is on the check-in-required gate. */
async waitForGated(): Promise<void> {
await this.page.getByTestId('checkin-required-gate').waitFor({ state: 'visible' });
}
/** The event name shown on Home/Agenda (to verify the Demo Event is loaded). */
eventTitle(): ReturnType<Page['locator']> {
return this.page.getByText(/Global Power Platform Bootcamp/).first();
}
}
+75
View File
@@ -0,0 +1,75 @@
import type { Page } from '@playwright/test';
/**
* The Connections screen — two tabs:
* - "My connections": established (accepted) connections.
* - "Requests": incoming (accept/decline) + outgoing (pending) requests.
*
* The three states (connected / outgoing-pending / incoming) must never be
* mixed (spec §18).
*/
export class ConnectionsPage {
constructor(
readonly page: Page,
) {}
/** Navigate to the Connections screen (bottom tab). */
async goto(): Promise<void> {
await this.page.getByTestId('tab-connections').click();
await this.page.getByTestId('connections-tab-mine').waitFor({ state: 'visible' });
}
/** Switch to the "My connections" tab. */
async gotoMine(): Promise<void> {
await this.goto();
await this.page.getByTestId('connections-tab-mine').click();
}
/** Switch to the "Requests" tab. */
async gotoRequests(): Promise<void> {
await this.goto();
await this.page.getByTestId('connections-tab-req').click();
}
/** The "Incoming" section header (present only when there are incoming requests). */
incomingHeader(): ReturnType<Page['locator']> {
return this.page.getByText('Incoming', { exact: true });
}
/** The "Sent" (outgoing) section header. */
sentHeader(): ReturnType<Page['locator']> {
return this.page.getByText('Sent', { exact: true });
}
/** Accept the (single) incoming request. */
async accept(): Promise<void> {
await this.page.getByTestId('connection-accept').click();
}
/** Decline the (single) incoming request. */
async decline(): Promise<void> {
await this.page.getByTestId('connection-decline').click();
}
/** Does the "My connections" tab list a given person's name? */
async mineContains(name: string): Promise<boolean> {
await this.gotoMine();
return (await this.page.getByText(name, { exact: true }).count()) > 0;
}
/** Does the Requests tab show an incoming request from a given person? */
async incomingContains(name: string): Promise<boolean> {
await this.gotoRequests();
const incoming = this.page.locator('text=Incoming');
if ((await incoming.count()) === 0) return false;
return (await this.page.getByText(name, { exact: true }).count()) > 0;
}
/** Does the Requests tab show an outgoing (sent) request to a given person? */
async outgoingContains(name: string): Promise<boolean> {
await this.gotoRequests();
const sent = this.page.locator('text=Sent');
if ((await sent.count()) === 0) return false;
return (await this.page.getByText(name, { exact: true }).count()) > 0;
}
}
+32
View File
@@ -0,0 +1,32 @@
import type { Page } from '@playwright/test';
/**
* The Feedback screen — a full-screen takeover to rate a session 1–5 stars and
* optionally leave a comment. Only reachable for a session the user was
* checked into (and that is over).
*/
export class FeedbackPage {
constructor(
readonly page: Page,
) {}
/** Select a star rating (1–5). */
async rate(n: number): Promise<void> {
await this.page.getByTestId(`feedback-star-${n}`).click();
}
/** Add a comment. */
async setComment(text: string): Promise<void> {
await this.page.getByTestId('feedback-comment').fill(text);
}
/** Submit the feedback. */
async submit(): Promise<void> {
await this.page.getByTestId('feedback-submit').click();
}
/** The session title shown in the feedback header. */
sessionTitle(): ReturnType<Page['locator']> {
return this.page.locator('.card .h2').first();
}
}
+27
View File
@@ -0,0 +1,27 @@
import type { Page } from '@playwright/test';
/**
* The Home screen — greeting, event name, Now/Next, the pending-material pill
* (📎, for speakers with a session missing its attachment), the pending-feedback
* pill (⭐), and quick actions.
*/
export class HomePage {
constructor(
readonly page: Page,
) {}
/** The pending-material pill (📎 N) — the red attachment indicator. */
materialPill(): ReturnType<Page['locator']> {
return this.page.getByTestId('material-pill');
}
/** The pending-feedback pill (⭐). */
feedbackPill(): ReturnType<Page['locator']> {
return this.page.getByTestId('feedback-pill');
}
/** The greeting header (e.g. "Good morning, Lena 👋"). */
greeting(): ReturnType<Page['locator']> {
return this.page.locator('.h1').first();
}
}
+54
View File
@@ -0,0 +1,54 @@
import type { Page } from '@playwright/test';
/**
* The Profile screen — self-service: LinkedIn URL + the two visibility toggles
* (Show my email / Show my LinkedIn), plus the points breakdown and logout.
*/
export class ProfilePage {
constructor(
readonly page: Page,
) {}
/** The "Show my email" checkbox (data-testid is on the input; the input is
* visually hidden, so we read state from it but click the wrapping label). */
showEmailToggle(): ReturnType<Page['locator']> {
return this.page.getByTestId('profile-show-email');
}
/** The "Show my LinkedIn" checkbox. */
showLinkedinToggle(): ReturnType<Page['locator']> {
return this.page.getByTestId('profile-show-linkedin');
}
/** The clickable label wrapping a toggle's hidden checkbox. */
private toggleLabel(input: ReturnType<Page['locator']>): ReturnType<Page['locator']> {
return input.locator('xpath=ancestor::label[1]');
}
/** Set the Show-email toggle to a value. */
async setShowEmail(value: boolean): Promise<void> {
const t = this.showEmailToggle();
if ((await t.isChecked()) !== value) await this.toggleLabel(t).click();
}
/** Set the Show-LinkedIn toggle to a value. */
async setShowLinkedin(value: boolean): Promise<void> {
const t = this.showLinkedinToggle();
if ((await t.isChecked()) !== value) await this.toggleLabel(t).click();
}
/** Set the LinkedIn URL field. */
async setLinkedinUrl(url: string): Promise<void> {
await this.page.getByTestId('profile-linkedin-url').fill(url);
}
/** Save the profile. */
async save(): Promise<void> {
await this.page.getByTestId('profile-save').click();
}
/** Log out. */
async logout(): Promise<void> {
await this.page.getByTestId('profile-logout').click();
}
}
+96
View File
@@ -0,0 +1,96 @@
import type { Page } from '@playwright/test';
/**
* The Scan screen — dual-purpose:
* - Attendee mode: scan a peer's lanyard → send a connection request.
* - Staff mode: Welcome Check-In (toggle on) or Session Check-In (toggle off,
* with a session selector).
*
* We drive the manual-code path (spec §2). The camera is not used.
*/
export class ScanPage {
constructor(
readonly page: Page,
) {}
/** Switch to staff check-in mode (staff only). The mode toggle only renders for
* staff; for a non-staff user the screen is already in attendee mode. */
async setStaffMode(): Promise<void> {
const btn = this.page.getByTestId('scan-mode-staff');
try {
await btn.waitFor({ state: 'visible', timeout: 3000 });
await btn.click();
} catch {
// Toggle not present (non-staff) — no-op.
}
}
/** Switch to attendee (connect) mode. No-op for non-staff users (the mode
* toggle only renders for staff, and they default to attendee mode). For
* staff the default mode is 'staff', so we must wait for the toggle to
* render and then click to switch to attendee mode. */
async setAttendeeMode(): Promise<void> {
const btn = this.page.getByTestId('scan-mode-attendee');
try {
await btn.waitFor({ state: 'visible', timeout: 3000 });
await btn.click();
} catch {
// Toggle not present (non-staff) — already in attendee mode.
}
}
/** The welcome/session check-in toggle (the checkbox inside the labelled control). */
private welcomeToggle(): ReturnType<Page['locator']> {
return this.page.getByTestId('welcome-checkin-toggle').locator('input');
}
/** Enable Welcome Check-In (staff). */
async setWelcomeMode(): Promise<void> {
const toggle = this.welcomeToggle();
if (!(await toggle.isChecked())) await toggle.click();
}
/** Disable Welcome Check-In → Session Check-In (staff). */
async setSessionMode(): Promise<void> {
const toggle = this.welcomeToggle();
if (await toggle.isChecked()) await toggle.click();
}
/** Select a session for Session Check-In (by option value = session id). */
async selectSession(sessionId: string): Promise<void> {
await this.page.getByTestId('session-selector').selectOption({ value: sessionId });
}
/** Provide a scanned code via the manual field and submit it. */
async scanCode(code: string): Promise<void> {
await this.page.getByTestId('scanner-manual-code').fill(code);
await this.page.getByTestId('scanner-manual-go').click();
}
/** The session check-in result sheet. */
sessionResult(): ReturnType<Page['locator']> {
return this.page.getByTestId('session-checkin-result');
}
/** The welcome check-in result sheet. */
welcomeResult(): ReturnType<Page['locator']> {
return this.page.getByTestId('welcome-checkin-result');
}
/** Dismiss the open result sheet (the "Scan next" button) so the backdrop
* no longer intercepts clicks on the mode/toggle controls. */
async dismissResult(): Promise<void> {
const btn = this.page.getByRole('button', { name: 'Scan next' });
if (await btn.isVisible().catch(() => false)) await btn.click();
}
/** The connect sheet's "Connect" button. */
connectButton(): ReturnType<Page['locator']> {
return this.page.getByTestId('connection-send');
}
/** Send a connection request (attendee mode, after scanning a peer). */
async sendConnection(): Promise<void> {
await this.connectButton().click();
}
}
+50
View File
@@ -0,0 +1,50 @@
import { test, expect } from './base';
import { APP_URL, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { AppPage } from '../src/pages/AppPage';
/**
* §12 Attendee Core Navigation — CONV-ATT-UI-001.
*
* A successfully admitted attendee can access Home, Agenda, Connections and
* Profile. The application must remain associated with the Demo Event, display
* the demo timetable, navigate successfully between areas, not produce frontend
* errors, and not lose authenticated state during normal navigation.
*/
test('CONV-ATT-UI-001 an admitted attendee can navigate all areas without errors', async ({ page }) => {
const app = new AppPage(page, APP_URL);
// Collect console + page errors for the report.
const errors: string[] = [];
page.on('console', (m) => m.type() === 'error' && errors.push(m.text()));
page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));
// ATTENDEE_A is a normal attendee (welcome-checked-in at reset).
await login(page, APP_URL, ID.attendeeA);
await app.waitForAdmitted();
// Home — the app is associated with the Demo Event.
await app.gotoTab('home');
await expect(app.eventTitle()).toBeVisible();
// Agenda — the demo timetable renders.
await app.gotoTab('agenda');
await expect(app.eventTitle()).toBeVisible();
await expect(page.getByText(/slots/)).toBeVisible();
// Connections — the area renders (My connections tab present).
await app.gotoTab('connections');
await expect(page.getByTestId('connections-tab-mine')).toBeVisible();
// Profile — the area renders (save control present).
await app.gotoTab('profile');
await expect(page.getByTestId('profile-save')).toBeVisible();
// Authenticated state is not lost during navigation: the tab bar (admitted)
// is still present and the user is not re-gated.
await expect(page.getByTestId('tab-home')).toBeVisible();
expect(await app.isGated()).toBe(false);
// No frontend errors were produced during navigation.
expect(errors, `Uncaught frontend errors: ${errors.join(' | ')}`).toEqual([]);
});
+27
View File
@@ -0,0 +1,27 @@
import { test as base, expect } from '@playwright/test';
import { resetAll } from '../src/helpers/reset';
/**
* Shared fixture: resets the demo rows the suite touches before every test, so
* tests are self-contained and execution order never matters (spec §3).
*
* Multi-user tests use the built-in `browser` fixture to create isolated
* `BrowserContext`s (one per user) so real-time behaviour is observed naturally
* (spec §2, §40).
*/
type Fixtures = {
/** Auto: reset state before the test. */
reset: void;
};
export const test = base.extend<Fixtures>({
reset: [
async ({}, use) => {
resetAll();
await use();
},
{ auto: true },
],
});
export { expect };
+121
View File
@@ -0,0 +1,121 @@
import { test, expect } from './base';
import { APP_URL, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { db } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
/**
* §8 Staff Welcome Check-In, §9 First-Time Attendee Access, §10 Real-Time
* Welcome Check-In Activation.
*/
test.describe('Welcome Check-In + attendee access', () => {
test('CONV-CHECKIN-001 welcome check-in via QR (manual code) persists state', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
// Staff mode + Welcome Check-In.
await app.gotoTab('scan');
await scan.setStaffMode();
await scan.setWelcomeMode();
// Scan ATTENDEE_NEW (manual code = the QR payload).
await scan.scanCode(ID.attendeeNew.qrToken);
await expect(scan.welcomeResult()).toBeVisible();
// Backend state is persisted: ATTENDEE_NEW is now welcome-checked-in.
expect(await db.waitForWelcomeCheckedIn(ID.attendeeNew.email)).toBe(true);
});
test('CONV-CHECKIN-002 welcome check-in via manual code is equivalent to QR', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
await app.gotoTab('scan');
await scan.setStaffMode();
await scan.setWelcomeMode();
// Manual code input (the same token the QR would carry).
await scan.scanCode(ID.attendeeNew.qrToken);
await expect(scan.welcomeResult()).toBeVisible();
// Equivalent backend state: welcome-checked-in, no session check-in created.
expect(await db.waitForWelcomeCheckedIn(ID.attendeeNew.email)).toBe(true);
// Give the commit a moment, then confirm no session check-in was created.
await new Promise((r) => setTimeout(r, 300));
expect(db.sessionCheckins(ID.attendeeNew.email)).toEqual([]);
});
test('CONV-ATT-AUTH-001 first-time attendee is gated before welcome check-in', async ({ page }) => {
const app = new AppPage(page, APP_URL);
// ATTENDEE_NEW (never checked in) logs in.
await login(page, APP_URL, ID.attendeeNew);
// The gate is shown; normal functionality is unavailable.
await app.waitForGated();
await expect(page.getByText(/Please see a staff member/)).toBeVisible();
await expect(page.getByTestId('tab-home')).toHaveCount(0);
});
test('CONV-ATT-AUTH-002 attendee activates automatically after staff welcome check-in (real-time)', async ({ browser }) => {
// Two simultaneous contexts: the attendee stays open; the staff checks them in.
const attendee = await createUser(browser, 'attendeeNew');
const staff = await createUser(browser, 'staff');
try {
const aApp = new AppPage(attendee.page, APP_URL);
const sApp = new AppPage(staff.page, APP_URL);
const sScan = new ScanPage(staff.page);
// 1. The attendee logs in and is gated (waiting screen).
await login(attendee.page, APP_URL, ID.attendeeNew);
await aApp.waitForGated();
// 2. The staff (separate context) logs in and performs the welcome check-in.
await login(staff.page, APP_URL, ID.staff);
await sApp.waitForAdmitted();
await sApp.gotoTab('scan');
await sScan.setStaffMode();
await sScan.setWelcomeMode();
await sScan.scanCode(ID.attendeeNew.qrToken);
await expect(sScan.welcomeResult()).toBeVisible();
// 3. The attendee's open browser lifts the gate automatically (4s poll) —
// no refresh, no restart, no re-login.
await aApp.waitForAdmitted();
await expect(await aApp.isGated()).toBe(false);
// Home/application content becomes available.
await expect(attendee.page.getByTestId('tab-home')).toBeVisible();
} finally {
await attendee.close();
await staff.close();
}
});
test('CONV-ATT-AUTH-003 returning attendee is not re-gated on re-login', async ({ page }) => {
const app = new AppPage(page, APP_URL);
// ATTENDEE_RETURNING (previously checked in) logs in → admitted directly.
await login(page, APP_URL, ID.attendeeReturning);
await app.waitForAdmitted();
await expect(await app.isGated()).toBe(false);
// Log out, then log in again → still admitted (no staff intervention).
await app.gotoTab('profile');
await page.getByTestId('profile-logout').click();
await page.getByTestId('login-splash').waitFor({ state: 'visible' });
await login(page, APP_URL, ID.attendeeReturning);
await app.waitForAdmitted();
await expect(await app.isGated()).toBe(false);
await expect(page.getByText(/Please see a staff member/)).toHaveCount(0);
});
});
+372
View File
@@ -0,0 +1,372 @@
import { test, expect } from './base';
import { APP_URL, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { signInJwt, userRpc } from '../src/helpers/api';
import { db, psql, sqlQuote } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
import { ConnectionsPage } from '../src/pages/ConnectionsPage';
/**
* §13–§20 Connections.
*
* The connection flow: a user scans a peer's lanyard (manual code = the QR
* payload) → the connect sheet → "Connect" → `create_connection_request`. The
* recipient sees it under Requests → Incoming and Accepts/Declines.
*/
test.describe('Connections', () => {
test('CONV-CONN-001 connection request by scanning a peer (QR)', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
const conns = new ConnectionsPage(page);
await login(page, APP_URL, ID.attendeeA);
await app.waitForAdmitted();
// Scan ATTENDEE_B's lanyard (manual code = the QR payload) and request.
await app.gotoTab('scan');
await scan.setAttendeeMode();
await scan.scanCode(ID.attendeeB.qrToken);
await scan.sendConnection();
// A sees B as a pending (outgoing) request.
await conns.gotoRequests();
expect(await conns.outgoingContains('Jonas Unger')).toBe(true);
// B must NOT yet appear as an established connection.
await conns.gotoMine();
expect(await conns.mineContains('Jonas Unger')).toBe(false);
// Backend: a pending connection row exists (A → B).
const rows = db.connections(ID.attendeeA.email);
expect(rows.some((r) => r.status === 'pending' && r.to === ID.attendeeB.email)).toBe(true);
});
test('CONV-CONN-002 connection request by manual code is equivalent to QR', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
const conns = new ConnectionsPage(page);
await login(page, APP_URL, ID.attendeeA);
await app.waitForAdmitted();
await app.gotoTab('scan');
await scan.setAttendeeMode();
// Manual code input (the same token the QR would carry).
await scan.scanCode(ID.attendeeB.qrToken);
await scan.sendConnection();
// Pending state behaves exactly as with QR scanning.
await conns.gotoRequests();
expect(await conns.outgoingContains('Jonas Unger')).toBe(true);
await conns.gotoMine();
expect(await conns.mineContains('Jonas Unger')).toBe(false);
// Backend: pending A → B.
const rows = db.connections(ID.attendeeA.email);
expect(rows.some((r) => r.status === 'pending' && r.to === ID.attendeeB.email)).toBe(true);
});
test('CONV-CONN-003 recipient sees the incoming request with Accept/Decline', async ({ browser }) => {
const a = await createUser(browser, 'attendeeA');
const b = await createUser(browser, 'attendeeB');
try {
const aApp = new AppPage(a.page, APP_URL);
const aScan = new ScanPage(a.page);
const bApp = new AppPage(b.page, APP_URL);
const bConns = new ConnectionsPage(b.page);
// A sends a request to B.
await login(a.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('scan');
await aScan.setAttendeeMode();
await aScan.scanCode(ID.attendeeB.qrToken);
await aScan.sendConnection();
// B sees A as an incoming request with Accept + Decline actions.
await login(b.page, APP_URL, ID.attendeeB);
await bApp.waitForAdmitted();
await bConns.gotoRequests();
await expect(b.page.getByText('Mia Moser', { exact: true })).toBeVisible();
await expect(b.page.getByTestId('connection-accept')).toBeVisible();
await expect(b.page.getByTestId('connection-decline')).toBeVisible();
// A still sees the request as pending (outgoing) until B responds.
const aConns = new ConnectionsPage(a.page);
await aConns.gotoRequests();
expect(await aConns.outgoingContains('Jonas Unger')).toBe(true);
} finally {
await a.close();
await b.close();
}
});
test('CONV-CONN-004 recipient accepts → established connection both ways', async ({ browser }) => {
const a = await createUser(browser, 'attendeeA');
const b = await createUser(browser, 'attendeeB');
try {
const aApp = new AppPage(a.page, APP_URL);
const aScan = new ScanPage(a.page);
const aConns = new ConnectionsPage(a.page);
const bApp = new AppPage(b.page, APP_URL);
const bConns = new ConnectionsPage(b.page);
// A sends to B.
await login(a.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('scan');
await aScan.setAttendeeMode();
await aScan.scanCode(ID.attendeeB.qrToken);
await aScan.sendConnection();
// B accepts.
await login(b.page, APP_URL, ID.attendeeB);
await bApp.waitForAdmitted();
await bConns.gotoRequests();
await bConns.accept();
// Both see each other in "My connections".
await bConns.gotoMine();
expect(await bConns.mineContains('Mia Moser')).toBe(true);
await aConns.gotoMine();
expect(await aConns.mineContains('Jonas Unger')).toBe(true);
// The pending request is no longer actionable.
await bConns.gotoRequests();
expect(await bConns.incomingContains('Mia Moser')).toBe(false);
// Backend: an accepted connection row exists.
const rows = db.connections(ID.attendeeA.email);
expect(rows.some((r) => r.status === 'accepted' && r.to === ID.attendeeB.email)).toBe(true);
} finally {
await a.close();
await b.close();
}
});
test('CONV-CONN-005 recipient declines → no connection is created', async ({ browser }) => {
const a = await createUser(browser, 'attendeeA');
const b = await createUser(browser, 'attendeeB');
try {
const aApp = new AppPage(a.page, APP_URL);
const aScan = new ScanPage(a.page);
const aConns = new ConnectionsPage(a.page);
const bApp = new AppPage(b.page, APP_URL);
const bConns = new ConnectionsPage(b.page);
// A sends to B.
await login(a.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('scan');
await aScan.setAttendeeMode();
await aScan.scanCode(ID.attendeeB.qrToken);
await aScan.sendConnection();
// B declines.
await login(b.page, APP_URL, ID.attendeeB);
await bApp.waitForAdmitted();
await bConns.gotoRequests();
await bConns.decline();
// No connection is created; the request is removed from actionable incoming.
await bConns.gotoRequests();
expect(await bConns.incomingContains('Mia Moser')).toBe(false);
// A must not see B as an established connection.
await aConns.gotoMine();
expect(await aConns.mineContains('Jonas Unger')).toBe(false);
// Backend: no accepted connection row.
const rows = db.connections(ID.attendeeA.email);
expect(rows.some((r) => r.status === 'accepted')).toBe(false);
} finally {
await a.close();
await b.close();
}
});
test('CONV-CONN-006 the Connections area correctly distinguishes the three states', async ({ page }) => {
const conns = new ConnectionsPage(page);
// Set up A's three states via the backend (as the relevant users):
// A ↔ B accepted (established), A → C pending (outgoing), D → A pending (incoming).
const aJwt = await signInJwt(ID.attendeeA.email, ID.attendeeA.qrToken);
const bJwt = await signInJwt(ID.attendeeB.email, ID.attendeeB.qrToken);
const cJwt = await signInJwt(ID.attendeeC.email, ID.attendeeC.qrToken);
const dJwt = await signInJwt(ID.attendeeD.email, ID.attendeeD.qrToken);
// A → B (then B accepts).
await userRpc(aJwt, 'create_connection_request', { p_target_qr: ID.attendeeB.qrToken });
// accept_connection needs the connection id; fetch it.
const abId = psql(
`select id from public.connections where from_email = ${sqlQuote(ID.attendeeA.email)} and to_email = ${sqlQuote(ID.attendeeB.email)} limit 1`,
);
await userRpc(bJwt, 'accept_connection', { p_connection_id: abId });
// A → C (pending, outgoing).
await userRpc(aJwt, 'create_connection_request', { p_target_qr: ID.attendeeC.qrToken });
// D → A (pending, incoming to A).
await userRpc(dJwt, 'create_connection_request', { p_target_qr: ID.attendeeA.qrToken });
// Now verify the UI separates the three states for A.
await login(page, APP_URL, ID.attendeeA);
await conns.gotoMine();
// Established: B (Jonas) is in My connections.
expect(await conns.mineContains('Jonas Unger')).toBe(true);
// Outgoing + incoming are NOT in My connections.
expect(await conns.mineContains('Emma Dorfer')).toBe(false);
expect(await conns.mineContains('Paul Klein')).toBe(false);
await conns.gotoRequests();
// Outgoing (Sent): C (Emma).
expect(await conns.outgoingContains('Emma Dorfer')).toBe(true);
// Incoming: D (Paul).
expect(await conns.incomingContains('Paul Klein')).toBe(true);
// The established B is NOT in Requests.
expect(await conns.incomingContains('Jonas Unger')).toBe(false);
expect(await conns.outgoingContains('Jonas Unger')).toBe(false);
});
test('CONV-CONN-007 staff can send, receive, accept, and decline connection requests', async ({ browser }) => {
const staff = await createUser(browser, 'staff');
const mia = await createUser(browser, 'attendeeA');
const jonas = await createUser(browser, 'attendeeB');
const emma = await createUser(browser, 'attendeeC');
try {
const sApp = new AppPage(staff.page, APP_URL);
const sScan = new ScanPage(staff.page);
const sConns = new ConnectionsPage(staff.page);
const mApp = new AppPage(mia.page, APP_URL);
const mConns = new ConnectionsPage(mia.page);
const jApp = new AppPage(jonas.page, APP_URL);
const jScan = new ScanPage(jonas.page);
const eApp = new AppPage(emma.page, APP_URL);
const eScan = new ScanPage(emma.page);
// 1. Staff sends a connection request to Mia.
await login(staff.page, APP_URL, ID.staff);
await sApp.waitForAdmitted();
await sApp.gotoTab('scan');
await sScan.setAttendeeMode();
await sScan.scanCode(ID.attendeeA.qrToken);
await sScan.sendConnection();
// 2. Mia accepts.
await login(mia.page, APP_URL, ID.attendeeA);
await mApp.waitForAdmitted();
await mConns.gotoRequests();
await mConns.accept();
// 3. Verify the connection both ways.
await mConns.gotoMine();
expect(await mConns.mineContains('Jose Lago')).toBe(true);
await sConns.gotoMine();
expect(await sConns.mineContains('Mia Moser')).toBe(true);
// 4. Jonas (a different attendee) sends the staff a request; the staff accepts.
await login(jonas.page, APP_URL, ID.attendeeB);
await jApp.waitForAdmitted();
await jApp.gotoTab('scan');
await jScan.setAttendeeMode();
await jScan.scanCode(ID.staff.qrToken);
await jScan.sendConnection();
await sConns.gotoRequests();
await sConns.accept();
// 5. The staff–Jonas connection is established both ways.
await sConns.gotoMine();
expect(await sConns.mineContains('Jonas Unger')).toBe(true);
await jApp.gotoTab('connections');
const jConns = new ConnectionsPage(jonas.page);
await jConns.gotoMine();
expect(await jConns.mineContains('Jose Lago')).toBe(true);
// 6. Emma sends the staff a request; the staff declines → no connection.
await login(emma.page, APP_URL, ID.attendeeC);
await eApp.waitForAdmitted();
await eApp.gotoTab('scan');
await eScan.setAttendeeMode();
await eScan.scanCode(ID.staff.qrToken);
await eScan.sendConnection();
await sConns.gotoRequests();
await sConns.decline();
// 7. Emma is NOT in the staff's established connections.
await sConns.gotoMine();
expect(await sConns.mineContains('Emma Dorfer')).toBe(false);
} finally {
await staff.close();
await mia.close();
await jonas.close();
await emma.close();
}
});
test('CONV-CONN-008 networking works across roles (staff, attendee, speaker, sponsor)', async ({ browser }) => {
// Representative cross-role pairs covering all four roles:
// speaker → attendee, and sponsor → attendee.
// (Staff networking is covered by CONV-CONN-007.)
const spk = await createUser(browser, 'speaker');
const spo = await createUser(browser, 'sponsor');
const att = await createUser(browser, 'attendeeB');
try {
const sApp = new AppPage(spk.page, APP_URL);
const sScan = new ScanPage(spk.page);
const sConns = new ConnectionsPage(spk.page);
const oApp = new AppPage(spo.page, APP_URL);
const oScan = new ScanPage(spo.page);
const oConns = new ConnectionsPage(spo.page);
const aApp = new AppPage(att.page, APP_URL);
const aConns = new ConnectionsPage(att.page);
// Speaker sends to attendee.
await login(spk.page, APP_URL, ID.speaker);
await sApp.waitForAdmitted();
await sApp.gotoTab('scan');
await sScan.setAttendeeMode();
await sScan.scanCode(ID.attendeeB.qrToken);
await sScan.sendConnection();
// Sponsor sends to the same attendee.
await login(spo.page, APP_URL, ID.sponsor);
await oApp.waitForAdmitted();
await oApp.gotoTab('scan');
await oScan.setAttendeeMode();
await oScan.scanCode(ID.attendeeB.qrToken);
await oScan.sendConnection();
// Attendee accepts both (two incoming requests → accept one at a time).
await login(att.page, APP_URL, ID.attendeeB);
await aApp.waitForAdmitted();
await aConns.gotoRequests();
await att.page.getByTestId('connection-accept').first().click();
await aConns.gotoRequests();
await att.page.getByTestId('connection-accept').first().click();
// Both see the established connections.
await aConns.gotoMine();
expect(await aConns.mineContains('Duncan Boyne')).toBe(true);
expect(await aConns.mineContains('Demo Sponsor')).toBe(true);
// Force the speaker's + sponsor's Connections screens to re-fetch (they
// were already mounted, so navigate away + back to trigger a fresh load).
await sApp.gotoTab('home');
await sConns.gotoMine();
expect(await sConns.mineContains('Jonas Unger')).toBe(true);
await oApp.gotoTab('home');
await oConns.gotoMine();
expect(await oConns.mineContains('Jonas Unger')).toBe(true);
// Backend: accepted cross-role connections exist (speaker + sponsor).
const spkRows = db.connections(ID.speaker.email);
expect(spkRows.some((r) => r.status === 'accepted' && r.to === ID.attendeeB.email)).toBe(true);
const spoRows = db.connections(ID.sponsor.email);
expect(spoRows.some((r) => r.status === 'accepted' && r.to === ID.attendeeB.email)).toBe(true);
} finally {
await spk.close();
await spo.close();
await att.close();
}
});
});
+313
View File
@@ -0,0 +1,313 @@
import path from 'node:path';
import { test, expect } from './base';
import { APP_URL, ID, SESSION_A, SESSION_B } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { signInJwt, userRpcResult } from '../src/helpers/api';
import { db } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
import { ConnectionsPage } from '../src/pages/ConnectionsPage';
import { AgendaPage } from '../src/pages/AgendaPage';
import { HomePage } from '../src/pages/HomePage';
import { FeedbackPage } from '../src/pages/FeedbackPage';
/**
* §38 End-to-end journeys + §39 Role security matrix.
*
* CONV-E2E-001: First-time attendee complete journey (3 contexts).
* CONV-E2E-002: Speaker journey (login → pending material → upload → done).
* Role security matrix: backend authorization checks across roles.
*/
/** The speaker's session title (slot 1). */
const SPEAKER_SESSION_TITLE = 'From Vision to Reality';
/** SESSION_B title (slot 2, "now" — not done). */
const SESSION_B_TITLE = '10 Essential tips to kickstart Power Platform Governance';
/** A small, valid test file for the material upload. */
const MATERIAL_FILE = path.join(__dirname, '..', 'fixtures', 'material.txt');
/** Poll until a session has material (robust against commit timing). */
async function waitForMaterial(sessionId: string, timeoutMs = 5000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (db.sessionHasMaterial(sessionId)) return true;
if (Date.now() > deadline) return db.sessionHasMaterial(sessionId);
await new Promise((r) => setTimeout(r, 200));
}
}
test.describe('E2E Journeys', () => {
test('CONV-E2E-001 first-time attendee complete journey', async ({ browser }) => {
// Three isolated contexts: the new attendee, the staff, and a second
// attendee (ATTENDEE_B) for the connection sub-journey.
const attendee = await createUser(browser, 'attendeeNew');
const staff = await createUser(browser, 'staff');
const other = await createUser(browser, 'attendeeB');
try {
const aApp = new AppPage(attendee.page, APP_URL);
const aScan = new ScanPage(attendee.page);
const aConns = new ConnectionsPage(attendee.page);
const aAgenda = new AgendaPage(attendee.page);
const sApp = new AppPage(staff.page, APP_URL);
const sScan = new ScanPage(staff.page);
const oApp = new AppPage(other.page, APP_URL);
const oConns = new ConnectionsPage(other.page);
// 1–2. The new attendee logs in and is gated (waiting screen).
await login(attendee.page, APP_URL, ID.attendeeNew);
await aApp.waitForGated();
await expect(attendee.page.getByText(/Please see a staff member/)).toBeVisible();
await expect(attendee.page.getByTestId('tab-home')).toHaveCount(0);
// 3–6. The staff (separate context) logs in and performs the welcome check-in.
await login(staff.page, APP_URL, ID.staff);
await sApp.waitForAdmitted();
await sApp.gotoTab('scan');
await sScan.setStaffMode();
await sScan.setWelcomeMode();
await sScan.scanCode(ID.attendeeNew.qrToken);
await expect(sScan.welcomeResult()).toBeVisible();
// Backend: the attendee is now welcome-checked-in.
expect(await db.waitForWelcomeCheckedIn(ID.attendeeNew.email)).toBe(true);
// Dismiss the welcome result sheet so it doesn't intercept later clicks.
await sScan.dismissResult();
// 7. The attendee's open browser lifts the gate automatically (4s poll) —
// no refresh, no restart, no re-login.
await aApp.waitForAdmitted();
await expect(await aApp.isGated()).toBe(false);
// 8–11. The app is fully usable: Home, Agenda, Connections, Profile.
const home = new HomePage(attendee.page);
await expect(home.greeting()).toBeVisible();
await expect(attendee.page.getByTestId('tab-home')).toBeVisible();
await aApp.gotoTab('agenda');
await expect(aApp.eventTitle()).toBeVisible();
await aApp.gotoTab('connections');
await expect(attendee.page.getByTestId('connections-tab-mine')).toBeVisible();
await aApp.gotoTab('profile');
await expect(attendee.page.getByTestId('profile-save')).toBeVisible();
// 12–14. ATTENDEE_NEW scans ATTENDEE_B and sends a connection request.
await aApp.gotoTab('scan');
await aScan.setAttendeeMode();
await aScan.scanCode(ID.attendeeB.qrToken);
await aScan.sendConnection();
await aConns.gotoRequests();
expect(await aConns.outgoingContains('Jonas Unger')).toBe(true);
// 15–17. ATTENDEE_B observes the incoming request and accepts it.
await login(other.page, APP_URL, ID.attendeeB);
await oApp.waitForAdmitted();
await oConns.gotoRequests();
await oConns.accept();
// 18–19. The established connection is visible from both parties.
await oConns.gotoMine();
expect(await oConns.mineContains('Lena Huber')).toBe(true);
// Force the attendee's Connections screen to re-fetch (it was already
// mounted, so navigate away + back to trigger a fresh load).
await aApp.gotoTab('home');
await aConns.gotoMine();
expect(await aConns.mineContains('Jonas Unger')).toBe(true);
// 20–22. STAFF_01 selects SESSION_A and checks ATTENDEE_NEW into it.
await sApp.gotoTab('scan');
await sScan.setSessionMode();
await sScan.selectSession(SESSION_A);
await sScan.scanCode(ID.attendeeNew.qrToken);
await expect(sScan.sessionResult()).toBeVisible();
// Backend: SESSION_A attendance is persisted.
expect(await db.waitForSessionCheckin(ID.attendeeNew.email, SESSION_A)).toBe(true);
// 23–24. SESSION_A feedback becomes available; SESSION_B remains unavailable.
await aApp.gotoTab('agenda');
await aAgenda.openSession('From Vision to Reality');
await expect(aAgenda.giveFeedbackButton()).toBeVisible();
await attendee.page.getByRole('button', { name: '✕' }).click();
await aAgenda.openSession(SESSION_B_TITLE);
await expect(aAgenda.giveFeedbackButton()).toHaveCount(0);
await attendee.page.getByRole('button', { name: '✕' }).click();
// 25–27. Navigate away, then return: SESSION_A feedback is still available.
await aApp.gotoTab('home');
await aApp.gotoTab('agenda');
await aAgenda.openSession('From Vision to Reality');
await expect(aAgenda.giveFeedbackButton()).toBeVisible();
// 28. Submit SESSION_A feedback.
await aAgenda.giveFeedbackButton().click();
const feedback = new FeedbackPage(attendee.page);
await feedback.rate(5);
await feedback.setComment('Great journey!');
await feedback.submit();
// Backend: the feedback is persisted for (ATTENDEE_NEW, SESSION_A).
const fbRows = db.feedback(ID.attendeeNew.email);
expect(fbRows.some((r) => r.sessionId === SESSION_A)).toBe(true);
// 29–32. Logout, log in again: Welcome Check-In is not requested again,
// and normal functionality remains available.
await aApp.gotoTab('profile');
await attendee.page.getByTestId('profile-logout').click();
await attendee.page.getByTestId('login-splash').waitFor({ state: 'visible' });
await login(attendee.page, APP_URL, ID.attendeeNew);
await aApp.waitForAdmitted();
await expect(await aApp.isGated()).toBe(false);
await expect(attendee.page.getByText(/Please see a staff member/)).toHaveCount(0);
await expect(home.greeting()).toBeVisible();
} finally {
await attendee.close();
await staff.close();
await other.close();
}
});
test('CONV-E2E-002 speaker journey: login → material → networking → participant functionality', async ({ browser }) => {
// Two contexts: the speaker and an attendee (for the networking sub-journey).
const speaker = await createUser(browser, 'speaker');
const attendee = await createUser(browser, 'attendeeA');
try {
const app = new AppPage(speaker.page, APP_URL);
const scan = new ScanPage(speaker.page);
const conns = new ConnectionsPage(speaker.page);
const agenda = new AgendaPage(speaker.page);
const aApp = new AppPage(attendee.page, APP_URL);
const aConns = new ConnectionsPage(attendee.page);
// 1. The speaker logs in and is admitted.
await login(speaker.page, APP_URL, ID.speaker);
await app.waitForAdmitted();
// 2. The pending-material pill is visible (the speaker's session has no material).
const home = new HomePage(speaker.page);
await expect(home.materialPill()).toBeVisible();
// 3. Open the session in the Agenda — the upload notice is visible.
await app.gotoTab('agenda');
await agenda.openSession(SPEAKER_SESSION_TITLE);
await expect(agenda.materialUploadInput()).toBeVisible();
// 4. Upload the material.
await agenda.uploadMaterial(MATERIAL_FILE);
// 5. Backend: the session now has material.
expect(await waitForMaterial(SESSION_A)).toBe(true);
// 6. Reload so the app picks up the updated session data, then verify
// the "Download material" link is visible.
await speaker.page.reload({ waitUntil: 'domcontentloaded' });
await app.waitForAdmitted();
await app.gotoTab('agenda');
await agenda.openSession(SPEAKER_SESSION_TITLE);
await expect(speaker.page.getByText(/Download material/)).toBeVisible();
// Close the session sheet.
await speaker.page.getByRole('button', { name: '✕' }).click();
// 7. Verify normal participant functionality: Agenda + Profile.
await app.gotoTab('profile');
await expect(speaker.page.getByTestId('profile-save')).toBeVisible();
// 8. Send a connection request to an attendee (speaker networking).
await app.gotoTab('scan');
await scan.setAttendeeMode();
await scan.scanCode(ID.attendeeA.qrToken);
await scan.sendConnection();
await conns.gotoRequests();
expect(await conns.outgoingContains('Mia Moser')).toBe(true);
// 9. The attendee sees the incoming request and accepts it.
await login(attendee.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aConns.gotoRequests();
await aConns.accept();
// 10. The connection is established both ways.
await aConns.gotoMine();
expect(await aConns.mineContains('Duncan Boyne')).toBe(true);
// Force the speaker's Connections screen to re-fetch (it was already
// mounted, so navigate away + back to trigger a fresh load).
await app.gotoTab('home');
await conns.gotoMine();
expect(await conns.mineContains('Mia Moser')).toBe(true);
// 11. The speaker remains able to use all normal participant functionality.
await app.gotoTab('agenda');
await expect(app.eventTitle()).toBeVisible();
await app.gotoTab('profile');
await expect(speaker.page.getByTestId('profile-save')).toBeVisible();
} finally {
await speaker.close();
await attendee.close();
}
});
});
test.describe('Role Security Matrix (§39)', () => {
test('welcome_checkin: only staff can call (non-staff → error)', async () => {
// Staff can call welcome_checkin (takes the attendee's QR token).
const staffJwt = await signInJwt(ID.staff.email, ID.staff.password!);
const staffResult = await userRpcResult(staffJwt, 'welcome_checkin', {
p_attendee_qr: ID.attendeeNew.qrToken,
});
expect(staffResult.ok).toBe(true);
// A non-staff attendee cannot call welcome_checkin.
const attendeeJwt = await signInJwt(ID.attendeeA.email, ID.attendeeA.qrToken);
const attendeeResult = await userRpcResult(attendeeJwt, 'welcome_checkin', {
p_attendee_qr: ID.attendeeB.qrToken,
});
expect(attendeeResult.ok).toBe(false);
});
test('checkin_attendee: only staff can call (non-staff → error)', async () => {
// Staff can call checkin_attendee (session check-in; takes QR + session).
const staffJwt = await signInJwt(ID.staff.email, ID.staff.password!);
const staffResult = await userRpcResult(staffJwt, 'checkin_attendee', {
p_attendee_qr: ID.attendeeA.qrToken,
p_session_id: SESSION_A,
});
expect(staffResult.ok).toBe(true);
// A non-staff attendee cannot call checkin_attendee.
const attendeeJwt = await signInJwt(ID.attendeeB.email, ID.attendeeB.qrToken);
const attendeeResult = await userRpcResult(attendeeJwt, 'checkin_attendee', {
p_attendee_qr: ID.attendeeC.qrToken,
p_session_id: SESSION_A,
});
expect(attendeeResult.ok).toBe(false);
});
test('set_session_material: only speaker/admin can call (attendee → error)', async () => {
// The speaker can call set_session_material for their own session.
const speakerJwt = await signInJwt(ID.speaker.email, ID.speaker.qrToken);
const speakerResult = await userRpcResult(speakerJwt, 'set_session_material', {
p_session_id: SESSION_A,
p_material_path: 'sessions/test/security-matrix.txt',
});
expect(speakerResult.ok).toBe(true);
// An attendee cannot call set_session_material.
const attendeeJwt = await signInJwt(ID.attendeeA.email, ID.attendeeA.qrToken);
const attendeeResult = await userRpcResult(attendeeJwt, 'set_session_material', {
p_session_id: SESSION_A,
p_material_path: 'sessions/test/attendee-should-fail.txt',
});
expect(attendeeResult.ok).toBe(false);
});
test('submit_feedback: only for attended sessions (not checked in → error)', async () => {
// An attendee who is NOT checked in to SESSION_A cannot submit feedback.
const attendeeJwt = await signInJwt(ID.attendeeD.email, ID.attendeeD.qrToken);
const result = await userRpcResult(attendeeJwt, 'submit_feedback', {
p_session_id: SESSION_A,
p_rating: 5,
p_comment: 'Security matrix test',
});
expect(result.ok).toBe(false);
expect(result.message).toMatch(/checked in/i);
});
});
+244
View File
@@ -0,0 +1,244 @@
import { test, expect } from './base';
import { APP_URL, ID, SESSION_A, SESSION_B, EVENT_ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { signInJwt, userRpcResult } from '../src/helpers/api';
import { db, psql } from '../src/helpers/db';
import { setSessionCheckin } from '../src/helpers/reset';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
import { AgendaPage } from '../src/pages/AgendaPage';
import { HomePage } from '../src/pages/HomePage';
import { FeedbackPage } from '../src/pages/FeedbackPage';
/**
* §29 Feedback.
*
* Feedback is available only for a session that is (a) done and (b) the user
* was checked into. The `give-feedback` button in the Agenda session sheet is
* shown when `selStatus === 'done' && selCheckedIn`. The backend RPC
* `submit_feedback` raises if the caller is not checked in to the session.
*
* Points: 10 with a comment, 5 without, 0 on resubmit (updates existing row).
*
* SESSION_A — slot 1 (09:15–10:00, "done" at the simulated 10:20 clock).
* SESSION_B — slot 2 (10:15–11:00, "now" — not done).
*/
/** SESSION_A title (for opening the session sheet). */
const SESSION_A_TITLE = 'From Vision to Reality';
/** SESSION_B title (for opening the session sheet). */
const SESSION_B_TITLE = '10 Essential tips to kickstart Power Platform Governance';
/** The full feedback row for a contact + session (event_id|contact_email|session_id|rating). */
function feedbackRow(contactEmail: string, sessionId: string): string {
return psql(
`select event_id || '|' || contact_email || '|' || session_id || '|' || rating
from public.feedback where contact_email = '${contactEmail.replace(/'/g, "''")}' and session_id = '${sessionId}' limit 1`,
);
}
/** The number of feedback rows a contact has for a session. */
function feedbackRowCount(contactEmail: string, sessionId: string): number {
const n = psql(
`select count(*) from public.feedback where contact_email = '${contactEmail.replace(/'/g, "''")}' and session_id = '${sessionId}'`,
);
return Number(n);
}
test.describe('Feedback', () => {
test('CONV-FEEDBACK-001 feedback unavailable for unattended session', async ({ page }) => {
const app = new AppPage(page, APP_URL);
// ATTENDEE_A is NOT checked into SESSION_A (reset clears all check-ins).
await login(page, APP_URL, ID.attendeeA);
await app.waitForAdmitted();
// Frontend: the "Give feedback" button is absent; the "not checked in"
// notice is shown instead (SESSION_A is done but the user wasn't there).
await app.gotoTab('agenda');
const agenda = new AgendaPage(page);
await agenda.openSession(SESSION_A_TITLE);
await expect(agenda.giveFeedbackButton()).toHaveCount(0);
await expect(agenda.notCheckedInNotice()).toBeVisible();
// Backend: submit_feedback raises (the user is not checked in).
const jwt = await signInJwt(ID.attendeeA.email, ID.attendeeA.qrToken);
const result = await userRpcResult(jwt, 'submit_feedback', {
p_session_id: SESSION_A,
p_rating: 5,
p_comment: 'Great session!',
});
expect(result.ok).toBe(false);
});
test('CONV-FEEDBACK-002 session attendance unlocks feedback (staff checks in via scanner)', async ({ browser }) => {
// Two contexts: the attendee stays open; the staff checks them in via the
// scanner. The attendee app must react without logout/login.
const attendee = await createUser(browser, 'attendeeA');
const staff = await createUser(browser, 'staff');
try {
const aApp = new AppPage(attendee.page, APP_URL);
const aAgenda = new AgendaPage(attendee.page);
const sApp = new AppPage(staff.page, APP_URL);
const sScan = new ScanPage(staff.page);
// 1. Confirm feedback for SESSION_A is unavailable to ATTENDEE_A.
await login(attendee.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('agenda');
await aAgenda.openSession(SESSION_A_TITLE);
await expect(aAgenda.giveFeedbackButton()).toHaveCount(0);
// Close the session sheet (it intercepts pointer events on the tab bar).
await attendee.page.getByRole('button', { name: '✕' }).click();
await attendee.page.locator('.backdrop').waitFor({ state: 'detached', timeout: 3000 }).catch(() => {});
// 2. STAFF_01 selects SESSION_A and checks ATTENDEE_A into it (scanner).
await login(staff.page, APP_URL, ID.staff);
await sApp.waitForAdmitted();
await sApp.gotoTab('scan');
await sScan.setStaffMode();
await sScan.setSessionMode();
await sScan.selectSession(SESSION_A);
await sScan.scanCode(ID.attendeeA.qrToken);
await expect(sScan.sessionResult()).toBeVisible();
// Backend: the session check-in is persisted.
expect(await db.waitForSessionCheckin(ID.attendeeA.email, SESSION_A)).toBe(true);
// 3. The attendee app reacts without logout/login: navigating to the
// Agenda re-fetches check-ins, and SESSION_A is now eligible.
await aApp.gotoTab('home');
await aApp.gotoTab('agenda');
await aAgenda.openSession(SESSION_A_TITLE);
await expect(aAgenda.giveFeedbackButton()).toBeVisible();
// Close the session sheet (it intercepts pointer events on the tab bar).
await attendee.page.getByRole('button', { name: '✕' }).click();
await attendee.page.locator('.backdrop').waitFor({ state: 'detached', timeout: 3000 }).catch(() => {});
// The feedback-pill on Home is also visible (pending feedback for a done
// session the user attended).
await aApp.gotoTab('home');
const home = new HomePage(attendee.page);
await expect(home.feedbackPill()).toBeVisible();
} finally {
await attendee.close();
await staff.close();
}
});
test('CONV-FEEDBACK-003 feedback can be given later (persists across navigation + reload)', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const agenda = new AgendaPage(page);
// ATTENDEE_A attended SESSION_A (direct DB — check-in is a precondition).
setSessionCheckin(ID.attendeeA.email, SESSION_A, ID.staff.email);
await login(page, APP_URL, ID.attendeeA);
await app.waitForAdmitted();
// 1. Do not immediately submit: confirm eligibility, then navigate away.
await app.gotoTab('agenda');
await agenda.openSession(SESSION_A_TITLE);
await expect(agenda.giveFeedbackButton()).toBeVisible();
// Close the session sheet (it intercepts pointer events on the tab bar).
// The Sheet only closes on backdrop click (not Escape).
await page.locator('.backdrop').click({ position: { x: 10, y: 10 } });
await app.waitForAdmitted();
// 3. Return later to the feedback functionality: SESSION_A is still eligible.
await app.gotoTab('agenda');
await agenda.openSession(SESSION_A_TITLE);
await expect(agenda.giveFeedbackButton()).toBeVisible();
});
test('CONV-FEEDBACK-004 feedback is session-specific (attended A, not B)', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const agenda = new AgendaPage(page);
// ATTENDEE_A attended SESSION_A but did NOT attend SESSION_B.
setSessionCheckin(ID.attendeeA.email, SESSION_A, ID.staff.email);
await login(page, APP_URL, ID.attendeeA);
await app.waitForAdmitted();
// Feedback is available for SESSION_A (done + checked-in).
await app.gotoTab('agenda');
await agenda.openSession(SESSION_A_TITLE);
await expect(agenda.giveFeedbackButton()).toBeVisible();
// Feedback is unavailable for SESSION_B (not checked in).
await page.locator('.backdrop').click({ position: { x: 10, y: 10 } });
await agenda.openSession(SESSION_B_TITLE);
await expect(agenda.giveFeedbackButton()).toHaveCount(0);
// Backend: the per-session check is enforced — SESSION_A ok, SESSION_B not.
const jwt = await signInJwt(ID.attendeeA.email, ID.attendeeA.qrToken);
const aRes = await userRpcResult(jwt, 'submit_feedback', {
p_session_id: SESSION_A,
p_rating: 5,
p_comment: 'A',
});
const bRes = await userRpcResult(jwt, 'submit_feedback', {
p_session_id: SESSION_B,
p_rating: 5,
p_comment: 'B',
});
expect(aRes.ok).toBe(true);
expect(bRes.ok).toBe(false);
});
test('CONV-FEEDBACK-005 submit session feedback (association + duplicate prevention)', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const agenda = new AgendaPage(page);
// ATTENDEE_A attended SESSION_A.
setSessionCheckin(ID.attendeeA.email, SESSION_A, ID.staff.email);
// Capture the baseline points (should be 0 after reset).
const beforePoints = db.registration(ID.attendeeA.email)?.points ?? 0;
await login(page, APP_URL, ID.attendeeA);
await app.waitForAdmitted();
// Open the session and click "Give feedback".
await app.gotoTab('agenda');
await agenda.openSession(SESSION_A_TITLE);
await agenda.giveFeedbackButton().click();
// Complete all required fields and submit.
const feedback = new FeedbackPage(page);
await feedback.rate(5);
await feedback.setComment('Excellent session, very insightful!');
await feedback.submit();
// Backend: the feedback is associated with the correct attendee, session,
// and event.
const row = feedbackRow(ID.attendeeA.email, SESSION_A);
expect(row).toContain(`${EVENT_ID}|`);
expect(row).toContain(`|${ID.attendeeA.email}|`);
expect(row).toContain(`|${SESSION_A}|`);
// Points: 10 awarded (with a comment).
const afterPoints = db.registration(ID.attendeeA.email)?.points ?? 0;
expect(afterPoints).toBe(beforePoints + 10);
// Duplicate submission: submit again (a different rating, no comment). The
// existing row is updated in place — no second independent response is
// created, and no further points are awarded.
await app.gotoTab('agenda');
await agenda.openSession(SESSION_A_TITLE);
await agenda.giveFeedbackButton().click();
await feedback.rate(4);
await feedback.submit();
// Still exactly one feedback row for SESSION_A.
expect(feedbackRowCount(ID.attendeeA.email, SESSION_A)).toBe(1);
// The rating was updated in place (5 → 4).
expect(feedbackRow(ID.attendeeA.email, SESSION_A)).toContain(`|${SESSION_A}|4`);
// Points unchanged by the resubmit (0 earned on resubmit).
const resubmitPoints = db.registration(ID.attendeeA.email)?.points ?? 0;
expect(resubmitPoints).toBe(beforePoints + 10);
});
});
+171
View File
@@ -0,0 +1,171 @@
import { test, expect } from './base';
import { APP_URL, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { signInJwt, userRpc } from '../src/helpers/api';
import { db } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { ProfilePage } from '../src/pages/ProfilePage';
import { ConnectionsPage } from '../src/pages/ConnectionsPage';
/**
* §24–§26 Profile Email/LinkedIn visibility.
*
* Visibility is enforced by the `lanyard_lookup` / `get_public_contacts` RPCs
* (which respect the contact's show_email / show_linkedin toggles). We verify
* the persisted setting (DB) and the value another user actually sees (via the
* public RPC, which is what the app's connection detail + scan use).
*/
/** What another user sees for a contact (via the public directory RPC). */
async function publicView(viewerJwt: string, targetEmail: string) {
const rows = await userRpc<{ email: string; show_email: boolean; linkedin_url: string | null }[]>(
viewerJwt,
'get_public_contacts',
{},
);
return rows.find((r) => r.email === targetEmail) ?? null;
}
test.describe('Profile visibility', () => {
test('CONV-PROFILE-001 Show Email enabled → visible to another user', async ({ browser }) => {
const a = await createUser(browser, 'userA');
const b = await createUser(browser, 'userB');
try {
const aApp = new AppPage(a.page, APP_URL);
const aProfile = new ProfilePage(a.page);
// A enables Show Email and saves.
await login(a.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('profile');
await aProfile.setShowEmail(true);
await aProfile.save();
// The setting persists (DB).
expect(db.contact(ID.attendeeA.email)?.showEmail).toBe(true);
// B can see A's email (via the public RPC the app uses).
const bJwt = await signInJwt(ID.attendeeB.email, ID.attendeeB.qrToken);
const view = await publicView(bJwt, ID.attendeeA.email);
expect(view?.show_email).toBe(true);
} finally {
await a.close();
await b.close();
}
});
test('CONV-PROFILE-002 Show Email disabled → hidden from another user', async ({ browser }) => {
const a = await createUser(browser, 'userA');
const b = await createUser(browser, 'userB');
try {
const aApp = new AppPage(a.page, APP_URL);
const aProfile = new ProfilePage(a.page);
// A disables Show Email and saves.
await login(a.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('profile');
await aProfile.setShowEmail(false);
await aProfile.save();
// The setting persists (DB).
expect(db.contact(ID.attendeeA.email)?.showEmail).toBe(false);
// B cannot see A's email (the public RPC omits it).
const bJwt = await signInJwt(ID.attendeeB.email, ID.attendeeB.qrToken);
const view = await publicView(bJwt, ID.attendeeA.email);
expect(view?.show_email).toBe(false);
} finally {
await a.close();
await b.close();
}
});
test('CONV-PROFILE-003 Show LinkedIn enabled → visible to another user', async ({ browser }) => {
const a = await createUser(browser, 'userA');
const b = await createUser(browser, 'userB');
try {
const aApp = new AppPage(a.page, APP_URL);
const aProfile = new ProfilePage(a.page);
// A sets a LinkedIn URL, enables Show LinkedIn, and saves.
await login(a.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('profile');
await aProfile.setLinkedinUrl('https://linkedin.com/in/mia-moser');
await aProfile.setShowLinkedin(true);
await aProfile.save();
// The setting persists (DB).
expect(db.contact(ID.attendeeA.email)?.showLinkedin).toBe(true);
// B can see A's LinkedIn (via the public RPC).
const bJwt = await signInJwt(ID.attendeeB.email, ID.attendeeB.qrToken);
const view = await publicView(bJwt, ID.attendeeA.email);
expect(view?.linkedin_url).toBe('https://linkedin.com/in/mia-moser');
} finally {
await a.close();
await b.close();
}
});
test('CONV-PROFILE-004 Show LinkedIn disabled → hidden from another user', async ({ browser }) => {
const a = await createUser(browser, 'userA');
const b = await createUser(browser, 'userB');
try {
const aApp = new AppPage(a.page, APP_URL);
const aProfile = new ProfilePage(a.page);
// A sets a LinkedIn URL but disables Show LinkedIn, and saves.
await login(a.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aApp.gotoTab('profile');
await aProfile.setLinkedinUrl('https://linkedin.com/in/mia-moser');
await aProfile.setShowLinkedin(false);
await aProfile.save();
// The setting persists (DB).
expect(db.contact(ID.attendeeA.email)?.showLinkedin).toBe(false);
// B cannot see A's LinkedIn (the public RPC omits it).
const bJwt = await signInJwt(ID.attendeeB.email, ID.attendeeB.qrToken);
const view = await publicView(bJwt, ID.attendeeA.email);
expect(view?.linkedin_url).toBeNull();
} finally {
await a.close();
await b.close();
}
});
test('CONV-PROFILE-005 visibility settings behave consistently across roles', async ({ browser }) => {
// Representative users from each role: staff, attendee, speaker, sponsor.
const roles = [ID.staff, ID.attendeeA, ID.speaker, ID.sponsor];
const contexts = [];
for (const r of roles) contexts.push(await createUser(browser, r.label));
try {
// Each role enables Show Email and saves; the setting persists and is
// respected (visible) regardless of role.
for (let i = 0; i < roles.length; i++) {
const ctx = contexts[i];
const app = new AppPage(ctx.page, APP_URL);
const profile = new ProfilePage(ctx.page);
await login(ctx.page, APP_URL, roles[i]);
await app.waitForAdmitted();
await app.gotoTab('profile');
await profile.setShowEmail(true);
await profile.save();
expect(db.contact(roles[i].email)?.showEmail).toBe(true);
}
// A viewer (attendee B) sees each role's email as visible.
const bJwt = await signInJwt(ID.attendeeB.email, ID.attendeeB.qrToken);
for (const r of roles) {
const view = await publicView(bJwt, r.email);
expect(view?.show_email, `${r.label} show_email should be visible`).toBe(true);
}
} finally {
for (const c of contexts) await c.close();
}
});
});
+92
View File
@@ -0,0 +1,92 @@
import { test, expect } from './base';
import { APP_URL, ID, SESSION_A, SESSION_B } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { db } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
/**
* §21–§23 Session Check-In + Welcome/Session independence.
*/
test.describe('Session Check-In', () => {
test('CONV-SESSION-001 staff checks an attendee into a session (QR)', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
await app.gotoTab('scan');
await scan.setStaffMode();
await scan.setSessionMode();
// SESSION_A is explicitly selected.
await scan.selectSession(SESSION_A);
// Scan ATTENDEE_A and complete the check-in.
await scan.scanCode(ID.attendeeA.qrToken);
await expect(scan.sessionResult()).toBeVisible();
// Attendance is registered for (ATTENDEE_A, SESSION_A) and persisted.
expect(await db.waitForSessionCheckin(ID.attendeeA.email, SESSION_A)).toBe(true);
// Attendance is NOT automatically created for other sessions.
const checkins = db.sessionCheckins(ID.attendeeA.email);
expect(checkins).toContain(SESSION_A);
expect(checkins).not.toContain(SESSION_B);
});
test('CONV-SESSION-002 session check-in via manual code is equivalent to QR', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
await app.gotoTab('scan');
await scan.setStaffMode();
await scan.setSessionMode();
await scan.selectSession(SESSION_A);
// Manual code input (the same token the QR would carry).
await scan.scanCode(ID.attendeeA.qrToken);
await expect(scan.sessionResult()).toBeVisible();
// Equivalent backend state: (ATTENDEE_A, SESSION_A) checked in.
expect(await db.waitForSessionCheckin(ID.attendeeA.email, SESSION_A)).toBe(true);
});
test('CONV-SESSION-003 welcome check-in and session check-in are independent states', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
await app.gotoTab('scan');
// 1. Welcome check-in only (no session).
await scan.setWelcomeMode();
await scan.scanCode(ID.attendeeA.qrToken);
await expect(scan.welcomeResult()).toBeVisible();
expect(await db.waitForWelcomeCheckedIn(ID.attendeeA.email)).toBe(true);
// Welcome check-in must NOT create any session attendance.
await new Promise((r) => setTimeout(r, 300));
expect(db.sessionCheckins(ID.attendeeA.email)).toEqual([]);
// Dismiss the result sheet so its backdrop doesn't block the mode toggle.
await scan.dismissResult();
// 2. Now a session check-in (SESSION_A) — a distinct, session-specific state.
await scan.setSessionMode();
await scan.selectSession(SESSION_A);
await scan.scanCode(ID.attendeeA.qrToken);
await expect(scan.sessionResult()).toBeVisible();
expect(await db.waitForSessionCheckin(ID.attendeeA.email, SESSION_A)).toBe(true);
// The session check-in references a specific session (SESSION_A, not SESSION_B).
const checkins = db.sessionCheckins(ID.attendeeA.email);
expect(checkins).toContain(SESSION_A);
expect(checkins).not.toContain(SESSION_B);
});
});
+169
View File
@@ -0,0 +1,169 @@
import path from 'node:path';
import { test, expect } from './base';
import { APP_URL, ID, SPEAKER_SESSION } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { signInJwt, userRpcResult } from '../src/helpers/api';
import { db } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { AgendaPage } from '../src/pages/AgendaPage';
import { HomePage } from '../src/pages/HomePage';
/**
* §27 Speaker role + §28 Speaker session material upload.
*
* SPEAKER_01 (Duncan Boyne) is a `session_speakers` row for SESSION_A (slot 1,
* "From Vision to Reality – A Live Launch Moment"). The seed leaves the
* speaker's `qr_token` NULL (a real gap — see findings), so the reset helper
* assigns a token + re-hashes the auth password.
*
* Material upload is a two-step backend operation: a Supabase Storage write to
* the `materials` bucket (RLS: `is_speaker_or_admin()`) + the `set_session_material`
* RPC (security definer; raises unless the caller is admin or a speaker of the
* session). We verify both the UI and the backend authorization.
*/
/** The speaker's session title (slot 1). */
const SPEAKER_SESSION_TITLE = 'From Vision to Reality';
/** A small, valid test file for the material upload. */
const MATERIAL_FILE = path.join(__dirname, '..', 'fixtures', 'material.txt');
/** Poll until a session has material (robust against commit timing). */
async function waitForMaterial(sessionId: string, timeoutMs = 5000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (db.sessionHasMaterial(sessionId)) return true;
if (Date.now() > deadline) return db.sessionHasMaterial(sessionId);
await new Promise((r) => setTimeout(r, 200));
}
}
test.describe('Speaker + material upload', () => {
test('CONV-SPEAKER-001 session assignment grants the Speaker role automatically', async ({ page }) => {
const app = new AppPage(page, APP_URL);
// SPEAKER_01 is a session_speakers row for SESSION_A (slot 1).
await login(page, APP_URL, ID.speaker);
await app.waitForAdmitted();
// The registration type is 'speaker' (auto-promoted by the trigger).
expect(db.registration(ID.speaker.email)?.type).toBe('speaker');
// Speaker-specific functionality is available: the Agenda marks the session
// with the "🎤 you" speaker tag.
await app.gotoTab('agenda');
const agenda = new AgendaPage(page);
await agenda.openSession(SPEAKER_SESSION_TITLE);
await expect(agenda.speakerTag()).toBeVisible();
});
test('CONV-MATERIAL-001 speaker sees the pending material request (red attachment)', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const home = new HomePage(page);
await login(page, APP_URL, ID.speaker);
await app.waitForAdmitted();
// Home displays the pending-material area (the red 📎 attachment pill).
await expect(home.materialPill()).toBeVisible();
// The material request references the relevant session (the Agenda shows the
// upload notice for the speaker's session).
await app.gotoTab('agenda');
const agenda = new AgendaPage(page);
await agenda.openSession(SPEAKER_SESSION_TITLE);
await expect(page.getByTestId('material-upload-notice')).toBeVisible();
});
test('CONV-MATERIAL-002 speaker uploads material and it persists across reload', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const agenda = new AgendaPage(page);
await login(page, APP_URL, ID.speaker);
await app.waitForAdmitted();
const home = new HomePage(page);
// The pending-material pill count before the upload (this session is one of
// the pending ones; the speaker may have other pending sessions too).
const beforeCount = Number(((await home.materialPill().textContent()) ?? '').replace(/\D/g, ''));
await app.gotoTab('agenda');
// Open the speaker's session and upload a valid test file.
await agenda.openSession(SPEAKER_SESSION_TITLE);
await agenda.uploadMaterial(MATERIAL_FILE);
// The upload is persisted (material_path set on the session).
expect(await waitForMaterial(SPEAKER_SESSION)).toBe(true);
// The upload state survives a reload: the session shows the material (📎) +
// a download link, and the pending-material pill no longer counts this
// session (the speaker's other session may still be pending, so the pill
// count decreases rather than reaching 0).
await page.reload();
await app.waitForAdmitted();
const afterCount = Number(((await home.materialPill().textContent()) ?? '').replace(/\D/g, ''));
expect(afterCount).toBe(beforeCount - 1);
await app.gotoTab('agenda');
await agenda.openSession(SPEAKER_SESSION_TITLE);
await expect(page.getByText(/Download material/)).toBeVisible();
});
test('CONV-MATERIAL-003 material upload is available whenever it is still relevant', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const agenda = new AgendaPage(page);
// The speaker's session (slot 1) is a "done" slot at the simulated clock,
// but the upload control is not time-gated (selNeedsMaterial has no time
// check) — it is available as long as the session is the user's and has no
// material yet.
await login(page, APP_URL, ID.speaker);
await app.waitForAdmitted();
await app.gotoTab('agenda');
await agenda.openSession(SPEAKER_SESSION_TITLE);
// The upload control is present (the session is the speaker's + no material).
await expect(agenda.materialUploadInput()).toBeVisible();
// The upload notice is shown (non-dismissible until uploaded).
await expect(page.getByTestId('material-upload-notice')).toBeVisible();
});
test('CONV-MATERIAL-004 material upload authorization (backend + frontend)', async ({ browser }) => {
// Authorized: the speaker can upload (storage write allowed for speakers).
const spk = await createUser(browser, 'speaker');
// Unauthorized: a plain attendee (no session/material assignment).
const att = await createUser(browser, 'attendeeA');
try {
// Backend: the speaker's JWT can call set_session_material.
const spkJwt = await signInJwt(ID.speaker.email, ID.speaker.qrToken);
const spkRes = await userRpcResult(spkJwt, 'set_session_material', {
p_session_id: SPEAKER_SESSION,
p_material_path: 'sessions/test/speaker.txt',
});
expect(spkRes.ok, `speaker set_session_material should succeed: ${spkRes.message}`).toBe(true);
// Backend: a plain attendee's JWT is rejected (not a speaker/admin).
const attJwt = await signInJwt(ID.attendeeA.email, ID.attendeeA.qrToken);
const attRes = await userRpcResult(attJwt, 'set_session_material', {
p_session_id: SPEAKER_SESSION,
p_material_path: 'sessions/test/attendee.txt',
});
expect(attRes.ok, `attendee set_session_material should be rejected`).toBe(false);
// Frontend: the plain attendee does not see the material upload control.
await login(att.page, APP_URL, ID.attendeeA);
const app = new AppPage(att.page, APP_URL);
await app.waitForAdmitted();
await app.gotoTab('agenda');
const agenda = new AgendaPage(att.page);
await agenda.openSession(SPEAKER_SESSION_TITLE);
await expect(att.page.getByTestId('material-upload')).toHaveCount(0);
} finally {
await spk.close();
await att.close();
}
});
});
+127
View File
@@ -0,0 +1,127 @@
import { test, expect } from './base';
import { APP_URL, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { createUser } from '../src/helpers/multi';
import { signInJwt, userRpc, userRpcResult } from '../src/helpers/api';
import { db } from '../src/helpers/db';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
import { ConnectionsPage } from '../src/pages/ConnectionsPage';
import { ProfilePage } from '../src/pages/ProfilePage';
import { HomePage } from '../src/pages/HomePage';
/**
* CONV-SPONSOR-001 — validate a Sponsor account.
*
* A sponsor can log in via the normal participant flow and use the app like any
* non-staff participant (Home, Agenda, Connections, Profile, connection
* requests, Show Email / Show LinkedIn). A sponsor must NOT automatically
* receive Staff privileges: it cannot perform Welcome Check-In or Session
* Check-In (enforced by the backend, not just the UI).
*/
/** What another user sees for a contact (via the public directory RPC). */
async function publicView(viewerJwt: string, targetEmail: string) {
const rows = await userRpc<{ email: string; show_email: boolean; linkedin_url: string | null }[]>(
viewerJwt,
'get_public_contacts',
{},
);
return rows.find((r) => r.email === targetEmail) ?? null;
}
test.describe('CONV-SPONSOR-001 — sponsor functionality', () => {
test('sponsor can use the app like a participant (Home, Agenda, Connections, Profile, privacy)', async ({ browser }) => {
const sponsor = await createUser(browser, 'sponsor');
const attendee = await createUser(browser, 'attendeeA');
try {
const sApp = new AppPage(sponsor.page, APP_URL);
const sScan = new ScanPage(sponsor.page);
const sConns = new ConnectionsPage(sponsor.page);
const sProfile = new ProfilePage(sponsor.page);
const aApp = new AppPage(attendee.page, APP_URL);
const aConns = new ConnectionsPage(attendee.page);
// 1. Log in via the normal participant flow (QR + ticket email).
await login(sponsor.page, APP_URL, ID.sponsor);
await sApp.waitForAdmitted();
// Backend: registration type is 'sponsor' (NOT staff) and checked in.
expect(db.registration(ID.sponsor.email)?.type).toBe('sponsor');
expect(db.registration(ID.sponsor.email)?.checkedIn).toBe(true);
// 2. Access Home (greeting renders).
const home = new HomePage(sponsor.page);
await expect(home.greeting()).toBeVisible();
// 3. Access Agenda (the demo timetable renders).
await sApp.gotoTab('agenda');
await expect(sApp.eventTitle()).toBeVisible();
await expect(sponsor.page.getByText(/slots/)).toBeVisible();
// 4. Access Profile (save control present).
await sApp.gotoTab('profile');
await expect(sponsor.page.getByTestId('profile-save')).toBeVisible();
// 5. Send a connection request to an attendee (sponsor networking).
await sApp.gotoTab('scan');
await sScan.setAttendeeMode();
await sScan.scanCode(ID.attendeeA.qrToken);
await sScan.sendConnection();
await sConns.gotoRequests();
expect(await sConns.outgoingContains('Mia Moser')).toBe(true);
// 6. The attendee sees the incoming request and accepts it.
await login(attendee.page, APP_URL, ID.attendeeA);
await aApp.waitForAdmitted();
await aConns.gotoRequests();
await aConns.accept();
// 7. The connection is established both ways.
await aConns.gotoMine();
expect(await aConns.mineContains('Demo Sponsor')).toBe(true);
// Force the sponsor's Connections screen to re-fetch (it was already
// mounted from step 5, so navigate away + back to trigger a fresh load).
await sApp.gotoTab('home');
await sConns.gotoMine();
expect(await sConns.mineContains('Mia Moser')).toBe(true);
// 8. Use Show Email + Show LinkedIn (privacy controls work for sponsors).
await sApp.gotoTab('profile');
await sProfile.setShowEmail(true);
await sProfile.setLinkedinUrl('https://linkedin.com/in/demo-sponsor');
await sProfile.setShowLinkedin(true);
await sProfile.save();
// The settings persist (DB).
expect(db.contact(ID.sponsor.email)?.showEmail).toBe(true);
expect(db.contact(ID.sponsor.email)?.showLinkedin).toBe(true);
// The attendee can see the sponsor's email + LinkedIn (via the public RPC).
const aJwt = await signInJwt(ID.attendeeA.email, ID.attendeeA.qrToken);
const view = await publicView(aJwt, ID.sponsor.email);
expect(view?.show_email).toBe(true);
expect(view?.linkedin_url).toBe('https://linkedin.com/in/demo-sponsor');
} finally {
await sponsor.close();
await attendee.close();
}
});
test('sponsor does not receive staff privileges (cannot perform check-ins)', async () => {
// Backend: a sponsor's JWT cannot call welcome_checkin (staff only).
const sponsorJwt = await signInJwt(ID.sponsor.email, ID.sponsor.qrToken);
const welcomeRes = await userRpcResult(sponsorJwt, 'welcome_checkin', {
p_attendee_qr: ID.attendeeNew.qrToken,
});
expect(welcomeRes.ok).toBe(false);
// Backend: a sponsor's JWT cannot call checkin_attendee (staff only).
const checkinRes = await userRpcResult(sponsorJwt, 'checkin_attendee', {
p_attendee_qr: ID.attendeeA.qrToken,
p_session_id: '37ab7060-3d81-4221-9322-6971e97d1175',
});
expect(checkinRes.ok).toBe(false);
// The registration type is 'sponsor', not 'staff' (no role elevation).
expect(db.registration(ID.sponsor.email)?.type).toBe('sponsor');
});
});
+119
View File
@@ -0,0 +1,119 @@
import { test, expect } from './base';
import { APP_URL, ID } from '../src/helpers/config';
import { toScanStep } from '../src/helpers/auth';
import { signInJwt } from '../src/helpers/api';
import { AppPage } from '../src/pages/AppPage';
/**
* §6 Staff Authentication.
*
* In this app the staff identity is provided via the lanyard QR (which resolves
* to the staff contact — i.e. the staff's email), and the staff password is
* always required. CONV-STAFF-AUTH-001 ("email + password") and -002 ("QR +
* password") therefore both exercise the same QR→identity + password flow; the
* QR is what carries the identity (the staff's email).
*/
test.describe('CONV-STAFF-AUTH', () => {
test('CONV-STAFF-AUTH-001 staff login (identity + password) succeeds and loads the demo event', async ({ page }) => {
const app = new AppPage(page, APP_URL);
await toScanStep(page, APP_URL);
// Provide the staff identity (QR) + the correct staff password.
await page.getByTestId('scanner-manual-code').fill(ID.staff.qrToken);
await page.getByTestId('scanner-manual-go').click();
await page.getByTestId('staff-login-password').fill(ID.staff.password!);
await page.getByTestId('login-confirm').click();
// Admitted: the tab bar is visible and the staff is recognized.
await app.waitForAdmitted();
await expect(await app.isGated()).toBe(false);
// Staff functionality is available: the Scan screen offers the Staff mode.
await app.gotoTab('scan');
await expect(page.getByTestId('scan-mode-staff')).toBeVisible();
// The Demo Event + timetable load.
await app.gotoTab('agenda');
await expect(app.eventTitle()).toBeVisible();
await expect(page.getByText(/slots/)).toBeVisible();
// No authentication error remains visible.
await expect(page.getByTestId('login-error')).toHaveCount(0);
});
test('CONV-STAFF-AUTH-002 staff login via QR + password succeeds', async ({ page }) => {
const app = new AppPage(page, APP_URL);
await toScanStep(page, APP_URL);
// The QR resolves to the staff (the confirm screen shows "Staff sign in").
await page.getByTestId('scanner-manual-code').fill(ID.staff.qrToken);
await page.getByTestId('scanner-manual-go').click();
await expect(page.getByTestId('staff-login-password')).toBeVisible();
// The password is mandatory and, once provided, authentication succeeds.
await page.getByTestId('staff-login-password').fill(ID.staff.password!);
await page.getByTestId('login-confirm').click();
await app.waitForAdmitted();
// Demo event + timetable load.
await app.gotoTab('agenda');
await expect(app.eventTitle()).toBeVisible();
});
test('CONV-STAFF-AUTH-003 QR alone does not authenticate staff (password mandatory)', async ({ page }) => {
await toScanStep(page, APP_URL);
// Provide the QR but no password.
await page.getByTestId('scanner-manual-code').fill(ID.staff.qrToken);
await page.getByTestId('scanner-manual-go').click();
await page.getByTestId('staff-login-password').waitFor({ state: 'visible' });
// The confirm control is disabled without a password → cannot continue.
await expect(page.getByTestId('login-confirm')).toBeDisabled();
// Backend: the QR token is NOT the staff's auth password.
const res = await signInJwt(ID.staff.email, ID.staff.qrToken).then(
() => 'ok',
() => 'rejected',
);
expect(res).toBe('rejected');
});
test('CONV-STAFF-AUTH-004 identity (email) alone does not authenticate staff', async ({ page }) => {
await toScanStep(page, APP_URL);
// Provide the identity (QR → staff email) but no password.
await page.getByTestId('scanner-manual-code').fill(ID.staff.qrToken);
await page.getByTestId('scanner-manual-go').click();
await page.getByTestId('staff-login-password').waitFor({ state: 'visible' });
await expect(page.getByTestId('login-confirm')).toBeDisabled();
// Backend: the staff email with an empty password does not authenticate.
const res = await signInJwt(ID.staff.email, '').then(
() => 'ok',
() => 'rejected',
);
expect(res).toBe('rejected');
});
test('CONV-STAFF-AUTH-005 incorrect staff password is rejected (email + QR variants)', async ({ page }) => {
// Variant A: identity + wrong password.
await toScanStep(page, APP_URL);
await page.getByTestId('scanner-manual-code').fill(ID.staff.qrToken);
await page.getByTestId('scanner-manual-go').click();
await page.getByTestId('staff-login-password').fill('wrong-password-xyz');
await page.getByTestId('login-confirm').click();
// A suitable authentication error is displayed and no session is created.
await expect(page.getByTestId('login-error')).toBeVisible();
await expect(page.getByTestId('tab-home')).toHaveCount(0);
// Variant B: QR + wrong password (backend).
const res = await signInJwt(ID.staff.email, 'wrong-password-xyz').then(
() => 'ok',
() => 'rejected',
);
expect(res).toBe('rejected');
});
});
+56
View File
@@ -0,0 +1,56 @@
import { test, expect } from './base';
import { APP_URL, ID } from '../src/helpers/config';
import { login } from '../src/helpers/auth';
import { AppPage } from '../src/pages/AppPage';
import { ScanPage } from '../src/pages/ScanPage';
/**
* §7 Staff Frontend — CONV-STAFF-UI-001.
*
* After a successful staff login, verify the staff can see and use the
* appropriate application areas and that no major component fails to render.
*/
test('CONV-STAFF-UI-001 staff frontend renders all areas without errors', async ({ page }) => {
const app = new AppPage(page, APP_URL);
const scan = new ScanPage(page);
// Collect console errors + failed requests for the report.
const errors: string[] = [];
page.on('console', (m) => m.type() === 'error' && errors.push(m.text()));
page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));
await login(page, APP_URL, ID.staff);
await app.waitForAdmitted();
// Demo Event information + timetable.
await app.gotoTab('agenda');
await expect(app.eventTitle()).toBeVisible();
await expect(page.getByText(/slots/)).toBeVisible();
// Session information (a session detail sheet opens).
await page.getByRole('button', { name: /From Vision to Reality/ }).first().click();
await expect(page.locator('.sheet')).toBeVisible();
await page.getByRole('button', { name: '✕' }).click();
// Scanner + manual code input.
await app.gotoTab('scan');
await expect(page.getByTestId('scanner-manual-code')).toBeVisible();
await expect(page.getByTestId('scanner-manual-go')).toBeVisible();
// Welcome Check-In + Session Check-In functionality (staff mode + toggle + session selector).
await scan.setStaffMode();
await expect(page.getByTestId('welcome-checkin-toggle')).toBeVisible();
await scan.setSessionMode();
await expect(page.getByTestId('session-selector')).toBeVisible();
// Normal Connections functionality.
await app.gotoTab('connections');
await expect(page.getByTestId('connections-tab-mine')).toBeVisible();
// Profile.
await app.gotoTab('profile');
await expect(page.getByTestId('profile-save')).toBeVisible();
// No uncaught errors.
expect(errors, `Uncaught frontend errors: ${errors.join(' | ')}`).toEqual([]);
});
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"types": ["node"],
"noEmit": true
},
"include": ["**/*.ts"]
}
+364
View File
@@ -0,0 +1,364 @@
# Convivo Acceptance Test Cases
This document maps every case in the **Convivo Acceptance Test Specification** to its
Playwright implementation in `e2e/`, describing what each test actually validates
(steps + assertions) and its current coverage status.
- **Framework:** Playwright (v1.63.0), Chromium headless, single worker.
- **Run:** `cd e2e && npx playwright test` (full suite) · `npx playwright test <name>` (subset) · `npx playwright show-report reports/html`.
- **Result:** **46/46 passing** (3.8 min).
- **Isolation:** every test resets backend state first (`src/helpers/reset.ts`); multi-user tests use one `BrowserContext` per participant (`src/helpers/multi.ts`).
- **Validation model:** assertions read **persisted backend state** (psql helper) and/or call the RPC **as a specific user's JWT** — not just UI toasts.
**Coverage legend:** ✅ full · ⚠️ partial · ❌ missing
---
## Standard identities (spec §4)
| Spec identity | Test identity | Email | QR token | Notes |
|---------------|---------------|-------|----------|-------|
| STAFF_01 | `ID.staff` | jose@appe.at | CVV-STF-2002 | password `appe-admin-2026` |
| ATTENDEE_NEW | `ID.attendeeNew` | lena.huber@gmail.com | CVV-ATT-1000 | reset to not-checked-in |
| ATTENDEE_RETURNING | `ID.attendeeReturning` | felix.berger@outlook.com | CVV-ATT-1001 | reset to checked-in |
| ATTENDEE_A | `ID.attendeeA` | mia.moser@proton.me | CVV-ATT-1002 | |
| ATTENDEE_B | `ID.attendeeB` | jonas.unger@web.de | CVV-ATT-1003 | |
| (extra) | `ID.attendeeC` | emma.dorfer@gmx.at | CVV-ATT-1004 | for independent tests |
| (extra) | `ID.attendeeD` | paul.klein@icloud.com | CVV-ATT-1005 | for independent tests |
| SPEAKER_01 | `ID.speaker` | duncanboyne@hotmail.co.uk | CVV-SPK-9001 | token assigned by reset (seed leaves NULL) |
| SPONSOR_01 | `ID.sponsor` | sponsor@demo.test | CVV-SPO-9001 | created by reset (none in seed) |
Sessions: `SESSION_A` (slot 1, "done", *From Vision to Reality – A Live Launch Moment*), `SESSION_B` (slot 2, "now", *10 Essential tips to kickstart Power Platform Governance*).
---
## §6 Staff Authentication — `staff-auth.spec.ts`
In this app the staff identity is carried by the lanyard QR (which resolves to the
staff contact/email); the staff password is always required. AUTH-001 ("email +
password") and AUTH-002 ("QR + password") therefore both exercise the same
QR→identity + password flow.
### CONV-STAFF-AUTH-001 — staff login (identity + password) succeeds ✅
**Test:** `CONV-STAFF-AUTH-001 staff login (identity + password) succeeds and loads the demo event`
**Validates:**
- Provide staff QR + correct password → `waitForAdmitted()`, `isGated() === false`.
- Staff functionality available: Scan screen shows `scan-mode-staff`.
- Demo Event + timetable load: `eventTitle()` visible, `/slots/` visible.
- No auth error remains: `login-error` has count 0.
### CONV-STAFF-AUTH-002 — staff login via QR + password ✅
**Test:** `CONV-STAFF-AUTH-002 staff login via QR + password succeeds`
**Validates:** QR resolves to staff (confirm screen shows `staff-login-password`); password mandatory; once provided, `waitForAdmitted()`; Demo Event + timetable load.
### CONV-STAFF-AUTH-003 — QR alone does not authenticate ✅
**Test:** `CONV-STAFF-AUTH-003 QR alone does not authenticate staff (password mandatory)`
**Validates:** QR provided, no password → `login-confirm` is **disabled** (cannot continue). Backend: `signInJwt(email, qrToken)` is **rejected** (the QR token is not the staff's auth password).
### CONV-STAFF-AUTH-004 — identity (email) alone does not authenticate ✅
**Test:** `CONV-STAFF-AUTH-004 identity (email) alone does not authenticate staff`
**Validates:** identity provided, no password → `login-confirm` disabled. Backend: `signInJwt(email, '')` rejected.
### CONV-STAFF-AUTH-005 — incorrect staff password rejected (email + QR variants) ✅
**Test:** `CONV-STAFF-AUTH-005 incorrect staff password is rejected (email + QR variants)`
**Validates:** Variant A (UI): wrong password → `login-error` visible, `tab-home` count 0 (no session). Variant B (backend): `signInJwt(email, 'wrong-password-xyz')` rejected.
---
## §7 Staff Frontend — `staff-ui.spec.ts`
### CONV-STAFF-UI-001 — staff frontend renders all areas without errors ✅
**Test:** `CONV-STAFF-UI-001 staff frontend renders all areas without errors`
**Validates** (collects console + page errors, asserts none):
- Demo Event info + timetable (`eventTitle()`, `/slots/`).
- Session information (a session detail sheet opens, then closes).
- Scanner + manual code input (`scanner-manual-code`, `scanner-manual-go`).
- Welcome Check-In + Session Check-In (staff mode, `welcome-checkin-toggle`, `session-selector`).
- Normal Connections (`connections-tab-mine`).
- Profile (`profile-save`).
- No uncaught frontend errors (`errors` array empty).
---
## §8 Staff Welcome Check-In — `checkin-attendee.spec.ts`
### CONV-CHECKIN-001 — welcome check-in via QR persists state ✅
**Test:** `CONV-CHECKIN-001 welcome check-in via QR (manual code) persists state`
**Validates:** staff mode + welcome mode → scan ATTENDEE_NEW (manual code = QR payload) → `welcomeResult()` visible → **backend** `waitForWelcomeCheckedIn(attendeeNew) === true`.
### CONV-CHECKIN-002 — welcome check-in via manual code is equivalent to QR ✅
**Test:** `CONV-CHECKIN-002 welcome check-in via manual code is equivalent to QR`
**Validates:** manual code input → `welcomeResult()` visible → backend welcome-checked-in; **no session check-in created** (`sessionCheckins` empty).
---
## §9 First-Time Attendee Access — `checkin-attendee.spec.ts`
### CONV-ATT-AUTH-001 — attendee gated before welcome check-in ✅
**Test:** `CONV-ATT-AUTH-001 first-time attendee is gated before welcome check-in`
**Validates:** ATTENDEE_NEW logs in → `waitForGated()`; "Please see a staff member" visible; `tab-home` count 0 (normal functionality unavailable).
---
## §10 Real-Time Welcome Check-In Activation — `checkin-attendee.spec.ts`
### CONV-ATT-AUTH-002 — attendee activates automatically after staff check-in ✅
**Test:** `CONV-ATT-AUTH-002 attendee activates automatically after staff welcome check-in (real-time)`
**Validates** (two simultaneous contexts — attendee stays open, no refresh/restart/re-login):
1. Attendee logs in → gated (waiting screen).
2. Staff (separate context) performs welcome check-in → `welcomeResult()` visible.
3. Attendee's open browser lifts the gate automatically (4s poll) → `waitForAdmitted()`, `isGated() === false`, `tab-home` visible.
---
## §11 Returning Attendee — `checkin-attendee.spec.ts`
### CONV-ATT-AUTH-003 — previously checked-in attendee logs in again ✅
**Test:** `CONV-ATT-AUTH-003 returning attendee is not re-gated on re-login`
**Validates:** ATTENDEE_RETURNING logs in → admitted, not gated; **logout** then **log in again** → still admitted, no "Please see a staff member" message (no staff intervention).
---
## §12 Attendee Core Navigation — `attendee-navigation.spec.ts`
### CONV-ATT-UI-001 — validate attendee navigation ✅
**Test:** `CONV-ATT-UI-001 an admitted attendee can navigate all areas without errors`
**Validates** (collects console + page errors, asserts none):
- ATTENDEE_A (admitted) navigates Home → Agenda → Connections → Profile in sequence.
- The app stays associated with the Demo Event (`eventTitle()` visible on Home + Agenda).
- The demo timetable renders (`/slots/` visible on Agenda).
- Connections + Profile areas render.
- Authenticated state is not lost (tab bar present, not re-gated).
- No frontend errors during navigation.
---
## §13–§20 Connections — `connections.spec.ts`
The connection flow: a user scans a peer's lanyard (manual code = the QR payload) → connect sheet → "Connect" → `create_connection_request`. The recipient sees it under Requests → Incoming and Accepts/Declines.
### CONV-CONN-001 — connection request by scanning a peer (QR) ✅
**Test:** `CONV-CONN-001 connection request by scanning a peer (QR)`
**Validates:** A scans B's lanyard → `sendConnection()`; A sees B as **pending (outgoing)**; B is **not** yet an established connection; **backend** a pending A→B row exists.
### CONV-CONN-002 — connection request by manual code is equivalent to QR ✅
**Test:** `CONV-CONN-002 connection request by manual code is equivalent to QR`
**Validates:** manual code input → same pending state as QR; backend pending A→B.
### CONV-CONN-003 — recipient sees the incoming request with Accept/Decline ✅
**Test:** `CONV-CONN-003 recipient sees the incoming request with Accept/Decline` (two contexts)
**Validates:** A sends to B; B sees A as incoming with `connection-accept` + `connection-decline` visible; A still sees the request as pending (outgoing) until B responds.
### CONV-CONN-004 — recipient accepts → established connection both ways ✅
**Test:** `CONV-CONN-004 recipient accepts → established connection both ways` (two contexts)
**Validates:** A sends, B accepts; both see each other in "My connections"; the pending request is no longer actionable; **backend** an accepted A→B row exists.
### CONV-CONN-005 — recipient declines → no connection is created ✅
**Test:** `CONV-CONN-005 recipient declines → no connection is created` (two contexts)
**Validates:** A sends, B declines; no connection created; request removed from actionable incoming; A does not see B as established; **backend** no accepted row.
### CONV-CONN-006 — the Connections area correctly distinguishes the three states ✅
**Test:** `CONV-CONN-006 the Connections area correctly distinguishes the three states`
**Validates** (three states set up via backend RPCs as the relevant users): A↔B accepted (established), A→C pending (outgoing), D→A pending (incoming). The UI separates them: established B in "My connections"; outgoing C + incoming D in Requests; B not in Requests.
### CONV-CONN-007 — staff can send, receive, accept, and decline connection requests ✅
**Test:** `CONV-CONN-007 staff can send, receive, accept, and decline connection requests` (four contexts)
**Validates:** staff→Mia (Mia accepts, both see it); Jonas→staff (staff accepts, both see it); Emma→staff (staff declines, Emma not established). Staff networking fully works.
### CONV-CONN-008 — networking works across roles ✅
**Test:** `CONV-CONN-008 networking works across roles (staff, attendee, speaker, sponsor)` (three contexts)
**Validates:** representative cross-role pairs covering all four roles — speaker→attendee and sponsor→attendee (staff networking is covered by CONN-007). The attendee accepts both; both parties see the established connections; **backend** accepted cross-role rows exist for both the speaker and the sponsor.
---
## §21–§23 Session Check-In — `session-checkin.spec.ts`
### CONV-SESSION-001 — staff checks an attendee into a session (QR) ✅
**Test:** `CONV-SESSION-001 staff checks an attendee into a session (QR)`
**Validates:** staff mode + session mode; **SESSION_A explicitly selected**; scan ATTENDEE_A → `sessionResult()` visible; **backend** `waitForSessionCheckin(attendeeA, SESSION_A) === true`; attendance **not** created for SESSION_B.
### CONV-SESSION-002 — session check-in via manual code is equivalent to QR ✅
**Test:** `CONV-SESSION-002 session check-in via manual code is equivalent to QR`
**Validates:** manual code input → equivalent backend state (ATTENDEE_A, SESSION_A) checked in.
### CONV-SESSION-003 — welcome check-in and session check-in are independent states ✅
**Test:** `CONV-SESSION-003 welcome check-in and session check-in are independent states`
**Validates:** (1) welcome check-in only → welcome-checked-in, **no session attendance created**; (2) then a session check-in (SESSION_A) → a distinct, session-specific state referencing SESSION_A (not SESSION_B).
---
## §24–§26 Profile Email/LinkedIn Visibility — `profile-visibility.spec.ts`
Visibility is enforced by the `lanyard_lookup` / `get_public_contacts` RPCs (which respect the contact's `show_email` / `show_linkedin` toggles). Tests verify the **persisted setting (DB)** and the **value another user actually sees** (via the public RPC the app uses).
### CONV-PROFILE-001 — Show Email enabled → visible to another user ✅
**Test:** `CONV-PROFILE-001 Show Email enabled → visible to another user` (two contexts)
**Validates:** A enables Show Email + saves; setting persists (DB `showEmail === true`); B sees A's email via the public RPC (`show_email === true`).
### CONV-PROFILE-002 — Show Email disabled → hidden from another user ✅
**Test:** `CONV-PROFILE-002 Show Email disabled → hidden from another user` (two contexts)
**Validates:** A disables Show Email + saves; persists (DB `false`); B cannot see A's email (`show_email === false`).
### CONV-PROFILE-003 — Show LinkedIn enabled → visible to another user ✅
**Test:** `CONV-PROFILE-003 Show LinkedIn enabled → visible to another user` (two contexts)
**Validates:** A sets a LinkedIn URL + enables Show LinkedIn + saves; persists (DB `true`); B sees A's LinkedIn URL via the public RPC.
### CONV-PROFILE-004 — Show LinkedIn disabled → hidden from another user ✅
**Test:** `CONV-PROFILE-004 Show LinkedIn disabled → hidden from another user` (two contexts)
**Validates:** A sets a LinkedIn URL but disables Show LinkedIn + saves; persists (DB `false`); B cannot see A's LinkedIn (`linkedin_url === null`).
### CONV-PROFILE-005 — visibility settings behave consistently across roles ✅
**Test:** `CONV-PROFILE-005 visibility settings behave consistently across roles` (four contexts: staff, attendee, speaker, sponsor)
**Validates:** each role enables Show Email + saves; the setting persists and is respected (visible) regardless of role; a viewer (attendee B) sees each role's email as visible.
---
## §27 Speaker Role Assignment — `speaker-material.spec.ts`
### CONV-SPEAKER-001 — session assignment grants the Speaker role automatically ✅
**Test:** `CONV-SPEAKER-001 session assignment grants the Speaker role automatically`
**Validates:** SPEAKER_01 (a `session_speakers` row for SESSION_A) logs in → admitted; **backend** registration type is `'speaker'` (auto-promoted by trigger); speaker-specific functionality available (Agenda marks the session with the "🎤 you" speaker tag).
---
## §28 Speaker Material Upload — `speaker-material.spec.ts`
Material upload is a two-step backend operation: a Supabase Storage write to the `materials` bucket (RLS: `is_speaker_or_admin()`) + the `set_session_material` RPC (security definer; raises unless the caller is admin or a speaker of the session).
### CONV-MATERIAL-001 — speaker sees the pending material request (red attachment) ✅
**Test:** `CONV-MATERIAL-001 speaker sees the pending material request (red attachment)`
**Validates:** Home displays the pending-material area (the red 📎 attachment pill); the material request references the relevant session (Agenda shows the upload notice for the speaker's session).
### CONV-MATERIAL-002 — speaker uploads material and it persists across reload ✅
**Test:** `CONV-MATERIAL-002 speaker uploads material and it persists across reload`
**Validates:** capture the pending-material pill count; open the session + upload a valid test file (Playwright file upload); **backend** `waitForMaterial(SESSION_A) === true`; **reload** → the session shows the material + a "Download material" link, and the pending pill count decreases by exactly 1 (the speaker may have other pending sessions).
### CONV-MATERIAL-003 — material upload is available whenever it is still relevant ✅
**Test:** `CONV-MATERIAL-003 material upload is available whenever it is still relevant`
**Validates:** the speaker's session (slot 1, "done") — the upload control is **not time-gated** (`selNeedsMaterial` has no time check); it is present as long as the session is the user's and has no material yet; the upload notice is shown (non-dismissible until uploaded).
### CONV-MATERIAL-004 — material upload authorization (backend + frontend) ✅
**Test:** `CONV-MATERIAL-004 material upload authorization (backend + frontend)` (two contexts)
**Validates:** **backend** the speaker's JWT can call `set_session_material` (ok); a plain attendee's JWT is rejected (not a speaker/admin); **frontend** the plain attendee does not see the material upload control. Being authenticated alone does not grant upload privileges.
---
## §31 Sponsor Functionality — `sponsor.spec.ts`
### CONV-SPONSOR-001 — validate a Sponsor account ✅
**Test:** `sponsor can use the app like a participant (Home, Agenda, Connections, Profile, privacy)` + `sponsor does not receive staff privileges (cannot perform check-ins)` (two tests, two contexts)
**Validates:**
- Sponsor logs in via the normal participant flow (QR + ticket email) → admitted; **backend** registration type `'sponsor'` (not staff) + checked-in.
- Access Home (greeting), Agenda (timetable), Profile (save control).
- Sends a connection request to an attendee; the attendee accepts; the connection is established both ways.
- Uses Show Email + Show LinkedIn; the settings persist (DB) and are visible to the attendee via the public RPC.
- **Negative checks (backend):** a sponsor's JWT cannot call `welcome_checkin` or `checkin_attendee` (staff only); the registration type is `'sponsor'`, not `'staff'` (no role elevation).
---
## §32–§36 Feedback — `feedback.spec.ts`
Feedback is available only for a session that is (a) done and (b) the user was checked into. The `give-feedback` button is shown when `selStatus === 'done' && selCheckedIn`. The backend RPC `submit_feedback` raises if the caller is not checked in. Points: 10 with a comment, 5 without, 0 on resubmit.
### CONV-FEEDBACK-001 — feedback unavailable for unattended session ✅
**Test:** `CONV-FEEDBACK-001 feedback unavailable for unattended session`
**Validates:** ATTENDEE_A not checked into SESSION_A → **frontend** "Give feedback" button absent + "not checked in" notice visible; **backend** `submit_feedback` raises (ok=false). Eligibility is not granted by authentication / welcome check-in / agenda visibility alone.
### CONV-FEEDBACK-002 — session attendance unlocks feedback ✅
**Test:** `CONV-FEEDBACK-002 session attendance unlocks feedback (staff checks in via scanner)` (two contexts)
**Validates:** (1) confirm feedback for SESSION_A is unavailable to ATTENDEE_A; (2) STAFF_01 selects SESSION_A and checks ATTENDEE_A in via the **scanner** → **backend** `waitForSessionCheckin` true; (3) the attendee app reacts **without logout/login** (navigating to the Agenda re-fetches check-ins) → "Give feedback" button visible; Home feedback-pill visible.
### CONV-FEEDBACK-003 — feedback can be given later ✅
**Test:** `CONV-FEEDBACK-003 feedback can be given later (persists across navigation + reload)`
**Validates:** ATTENDEE_A attended SESSION_A (direct DB — a precondition); confirm eligibility, then **navigate away**; **reload** Convivo (session restored from storage); **return later** → SESSION_A is still eligible ("Give feedback" button visible). The opportunity is persisted.
### CONV-FEEDBACK-004 — feedback is session-specific ✅
**Test:** `CONV-FEEDBACK-004 feedback is session-specific (attended A, not B)`
**Validates:** ATTENDEE_A attended SESSION_A but not SESSION_B; **frontend** "Give feedback" visible for SESSION_A, absent for SESSION_B; **backend** the per-session check is enforced — `submit_feedback` for SESSION_A ok, for SESSION_B rejected.
### CONV-FEEDBACK-005 — submit session feedback ✅
**Test:** `CONV-FEEDBACK-005 submit session feedback (association + duplicate prevention)`
**Validates:** ATTENDEE_A attended SESSION_A; capture baseline points; open session → "Give feedback" → rate 5 + comment + submit; **backend** the feedback is associated with the correct attendee, session, and event; points +10 (with a comment). **Duplicate submission:** submit again (different rating, no comment) → the existing row is updated in place (no second independent response), and no further points are awarded (0 on resubmit).
---
## §37 Mandatory End-to-End Scenario — `e2e-journeys.spec.ts`
### CONV-E2E-001 — first-time attendee complete journey ✅
**Test:** `CONV-E2E-001 first-time attendee complete journey` (three contexts: new attendee, staff, ATTENDEE_B)
**Validates** (the full 32-step journey):
- (1–2) new attendee gated ("Please see a staff member", no `tab-home`).
- (3–6) staff (separate context) performs welcome check-in → `welcomeResult()` visible; **backend** `waitForWelcomeCheckedIn` true.
- (7) attendee's open browser lifts the gate automatically (4s poll) — no refresh/restart/re-login.
- (8–11) the app is fully usable: Home, Agenda, Connections, Profile.
- (12–14) ATTENDEE_NEW scans ATTENDEE_B and sends a connection request (outgoing pending).
- (15–17) ATTENDEE_B observes the incoming request and accepts it.
- (18–19) the established connection is visible from both parties.
- (20–22) STAFF_01 selects SESSION_A and checks ATTENDEE_NEW in; **backend** `waitForSessionCheckin` true.
- (23–24) SESSION_A feedback becomes available; SESSION_B remains unavailable.
- (25–27) navigate away, then return: SESSION_A feedback is still available.
- (28) submit SESSION_A feedback; **backend** the feedback is persisted for (ATTENDEE_NEW, SESSION_A).
- (29–32) logout, log in again: Welcome Check-In is not requested again, and normal functionality remains available.
---
## §38 Mandatory Speaker End-to-End Scenario — `e2e-journeys.spec.ts`
### CONV-E2E-002 — speaker journey ✅
**Test:** `CONV-E2E-002 speaker journey: login → material → networking → participant functionality` (two contexts: speaker, attendee)
**Validates:** (1) speaker logs in + admitted; (2) pending-material pill visible; (3) open the session in the Agenda — upload notice + upload input visible; (4) upload the material; **backend** `waitForMaterial(SESSION_A)` true; (5) reload → "Download material" link visible; (6) verify normal participant functionality (Agenda + Profile); (7) send a connection request to an attendee (speaker networking); (8) the attendee accepts; (9) the connection is established both ways; (10) the speaker remains able to use all normal participant functionality (Agenda + Profile).
---
## §39 Role Security Matrix — `e2e-journeys.spec.ts`
Backend authorization checks across roles (each RPC called **as** a specific user's JWT to prove the backend enforces the rule, not just the frontend).
### welcome_checkin: only staff can call ✅
**Test:** `welcome_checkin: only staff can call (non-staff → error)`
**Validates:** staff JWT → `welcome_checkin` ok; a non-staff attendee JWT → rejected.
### checkin_attendee: only staff can call ✅
**Test:** `checkin_attendee: only staff can call (non-staff → error)`
**Validates:** staff JWT → `checkin_attendee` (QR + session) ok; a non-staff attendee JWT → rejected.
### set_session_material: only speaker/admin can call ✅
**Test:** `set_session_material: only speaker/admin can call (attendee → error)`
**Validates:** speaker JWT → `set_session_material` for their own session ok; an attendee JWT → rejected.
### submit_feedback: only for attended sessions ✅
**Test:** `submit_feedback: only for attended sessions (not checked in → error)`
**Validates:** an attendee **not** checked in to SESSION_A → `submit_feedback` rejected (message matches `/checked in/i`).
---
## Coverage Summary
| Spec section | Cases | Status |
|--------------|-------|--------|
| §6 Staff Authentication | STAFF-AUTH-001..005 | ✅ 5/5 |
| §7 Staff Frontend | STAFF-UI-001 | ✅ 1/1 |
| §8 Staff Welcome Check-In | CHECKIN-001..002 | ✅ 2/2 |
| §9 First-Time Attendee Access | ATT-AUTH-001 | ✅ 1/1 |
| §10 Real-Time Activation | ATT-AUTH-002 | ✅ 1/1 |
| §11 Returning Attendee | ATT-AUTH-003 | ✅ 1/1 |
| §12 Attendee Core Navigation | ATT-UI-001 | ✅ 1/1 |
| §13–§20 Connections | CONN-001..008 | ✅ 8/8 |
| §21–§23 Session Check-In | SESSION-001..003 | ✅ 3/3 |
| §24–§26 Profile Visibility | PROFILE-001..005 | ✅ 5/5 |
| §27 Speaker Role | SPEAKER-001 | ✅ 1/1 |
| §28 Material Upload | MATERIAL-001..004 | ✅ 4/4 |
| §31 Sponsor | SPONSOR-001 | ✅ 2/2 (capabilities + negative) |
| §32–§36 Feedback | FEEDBACK-001..005 | ✅ 5/5 |
| §37 E2E Attendee Journey | E2E-001 | ✅ full 32-step journey |
| §38 E2E Speaker Journey | E2E-002 | ✅ full journey + networking |
| §39 Role Security Matrix | 4 checks | ✅ 4/4 |
**Totals:** 46 tests, all passing (3.8 min). Every spec case is now fully validated with backend assertions. The previously partial/missing cases have been closed:
1. **CONV-E2E-001** — extended to the full 32-step journey (connection sub-journey, session-check-in + feedback sub-journey, logout/re-login).
2. **CONV-SPONSOR-001** — now covers capabilities (Home/Agenda/Connections/Profile, connection requests, Show Email/LinkedIn) + negative checks (no staff privileges).
3. **CONV-ATT-UI-001** — dedicated navigation test added.
4. **CONV-E2E-002** — now covers Connections/Profile + the speaker networking sub-journey.
5. **Feedback sub-cases** — §33 (two-context staff-scan flow), §34 (given later across reload), §35 (per-session contrast), §36 (association + duplicate prevention).
6. **CONV-CONN-008** — now covers all four roles (speaker + sponsor → attendee).