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.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
committed 2026-09-09 10:13:26 +02:00
1 parent b08a439949
commit d5ec009cb5
44 files changed
+3715 -26

No files matched your search

+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();
}