feat(points): staff auto-connect never scores; event feedback pays +5

- Migration 20261020120000: staff (type staff / Admin / @appe.at) are
  auto-connected to every participant of the event via connections.auto
  rows inserted directly as accepted - never through accept_connection,
  so zero points by construction; backfill + idempotent helper + trigger.
- Migration 20261020130000: submit_event_feedback awards +5 on the first
  submission per participant x event (edits earn 0), gated by
  _points_eligible; response gains earned column; ACL restored.
- Admin: points move from Contacts to Registrations (active-event rows
  only, in-place save); Dashboard Top points drops emails; Dashboard and
  Activity hide auto connections.
- Attendee: leaderboard masks surnames (Max M.); EventFeedback toast
  shows +5 pts on paid submissions.
- Tests: staff_auto_connections_tests.sql (14 assertions), rpc_tests
  section 11 (4 assertions). Docs + release record 2026-10-20.
- README: document the git-ignored .env provisioning step (missing key
  = white screen).

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-10-20 22:15:29 +02:00
1 parent e243b83a56
commit 3ee91b5ad6
22 files changed
+809 -166

No files matched your search

+7 -1
View File
@@ -218,13 +218,19 @@ npm run db:start
# 2. (Re)apply migrations + seed, then restart the stack # 2. (Re)apply migrations + seed, then restart the stack
npm run db:reset npm run db:reset
# 3. Run the apps (Vite dev servers, proxy to the core) # 3. One-time: provision each app's dev env (git-ignored, never committed)
cp apps/convivo/.env.example apps/convivo/.env
cp apps/admin/.env.example apps/admin/.env
# 4. Run the apps (Vite dev servers, proxy to the core)
npm run app:dev # attendee app on :3000 npm run app:dev # attendee app on :3000
npm run admin:dev # admin console on :3001 npm run admin:dev # admin console on :3001
npm run sidecar:dev # Sessionize sync sidecar on :3002 npm run sidecar:dev # Sessionize sync sidecar on :3002
``` ```
Open **http://localhost:3000** (attendee) and **http://localhost:3001** (admin). Studio is at **http://localhost:54323** (user `postgres`, password `postgres`). Open **http://localhost:3000** (attendee) and **http://localhost:3001** (admin). Studio is at **http://localhost:54323** (user `postgres`, password `postgres`).
> **Blank white page?** You skipped step 3. Without `VITE_SUPABASE_ANON_KEY` the Supabase client throws at load and React renders nothing (the server still answers HTTP 200 — the failure is in the browser console). The `.env` files are git-ignored, so a fresh clone or worktree never has them; the values in `.env.example` are the standard local-stack demo keys and are not secrets. After creating them, restart Vite (env is read only at startup) and hard-refresh the browser (Ctrl+Shift+R).
### Option B — Docker (apps as sidecars) ### Option B — Docker (apps as sidecars)
```bash ```bash
# 1. Start the Supabase core (creates the supabase_network_Convivo network) # 1. Start the Supabase core (creates the supabase_network_Convivo network)
+2
View File
@@ -313,6 +313,8 @@ export interface Connection {
status: ConnectionStatus; status: ConnectionStatus;
created_at: string; created_at: string;
resolved_at: string | null; resolved_at: string | null;
/** Staff auto-pairing (never a hand-made connection, never scored). */
auto: boolean;
} }
export interface Checkin { export interface Checkin {
+3 -1
View File
@@ -52,7 +52,9 @@ export function Activity() {
const ss = await getSessions(ev.id); const ss = await getSessions(ev.id);
setSessions(ss); setSessions(ss);
setCheckins(ck.filter((x) => x.event_id === ev.id)); setCheckins(ck.filter((x) => x.event_id === ev.id));
setConnections(cn.filter((x) => x.event_id === ev.id)); // Staff auto-pairings (connections.auto) are bookkeeping, not real
// networking — the console only shows hand-made connections.
setConnections(cn.filter((x) => x.event_id === ev.id && !x.auto));
setFeedback(fb.filter((x) => x.event_id === ev.id)); setFeedback(fb.filter((x) => x.event_id === ev.id));
setEventFeedback(efb.filter((x) => x.event_id === ev.id)); setEventFeedback(efb.filter((x) => x.event_id === ev.id));
try { try {
+3 -99
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { adjustPoints, deleteContact, getAllContacts, updateContact, upsertContact } from '../lib/api'; import { deleteContact, getAllContacts, updateContact, upsertContact } from '../lib/api';
import type { Contact } from '../lib/types'; import type { Contact } from '../lib/types';
import { useSilentRefresh } from '../lib/useSilentRefresh'; import { useSilentRefresh } from '../lib/useSilentRefresh';
import { useToast } from '../context/ToastContext'; import { useToast } from '../context/ToastContext';
@@ -24,7 +24,6 @@ export function Contacts() {
const [editing, setEditing] = useState<Contact | null>(null); const [editing, setEditing] = useState<Contact | null>(null);
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
const [pointsFor, setPointsFor] = useState<Contact | null>(null);
const [deleting, setDeleting] = useState<string | null>(null); const [deleting, setDeleting] = useState<string | null>(null);
async function load(silent = false) { async function load(silent = false) {
@@ -59,7 +58,7 @@ export function Contacts() {
// Background pull, paused while a modal is open so nothing re-renders under a // Background pull, paused while a modal is open so nothing re-renders under a
// form. Writes here already `await load()`, so no refreshSoon is needed. // form. Writes here already `await load()`, so no refreshSoon is needed.
useSilentRefresh(() => load(true), { useSilentRefresh(() => load(true), {
enabled: contacts !== null && !editing && !creating && !pointsFor && !deleting, enabled: contacts !== null && !editing && !creating && !deleting,
}); });
// General search: first name, last name or email address. // General search: first name, last name or email address.
@@ -106,7 +105,7 @@ export function Contacts() {
<div className="page-head"> <div className="page-head">
<div> <div>
<h1>Contacts</h1> <h1>Contacts</h1>
<div className="sub">{contacts.length} people · manage contacts and points.</div> <div className="sub">{contacts.length} people · manage contacts.</div>
</div> </div>
<div className="row" style={{ gap: 10 }}> <div className="row" style={{ gap: 10 }}>
<input <input
@@ -172,9 +171,6 @@ export function Contacts() {
<button className="btn small" onClick={() => setEditing(c)}> <button className="btn small" onClick={() => setEditing(c)}>
Edit Edit
</button> </button>
<button className="btn small" onClick={() => setPointsFor(c)}>
Points
</button>
<button <button
className="btn small danger" className="btn small danger"
disabled={deleting === c.email} disabled={deleting === c.email}
@@ -214,16 +210,6 @@ export function Contacts() {
/> />
)} )}
{pointsFor && (
<AdjustPointsModal
contact={pointsFor}
onClose={() => setPointsFor(null)}
onSaved={async (msg) => {
setPointsFor(null);
push('success', msg);
}}
/>
)}
</div> </div>
); );
} }
@@ -365,85 +351,3 @@ function CreateContactModal({
</Modal> </Modal>
); );
} }
function AdjustPointsModal({
contact,
onClose,
onSaved,
}: {
contact: Contact;
onClose: () => void;
onSaved: (msg: string) => void;
}) {
const [delta, setDelta] = useState('10');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
// Mirrors the contact-side half of the SQL predicate `_points_eligible`
// (which additionally requires a non-staff registration in the active event).
const canEarn = !contact.is_admin && !/@appe\.at$/i.test(contact.email);
async function save() {
const d = parseInt(delta, 10);
if (Number.isNaN(d) || d === 0) return;
setBusy(true);
try {
await adjustPoints(contact.email, d, reason.trim() || 'manual adjustment');
onSaved(`${d > 0 ? '+' : ''}${d} points for ${contact.full_name}`);
onClose();
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Adjustment failed');
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Points — ${contact.full_name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy || !canEarn} onClick={save} data-testid="adjust-points-apply"
title={canEarn ? undefined : 'This contact is excluded from points, so there is nothing to apply'}>
{busy ? 'Applying…' : 'Apply'}
</button>
</>
}
>
<div className="row" style={{ justifyContent: 'center', gap: 16 }}>
<Avatar name={contact.full_name} id={contact.email} size={52} fs={18} />
<div>
<div style={{ fontWeight: 700 }}>{contact.full_name}</div>
<div className="muted small">{contact.email}</div>
</div>
</div>
<div className="field">
<label>Adjustment for the active event (use a negative number to subtract)</label>
<input className="input mono" type="number" value={delta} onChange={(e) => setDelta(e.target.value)} />
{/* _points_eligible needs a registration row in the ACTIVE event; without
one the award is a no-op, so the target of the adjustment is worth
stating explicitly. */}
<span className="muted small">Goes to this person’s pass for the active event — with no pass there, nothing can be awarded.</span>
</div>
<div className="field">
<label>Reason (optional)</label>
<input className="input" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. prize, correction" />
</div>
{/* adjust_points routes through _award_points, which no-ops for staff,
admin contacts and @appe.at addresses — and returns void, so the call
would "succeed" having changed nothing. Say so up front instead of
letting the admin believe the score moved. */}
{!canEarn && (
<p className="pts-exempt-note" data-testid="adjust-points-exempt">
This person does not earn points (Admin/staff contact or an @appe.at address), so
{delta.trim().startsWith('-') ? ' subtracting' : ' adding'} points changes nothing and they stay off
the leaderboard. That is deliberate — change their type in Registrations if it is wrong.
</p>
)}
</Modal>
);
}
+3 -2
View File
@@ -43,7 +43,9 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
if (cancelledRef.current) return; if (cancelledRef.current) return;
setContacts(c); setContacts(c);
setCheckins(ck.filter((x) => x.event_id === ev.id)); setCheckins(ck.filter((x) => x.event_id === ev.id));
setConnections(conn.filter((x) => x.event_id === ev.id)); // `auto` rows are the staff auto-pairings (migration 20261020120000):
// background bookkeeping, not real activity — keep them out of the feed.
setConnections(conn.filter((x) => x.event_id === ev.id && !x.auto));
setFeedback(f.filter((x) => x.event_id === ev.id)); setFeedback(f.filter((x) => x.event_id === ev.id));
setLb(l.filter((x) => x.event_id === ev.id)); setLb(l.filter((x) => x.event_id === ev.id));
setLoaded(true); setLoaded(true);
@@ -172,7 +174,6 @@ export function Dashboard({ onNavigate }: { onNavigate: (v: View) => void }) {
<Avatar name={r.full_name} id={r.contact_email} size={36} fs={13} /> <Avatar name={r.full_name} id={r.contact_email} size={36} fs={13} />
<div className="grow"> <div className="grow">
<div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name}</div> <div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name}</div>
<div className="muted small">{r.contact_email}</div>
</div> </div>
<span className="pts">{r.points}</span> <span className="pts">{r.points}</span>
</div> </div>
+117 -1
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { import {
adjustPoints,
createRegistration, createRegistration,
deleteContacts, deleteContacts,
enqueueBadgePrint, enqueueBadgePrint,
@@ -45,6 +46,9 @@ export function Registrations() {
const [deletingAll, setDeletingAll] = useState(false); const [deletingAll, setDeletingAll] = useState(false);
const [mergeFor, setMergeFor] = useState<Registration | null>(null); const [mergeFor, setMergeFor] = useState<Registration | null>(null);
const [badgeFor, setBadgeFor] = useState<Registration | null>(null); const [badgeFor, setBadgeFor] = useState<Registration | null>(null);
// Points adjustment. It lives here, not in Contacts, because the value sits
// on the pass (registrations.points) that this table manages row by row.
const [pointsFor, setPointsFor] = useState<Registration | null>(null);
const [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]); const [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]);
const [printingIds, setPrintingIds] = useState<Set<string>>(new Set()); const [printingIds, setPrintingIds] = useState<Set<string>>(new Set());
// Rows with a write in flight (check-in toggle or pass-type change). Per-row // Rows with a write in flight (check-in toggle or pass-type change). Per-row
@@ -472,7 +476,20 @@ export function Registrations() {
than showing a bare 0, which reads like a broken than showing a bare 0, which reads like a broken
check-in. Mirrors the SQL predicate exactly. */} check-in. Mirrors the SQL predicate exactly. */}
{canEarnPoints(r) ? ( {canEarnPoints(r) ? (
<span className="pts">{r.points}</span> <div className="row" style={{ gap: 8, justifyContent: 'flex-end' }}>
<span className="pts">{r.points}</span>
{event.is_active ? (
<button className="btn small" data-testid={`points-adjust-${r.id}`} onClick={() => setPointsFor(r)}>
Points
</button>
) : (
<Tooltip title="Only the active event" content="adjust_points always lands on the active event’s pass. Adjusting a different event’s row would silently change the wrong person’s other pass, so points can only be adjusted while the active event is selected.">
<button className="btn small" disabled>
Points
</button>
</Tooltip>
)}
</div>
) : ( ) : (
<Tooltip title="Does not earn points" content="Staff and organiser accounts (type staff, Admin contacts, or an @appe.at address) are excluded from points and the leaderboard on purpose."> <Tooltip title="Does not earn points" content="Staff and organiser accounts (type staff, Admin contacts, or an @appe.at address) are excluded from points and the leaderboard on purpose.">
<span className="pts pts-exempt" data-testid={`points-exempt-${r.id}`}> <span className="pts pts-exempt" data-testid={`points-exempt-${r.id}`}>
@@ -539,6 +556,28 @@ export function Registrations() {
</Modal> </Modal>
)} )}
{pointsFor && (
<AdjustPointsModal
registration={pointsFor}
contact={byEmail.get(pointsFor.contact_email)}
onClose={() => setPointsFor(null)}
onSaved={(msg, appliedDelta, ok) => {
setPointsFor(null);
if (ok && appliedDelta !== null) {
// Patch in place — the list is sorted by points, a reload would
// slide this row somewhere else mid-edit (same rule as the
// check-in toggle). refreshSoon() settles the truth afterwards.
const rowId = pointsFor.id;
setRegistrations((rows) => rows.map((row) => (row.id === rowId
? { ...row, points: Math.max(0, row.points + appliedDelta) }
: row)));
refreshSoon();
}
push(ok ? 'success' : 'error', msg);
}}
/>
)}
{badgeFor && ( {badgeFor && (
<BadgePreviewModal <BadgePreviewModal
registration={badgeFor} registration={badgeFor}
@@ -786,6 +825,83 @@ function AddRegistrationModal({
* 'sponsor' but no sponsor exists for that contact yet. Lets them create the * 'sponsor' but no sponsor exists for that contact yet. Lets them create the
* sponsor (with a contact search) and then retry the type change. * sponsor (with a contact search) and then retry the type change.
*/ */
/**
* Adjust one attendee's points, from the row that owns the pass. Mirrors the
* old Contacts modal, minus the exemption note: rows that cannot earn points
* (_points_eligible mirror) never show the button, and the RPC re-checks the
* same predicate server-side. Only offered for the active event —
* adjust_points always targets the active event's pass.
*/
function AdjustPointsModal({
registration,
contact,
onClose,
onSaved,
}: {
registration: Registration;
contact?: Contact;
onClose: () => void;
onSaved: (msg: string, appliedDelta: number | null, ok: boolean) => void;
}) {
const [delta, setDelta] = useState('10');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
const name = contact?.full_name ?? registration.contact_email;
async function save() {
const d = parseInt(delta, 10);
if (Number.isNaN(d) || d === 0) return;
setBusy(true);
try {
await adjustPoints(registration.contact_email, d, reason.trim() || 'manual adjustment');
onSaved(`${d > 0 ? '+' : ''}${d} points for ${name}`, d, true);
onClose();
} catch (e) {
onSaved(e instanceof Error ? e.message : 'Adjustment failed', null, false);
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={`Points — ${name}`}
onClose={onClose}
footer={
<>
<button className="btn" onClick={onClose}>
Cancel
</button>
<button className="btn primary" disabled={busy} onClick={save} data-testid="adjust-points-apply">
{busy ? 'Applying…' : 'Apply'}
</button>
</>
}
>
<div className="row" style={{ justifyContent: 'center', gap: 16 }}>
<Avatar name={name} id={registration.contact_email} size={52} fs={18} />
<div>
<div style={{ fontWeight: 700 }}>{name}</div>
<div className="muted small">{registration.contact_email}</div>
</div>
</div>
<div className="field">
<label>Adjustment (use a negative number to subtract)</label>
<input className="input mono" type="number" value={delta} onChange={(e) => setDelta(e.target.value)} />
<span className="muted small">
Goes to this person’s pass in {registration.qr_token ? `ticket ${registration.qr_token}` : 'this registration'} —
the row you opened this from.
</span>
</div>
<div className="field">
<label>Reason (optional)</label>
<input className="input" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. prize, correction" />
</div>
</Modal>
);
}
function SponsorLookupModal({ function SponsorLookupModal({
registration, registration,
contact, contact,
+3 -2
View File
@@ -100,8 +100,9 @@ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[
} }
/** Submit (or update) the current user's event-level feedback. */ /** Submit (or update) the current user's event-level feedback. */
export async function submitEventFeedback(rating: number, comment: string): Promise<void> { export async function submitEventFeedback(rating: number, comment: string): Promise<{ feedback_id: string; points: number; earned: number }> {
await rpc('submit_event_feedback', { p_rating: rating, p_comment: comment }); const rows = await rpc<{ feedback_id: string; points: number; earned: number }[]>('submit_event_feedback', { p_rating: rating, p_comment: comment });
return rows[0];
} }
/** Read the current user's own event-level feedback (null if not yet submitted). */ /** Read the current user's own event-level feedback (null if not yet submitted). */
+2 -2
View File
@@ -53,8 +53,8 @@ export function EventFeedback({ onDone }: { onDone: () => void }) {
if (rating === 0) return; if (rating === 0) return;
setBusy(true); setBusy(true);
try { try {
await submitEventFeedback(rating, comment.trim()); const res = await submitEventFeedback(rating, comment.trim());
toast('Thanks for your feedback! ⭐', 'ok'); toast(res.earned > 0 ? `Thanks! +${res.earned} pts ⭐` : 'Thanks for your feedback! ⭐', 'ok');
setSubmitted(true); setSubmitted(true);
onDone(); onDone();
} catch (e) { } catch (e) {
+13 -3
View File
@@ -5,6 +5,16 @@ import { getLeaderboard } from '../lib/api';
import type { LeaderboardRow } from '../lib/types'; import type { LeaderboardRow } from '../lib/types';
import { Avatar, Spinner } from '../components/ui'; import { Avatar, Spinner } from '../components/ui';
/**
* Leaderboard display name: first name + the initial of the last name
* ("Max Muster" → "Max M.") — surnames stay private on a public screen.
*/
function maskedName(fullName: string): string {
const parts = fullName.trim().split(/\s+/).filter(Boolean);
if (parts.length < 2) return parts[0] ?? fullName;
return `${parts[0]} ${parts[parts.length - 1].charAt(0).toUpperCase()}.`;
}
export function Leaderboard() { export function Leaderboard() {
const { contact } = useAuth(); const { contact } = useAuth();
const [rows, setRows] = useState<LeaderboardRow[]>([]); const [rows, setRows] = useState<LeaderboardRow[]>([]);
@@ -72,7 +82,7 @@ export function Leaderboard() {
return ( return (
<div className="pod" key={r.contact_email}> <div className="pod" key={r.contact_email}>
<div className={`bar ${cls}`}>{r.points}</div> <div className={`bar ${cls}`}>{r.points}</div>
<div className="pname">{r.full_name.split(' ')[0]}</div> <div className="pname">{maskedName(r.full_name)}</div>
<div className="ppoints">#{idx + 1}</div> <div className="ppoints">#{idx + 1}</div>
</div> </div>
); );
@@ -87,9 +97,9 @@ export function Leaderboard() {
return ( return (
<div className={`lb-row ${isMe ? 'me' : ''}`} key={r.contact_email}> <div className={`lb-row ${isMe ? 'me' : ''}`} key={r.contact_email}>
<span className="rank">{rank}</span> <span className="rank">{rank}</span>
<Avatar name={r.full_name} id={r.contact_email} size={38} fs={13} /> <Avatar name={maskedName(r.full_name)} id={r.contact_email} size={38} fs={13} />
<div className="grow"> <div className="grow">
<div style={{ fontWeight: 700, fontSize: 14 }}>{r.full_name} {isMe && <span className="muted small">(you)</span>}</div> <div style={{ fontWeight: 700, fontSize: 14 }}>{maskedName(r.full_name)} {isMe && <span className="muted small">(you)</span>}</div>
</div> </div>
<span className="pts">{r.points}</span> <span className="pts">{r.points}</span>
</div> </div>
+31
View File
@@ -143,6 +143,25 @@ Accepts an **incoming** request.
### `reject_connection(p_connection_id)` → `connections` ### `reject_connection(p_connection_id)` → `connections`
Same guards as accept, but sets `status = 'rejected'`. No points. Same guards as accept, but sets `status = 'rejected'`. No points.
### Staff auto-connect (trigger, `20261020120000_staff_auto_connections.sql`)
Every staff member is connected to **every other participant of the same
event** without any user action — this is not an RPC:
- The staff set equals the points-exempt set (`_points_eligible`): registration
type `staff`, Admin contact, or an `@appe.at` address; everyone else is a
"person". Only staff × person pairs are created — never staff × staff.
- Rows are inserted as `status = 'accepted'`, `auto = true` by the trigger
`registrations_autoconnect_staff` (on registration insert / type change) and
by the idempotent backfill helper `_autoconnect_staff_event(event)`.
- **No points are ever awarded:** these rows never pass through
`accept_connection`/`_award_points`.
- Existing pairs (including a manually `rejected` one) are never touched — the
unique pair index makes every pass a no-op.
- Scanning a staff lanyard behaves as already-connected:
`create_connection_request`'s idempotency rule returns the existing
`accepted` row and the app shows "You're connected!".
- `auto = true` rows appear in the attendee's connections list but are excluded
from the admin Dashboard feed and the Activity connections table.
### `checkin_attendee(p_session_id, p_attendee_qr)` → `(checkin_id, attendee_email, attendee_name, points, already, points_awarded)` ### `checkin_attendee(p_session_id, p_attendee_qr)` → `(checkin_id, attendee_email, attendee_name, points, already, points_awarded)`
Staff checks an attendee into a session. Staff checks an attendee into a session.
- **Role check:** `is_staff_or_admin()` (i.e. `is_admin()`) or it raises - **Role check:** `is_staff_or_admin()` (i.e. `is_admin()`) or it raises
@@ -270,6 +289,18 @@ Post-session feedback.
- Recalculates `sessions.average_feedback`, updates the `ai_generated_feedback` - Recalculates `sessions.average_feedback`, updates the `ai_generated_feedback`
state machine, and recalcs the event aggregates. state machine, and recalcs the event aggregates.
### `submit_event_feedback(p_rating, p_comment)` → `(feedback_id, points, earned)`
Event-level feedback ("Rate this event" from Home), one row per (event, contact)
in `event_feedback`.
- Requires the caller to be **registered** for the active event; `rating` 1–5.
- **First submission earns +5** (category `feedback`, `_points_eligible` gate —
staff / Admin / `@appe.at` earn nothing).
- **Idempotent:** re-submitting upserts the row and earns **0** (an edit of an
already-rewarded answer never pays twice).
- `get_my_event_feedback()` returns the caller's existing answer for pre-fill.
- `20261020130000_event_feedback_points.sql` added the award + the `earned`
response column (drop/recreate — the return type changed; ACL restored).
### `adjust_points(p_contact_email, p_delta, p_reason)` → `void` ### `adjust_points(p_contact_email, p_delta, p_reason)` → `void`
**Admin-only** manual points adjustment (category `admin`) for the active event. **Admin-only** manual points adjustment (category `admin`) for the active event.
Used by the APPE Admin console to award prizes or correct mistakes. Goes through Used by the APPE Admin console to award prizes or correct mistakes. Goes through
+21
View File
@@ -213,6 +213,15 @@ for the slot before inserting).
| `status` | `text` | `pending` \| `accepted` \| `rejected` (default `pending`) | | `status` | `text` | `pending` \| `accepted` \| `rejected` (default `pending`) |
| `created_at` | `timestamptz` | | | `created_at` | `timestamptz` | |
| `resolved_at` | `timestamptz` | set when accepted/rejected | | `resolved_at` | `timestamptz` | set when accepted/rejected |
| `auto` | `boolean` | staff auto-pairing (never hand-made, never scored) — `20261020120000_staff_auto_connections.sql` |
**Staff auto-connect:** the trigger `registrations_autoconnect_staff` inserts a
staff × person pair as `accepted`, `auto = true` whenever a registration is
created or changes type (plus a backfill in the migration). Staff here means
exactly the points-exempt set (`_points_eligible`): type `staff`, Admin contact,
or an `@appe.at` address. No points are ever awarded for these rows, and
existing pairs — including manually rejected ones — are never touched. The admin
console hides `auto` rows from its activity views.
**Constraint:** unique per **unordered pair per event** via **Constraint:** unique per **unordered pair per event** via
`unique index connections_pair_uniq on (event_id, least(from_email, to_email), `unique index connections_pair_uniq on (event_id, least(from_email, to_email),
@@ -248,6 +257,18 @@ contact per session (prevents double points).
**Constraint:** `unique (event_id, contact_email, session_id)` — one feedback per **Constraint:** `unique (event_id, contact_email, session_id)` — one feedback per
contact per session. contact per session.
Points (awarded by `submit_feedback`, first submission only): **+5** rating
only, **+10** rating + non-empty comment.
## `event_feedback` — event-level rating
Same shape as `feedback` but `session_id` is replaced by
`unique (event_id, contact_email)` — one answer per participant per event,
upserted by `submit_event_feedback` (read by `get_my_event_feedback`).
Points: **+5** on the **first** submission only (edits earn nothing), gated by
`_points_eligible` — see `20261020130000_event_feedback_points.sql`.
## `leaderboard` — Realtime mirror ## `leaderboard` — Realtime mirror
A public, Realtime-friendly mirror of points **per event**. **Not** the source of A public, Realtime-friendly mirror of points **per event**. **Not** the source of
+35
View File
@@ -740,7 +740,42 @@ configured API endpoint includes the services missing from Excel.
## Files ## Files
- [`supabase/tests/rpc_tests.sql`](../../supabase/tests/rpc_tests.sql) — the test - [`supabase/tests/rpc_tests.sql`](../../supabase/tests/rpc_tests.sql) — the test
script (fixtures + assertions + summary). script (fixtures + assertions + summary).
- [`supabase/tests/run-rpc-tests.js`](../../supabase/tests/run-rpc-tests.js) — the - [`supabase/tests/run-rpc-tests.js`](../../supabase/tests/run-rpc-tests.js) — the
runner (executes the script, parses the summary, sets the exit code). runner (executes the script, parses the summary, sets the exit code).
# Staff Auto-Connect + Leaderboard Masking Regression
Migration `20261020120000_staff_auto_connections.sql` (staff are auto-paired
with every non-exempt registration of the event as `accepted` + `auto = true`,
**never** through `accept_connection`, so **never for points**), plus the
Contacts → Registrations points move and the leaderboard name mask
(first name + last-name initial + dot). Re-verify the migration and run its
SQL suite — both safe on an already-applied database (everything rolls back):
```sh
docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres \
-v ON_ERROR_STOP=1 < supabase/migrations/20261020120000_staff_auto_connections.sql
docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres \
-v ON_ERROR_STOP=1 < supabase/tests/staff_auto_connections_tests.sql # 14 assertions
CONVIVO_BASE_URL=http://127.0.0.1:3000 npm test --prefix e2e -- leaderboard-live.spec.ts --project=chromium
CONVIVO_BASE_URL=http://127.0.0.1:3000 npm test --prefix e2e -- connections.spec.ts --grep CONV-CONN-007 --project=chromium
npm run test:rpc # section 11 covers submit_event_feedback: first submit +5, edit earns nothing, one points_log row, staff earns nothing (self-contained fixtures — green even with the seed drift below)
```
`leaderboard-live.spec.ts` pins the masked display: podium names are exactly
`Board P. / Board P. / Board T.` (rendering order 2nd-1st-3rd), the list shows
`Board F.`, and full names (`Board Player`, `Board Fourth`) must have count 0.
**CONV-CONN-007 was rewritten** by the feature itself: the old spec drove
*manual* staff networking (request → accept → decline), which the auto-pair
made impossible — scanning a staff lanyard now lands on an already-accepted
pair. The rewrite asserts pre-connected lists on both sides, the instant
"You're connected!" toast, `accepted|true` for the pair in the DB (`status`
and the new `auto` flag), and unchanged points plus zero `points_log` rows for
both parties. Its demo identities still ride the seed drift described in
[Full E2E Suite Status](#full-e2e-suite-status) (the whole connections file is
in that known-red list), so the SQL suite above is the real gate for the
backend guarantee.
+4 -4
View File
@@ -14,13 +14,13 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
| View | Purpose | | View | Purpose |
|---|---| |---|---|
| **Dashboard** | Active event card (name, dates, location, aggregates: avg feedback, #sessions, #speakers, #registrations, #checked-in) + top points + recent activity. | | **Dashboard** | Active event card (name, dates, location, aggregates: avg feedback, #sessions, #speakers, #registrations, #checked-in) + top points (**name only** — no email addresses are shown) + recent activity (staff auto-pairings are background bookkeeping, not activity, and never appear here). |
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) A general search matches **first name, last name or email address**; the **LinkedIn**, **Visibility** and **Admin** columns each have an Excel-style **multi-select filter** with live counts. | | **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility. **Points are no longer managed here** — the value lives on the pass, so the adjustment moved to the **Registrations** row that owns it. (No QR token here — it lives on the registration.) A general search matches **first name, last name or email address**; the **LinkedIn**, **Visibility** and **Admin** columns each have an Excel-style **multi-select filter** with live counts. |
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company), plus a **Print** button that queues the badge on the print station ([../backend/printing.md](../backend/printing.md)). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. The **checked-in toggle is per-row and optimistic**: it patches that one row (and its points) in place — **no list reload**, so rows never jump or vanish mid-edit (the list is sorted by points) — while a small "Saving…" pulse marks the busy row and only that checkbox is disabled; other rows stay live and a second row can be toggled concurrently. A rejected write rolls the row back to the server's values. Changing the type behaves the same way. The toggle is what grants front-desk eligibility from the console (see [../backend/rpcs.md](../backend/rpcs.md)). | | **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company), plus a **Print** button that queues the badge on the print station ([../backend/printing.md](../backend/printing.md)). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. The **checked-in toggle is per-row and optimistic**: it patches that one row (and its points) in place — **no list reload**, so rows never jump or vanish mid-edit (the list is sorted by points) — while a small "Saving…" pulse marks the busy row and only that checkbox is disabled; other rows stay live and a second row can be toggled concurrently. A rejected write rolls the row back to the server's values. Changing the type behaves the same way. The toggle is what grants front-desk eligibility from the console (see [../backend/rpcs.md](../backend/rpcs.md)). Points moved here from Contacts: each point-earning row of the **active** event carries a **Points** button (`adjust_points` always targets the active event's pass, so on other events the button is disabled with an explanatory tooltip), opening a modal that applies the delta, patches the row in place — no reload, no reordering — and lets the silent refresher settle the truth. Rows excluded from points (the `_points_eligible` mirror: type staff, Admin contact, `@appe.at`) show the "no points" marker and no button. |
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). | | **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). |
| **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. | | **Schedule** | Slots (with a **type optionset** — `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. |
| **Sessions** | Everything about the **active event's sessions** in one place (nav sits between Schedule and Activity): one row per session with its slot date/time, room / level / area, **speakers**, **check-in count** (with capacity when set), **average rating and response count**, and whether an AI summary is stored, **out of date**, or impossible. Click a row to expand it: description, the full **speaker list**, the **roster of who checked in** (with time and which staff member scanned them), and the stored **AI summary**. A **search** box matches title, room, level, area or speaker, and the **attendee filter** answers "which sessions did this person actually attend?" — the list narrows to those sessions, the header states the count, and the expanded roster highlights that person. **Generate AI Feedback Summary** (see below) summarises every session with feedback in one click. Data comes from `sessions` ⨝ `slots` ⨝ `session_speakers` ⨝ `checkins` ⨝ `feedback`, joined in the client so the numbers match the other views exactly and no new RLS policy is needed. | | **Sessions** | Everything about the **active event's sessions** in one place (nav sits between Schedule and Activity): one row per session with its slot date/time, room / level / area, **speakers**, **check-in count** (with capacity when set), **average rating and response count**, and whether an AI summary is stored, **out of date**, or impossible. Click a row to expand it: description, the full **speaker list**, the **roster of who checked in** (with time and which staff member scanned them), and the stored **AI summary**. A **search** box matches title, room, level, area or speaker, and the **attendee filter** answers "which sessions did this person actually attend?" — the list narrows to those sessions, the header states the count, and the expanded roster highlights that person. **Generate AI Feedback Summary** (see below) summarises every session with feedback in one click. Data comes from `sessions` ⨝ `slots` ⨝ `session_speakers` ⨝ `checkins` ⨝ `feedback`, joined in the client so the numbers match the other views exactly and no new RLS policy is needed. |
| **Activity** | Tables of check-ins, connections, and feedback (per active event), with manual **Generate AI Summary** controls for the event and individual sessions. | | **Activity** | Tables of check-ins, connections, and feedback (per active event; staff auto-pairings — `connections.auto` — are hidden here too), with manual **Generate AI Summary** controls for the event and individual sessions. |
| **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). | | **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). |
| **Badges** | A **per-event WYSIWYG badge / PDF layout editor** (modelled on pretix's PDF Editor). Pick the event, then design one or more named **layouts** (a **Default** per event, switchable / creatable / deletable). Add **text boxes**, **QR codes** and **images** to a millimetre canvas; drag to move, use the 8 resize handles + rotation handle, **Shift-click to multi-select**, and **press `Del`** to remove. While dragging, **PowerPoint-style smart guides** appear — dashed alignment lines (edges / centres, page and neighbouring items) plus equal-spacing lines — and the element **snaps** to them. A **Word-style align** toolbar (left / center / right, top / middle / bottom) plus **PowerPoint-style** object alignment — align to the **page** or to the **selection**, and **distribute** horizontally / vertically — with the same controls in the properties panel. Text binds to attendee fields (name, email, ticket type, QR token, event name, **company / organizer**, or static) with font, size, line-height, colour, bold/italic, a labelled **Align text in box** section (horizontal left / center / right and vertical top / middle / bottom, inside the element's own frame) and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo** (`Ctrl`+`Z` / `Ctrl`+`Y`, also `Ctrl`+`Shift`+`Z`), a **Preview** mode (no handles), a **JSON** view of the layout, and **Save**. Previewed against a real sample registration. See [../backend/rpcs.md#badge-editor](../backend/rpcs.md#badge-editor). | | **Badges** | A **per-event WYSIWYG badge / PDF layout editor** (modelled on pretix's PDF Editor). Pick the event, then design one or more named **layouts** (a **Default** per event, switchable / creatable / deletable). Add **text boxes**, **QR codes** and **images** to a millimetre canvas; drag to move, use the 8 resize handles + rotation handle, **Shift-click to multi-select**, and **press `Del`** to remove. While dragging, **PowerPoint-style smart guides** appear — dashed alignment lines (edges / centres, page and neighbouring items) plus equal-spacing lines — and the element **snaps** to them. A **Word-style align** toolbar (left / center / right, top / middle / bottom) plus **PowerPoint-style** object alignment — align to the **page** or to the **selection**, and **distribute** horizontally / vertically — with the same controls in the properties panel. Text binds to attendee fields (name, email, ticket type, QR token, event name, **company / organizer**, or static) with font, size, line-height, colour, bold/italic, a labelled **Align text in box** section (horizontal left / center / right and vertical top / middle / bottom, inside the element's own frame) and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo** (`Ctrl`+`Z` / `Ctrl`+`Y`, also `Ctrl`+`Shift`+`Z`), a **Preview** mode (no handles), a **JSON** view of the layout, and **Save**. Previewed against a real sample registration. See [../backend/rpcs.md#badge-editor](../backend/rpcs.md#badge-editor). |
| **Printing** | Badge-print control center: printer stations (add / inline **rename** / **revoke**, the `cvp_…` token shown **once** on creation), live station cards with state + staff hints, queue counters (pending / in flight / dead letters / completed), the last completed jobs with **Reprint**, and dead letters with **Requeue** / **Discard**. Backed by `get_print_overview` (polled every 5 s) — see [../backend/printing.md](../backend/printing.md). | | **Printing** | Badge-print control center: printer stations (add / inline **rename** / **revoke**, the `cvp_…` token shown **once** on creation), live station cards with state + staff hints, queue counters (pending / in flight / dead letters / completed), the last completed jobs with **Reprint**, and dead letters with **Requeue** / **Discard**. Backed by `get_print_overview` (polled every 5 s) — see [../backend/printing.md](../backend/printing.md). |
+17 -1
View File
@@ -332,12 +332,25 @@ Data: `getMyCheckins()` + `getTalkCohort()` + the agenda (via `useEvent()`).
A **full-screen takeover** (no tab bar), opened from the Agenda session sheet. A **full-screen takeover** (no tab bar), opened from the Agenda session sheet.
- Shows the session (slot · time · room · title). - Shows the session (slot · time · room · title).
- **1–5 star** rating + optional comment ("bonus points for details"). - **1–5 star** rating + optional comment — **+5 pts** rating only, **+10 pts**
rating + comment ("bonus points for details").
- On submit: `submitFeedback(sessionId, rating, comment)` → a success toast - On submit: `submitFeedback(sessionId, rating, comment)` → a success toast
("+N pts ⭐"). ("+N pts ⭐").
Data: `useEvent()` (session/slot) + `submitFeedback`. Data: `useEvent()` (session/slot) + `submitFeedback`.
## Event Feedback
A **full-screen takeover**, opened from Home ("Rate this event").
- **1–5 star** rating of the whole event + optional comment; one answer per
participant (`event_feedback`, pre-filled via `getMyEventFeedback()` when
already answered — re-submitting edits it).
- **First submission earns +5 pts** (edits earn nothing; staff/Admin/@appe.at
earn nothing) — toast "Thanks! +5 pts ⭐", plain thanks otherwise.
Data: `useEvent()` + `submitEventFeedback` / `getMyEventFeedback`.
## Leaderboard ## Leaderboard
The live leaderboard. The live leaderboard.
@@ -345,6 +358,9 @@ The live leaderboard.
- **Podium** for the top 3 (1st/2nd/3rd bars), then the rest as ranked rows. - **Podium** for the top 3 (1st/2nd/3rd bars), then the rest as ranked rows.
- **Staff are excluded** — only attendees appear (enforced in - **Staff are excluded** — only attendees appear (enforced in
`get_leaderboard()` / `_sync_leaderboard`). `get_leaderboard()` / `_sync_leaderboard`).
- **Names are masked** — first name + the initial of the last name plus a dot
(`Max Muster` → `Max M.`), on the podium and in the rows alike; surnames are
never rendered (`maskedName()` in `Leaderboard.tsx`).
- **Your row is highlighted** (`me`). - **Your row is highlighted** (`me`).
- **Live:** subscribes to Realtime `postgres_changes` on the `leaderboard` table - **Live:** subscribes to Realtime `postgres_changes` on the `leaderboard` table
and re-fetches on any change — so it updates the moment points change anywhere. and re-fetches on any change — so it updates the moment points change anywhere.
+87
View File
@@ -0,0 +1,87 @@
# Staff Auto-Connect, Points Hygiene, Leaderboard Privacy (2026-10-20)
Three user-requested changes, one migration:
`20261020120000_staff_auto_connections.sql` (applied to the local stack,
**pending production**).
## 1. Staff are automatically connected to everyone — never for points
Every staff member now appears in every other participant's "My connections"
list for the same event, from the moment either registration exists — no
request, no accept step. **Connecting with staff never grants points** (the
explicit requirement): the rows are inserted directly as `accepted` and never
pass through `accept_connection`/`_award_points`.
- "Staff" is exactly the points-exempt set (`_points_eligible`): registration
type `staff`, Admin contact, or an `@appe.at` address. Everyone else is a
"person". Only staff × person pairs are created — never staff × staff,
never person × person.
- Trigger `registrations_autoconnect_staff` fires on registration INSERT and
on type changes (both directions: a late attendee pairs with existing staff,
a newly registered staff member pairs with everyone). `_autoconnect_staff_event(event)`
is the idempotent full pass, run once per event as the backfill.
- The unique pair index makes every pass conflict-free: an existing pair —
including a manually **rejected** one — is never touched.
- New column `connections.auto` (default `false`) marks these rows. Attendees
see them normally; the admin console (Dashboard activity feed, Activity
connections table) filters them out so counts stay honest.
- Scanning a staff lanyard is already-connected behaviour: `create_connection_request`
returns the existing `accepted` row and the app toasts "You're connected!".
## Points logic, as reviewed on 2026-10-20
Every award goes through `_award_points(event, email, delta, category)`, which
clamps at 0 (`greatest(0, points + delta)`), logs to `points_log`, and no-ops
without a registration unless `_points_eligible` holds — i.e. there is a
registration in **that** event with type ≠ `staff`, the contact is **not**
`is_admin`, and the email is **not** on `@appe.at`.
| Event | Who earns | Δ | category | Where |
|---|---|---|---|---|
| Welcome (front-desk) check-in | attendee | **+10** | `checkin` | `welcome_checkin` / `set_registration_checked_in` (un-toggling removes exactly what it added, as `admin`) |
| Session check-in | attendee | **+10** | `checkin` | `checkin_attendee` (once per session; service sessions excluded) |
| Connection accepted | both people | **+5 each** | `connection` | `accept_connection` |
| Talk networking bonus | both people | **+`events.talk_networking_bonus` each** | `talk_networking` | `accept_connection`, only if both attended the same session |
| Session feedback | attendee | **+5** rating only, **+10** rating + comment | `feedback` | `submit_feedback` (first submission only) |
| **Event feedback** | attendee | **+5** | `feedback` | `submit_event_feedback` — first submission only, added by `20261020130000_event_feedback_points.sql` |
| Admin adjustment | any eligible attendee | **±n** | `admin` | `adjust_points` (admin-only; **always the active event**) |
| **Staff connection (auto)** | **nobody** | **0** | — | trigger insert, never `accept_connection` |
## 2. Admin console: points belong to the pass, not the contact
- **Contacts**: the Points button + modal **removed** — a contact without a
pass cannot earn anything, so editing points there could silently do nothing.
- **Registrations**: eligible rows of the **active** event get a **Points**
button → the adjustment modal. On non-active events the button is disabled
with a tooltip because `adjust_points` always targets the active event's
pass. The save patches the row in place (no reload, no reorder) and the
silent refresher settles the truth — the same self-healing pattern as the
check-in toggle.
- **Dashboard "Top points"**: email addresses removed — name only.
- Dashboard feed + Activity hide `auto` connections.
## 3. Leaderboard names are masked
`Leaderboard.tsx` now renders **first name + last-name initial + dot**
("Max Muster" → "Max M.") on the podium *and* in the ranked rows (the podium
previously showed the bare first name; rows leaked the full surname). The
`(you)` marker still matches on the email, which never leaves the client.
## Verification
- `supabase/tests/staff_auto_connections_tests.sql` — **14 assertions green**
(pair creation both directions, staff×staff/people×people never paired,
**zero points_log rows and unchanged points**, late arrivals, rejected-pair
protection, idempotent re-run, type flip, helper revokes).
- Live local stack after the backfill: 678 auto rows, 6 staff in the active
event, **0 new `points_log` rows**.
- `npm run build` green for both apps.
- e2e: `leaderboard-live.spec.ts` now asserts the masked names (and that full
names do **not** appear). `connections.spec.ts` **CONV-CONN-007 rewritten** —
its old premise (manual staff networking, staff declining a request) is
obsolete by design: the feature pre-accepts those pairs. The rewrite asserts
pre-connected lists both ways, the instant-connect toast, `status|auto =
accepted|true` in the DB, and unchanged points for both parties. Like the
rest of that file it still rides the known seed drift (see
[../backend/tests.md](../backend/tests.md)); the backend guarantee is what
the SQL suite covers. Runbook: [../backend/tests.md](../backend/tests.md).
+1
View File
@@ -10,6 +10,7 @@ appended, so the record shows what was believed and when it was fixed.
| Date | Contents | | Date | Contents |
|---|---| |---|---|
| [2026-10-20](./2026-10-20.md) | Staff auto-connected to everyone (never for points, `connections.auto`), points adjustment moved Contacts → Registrations with active-event guard, Dashboard top-points without emails, leaderboard names masked, event feedback pays +5 (session feedback confirmed +5/+10) — local stack applied, **production pending** |
| [2026-10-19](./2026-10-19.md) | Welcome-check-in confirmation + camera fixes; per-row check-in toggle, front-desk gate, badge copies — **deployed**; then points correctness (welcome +10, toggle restore, visible exclusions), Sessions view, AI connection test, silent refresh, tooltip containment, speaker pending-material deep link — **deployed**, incl. the corrected test numbers and the seed-drift diagnosis | | [2026-10-19](./2026-10-19.md) | Welcome-check-in confirmation + camera fixes; per-row check-in toggle, front-desk gate, badge copies — **deployed**; then points correctness (welcome +10, toggle restore, visible exclusions), Sessions view, AI connection test, silent refresh, tooltip containment, speaker pending-material deep link — **deployed**, incl. the corrected test numbers and the seed-drift diagnosis |
| [2026-10-18](./2026-10-18.md) | Badge print queue on the Pi stations | | [2026-10-18](./2026-10-18.md) | Badge print queue on the Pi stations |
| [2026-10-17](./2026-10-17.md) | Reports + event feedback work | | [2026-10-17](./2026-10-17.md) | Reports + event feedback work |
+48 -48
View File
@@ -229,78 +229,78 @@ test.describe('Connections', () => {
expect(await conns.outgoingContains('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 }) => {
test('CONV-CONN-007 staff are auto-connected to everyone and never for points', async ({ browser }) => {
// Staff ↔ people connections are created by the registrations trigger
// (migration 20261020120000_staff_auto_connections) with auto = true:
// no request, no accept step — and never any points. This replaces the
// old manual staff networking flow, which the feature made impossible:
// scanning a staff lanyard now lands on an already-accepted pair.
const staff = await createUser(browser, 'staff'); const staff = await createUser(browser, 'staff');
const mia = await createUser(browser, 'attendeeA'); const mia = await createUser(browser, 'attendeeA');
const jonas = await createUser(browser, 'attendeeB'); const jonas = await createUser(browser, 'attendeeB');
const emma = await createUser(browser, 'attendeeC');
try { try {
const sApp = new AppPage(staff.page, APP_URL); const sApp = new AppPage(staff.page, APP_URL);
const sScan = new ScanPage(staff.page);
const sConns = new ConnectionsPage(staff.page); const sConns = new ConnectionsPage(staff.page);
const mApp = new AppPage(mia.page, APP_URL); const mApp = new AppPage(mia.page, APP_URL);
const mConns = new ConnectionsPage(mia.page); const mConns = new ConnectionsPage(mia.page);
const mScan = new ScanPage(mia.page);
const jApp = new AppPage(jonas.page, APP_URL); const jApp = new AppPage(jonas.page, APP_URL);
const jScan = new ScanPage(jonas.page); const jConns = new ConnectionsPage(jonas.page);
const eApp = new AppPage(emma.page, APP_URL);
const eScan = new ScanPage(emma.page);
// 1. Staff sends a connection request to Mia. const pair = (a: string, b: string) => psql(
`select c.status || '|' || c.auto::text from public.connections c
where c.event_id = (select id from public.events where is_active limit 1)
and least(c.from_email, c.to_email) = least(${sqlQuote(a)}, ${sqlQuote(b)})
and greatest(c.from_email, c.to_email) = greatest(${sqlQuote(a)}, ${sqlQuote(b)});`,
);
const score = (email: string) => psql(
`select coalesce(sum(points), 0) from public.registrations
where event_id = (select id from public.events where is_active limit 1)
and contact_email = ${sqlQuote(email)};`,
);
// 1. No manual flow needed: the staff member already has everyone.
await login(staff.page, APP_URL, ID.staff); await login(staff.page, APP_URL, ID.staff);
await sApp.waitForAdmitted(); await sApp.waitForAdmitted();
await sApp.gotoTab('scan'); expect(await sConns.mineContains('Mia Moser')).toBe(true);
await sScan.setAttendeeMode(); expect(await sConns.mineContains('Jonas Unger')).toBe(true);
await sScan.scanCode(ID.attendeeA.qrToken);
await sScan.sendConnection();
// 2. Mia accepts. // 2. Mia sees the staff in her own connections without ever asking,
// and the backend row is an auto-created accepted pair.
await login(mia.page, APP_URL, ID.attendeeA); await login(mia.page, APP_URL, ID.attendeeA);
await mApp.waitForAdmitted(); 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); expect(await mConns.mineContains('Jose Lago')).toBe(true);
await sConns.gotoMine(); expect(pair(ID.staff.email, ID.attendeeA.email)).toBe('accepted|true');
expect(await sConns.mineContains('Mia Moser')).toBe(true);
// 4. Jonas (a different attendee) sends the staff a request; the staff accepts. // 3. Scanning a staff lanyard connects instantly — no request is born.
const miaScore = score(ID.attendeeA.email);
const staffScore = score(ID.staff.email);
await mApp.gotoTab('scan');
await mScan.setAttendeeMode();
await mScan.scanCode(ID.staff.qrToken);
await mScan.sendConnection();
await expect(mia.page.getByText(/You.re connected/)).toBeVisible();
// 4. Neither side earns a point for connecting with staff.
expect(score(ID.attendeeA.email)).toBe(miaScore);
expect(score(ID.staff.email)).toBe(staffScore);
expect(psql(
`select count(*) from public.points_log
where created_at > now() - interval '2 minutes'
and contact_email in (${sqlQuote(ID.staff.email)}, ${sqlQuote(ID.attendeeA.email)});`,
)).toBe('0');
// 5. Jonas is connected to the staff the same instant, both directions.
await login(jonas.page, APP_URL, ID.attendeeB); await login(jonas.page, APP_URL, ID.attendeeB);
await jApp.waitForAdmitted(); 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); expect(await jConns.mineContains('Jose Lago')).toBe(true);
await sApp.gotoTab('home');
// 6. Emma sends the staff a request; the staff declines → no connection. expect(await sConns.mineContains('Jonas Unger')).toBe(true);
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 { } finally {
await staff.close(); await staff.close();
await mia.close(); await mia.close();
await jonas.close(); await jonas.close();
await emma.close();
} }
}); });
+5 -2
View File
@@ -46,8 +46,11 @@ test('real leaderboard updates scores and ranks without rewarding staff or admin
commit;`); commit;`);
await login(page, APP_URL, { email: emails[0], qrToken: password, type: 'attendee', label: 'Disposable leaderboard player' }); await login(page, APP_URL, { email: emails[0], qrToken: password, type: 'attendee', label: 'Disposable leaderboard player' });
await page.getByText('Leaderboard', { exact: true }).click(); await page.getByText('Leaderboard', { exact: true }).click();
await expect(page.locator('.podium .pname')).toHaveText(['Board', 'Board', 'Board']); // Names on the leaderboard are masked: first name + last-name initial.
await expect(page.getByText('Board Fourth', { exact: true })).toBeVisible(); await expect(page.locator('.podium .pname')).toHaveText(['Board P.', 'Board P.', 'Board T.']);
await expect(page.getByText('Board F.', { exact: true })).toBeVisible();
await expect(page.getByText('Board Player', { exact: true })).toHaveCount(0);
await expect(page.getByText('Board Fourth', { exact: true })).toHaveCount(0);
await expect(page.getByText(/You.re ranked/)).toContainText('#1'); await expect(page.getByText(/You.re ranked/)).toContainText('#1');
await expect.poll(() => subscribed, { timeout: 20_000, message: 'Realtime subscription acknowledged' }).toBe(true) await expect.poll(() => subscribed, { timeout: 20_000, message: 'Realtime subscription acknowledged' }).toBe(true)
.catch(error => { throw new Error(`${error.message}\n${transportMessages.join('\n')}`); }); .catch(error => { throw new Error(`${error.message}\n${transportMessages.join('\n')}`); });
@@ -0,0 +1,108 @@
-- =============================================================================
-- Convivo — Staff are automatically connected to everyone (never for points)
--
-- Every staff member is an automatic connection for every other participant
-- of the same event. Rows are inserted straight into `connections` as
-- 'accepted' by a trigger on `registrations`; existing events are backfilled
-- at the bottom of this file. Three properties matter:
--
-- 1. NO POINTS ARE EVER AWARDED. The rows never pass through
-- accept_connection, so _award_points is never called for a staff
-- pairing — and the staff side is points-exempt by _points_eligible
-- anyway, so even a later manual path cannot score them.
-- 2. "Staff" mirrors the points-exemption set exactly: registration type
-- 'staff', Admin contacts, or an @appe.at address (the organiser
-- domain). Everyone else (attendees, speakers, sponsors) is "people".
-- Pairs are staff × people only — staff × staff pairs are not created.
-- 3. Rows are marked auto = true so the admin console can tell them apart
-- from people who actually connected (Dashboard activity feed and the
-- Activity view hide them; the attendee app shows them normally).
--
-- Idempotent by construction: the unique pair index turns every re-run into
-- a no-op, and an existing pair — including a manually rejected one — is
-- never touched. If a registration changes type, the trigger pairs the new
-- role; previously created rows are kept (deleting them could destroy a
-- genuine manual connection of the same pair).
-- =============================================================================
alter table public.connections add column if not exists auto boolean not null default false;
-- Full pairing pass for one event (idempotent). Used by the backfill below
-- and safe to re-run manually after a bulk import.
create or replace function public._autoconnect_staff_event(p_event_id uuid)
returns void
language plpgsql security definer set search_path = '' as $$
begin
insert into public.connections (event_id, from_email, to_email, status, resolved_at, auto)
select p_event_id, s.email, o.email, 'accepted', now(), true
from (
select r.contact_email as email
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.event_id = p_event_id
and (r."type" = 'staff' or c.is_admin or r.contact_email like '%@appe.at')
group by 1
) s
join (
select r.contact_email as email
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.event_id = p_event_id
and r."type" <> 'staff' and not c.is_admin and r.contact_email not like '%@appe.at'
) o on o.email <> s.email
on conflict (event_id, least(from_email, to_email), greatest(from_email, to_email)) do nothing;
end;
$$;
-- A new registration (or a type change) is paired with the opposite side of
-- its event immediately, in whichever direction it arrives: a staff row
-- pairs with every existing person, a person pairs with every existing
-- staff member. Multi-row INSERTs are safe — AFTER ROW triggers run once the
-- statement has landed, so rows of the same statement see each other.
create or replace function public._registrations_autoconnect_staff()
returns trigger
language plpgsql security definer set search_path = '' as $$
declare
v_staff boolean;
begin
-- The FK on registrations.contact_email guarantees the contact exists.
select (new."type" = 'staff' or c.is_admin or new.contact_email like '%@appe.at')
into v_staff
from public.contacts c
where c.email = new.contact_email;
if v_staff then
insert into public.connections (event_id, from_email, to_email, status, resolved_at, auto)
select new.event_id, new.contact_email, r.contact_email, 'accepted', now(), true
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.event_id = new.event_id
and r.contact_email <> new.contact_email
and r."type" <> 'staff' and not c.is_admin and r.contact_email not like '%@appe.at'
on conflict (event_id, least(from_email, to_email), greatest(from_email, to_email)) do nothing;
else
insert into public.connections (event_id, from_email, to_email, status, resolved_at, auto)
select new.event_id, r.contact_email, new.contact_email, 'accepted', now(), true
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.event_id = new.event_id
and r.contact_email <> new.contact_email
and (r."type" = 'staff' or c.is_admin or r.contact_email like '%@appe.at')
on conflict (event_id, least(from_email, to_email), greatest(from_email, to_email)) do nothing;
end if;
return new;
end;
$$;
drop trigger if exists registrations_autoconnect_staff on public.registrations;
create trigger registrations_autoconnect_staff
after insert or update of "type", event_id on public.registrations
for each row execute function public._registrations_autoconnect_staff();
-- Backfill every event already in the database.
select public._autoconnect_staff_event(e.id) from public.events e;
-- Internal helpers: never callable through the API (the trigger runs as the
-- function owner, postgres, which is what bypasses RLS on `connections`).
revoke all on function public._autoconnect_staff_event(uuid), public._registrations_autoconnect_staff()
from public, anon, authenticated;
@@ -0,0 +1,69 @@
-- =============================================================================
-- 20261020130000_event_feedback_points.sql
-- Event-level feedback is worth points: **+5 for the first submission**
-- (per participant × event). Re-submitting edits the existing row and awards
-- nothing, mirroring the session-feedback idempotency rule. Staff / Admin
-- contacts / @appe.at earn nothing — the same `_points_eligible` gate every
-- other award uses. Session feedback is unchanged (+5 rating only, +10 with
-- comment — already live since 20260824000000 / 20261015164546).
-- The response gains an `earned` column so the app can show "+5 pts".
-- =============================================================================
-- =============================================================================
-- The return type gains a column, which `create or replace` cannot do —
-- drop + recreate, then restore the exact ACL the original migrations left
-- (EXECUTE for PUBLIC + authenticated; no direct anon grant).
-- =============================================================================
drop function if exists public.submit_event_feedback(integer, text);
create function public.submit_event_feedback(p_rating integer, p_comment text)
returns table (feedback_id uuid, points integer, earned integer)
language plpgsql security definer set search_path = public as $$
declare
v_email text := public.current_email();
v_event_id uuid;
v_fb_id uuid;
v_points integer;
v_clean text;
v_exists boolean;
v_earned integer;
begin
if v_email is null then raise exception 'not authenticated'; end if;
if p_rating is null or p_rating < 1 or p_rating > 5 then
raise exception 'rating must be between 1 and 5';
end if;
select id into v_event_id from public.events where is_active limit 1;
if v_event_id is null then raise exception 'no active event'; end if;
if not exists (select 1 from public.registrations
where event_id = v_event_id and contact_email = v_email) then
raise exception 'you must be registered for this event to give feedback';
end if;
v_clean := nullif(btrim(coalesce(p_comment, '')), '');
-- First submission only gets the award; an edit of an existing answer
-- (or an ineligible contact) earns nothing.
select exists (select 1 from public.event_feedback
where event_id = v_event_id and contact_email = v_email) into v_exists;
v_earned := case
when v_exists then 0
when not public._points_eligible(v_event_id, v_email) then 0
else 5
end;
insert into public.event_feedback (event_id, contact_email, rating, comment)
values (v_event_id, v_email, p_rating, v_clean)
on conflict (event_id, contact_email) do update
set rating = excluded.rating, comment = excluded.comment
returning id into v_fb_id;
if v_earned > 0 then
perform public._award_points(v_event_id, v_email, v_earned, 'feedback');
end if;
select r.points into v_points from public.registrations r
where r.event_id = v_event_id and r.contact_email = v_email;
return query select v_fb_id, coalesce(v_points, 0), v_earned;
end;
$$;
grant execute on function public.submit_event_feedback(integer, text) to public, authenticated;
+68
View File
@@ -441,6 +441,74 @@ exception when others then
end; end;
$$; $$;
-- =============================================================================
-- 11. submit_event_feedback: first submission +5, re-submit idempotent,
-- ineligible contacts earn nothing.
-- Self-contained fixtures (seed-independent) — everything rolls back.
-- =============================================================================
do $$
declare
v_event uuid;
v_before integer;
v_after integer;
v_earned integer;
v_count integer;
v_ok boolean;
v_msg text;
begin
v_event := (select id from public.events where is_active limit 1);
if v_event is null then
insert into test_results values ('event feedback (11)', false, 'no active event');
return;
end if;
insert into public.contacts (email, full_name) values
('[email protected]', 'Effie Probe'),
('[email protected]', 'Stella Probe');
insert into public.registrations (event_id, contact_email, type) values
(v_event, '[email protected]', 'attendee'),
(v_event, '[email protected]', 'staff');
-- First submission (attendee) -> +5.
perform set_user('[email protected]');
select points into v_before from public.registrations
where contact_email = '[email protected]' and event_id = v_event;
select earned into v_earned from public.submit_event_feedback(4, 'Well organised');
select points into v_after from public.registrations
where contact_email = '[email protected]' and event_id = v_event;
v_ok := (v_earned = 5 and v_after = v_before + 5);
v_msg := format('expected earned=5/points=%s, got earned=%s points=%s', v_before + 5, v_earned, v_after);
insert into test_results values ('event feedback first submit earns +5', v_ok, case when v_ok then null else v_msg end);
-- Edit the answer: row updates, no second award.
select earned into v_earned from public.submit_event_feedback(5, 'Minor tweaks');
select points into v_after from public.registrations
where contact_email = '[email protected]' and event_id = v_event;
v_ok := (v_earned = 0 and v_after = v_before + 5);
v_msg := format('expected earned=0/points=%s, got earned=%s points=%s', v_before + 5, v_earned, v_after);
insert into test_results values ('event feedback edit earns nothing', v_ok, case when v_ok then null else v_msg end);
-- Exactly one +5 'feedback' points_log row.
select count(*) into v_count from public.points_log
where event_id = v_event and contact_email = '[email protected]'
and category = 'feedback' and delta = 5;
v_ok := (v_count = 1);
insert into test_results values ('event feedback logs one +5 row', v_ok,
case when v_ok then null else 'expected 1 points_log row, got ' || v_count end);
-- Staff registration -> eligible check fails, earns nothing, no log row.
perform set_user('[email protected]');
select earned into v_earned from public.submit_event_feedback(5, 'Staff view');
select count(*) into v_count from public.points_log
where event_id = v_event and contact_email = '[email protected]';
v_ok := (v_earned = 0 and v_count = 0);
v_msg := format('expected earned=0/log=0, got earned=%s log=%s', v_earned, v_count);
insert into test_results values ('event feedback staff earns nothing', v_ok, case when v_ok then null else v_msg end);
exception when others then
insert into test_results values ('event feedback (11)', false, 'error: ' || sqlerrm);
end;
$$;
-- ============================================================================= -- =============================================================================
-- Summary (printed BEFORE the rollback, since the temp table is dropped by it) -- Summary (printed BEFORE the rollback, since the temp table is dropped by it)
-- ============================================================================= -- =============================================================================
@@ -0,0 +1,162 @@
\set ON_ERROR_STOP on
begin;
-- Regression suite for 20261020120000_staff_auto_connections.sql.
-- Run against a database that already has the migration applied:
-- docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -v ON_ERROR_STOP=1 \
-- < supabase/tests/staff_auto_connections_tests.sql
-- Everything is created inside this transaction and rolled back at the end.
create temporary table staff_conn_results (name text);
create function pg_temp.assert_conn(p_condition boolean, p_name text) returns void
language plpgsql as $$
begin
if p_condition is distinct from true then raise exception 'FAIL: %', p_name; end if;
insert into staff_conn_results values (p_name);
end;
$$;
-- ---------------------------------------------------------------------------
-- Fixture: one disposable (inactive) event. Staff side = type 'staff', an
-- is_admin contact, or an @appe.at address; people side = everyone else.
-- ---------------------------------------------------------------------------
insert into public.events (id, name, start_date, end_date, is_active)
values ('a0170000-0000-0000-0000-000000000001', 'Staff autoconnect regression', current_date, current_date, false);
insert into public.contacts (email, full_name, is_admin)
values ('[email protected]', 'Staff One', false),
('[email protected]', 'Admin Person', true),
('[email protected]', 'Domain Person', false),
('[email protected]', 'Att One', false),
('[email protected]', 'Att Two', false),
('[email protected]', 'Speaker One', false);
insert into public.registrations (event_id, contact_email, type, qr_token, points)
values ('a0170000-0000-0000-0000-000000000001', '[email protected]', 'staff', 'SC-1', 0),
('a0170000-0000-0000-0000-000000000001', '[email protected]', 'attendee', 'SC-2', 0),
('a0170000-0000-0000-0000-000000000001', '[email protected]', 'attendee', 'SC-3', 0),
('a0170000-0000-0000-0000-000000000001', '[email protected]', 'attendee', 'SC-4', 0),
('a0170000-0000-0000-0000-000000000001', '[email protected]', 'attendee', 'SC-5', 0),
('a0170000-0000-0000-0000-000000000001', '[email protected]', 'speaker', 'SC-6', 0);
-- 3 staff-side registrations × 3 people = 9 auto pairs, all accepted+auto.
select pg_temp.assert_conn(
(select count(*) from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001'
and status = 'accepted' and auto and resolved_at is not null) = 9,
'staff x people pairs created by the trigger');
-- Every auto pair crosses the staff/people boundary exactly — no staff ×
-- staff and no people × people rows were ever created.
select pg_temp.assert_conn(
(with staff_side(e) as (values ('[email protected]'), ('[email protected]'), ('[email protected]')),
auto_rows(a, b) as (
select least(c.from_email, c.to_email), greatest(c.from_email, c.to_email)
from public.connections c
where c.event_id = 'a0170000-0000-0000-0000-000000000001' and c.auto)
select count(*) from auto_rows r
where (r.a in (select e from staff_side)) = (r.b in (select e from staff_side))) = 0,
'every auto pair is exactly one staff side and one person');
select pg_temp.assert_conn(
exists (select 1 from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001'
and from_email = '[email protected]' and to_email = '[email protected]'
and status = 'accepted' and auto),
'staff-to-attendee row stored accepted and auto');
-- ---------------------------------------------------------------------------
-- NO POINTS: the whole feature must never touch points or points_log.
-- ---------------------------------------------------------------------------
select pg_temp.assert_conn(
(select count(*) from public.points_log
where event_id = 'a0170000-0000-0000-0000-000000000001') = 0,
'auto-connect writes no points_log rows');
select pg_temp.assert_conn(
(select bool_and(points = 0) from public.registrations
where event_id = 'a0170000-0000-0000-0000-000000000001'),
'auto-connect leaves every points value at 0');
-- ---------------------------------------------------------------------------
-- Late arrivals pair in both directions.
-- ---------------------------------------------------------------------------
insert into public.contacts (email, full_name, is_admin) values ('[email protected]', 'Late Person', false);
insert into public.registrations (event_id, contact_email, type, qr_token, points)
values ('a0170000-0000-0000-0000-000000000001', '[email protected]', 'attendee', 'SC-7', 0);
select pg_temp.assert_conn(
(select count(*) from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001' and auto) = 12,
'a person registered after the staff pairs with all three staff');
insert into public.contacts (email, full_name, is_admin) values ('[email protected]', 'Staff Two', false);
insert into public.registrations (event_id, contact_email, type, qr_token, points)
values ('a0170000-0000-0000-0000-000000000001', '[email protected]', 'staff', 'SC-8', 0);
select pg_temp.assert_conn(
(select count(*) from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001' and auto) = 16,
'a staff member registered later pairs with all four people');
-- ---------------------------------------------------------------------------
-- Existing manual pairs are never touched.
-- ---------------------------------------------------------------------------
-- People x people stay connectable by hand and stay pending.
insert into public.connections (event_id, from_email, to_email, status)
values ('a0170000-0000-0000-0000-000000000001', '[email protected]', '[email protected]', 'pending');
-- A staff that was manually rejected before registering: the trigger must
-- not flip the rejection back to accepted (and must still pair the rest).
insert into public.contacts (email, full_name, is_admin) values ('[email protected]', 'Staff Three', false);
insert into public.connections (event_id, from_email, to_email, status, resolved_at)
values ('a0170000-0000-0000-0000-000000000001', '[email protected]', '[email protected]', 'rejected', now());
insert into public.registrations (event_id, contact_email, type, qr_token, points)
values ('a0170000-0000-0000-0000-000000000001', '[email protected]', 'staff', 'SC-9', 0);
select public._autoconnect_staff_event('a0170000-0000-0000-0000-000000000001'); -- idempotent re-run
select pg_temp.assert_conn(
(select count(*) from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001') = 21,
'backfill re-run inserts nothing new (19 auto + pending + rejected)');
select pg_temp.assert_conn(
(select count(*) from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001' and auto) = 19,
'late staff pairs with three people and skips the rejected pair');
select pg_temp.assert_conn(
exists (select 1 from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001'
and least(from_email, to_email) = '[email protected]'
and greatest(from_email, to_email) = '[email protected]'
and status = 'pending'),
'manual pending people-pair untouched by the backfill');
select pg_temp.assert_conn(
exists (select 1 from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001'
and least(from_email, to_email) = '[email protected]'
and greatest(from_email, to_email) = '[email protected]'
and status = 'rejected'),
'manually rejected staff pair is not re-accepted');
-- ---------------------------------------------------------------------------
-- Type change: attendee becomes staff and pairs with the remaining people.
-- ---------------------------------------------------------------------------
update public.registrations set "type" = 'staff'
where event_id = 'a0170000-0000-0000-0000-000000000001' and contact_email = '[email protected]';
select pg_temp.assert_conn(
exists (select 1 from public.connections
where event_id = 'a0170000-0000-0000-0000-000000000001'
and from_email = '[email protected]' and to_email = '[email protected]'
and status = 'accepted' and auto),
'type flip to staff creates the new staff-side pairs');
select pg_temp.assert_conn(
(select count(*) from public.points_log
where event_id = 'a0170000-0000-0000-0000-000000000001') = 0,
'type flip still awards no points');
-- ---------------------------------------------------------------------------
-- Helpers stay internal.
-- ---------------------------------------------------------------------------
select pg_temp.assert_conn(
not has_function_privilege('authenticated', 'public._autoconnect_staff_event(uuid)', 'execute')
and not has_function_privilege('anon', 'public._registrations_autoconnect_staff()', 'execute'),
'API roles cannot call the autoconnect helpers');
select count(*) as passed_assertions from staff_conn_results;
rollback;