feat(admin): per-row badge preview with unconfigured tooltip, Excel-style column filters and search in Contacts/Registrations

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

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
committed 2026-10-16 08:53:46 +02:00
1 parent 30ed4388c0
commit 8e38052f4c
10 files changed
+988 -121

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
import { QRCodeSVG } from 'qrcode.react';
import type { BadgeElement, BadgeQrElement, BadgeSample, BadgeTextElement } from '../lib/types';
// CSS 96 dpi: 1mm = 3.7795px. Shared by the editor canvas and read-only previews.
export const MM = 3.7795275591;
export const CONTENT_LABEL: Record<BadgeTextElement['content'], string> = {
attendee_name: 'Attendee name',
full_name: 'Full name',
email: 'Email address',
ticket_type: 'Ticket type',
event_name: 'Event name',
company: 'Company / organizer',
qr_token: 'QR / badge token',
static: 'Static text',
};
export const QR_LABEL: Record<BadgeQrElement['value'], string> = {
qr_token: 'QR / badge token',
checkin_url: 'Check-in URL',
email: 'Email address',
attendee_name: 'Attendee name',
static: 'Static value',
};
/** Resolve the bound content of a text element against a sample attendee. */
export function resolveText(el: BadgeTextElement, sample: BadgeSample): string {
let v: string;
switch (el.content) {
case 'attendee_name':
case 'full_name': v = sample.full_name; break;
case 'email': v = sample.email; break;
case 'ticket_type': v = sample.ticket_type; break;
case 'event_name': v = sample.event_name; break;
case 'company': v = sample.company; break;
case 'qr_token': v = sample.qr_token; break;
default: v = el.text;
}
if (el.transform === 'uppercase') return v.toUpperCase();
if (el.transform === 'lowercase') return v.toLowerCase();
if (el.transform === 'capitalize') return v.replace(/\b\w/g, (m) => m.toUpperCase());
return v;
}
/** Resolve the encoded value of a QR element against a sample attendee. */
export function resolveQr(el: BadgeQrElement, sample: BadgeSample): string {
switch (el.value) {
case 'qr_token': return sample.qr_token || 'CONVIVO-QR';
case 'checkin_url': return `${window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`;
case 'email': return sample.email || '[email protected]';
case 'attendee_name': return sample.full_name || 'Attendee';
default: return el.static_value || 'https://example.com';
}
}
/** The visual body of one badge element (text / QR / image), no editing chrome. */
export function BadgeElementBody({ el, sample, pxPerMm }: { el: BadgeElement; sample: BadgeSample; pxPerMm: number }) {
if (el.type === 'text') {
const text = resolveText(el, sample);
return (
<div
className="badge-text-body"
style={{
fontFamily: `"${el.font}", sans-serif`,
fontSize: el.font_size * (pxPerMm / MM), // pt→mm→px so print scale matches
lineHeight: el.line_height,
color: el.color,
fontWeight: el.bold ? 700 : 400,
fontStyle: el.italic ? 'italic' : 'normal',
justifyContent: el.align_h === 'left' ? 'flex-start' : el.align_h === 'right' ? 'flex-end' : 'center',
alignItems: el.align_v === 'top' ? 'flex-start' : el.align_v === 'bottom' ? 'flex-end' : 'center',
textAlign: el.align_h,
}}
>
<span>{text || <span className="badge-el-placeholder">{CONTENT_LABEL[el.content]}</span>}</span>
</div>
);
}
if (el.type === 'qr') {
const size = Math.round(Math.min(el.width, el.height) * pxPerMm);
return (
<div className="badge-qr-body">
<QRCodeSVG value={resolveQr(el, sample)} size={Math.max(16, size)} level="M" marginSize={0} />
</div>
);
}
// image
if (!el.src) {
return <div className="badge-image-body badge-image-empty">Image</div>;
}
return <img className="badge-image-body" src={el.src} alt="" style={{ objectFit: el.fit }} />;
}
export interface BadgePageData {
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
}
/**
* Read-only rendering of a badge layout for a specific attendee — the exact
* same markup the editor canvas produces, minus the editing chrome.
*/
export function BadgePagePreview({ layout, sample, pxPerMm, className = '' }: {
layout: BadgePageData; sample: BadgeSample; pxPerMm: number; className?: string;
}) {
return (
<div
className={`badge-page badge-page-static ${className}`}
style={{ width: layout.page_width_mm * pxPerMm, height: layout.page_height_mm * pxPerMm }}
>
{layout.elements.map((el) => (
<div
key={el.id}
className={`badge-el badge-el-${el.type}`}
style={{
left: el.x * pxPerMm, top: el.y * pxPerMm,
width: el.width * pxPerMm, height: el.height * pxPerMm,
transform: `rotate(${el.rotation}deg)`,
cursor: 'default',
}}
>
<BadgeElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
</div>
))}
</div>
);
}
/** Fit a layout inside a box of `maxW` × `maxH` px, returning the px-per-mm scale. */
export function fitScale(layout: BadgePageData, maxW: number, maxH: number): number {
return Math.min(maxW / layout.page_width_mm, maxH / layout.page_height_mm);
}
+139 -1
View File
@@ -1,4 +1,6 @@
import { type ReactNode } from 'react'; import { cloneElement, isValidElement, useEffect, useRef, useState, useId, type ReactElement, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { Filter } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react'; import { QRCodeSVG } from 'qrcode.react';
const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777']; const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777'];
@@ -108,3 +110,139 @@ export function Toggle({
</label> </label>
); );
} }
/**
* Hover/focus tooltip rendered through a portal, so it is never clipped by
* scrollable or `overflow: hidden` ancestors (e.g. data tables). The card
* visual follows the Uiverse dark-glass tooltip already used in Interfaces,
* re-themed to the APPE red accent. Wrap any element — including a disabled
* button, whose own mouse events browsers suppress.
*/
export function Tooltip({ content, title, children }: {
content: ReactNode;
title?: string;
children: ReactNode;
}) {
const anchor = useRef<HTMLSpanElement>(null);
const id = useId();
const [pos, setPos] = useState<{ x: number; y: number } | null>(null);
const show = () => {
const r = anchor.current?.getBoundingClientRect();
if (r) setPos({ x: r.left + r.width / 2, y: r.top });
};
const hide = () => setPos(null);
// Point the control at the card so screen readers announce the explanation
// when it is focused (focus also reveals it visually).
const child = isValidElement(children)
? cloneElement(children as ReactElement<{ 'aria-describedby'?: string }>, { 'aria-describedby': id })
: children;
return (
<span className="tip-anchor" ref={anchor} onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}>
{child}
{pos && createPortal(
<div className="tip-card" role="tooltip" id={id} style={{ left: pos.x, top: pos.y - 10 }}>
{title && (
<div className="tip-head">
<span className="tip-ico" aria-hidden="true">
<svg viewBox="0 0 20 20" fill="currentColor" width="15" height="15">
<path clipRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" fillRule="evenodd" />
</svg>
</span>
<strong>{title}</strong>
</div>
)}
<p>{content}</p>
<span className="tip-arrow" aria-hidden="true" />
</div>,
document.body,
)}
</span>
);
}
/** One selectable value inside a `ColumnFilter`, with a live result count. */
export interface ColumnFilterOption {
value: string;
label: string;
count: number;
}
/**
* Excel-style multi-select filter for a table column. Rendered through a portal
* so the dropdown is never clipped by the table's `overflow: hidden`. An empty
* selection means "no filter" (everything matches).
*/
export function ColumnFilter({ label, options, selected, onChange }: {
label: string;
options: ColumnFilterOption[];
selected: string[];
onChange: (next: string[]) => void;
}) {
const btnRef = useRef<HTMLButtonElement>(null);
const popRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
const active = selected.length > 0;
const toggleOpen = () => {
if (!open) {
const r = btnRef.current?.getBoundingClientRect();
if (r) setPos({ left: Math.min(Math.max(8, r.left), window.innerWidth - 240), top: r.bottom + 6 });
}
setOpen((o) => !o);
};
const toggleValue = (value: string) =>
onChange(selected.includes(value) ? selected.filter((v) => v !== value) : [...selected, value]);
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => {
const t = e.target as Node;
if (popRef.current?.contains(t) || btnRef.current?.contains(t)) return;
setOpen(false);
};
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
const onScroll = () => setOpen(false);
window.addEventListener('mousedown', onDown);
window.addEventListener('keydown', onKey);
window.addEventListener('scroll', onScroll, true);
return () => {
window.removeEventListener('mousedown', onDown);
window.removeEventListener('keydown', onKey);
window.removeEventListener('scroll', onScroll, true);
};
}, [open]);
return (
<span className="colfilter">
<button
ref={btnRef}
type="button"
className={`colfilter-btn ${active ? 'on' : ''}`}
onClick={toggleOpen}
aria-label={`Filter ${label}`}
aria-expanded={open}
title={`Filter ${label}`}
>
<Filter size={13} aria-hidden="true" />
{active && <span className="colfilter-count">{selected.length}</span>}
</button>
{open && pos && createPortal(
<div className="colfilter-pop" ref={popRef} role="group" aria-label={`Filter ${label}`} style={{ left: pos.left, top: pos.top }}>
<div className="colfilter-head">
<strong>{label}</strong>
{active && <button type="button" className="colfilter-clear" onClick={() => onChange([])}>Clear</button>}
</div>
{options.map((o) => (
<label key={o.value} className="colfilter-opt">
<input type="checkbox" checked={selected.includes(o.value)} onChange={() => toggleValue(o.value)} />
<span className="lbl">{o.label}</span>
<span className="cnt">{o.count}</span>
</label>
))}
</div>,
document.body,
)}
</span>
);
}
+58
View File
@@ -171,6 +171,34 @@ body {
.uiverse-tooltip .uiverse-card h3 { margin: 0; font-size: 13px; font-weight: 600; color: #fff; } .uiverse-tooltip .uiverse-card h3 { margin: 0; font-size: 13px; font-weight: 600; color: #fff; }
.uiverse-tooltip .uiverse-card p { margin: 0; font-size: 13px; line-height: 1.5; color: #d1d5db; } .uiverse-tooltip .uiverse-card p { margin: 0; font-size: 13px; line-height: 1.5; color: #d1d5db; }
.uiverse-tooltip .uiverse-card .uiverse-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 11px; color: #9ca3af; } .uiverse-tooltip .uiverse-card .uiverse-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 11px; color: #9ca3af; }
/* Portal tooltip (same Uiverse dark-glass card, APPE-red themed). Rendered on
document.body so it is never clipped by table overflow. */
.tip-anchor { position: relative; display: inline-flex; }
/* Disabled buttons swallow mouse events, so make them hit-test-transparent and
let the wrapper carry the hover (and the not-allowed cursor). */
.tip-anchor > button:disabled { pointer-events: none; }
.tip-anchor:has(> button:disabled) { cursor: not-allowed; }
.tip-card {
position: fixed; transform: translate(-50%, -100%); width: 250px; padding: 13px 15px;
background: linear-gradient(135deg, rgba(17,24,39,.97), rgba(31,41,55,.97));
backdrop-filter: blur(8px); border: 1px solid rgba(213,0,0,.35); border-radius: 14px;
box-shadow: 0 0 26px rgba(213,0,0,.18), 0 14px 34px rgba(0,0,0,.35);
z-index: 120; pointer-events: none; animation: tip-in .18s ease;
}
@keyframes tip-in { from { opacity: 0; transform: translate(-50%, calc(-100% + 6px)); } to { opacity: 1; transform: translate(-50%, -100%); } }
.tip-card .tip-head { display: flex; align-items: center; gap: 9px; margin-bottom: 6px; }
.tip-card .tip-head strong { font-size: 13px; font-weight: 700; color: #fff; }
.tip-card .tip-ico {
display: flex; align-items: center; justify-content: center; width: 26px; height: 26px;
border-radius: 50%; background: rgba(213,0,0,.22); color: #ff6b6b; flex-shrink: 0;
}
.tip-card p { margin: 0; font-size: 12.5px; line-height: 1.5; color: #d1d5db; }
.tip-card .tip-arrow {
position: absolute; bottom: -6px; left: 50%; transform: translateX(-50%) rotate(45deg);
width: 12px; height: 12px; background: rgba(31,41,55,.97);
border-right: 1px solid rgba(213,0,0,.35); border-bottom: 1px solid rgba(213,0,0,.35);
}
/* sponsor tiers */ /* sponsor tiers */
.pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); } .pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); }
.pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; } .pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; }
@@ -227,6 +255,31 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; } .mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; } .row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; }
/* ---------- Column filter (Excel-style, portalled so it isn't clipped) ---------- */
.colfilter { position: relative; display: inline-flex; margin-left: 6px; vertical-align: middle; }
.colfilter-btn {
display: inline-flex; align-items: center; gap: 3px; padding: 3px 6px; border-radius: 7px;
border: 1px solid var(--line); background: var(--surface); color: var(--muted);
cursor: pointer; font: inherit; transition: all .15s ease;
}
.colfilter-btn:hover { border-color: rgba(213,0,0,.4); color: var(--accent); }
.colfilter-btn.on { background: var(--accent-soft); border-color: rgba(213,0,0,.45); color: var(--accent); }
.colfilter-count { font-size: 10px; font-weight: 800; min-width: 14px; text-align: center; }
.colfilter-pop {
position: fixed; z-index: 130; width: 220px; max-height: 300px; overflow-y: auto; padding: 8px;
background: var(--surface); border: 1px solid var(--line); border-radius: 12px;
box-shadow: 0 16px 40px rgba(66,60,60,.22); animation: colfilter-in .14s ease;
}
@keyframes colfilter-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
.colfilter-head { display: flex; align-items: center; justify-content: space-between; padding: 4px 8px 8px; border-bottom: 1px solid var(--line); margin-bottom: 6px; }
.colfilter-head strong { font-size: 12px; text-transform: uppercase; letter-spacing: .4px; color: var(--muted); }
.colfilter-clear { border: none; background: none; color: var(--accent); font-size: 12px; font-weight: 700; cursor: pointer; padding: 2px 4px; }
.colfilter-opt { display: flex; align-items: center; gap: 9px; padding: 7px 8px; border-radius: 8px; cursor: pointer; font-size: 13px; }
.colfilter-opt:hover { background: var(--surface-2); }
.colfilter-opt input { accent-color: var(--accent); width: 15px; height: 15px; cursor: pointer; }
.colfilter-opt .lbl { flex: 1; text-transform: capitalize; }
.colfilter-opt .cnt { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
/* ---------- Modal ---------- */ /* ---------- Modal ---------- */
.backdrop { position: fixed; inset: 0; background: rgba(5,5,10,.6); backdrop-filter: blur(3px); z-index: 70; display: flex; align-items: center; justify-content: center; padding: 20px; } .backdrop { position: fixed; inset: 0; background: rgba(5,5,10,.6); backdrop-filter: blur(3px); z-index: 70; display: flex; align-items: center; justify-content: center; padding: 20px; }
.modal { .modal {
@@ -424,6 +477,11 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.badge-el-placeholder { color: #cbd5e1; font-style: italic; } .badge-el-placeholder { color: #cbd5e1; font-style: italic; }
.badge-align-group { margin-top: 8px; } .badge-align-group { margin-top: 8px; }
.badge-align-group-label { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; } .badge-align-group-label { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
.badge-preview-stage {
display: flex; justify-content: center; align-items: center; padding: 16px;
background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px; min-height: 180px;
}
.badge-page-static { flex: none; }
.badge-qr-body { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } .badge-qr-body { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
.badge-qr-body svg { width: 100%; height: 100%; } .badge-qr-body svg { width: 100%; height: 100%; }
.badge-image-body { width: 100%; height: 100%; display: block; } .badge-image-body { width: 100%; height: 100%; display: block; }
+2 -88
View File
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import { import {
Copy, Copy,
Eye, Eye,
@@ -46,30 +45,11 @@ import type {
} from '../lib/types'; } from '../lib/types';
import { useToast } from '../context/ToastContext'; import { useToast } from '../context/ToastContext';
import { Empty, Spinner } from '../components/ui'; import { Empty, Spinner } from '../components/ui';
import { CONTENT_LABEL, MM, QR_LABEL, BadgeElementBody } from '../components/BadgeRender';
// CSS 96 dpi: 1mm = 3.7795px. Multiplied by the editor zoom.
const MM = 3.7795275591;
const MIN_MM = 2; const MIN_MM = 2;
const FONTS = ['Open Sans', 'Helvetica', 'Arial', 'Georgia', 'Times New Roman', 'Courier New', 'system-ui']; const FONTS = ['Open Sans', 'Helvetica', 'Arial', 'Georgia', 'Times New Roman', 'Courier New', 'system-ui'];
const CONTENT_LABEL: Record<BadgeTextElement['content'], string> = {
attendee_name: 'Attendee name',
full_name: 'Full name',
email: 'Email address',
ticket_type: 'Ticket type',
event_name: 'Event name',
company: 'Company / organizer',
qr_token: 'QR / badge token',
static: 'Static text',
};
const QR_LABEL: Record<BadgeQrElement['value'], string> = {
qr_token: 'QR / badge token',
checkin_url: 'Check-in URL',
email: 'Email address',
attendee_name: 'Attendee name',
static: 'Static value',
};
// Text alignment *within* an element's own box (not the box on the page). // Text alignment *within* an element's own box (not the box on the page).
const ALIGN_H: { v: BadgeTextElement['align_h']; label: string; Icon: typeof AlignLeft }[] = [ const ALIGN_H: { v: BadgeTextElement['align_h']; label: string; Icon: typeof AlignLeft }[] = [
{ v: 'left', label: 'Align text left', Icon: AlignLeft }, { v: 'left', label: 'Align text left', Icon: AlignLeft },
@@ -220,35 +200,6 @@ const add = (a: Vec, b: Vec): Vec => ({ x: a.x + b.x, y: a.y + b.y });
const sub = (a: Vec, b: Vec): Vec => ({ x: a.x - b.x, y: a.y - b.y }); const sub = (a: Vec, b: Vec): Vec => ({ x: a.x - b.x, y: a.y - b.y });
const centerOf = (e: BadgeElement): Vec => ({ x: e.x + e.width / 2, y: e.y + e.height / 2 }); const centerOf = (e: BadgeElement): Vec => ({ x: e.x + e.width / 2, y: e.y + e.height / 2 });
// Resolve the bound content of a text element against a sample attendee.
function resolveText(el: BadgeTextElement, sample: BadgeSample): string {
let v: string;
switch (el.content) {
case 'attendee_name':
case 'full_name': v = sample.full_name; break;
case 'email': v = sample.email; break;
case 'ticket_type': v = sample.ticket_type; break;
case 'event_name': v = sample.event_name; break;
case 'company': v = sample.company; break;
case 'qr_token': v = sample.qr_token; break;
default: v = el.text;
}
if (el.transform === 'uppercase') return v.toUpperCase();
if (el.transform === 'lowercase') return v.toLowerCase();
if (el.transform === 'capitalize') return v.replace(/\b\w/g, (m) => m.toUpperCase());
return v;
}
function resolveQr(el: BadgeQrElement, sample: BadgeSample): string {
switch (el.value) {
case 'qr_token': return sample.qr_token || 'CONVIVO-QR';
case 'checkin_url': return `${window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`;
case 'email': return sample.email || '[email protected]';
case 'attendee_name': return sample.full_name || 'Attendee';
default: return el.static_value || 'https://example.com';
}
}
type Handle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'; type Handle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
const HANDLES: { id: Handle; dir: Vec; css: string }[] = [ const HANDLES: { id: Handle; dir: Vec; css: string }[] = [
{ id: 'nw', dir: { x: -1, y: -1 }, css: 'nw' }, { id: 'nw', dir: { x: -1, y: -1 }, css: 'nw' },
@@ -872,7 +823,7 @@ function BadgeElementView({
style={style} style={style}
onPointerDown={interactive ? (e) => onMove(e, el) : undefined} onPointerDown={interactive ? (e) => onMove(e, el) : undefined}
> >
<ElementBody el={el} sample={sample} pxPerMm={pxPerMm} /> <BadgeElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
{selected && interactive && ( {selected && interactive && (
<> <>
{HANDLES.map((h) => ( {HANDLES.map((h) => (
@@ -890,43 +841,6 @@ function BadgeElementView({
); );
} }
function ElementBody({ el, sample, pxPerMm }: { el: BadgeElement; sample: BadgeSample; pxPerMm: number }) {
if (el.type === 'text') {
const text = resolveText(el, sample);
return (
<div
className="badge-text-body"
style={{
fontFamily: `"${el.font}", sans-serif`,
fontSize: el.font_size * (pxPerMm / MM), // pt→mm→px so print scale matches
lineHeight: el.line_height,
color: el.color,
fontWeight: el.bold ? 700 : 400,
fontStyle: el.italic ? 'italic' : 'normal',
justifyContent: el.align_h === 'left' ? 'flex-start' : el.align_h === 'right' ? 'flex-end' : 'center',
alignItems: el.align_v === 'top' ? 'flex-start' : el.align_v === 'bottom' ? 'flex-end' : 'center',
textAlign: el.align_h,
}}
>
<span>{text || <span className="badge-el-placeholder">{CONTENT_LABEL[el.content]}</span>}</span>
</div>
);
}
if (el.type === 'qr') {
const size = Math.round(Math.min(el.width, el.height) * pxPerMm);
return (
<div className="badge-qr-body">
<QRCodeSVG value={resolveQr(el, sample)} size={Math.max(16, size)} level="M" marginSize={0} />
</div>
);
}
// image
if (!el.src) {
return <div className="badge-image-body badge-image-empty">Image</div>;
}
return <img className="badge-image-body" src={el.src} alt="" style={{ objectFit: el.fit }} />;
}
// ---- properties panel ------------------------------------------------------- // ---- properties panel -------------------------------------------------------
function Num({ label, value, onChange, step = 0.1, min }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number }) { function Num({ label, value, onChange, step = 0.1, min }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number }) {
return ( return (
+42 -12
View File
@@ -2,13 +2,24 @@ import { useEffect, useMemo, useState } from 'react';
import { adjustPoints, deleteContact, getAllContacts, updateContact, upsertContact } from '../lib/api'; import { adjustPoints, deleteContact, getAllContacts, updateContact, upsertContact } from '../lib/api';
import type { Contact } from '../lib/types'; import type { Contact } from '../lib/types';
import { useToast } from '../context/ToastContext'; import { useToast } from '../context/ToastContext';
import { Avatar, Empty, Modal, Spinner, Toggle } from '../components/ui'; import { Avatar, ColumnFilter, Empty, Modal, Spinner, Toggle, type ColumnFilterOption } from '../components/ui';
// Multi-select column filters are Excel-style: an empty selection means "all".
const VIS_LABELS: Record<string, string> = { both: 'Both shown', email: 'Email only', linkedin: 'LinkedIn only', none: 'None shown' };
const visKey = (c: Contact) => (c.show_email && c.show_linkedin ? 'both' : c.show_email ? 'email' : c.show_linkedin ? 'linkedin' : 'none');
const ynOptions = (rows: Contact[], fn: (c: Contact) => boolean): ColumnFilterOption[] => [
{ value: 'yes', label: 'Yes', count: rows.filter(fn).length },
{ value: 'no', label: 'No', count: rows.filter((c) => !fn(c)).length },
];
export function Contacts() { export function Contacts() {
const { push } = useToast(); const { push } = useToast();
const [contacts, setContacts] = useState<Contact[] | null>(null); const [contacts, setContacts] = useState<Contact[] | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const [fLinkedin, setFLinkedin] = useState<string[]>([]);
const [fVis, setFVis] = useState<string[]>([]);
const [fAdmin, setFAdmin] = useState<string[]>([]);
const [editing, setEditing] = useState<Contact | null>(null); const [editing, setEditing] = useState<Contact | null>(null);
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
@@ -41,18 +52,37 @@ export function Contacts() {
load(); load();
}, []); }, []);
const filtered = useMemo(() => { // General search: first name, last name or email address.
const searched = useMemo(() => {
if (!contacts) return []; if (!contacts) return [];
const q = query.trim().toLowerCase(); const q = query.trim().toLowerCase();
if (!q) return contacts; if (!q) return contacts;
return contacts.filter( return contacts.filter((c) => {
(c) => const name = c.full_name.toLowerCase();
c.full_name.toLowerCase().includes(q) || return name.split(/\s+/).some((part) => part.includes(q)) || name.includes(q) || c.email.toLowerCase().includes(q);
c.email.toLowerCase().includes(q) || });
(c.linkedin_url ?? '').toLowerCase().includes(q),
);
}, [contacts, query]); }, [contacts, query]);
const passLinkedin = (c: Contact) => fLinkedin.length === 0 || fLinkedin.includes(c.linkedin_url ? 'yes' : 'no');
const passVis = (c: Contact) => fVis.length === 0 || fVis.includes(visKey(c));
const passAdmin = (c: Contact) => fAdmin.length === 0 || fAdmin.includes(c.is_admin ? 'yes' : 'no');
const filtered = useMemo(
() => searched.filter((c) => passLinkedin(c) && passVis(c) && passAdmin(c)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[searched, fLinkedin, fVis, fAdmin],
);
// Option counts follow Excel: each column counts what the OTHER filters leave.
const linkedinOptions = ynOptions(searched.filter((c) => passVis(c) && passAdmin(c)), (c) => !!c.linkedin_url);
const adminOptions = ynOptions(searched.filter((c) => passLinkedin(c) && passVis(c)), (c) => c.is_admin);
const visCounts = new Map<string, number>();
for (const c of searched.filter((c) => passLinkedin(c) && passAdmin(c))) {
const k = visKey(c);
visCounts.set(k, (visCounts.get(k) ?? 0) + 1);
}
const visOptions = ['both', 'email', 'linkedin', 'none']
.filter((k) => visCounts.has(k))
.map((k) => ({ value: k, label: VIS_LABELS[k], count: visCounts.get(k)! }));
if (error) return <Empty icon="⚠️" text={error} />; if (error) return <Empty icon="⚠️" text={error} />;
if (!contacts) if (!contacts)
return ( return (
@@ -72,7 +102,7 @@ export function Contacts() {
<input <input
className="input" className="input"
style={{ maxWidth: 260 }} style={{ maxWidth: 260 }}
placeholder="Search name, email…" placeholder="Search first name, last name, email…"
value={query} value={query}
onChange={(e) => setQuery(e.target.value)} onChange={(e) => setQuery(e.target.value)}
/> />
@@ -87,9 +117,9 @@ export function Contacts() {
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>LinkedIn</th> <th>LinkedIn <ColumnFilter label="LinkedIn" options={linkedinOptions} selected={fLinkedin} onChange={setFLinkedin} /></th>
<th>Visibility</th> <th>Visibility <ColumnFilter label="Visibility" options={visOptions} selected={fVis} onChange={setFVis} /></th>
<th>Admin</th> <th>Admin <ColumnFilter label="Admin" options={adminOptions} selected={fAdmin} onChange={setFAdmin} /></th>
<th style={{ textAlign: 'right' }}>Actions</th> <th style={{ textAlign: 'right' }}>Actions</th>
</tr> </tr>
</thead> </thead>
+154 -13
View File
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { import {
createRegistration, createRegistration,
deleteContacts, deleteContacts,
getBadgeLayouts,
getAllContacts, getAllContacts,
getAllEvents, getAllEvents,
getActiveEvent, getActiveEvent,
@@ -12,12 +13,18 @@ import {
setRegistrationType, setRegistrationType,
upsertSponsor, upsertSponsor,
} from '../lib/api'; } from '../lib/api';
import type { Contact, Event, Registration, RegistrationType, Sponsor, SponsorType } from '../lib/types'; import type { BadgeLayout, BadgeSample, Contact, Event, Registration, RegistrationType, Sponsor, SponsorType } from '../lib/types';
import { useToast } from '../context/ToastContext'; import { useToast } from '../context/ToastContext';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
import { Avatar, Empty, Modal, QrImage, Spinner, Toggle, TypeBadge } from '../components/ui'; import { Avatar, ColumnFilter, Empty, Modal, QrImage, Spinner, Toggle, Tooltip, TypeBadge, type ColumnFilterOption } from '../components/ui';
import { BadgePagePreview, fitScale } from '../components/BadgeRender';
const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor']; const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor'];
// Multi-select column filters are Excel-style: an empty selection means "all".
const ynOptions = (rows: Registration[], fn: (r: Registration) => boolean): ColumnFilterOption[] => [
{ value: 'yes', label: 'Yes', count: rows.filter(fn).length },
{ value: 'no', label: 'No', count: rows.filter((r) => !fn(r)).length },
];
export function Registrations() { export function Registrations() {
const { push } = useToast(); const { push } = useToast();
@@ -35,12 +42,20 @@ export function Registrations() {
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
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 [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]);
const [fType, setFType] = useState<string[]>([]);
const [fTicket, setFTicket] = useState<string[]>([]);
const [fCheckedIn, setFCheckedIn] = useState<string[]>([]);
const selectedEventId = useRef(selectedId); const selectedEventId = useRef(selectedId);
selectedEventId.current = selectedId; selectedEventId.current = selectedId;
const event = events.find((e) => e.id === selectedId) ?? null; const event = events.find((e) => e.id === selectedId) ?? null;
const eventRegistrations = registrations.filter((registration) => registration.event_id === selectedId); const eventRegistrations = registrations.filter((registration) => registration.event_id === selectedId);
const ticketed = eventRegistrations.filter((registration) => registration.qr_token?.trim()); const ticketed = eventRegistrations.filter((registration) => registration.qr_token?.trim());
// A badge is "configured" once a layout for this event actually has elements;
// an empty layout would render a blank white badge, so treat it as unconfigured.
const badgeConfigured = badgeLayouts.some((l) => Array.isArray(l.elements) && l.elements.length > 0);
async function reloadRegistrations(eventId: string) { async function reloadRegistrations(eventId: string) {
const rows = await getRegistrations(eventId); const rows = await getRegistrations(eventId);
@@ -79,6 +94,11 @@ export function Registrations() {
if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load'); if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
} }
})(); })();
// Badge layouts are best-effort: a failure just leaves the Badge buttons
// disabled (treated as "not configured") rather than breaking the list.
getBadgeLayouts(selectedId)
.then((ls) => { if (!cancelled) setBadgeLayouts(ls); })
.catch(() => { if (!cancelled) setBadgeLayouts([]); });
return () => { return () => {
cancelled = true; cancelled = true;
}; };
@@ -114,21 +134,40 @@ export function Registrations() {
const byEmail = useMemo(() => new Map(contacts.map((c) => [c.email, c])), [contacts]); const byEmail = useMemo(() => new Map(contacts.map((c) => [c.email, c])), [contacts]);
const filtered = useMemo(() => { // General search: first name, last name, email address or type.
if (!registrations) return []; const searched = useMemo(() => {
const q = query.trim().toLowerCase(); const q = query.trim().toLowerCase();
if (!q) return registrations.filter((r) => r.event_id === selectedId); const rows = registrations.filter((r) => r.event_id === selectedId);
return registrations.filter((r) => { if (!q) return rows;
if (r.event_id !== selectedId) return false; return rows.filter((r) => {
const c = byEmail.get(r.contact_email); const name = (byEmail.get(r.contact_email)?.full_name ?? '').toLowerCase();
return ( return (
(c?.full_name ?? '').toLowerCase().includes(q) || name.split(/\s+/).some((part) => part.includes(q)) ||
name.includes(q) ||
r.contact_email.toLowerCase().includes(q) || r.contact_email.toLowerCase().includes(q) ||
r.type.toLowerCase().includes(q) r.type.toLowerCase().includes(q)
); );
}); });
}, [registrations, query, byEmail, selectedId]); }, [registrations, query, byEmail, selectedId]);
const hasTicket = (r: Registration) => !!r.qr_token?.trim();
const passType = (r: Registration) => fType.length === 0 || fType.includes(r.type);
const passTicket = (r: Registration) => fTicket.length === 0 || fTicket.includes(hasTicket(r) ? 'yes' : 'no');
const passCheckedIn = (r: Registration) => fCheckedIn.length === 0 || fCheckedIn.includes(r.checked_in ? 'yes' : 'no');
const filtered = useMemo(
() => searched.filter((r) => passType(r) && passTicket(r) && passCheckedIn(r)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[searched, fType, fTicket, fCheckedIn],
);
// Option counts follow Excel: each column counts what the OTHER filters leave.
const typeCounts = new Map<string, number>();
for (const r of searched.filter((r) => passTicket(r) && passCheckedIn(r))) typeCounts.set(r.type, (typeCounts.get(r.type) ?? 0) + 1);
const typeOptions = [...typeCounts.entries()]
.sort((a, b) => TYPES.indexOf(a[0] as RegistrationType) - TYPES.indexOf(b[0] as RegistrationType))
.map(([value, count]) => ({ value, label: value, count }));
const ticketOptions = ynOptions(searched.filter((r) => passType(r) && passCheckedIn(r)), hasTicket);
const checkedInOptions = ynOptions(searched.filter((r) => passType(r) && passTicket(r)), (r) => r.checked_in);
async function changeType(r: Registration, type: RegistrationType) { async function changeType(r: Registration, type: RegistrationType) {
setBusy(true); setBusy(true);
try { try {
@@ -215,7 +254,7 @@ export function Registrations() {
<input <input
className="input" className="input"
style={{ maxWidth: 220 }} style={{ maxWidth: 220 }}
placeholder="Search name, email, type…" placeholder="Search first name, last name, email, type…"
value={query} value={query}
onChange={(e) => setQuery(e.target.value)} onChange={(e) => setQuery(e.target.value)}
/> />
@@ -233,9 +272,9 @@ export function Registrations() {
<thead> <thead>
<tr> <tr>
<th>Contact</th> <th>Contact</th>
<th>Type</th> <th>Type <ColumnFilter label="Type" options={typeOptions} selected={fType} onChange={setFType} /></th>
<th>QR token</th> <th>QR token <ColumnFilter label="Ticket" options={ticketOptions} selected={fTicket} onChange={setFTicket} /></th>
<th>Checked in</th> <th>Checked in <ColumnFilter label="Checked in" options={checkedInOptions} selected={fCheckedIn} onChange={setFCheckedIn} /></th>
<th style={{ textAlign: 'right' }}>Points</th> <th style={{ textAlign: 'right' }}>Points</th>
</tr> </tr>
</thead> </thead>
@@ -277,6 +316,17 @@ export function Registrations() {
{r.qr_token?.trim() && <button className="btn small" onClick={() => setQrFor(r)}> {r.qr_token?.trim() && <button className="btn small" onClick={() => setQrFor(r)}>
QR QR
</button>} </button>}
{badgeConfigured ? (
<button className="btn small" onClick={() => setBadgeFor(r)} title="Preview this attendee's badge">
Badge
</button>
) : (
<Tooltip title="No badge yet" content="A badge needs to be configured for this event first. Design one in the Badges view.">
<button className="btn small" disabled>
Badge
</button>
</Tooltip>
)}
{!r.qr_token?.trim() && r.import_source === 'sessionize' && ( {!r.qr_token?.trim() && r.import_source === 'sessionize' && (
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}> <button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
Merge tickets Merge tickets
@@ -348,6 +398,16 @@ export function Registrations() {
</Modal> </Modal>
)} )}
{badgeFor && (
<BadgePreviewModal
registration={badgeFor}
contact={byEmail.get(badgeFor.contact_email)}
event={event}
layouts={badgeLayouts}
onClose={() => setBadgeFor(null)}
/>
)}
{sponsorFor && ( {sponsorFor && (
<SponsorLookupModal <SponsorLookupModal
registration={sponsorFor} registration={sponsorFor}
@@ -365,6 +425,87 @@ export function Registrations() {
); );
} }
/** Renders the event's badge layout for one attendee, chosen from its layouts. */
function BadgePreviewModal({ registration, contact, event, layouts, onClose }: {
registration: Registration;
contact?: Contact;
event: Event;
layouts: BadgeLayout[];
onClose: () => void;
}) {
const hasContent = (l: BadgeLayout) => Array.isArray(l.elements) && l.elements.length > 0;
const [layoutName, setLayoutName] = useState(() => {
const def = (layouts.find((l) => l.is_default && hasContent(l)) ?? layouts.find(hasContent) ?? layouts[0]);
return def?.name ?? '';
});
const sample: BadgeSample = {
full_name: contact?.full_name ?? registration.contact_email,
email: registration.contact_email,
ticket_type: registration.type,
qr_token: registration.qr_token ?? '',
event_name: event.name,
company: event.company ?? '',
};
const layout = layouts.find((l) => l.name === layoutName) ?? null;
const name = contact?.full_name ?? registration.contact_email;
// Fit the badge to the stage's real width (responsive) and the viewport height.
const stageRef = useRef<HTMLDivElement>(null);
const [stageW, setStageW] = useState(0);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const measure = () => setStageW(el.clientWidth);
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, [layout]);
const maxH = Math.max(180, Math.min(420, Math.round(window.innerHeight * 0.45)));
const pxPerMm = layout && stageW > 0 ? fitScale(layout, stageW, maxH) : 0;
return (
<Modal
open
title={`Badge — ${name}`}
onClose={onClose}
footer={
<button className="btn primary" onClick={onClose}>
Done
</button>
}
>
{layouts.length === 0 && (
<Empty icon="🎫" text="No badge layout for this event yet. Design one in the Badges view." />
)}
{layouts.length > 0 && !layout && (
<Empty icon="🎫" text="This event's badge layout is empty. Add elements to it in the Badges view." />
)}
{layout && (
<>
{layouts.length > 1 && (
<label className="badge-field">
<span>Layout</span>
<select className="input" value={layoutName} onChange={(e) => setLayoutName(e.target.value)}>
{layouts.map((l) => (
<option key={l.id} value={l.name}>{l.name}{l.is_default ? ' ★' : ''}</option>
))}
</select>
</label>
)}
<div className="badge-preview-stage" ref={stageRef}>
{pxPerMm > 0 && <BadgePagePreview layout={layout} sample={sample} pxPerMm={pxPerMm} />}
</div>
<p className="muted small" style={{ textAlign: 'center' }}>
{layout.name} · {layout.page_width_mm} × {layout.page_height_mm} mm
</p>
</>
)}
</Modal>
);
}
function MergeTicketsModal({ source, contacts, tickets, onClose, onMerged }: { function MergeTicketsModal({ source, contacts, tickets, onClose, onMerged }: {
source: Registration; source: Registration;
contacts: Map<string, Contact>; contacts: Map<string, Contact>;
+43 -2
View File
@@ -19,11 +19,52 @@ layout onto the millimetre canvas with a bound attendee name, adding/selecting a
text element and its handles, editing `x` to move an element, saving via text element and its handles, editing `x` to move an element, saving via
`save_badge_layout`, preview mode hiding the handles, the JSON view, a failed `save_badge_layout`, preview mode hiding the handles, the JSON view, a failed
save, the mobile layout, the **Delete key** removing the selection, binding the save, the mobile layout, the **Delete key** removing the selection, binding the
**company / organizer** field, **align-centre** on the page, and **Shift-click **company / organizer** field, **align-centre** on the page, **Shift-click**
multi-select** for group alignment. No real attendee data changes. multi-select for group alignment, **drag-to-centre smart guides** with snapping,
the labelled **Align text in box** section (its horizontal / vertical buttons
change the rendered text alignment and persist through save and reload), and the
**`Ctrl`+`Z` / `Ctrl`+`Y`** undo / redo shortcuts (ignored while a panel field has
focus). No real attendee data changes.
See [RPC rules](./rpcs.md#badge-editor) and the [Badges view](../frontend/admin-app.md). See [RPC rules](./rpcs.md#badge-editor) and the [Badges view](../frontend/admin-app.md).
# Registration Badge Preview Regression
No migration is involved — the preview reuses the badge layouts above. Run:
```sh
CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- registration-badge-preview.spec.ts --project=chromium
```
The suite is API-mocked and covers a **Badge** button on every registration row,
rendering the default layout with **that row's own** name / ticket type / company
and a real QR SVG, per-attendee isolation (one row never shows another's data),
switching layouts inside the modal, hiding the picker when only one layout
exists, the **disabled (grayed-out) Badge button** when the event has no layout
or only an **empty** one, the hover **tooltip** explaining a badge must be
configured first (portalled to `document.body`, so the table never clips it), a
failed layout load leaving the buttons disabled without breaking the list,
layouts loading **once per event** (reused by every preview, no per-open
request), closing via **Done** and the backdrop, and fitting a mobile viewport.
No real attendee data changes.
# Table Filters Regression
No migration is involved — column filters and search are frontend-only. Run:
```sh
CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- table-filters.spec.ts --project=chromium
```
The suite is API-mocked and covers the **Contacts** and **Registrations** views:
the general search matching **first name / last name / email** (plus **type** on
Registrations), the per-column **multi-select filters** (Contacts: LinkedIn,
Visibility, Admin; Registrations: Type, Ticket, Checked in), filters **combining**
with each other and the search, **live option counts** that follow the other
active filters (Excel-style), the **active-count badge** on a filter button,
**Clear**, and that the dropdown is **portalled to `document.body`** so the
table's `overflow: hidden` never clips it. No real data changes.
# Raffle Regression # Raffle Regression
After applying `20261015180640_raffle`, run: After applying `20261015180640_raffle`, run:
+29 -5
View File
@@ -15,13 +15,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 + recent activity. |
| **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) | | **Contacts** | Table of all contacts (email, name, LinkedIn, visibility toggles, `is_admin`). Edit, toggle `is_admin`, set visibility, adjust points. (No QR token here — it lives on the registration.) A general search matches **first name, last name or email address**; the **LinkedIn**, **Visibility** and **Admin** columns each have an Excel-style **multi-select filter** with live counts. |
| **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset). | | **Registrations** | Per active event: list (contact, type, **QR token**, checked_in, points). Change type (enforces the sponsor rule — a failed sponsor change opens an **in-place sponsor lookup** popup), mark checked-in, **view the QR token** (final — no reset), and **preview the attendee's badge** (renders the event's badge layout with that row's own name / ticket type / QR token / company). When the event has **no badge configured**, the Badge button stays visible but **grayed out**, and hovering it shows a tooltip explaining a badge must be designed first. A general search matches **first name, last name, email address or type**; the **Type**, **QR token** (ticket) and **Checked in** columns each have an Excel-style **multi-select filter** with live counts. |
| **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). | | **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. |
| **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), 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, alignment and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo**, 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). |
| **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. | | **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. |
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. | | **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time — activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
| **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). | | **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). |
@@ -112,13 +112,14 @@ apps/admin/src/
│ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points) │ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points)
│ └─ types.ts # TS types mirroring the DB │ └─ types.ts # TS types mirroring the DB
├─ components/ ├─ components/
│ └─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, TypeBadge, Toggle │ ├─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, TypeBadge, Toggle, Tooltip, ColumnFilter
│ └─ BadgeRender.tsx # shared badge renderer: resolveText/resolveQr, BadgeElementBody, BadgePagePreview, fitScale
├─ screens/ ├─ screens/
│ └─ Login.tsx # email-only magic-link login (admin-only) │ └─ Login.tsx # email-only magic-link login (admin-only)
└─ views/ └─ views/
├─ Dashboard.tsx # active event + aggregates + top points + activity ├─ Dashboard.tsx # active event + aggregates + top points + activity
├─ Contacts.tsx # table + edit / is_admin / visibility / points ├─ Contacts.tsx # table + edit / is_admin / visibility / points
├─ Registrations.tsx# per-event list + type / QR token (view) / checked-in + sponsor lookup ├─ Registrations.tsx# per-event list + type / QR token (view) / badge preview / checked-in + sponsor lookup
├─ Sponsors.tsx # sponsor CRUD ├─ Sponsors.tsx # sponsor CRUD
├─ Schedule.tsx # slots + sessions + speakers + material ├─ Schedule.tsx # slots + sessions + speakers + material
├─ Activity.tsx # check-ins / connections / feedback tables ├─ Activity.tsx # check-ins / connections / feedback tables
@@ -156,6 +157,29 @@ opens a modal with the scannable code. The token is **final** — it is generate
per event and can't be reset from the UI (the `reset_registration_qr_token` RPC per event and can't be reset from the UI (the `reset_registration_qr_token` RPC
still exists, but the admin UI no longer exposes a reset action). still exists, but the admin UI no longer exposes a reset action).
### Previewing a badge
Every registration row also has a **Badge** button. It opens a modal that renders
the event's **badge layout** for that specific attendee — the same millimetre
markup the Badges editor draws, minus the editing chrome — so the bound fields
resolve against that row's own **name**, **ticket type**, **QR token**, plus the
event's **name** and **company / organizer**. The event's layouts are loaded with
the list (one request per event, reused by every preview); when an event has
several layouts a **Layout** dropdown picks between them (the default is
preselected), and the badge is scaled to fit the dialog on any viewport.
A badge counts as **configured** only when a layout for the event actually has
elements — an empty layout would render a blank white badge. When nothing is
configured, the **Badge** button is still shown on every row but **disabled**
(grayed out, not clickable), and hovering or focusing it reveals a tooltip —
*“A badge needs to be configured for this event first. Design one in the Badges
view.”* — pointing the admin to the **Badges** view. The tooltip is the shared
`Tooltip` component in `components/ui.tsx`: the Uiverse dark-glass card already
used in Interfaces, re-themed to the APPE red accent and rendered through a
portal so it is never clipped by the table's `overflow: hidden`. The shared badge
renderer lives in `components/BadgeRender.tsx`, used by both the editor and this
preview.
### Sponsor lookup (in-place) ### Sponsor lookup (in-place)
Setting a registration's type to **Sponsor** requires a sponsor lookup. If none Setting a registration's type to **Sponsor** requires a sponsor lookup. If none
@@ -0,0 +1,214 @@
import { test, expect, type Page } from '@playwright/test';
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const user = { id: '99999999-9999-4999-8999-999999999999', email: '[email protected]', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
const jane = { id: '11111111-1111-4111-8111-111111111111', event_id: eventId, contact_email: '[email protected]', type: 'attendee', qr_token: 'CV-JANE-01', external_id: null, import_source: null, checked_in: false, points: 0 };
const sam = { id: '22222222-2222-4222-8222-222222222222', event_id: eventId, contact_email: '[email protected]', type: 'speaker', qr_token: 'CV-SAM-02', external_id: null, import_source: null, checked_in: true, points: 12 };
function layout(name: string, isDefault: boolean, elements: Record<string, unknown>[]) {
return {
id: `l-${name.toLowerCase()}`, event_id: eventId, name, is_default: isDefault,
page_width_mm: 100, page_height_mm: 70, created_at: '2026-10-23T10:00:00Z', updated_at: '2026-10-23T10:00:00Z', elements,
};
}
const textEl = (id: string, content: string, extra: Record<string, unknown> = {}) => ({
id, type: 'text', x: 8, y: 8, width: 60, height: 12, rotation: 0, content, text: 'fallback',
font: 'Open Sans', font_size: 14, line_height: 1.2, color: '#000000', bold: false, italic: false,
align_h: 'left', align_v: 'middle', transform: 'none', ...extra,
});
const qrEl = (id: string, value: string) => ({ id, type: 'qr', x: 70, y: 40, width: 24, height: 24, rotation: 0, value, static_value: '' });
interface Options { layouts?: Record<string, unknown>[]; failLayouts?: boolean; }
async function openRegistrations(page: Page, options: Options = {}) {
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'mock-refresh-token', expires_in: 3600, token_type: 'bearer' };
const event = { id: eventId, name: 'Badge Conference', company: 'Austrian Power Platform Enthusiasts', is_active: true, start_date: '2026-10-23', end_date: '2026-10-23', num_registrations: 2, num_checked_in_registrations: 1, num_sessions: 0, num_speakers: 1 };
const contacts = [
{ email: user.email, full_name: 'Admin', is_admin: true },
{ email: '[email protected]', full_name: 'Jane Attendee', is_admin: false },
{ email: '[email protected]', full_name: 'Sam Speaker', is_admin: false },
];
const layouts = options.layouts ?? [
layout('Default', true, [textEl('t-name', 'attendee_name'), textEl('t-type', 'ticket_type', { y: 24 }), textEl('t-company', 'company', { y: 40 }), qrEl('q1', 'qr_token')]),
layout('Compact', false, [textEl('c-name', 'full_name'), qrEl('cq', 'checkin_url')]),
];
let layoutRequests = 0;
await page.route('**/auth/v1/**', (route) => route.fulfill({ json: new URL(route.request().url()).pathname.endsWith('/user') ? user : session }));
await page.route('**/rest/v1/**', (route) => {
const url = new URL(route.request().url());
const table = url.pathname.split('/').pop();
if (table === 'badge_layouts') {
layoutRequests += 1;
if (options.failLayouts) return route.fulfill({ status: 500, json: { message: 'layouts unavailable' } });
return route.fulfill({ json: layouts });
}
if (table === 'registrations') return route.fulfill({ json: [jane, sam] });
if (table === 'contacts') return route.fulfill({ json: url.searchParams.has('email') ? contacts[0] : contacts });
if (table === 'events') return route.fulfill({ json: url.searchParams.has('is_active') ? event : [event] });
return route.fulfill({ json: [] });
});
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
// The nav only renders once auth resolves; "Sign out" is hidden on mobile widths.
const registrationsNav = page.locator('.nav').getByRole('button', { name: /Registrations/ });
await expect(registrationsNav).toBeVisible();
await registrationsNav.click();
await expect(page.getByRole('row').filter({ hasText: '[email protected]' })).toBeVisible();
return { layoutRequestCount: () => layoutRequests };
}
const row = (page: Page, email: string) => page.getByRole('row').filter({ hasText: email });
test('every registration row offers a Badge preview button', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page);
await expect(row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true })).toBeVisible();
await expect(row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true })).toBeVisible();
});
test('the badge preview renders the attendee data on the default layout', async ({ page }, testInfo) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page);
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Badge — Jane Attendee' });
await expect(dialog).toBeVisible();
const stage = dialog.locator('.badge-preview-stage');
await expect(stage).toBeVisible();
// Bound fields resolve against THIS attendee, not the editor's demo sample.
await expect(stage).toContainText('Jane Attendee');
await expect(stage).toContainText('attendee');
await expect(stage).toContainText('Austrian Power Platform Enthusiasts');
// The QR element renders an actual SVG code.
await expect(stage.locator('.badge-qr-body svg')).toHaveCount(1);
await expect(dialog.getByText('Default · 100 × 70 mm')).toBeVisible();
await page.screenshot({ path: testInfo.outputPath('badge-preview-jane.png'), fullPage: true });
});
test('the preview is per-attendee: a different row shows different data', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page);
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
const stage = page.getByRole('dialog', { name: 'Badge — Sam Speaker' }).locator('.badge-preview-stage');
await expect(stage).toContainText('Sam Speaker');
await expect(stage).toContainText('speaker');
await expect(stage).not.toContainText('Jane Attendee');
});
test('layouts can be switched inside the preview', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page);
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Badge — Jane Attendee' });
await expect(dialog.getByLabel('Layout')).toHaveValue('Default');
await dialog.getByLabel('Layout').selectOption('Compact');
await expect(dialog.getByText('Compact · 100 × 70 mm')).toBeVisible();
// Compact has no company element, so the organizer text disappears.
await expect(dialog.locator('.badge-preview-stage')).not.toContainText('Austrian Power Platform Enthusiasts');
});
test('a single layout hides the layout picker', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page, { layouts: [layout('Default', true, [textEl('t-name', 'attendee_name')])] });
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Badge — Jane Attendee' });
await expect(dialog.locator('.badge-preview-stage')).toContainText('Jane Attendee');
await expect(dialog.getByLabel('Layout')).toHaveCount(0);
});
test('with no layout configured, the Badge button is shown but disabled', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page, { layouts: [] });
const badge = row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true });
await expect(badge).toBeVisible();
await expect(badge).toBeDisabled();
// Clicking the disabled button opens nothing.
await badge.click({ force: true });
await expect(page.getByRole('dialog', { name: 'Badge — Jane Attendee' })).toHaveCount(0);
});
test('an empty layout (blank white badge) also disables the Badge button', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page, { layouts: [layout('Default', true, [])] });
const badge = row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true });
await expect(badge).toBeVisible();
await expect(badge).toBeDisabled();
});
test('hovering a disabled Badge button reveals the configure-first tooltip', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page, { layouts: [] });
const badge = row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true });
await expect(badge).toBeDisabled();
// The card is not in the DOM until hover (it is portalled to <body>).
await expect(page.getByRole('tooltip')).toHaveCount(0);
// The wrapper carries the hover, since the disabled button is hit-test-transparent.
await badge.locator('xpath=ancestor::span[contains(@class,"tip-anchor")]').hover();
const tip = page.getByRole('tooltip');
await expect(tip).toBeVisible();
await expect(tip).toContainText('No badge yet');
await expect(tip).toContainText('A badge needs to be configured for this event first. Design one in the Badges view.');
// It renders on document.body, so the table's overflow never clips it.
await expect(tip.locator('xpath=ancestor::body')).toHaveCount(1);
await page.mouse.move(5, 5);
await expect(page.getByRole('tooltip')).toHaveCount(0);
});
test('a configured Badge button has no tooltip and stays clickable', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page);
const badge = row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true });
await expect(badge).toBeEnabled();
await badge.hover();
await expect(page.getByRole('tooltip')).toHaveCount(0);
});
test('a failed layout load leaves the buttons disabled without breaking the list', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page, { failLayouts: true });
// The registrations table still renders normally.
await expect(row(page, '[email protected]')).toBeVisible();
await expect(row(page, '[email protected]')).toBeVisible();
await expect(row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true })).toBeDisabled();
});
test('layouts load once for the list, not per preview', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
const state = await openRegistrations(page);
// StrictMode double-invokes effects in dev, so the list load may fetch twice.
const afterLoad = state.layoutRequestCount();
expect(afterLoad).toBeGreaterThanOrEqual(1);
expect(afterLoad).toBeLessThanOrEqual(2);
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
await expect(page.getByRole('dialog', { name: 'Badge — Jane Attendee' })).toBeVisible();
// Opening the modal reuses the already-loaded layouts — no extra request.
expect(state.layoutRequestCount()).toBe(afterLoad);
});
test('the preview closes via Done and the backdrop', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openRegistrations(page);
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Badge — Jane Attendee' });
await dialog.getByRole('button', { name: 'Done' }).click();
await expect(dialog).toHaveCount(0);
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
await expect(page.getByRole('dialog', { name: 'Badge — Sam Speaker' })).toBeVisible();
await page.mouse.click(10, 10); // backdrop
await expect(page.getByRole('dialog', { name: 'Badge — Sam Speaker' })).toHaveCount(0);
});
test('the badge preview fits a mobile viewport', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await openRegistrations(page);
await row(page, '[email protected]').getByRole('button', { name: 'Badge', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Badge — Jane Attendee' });
await expect(dialog.locator('.badge-preview-stage')).toContainText('Jane Attendee');
const box = await dialog.locator('.badge-page').boundingBox();
expect(box).not.toBeNull();
expect(box!.width).toBeLessThanOrEqual(390);
});
+175
View File
@@ -0,0 +1,175 @@
import { test, expect, type Page } from '@playwright/test';
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const user = { id: '99999999-9999-4999-8999-999999999999', email: '[email protected]', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
const contacts = [
{ email: '[email protected]', full_name: 'Admin User', linkedin_url: null, show_email: true, show_linkedin: true, is_admin: true, created_at: 'x' },
{ email: '[email protected]', full_name: 'Jane Doe', linkedin_url: 'https://linkedin.com/in/janedoe', show_email: true, show_linkedin: false, is_admin: false, created_at: 'x' },
{ email: '[email protected]', full_name: 'John Doe', linkedin_url: null, show_email: false, show_linkedin: false, is_admin: false, created_at: 'x' },
{ email: '[email protected]', full_name: 'Amy Doe', linkedin_url: 'https://linkedin.com/in/amydoe', show_email: true, show_linkedin: true, is_admin: false, created_at: 'x' },
{ email: '[email protected]', full_name: 'Sam Roe', linkedin_url: null, show_email: false, show_linkedin: true, is_admin: false, created_at: 'x' },
];
const registrations = [
{ id: 'r1', event_id: eventId, contact_email: '[email protected]', type: 'attendee', qr_token: 'CV-JANE-01', external_id: null, import_source: null, checked_in: true, points: 5 },
{ id: 'r2', event_id: eventId, contact_email: '[email protected]', type: 'speaker', qr_token: 'CV-JOHN-02', external_id: null, import_source: null, checked_in: false, points: 12 },
{ id: 'r3', event_id: eventId, contact_email: '[email protected]', type: 'attendee', qr_token: null, external_id: null, import_source: 'sessionize', checked_in: false, points: 0 },
{ id: 'r4', event_id: eventId, contact_email: '[email protected]', type: 'staff', qr_token: 'CV-SAM-04', external_id: null, import_source: null, checked_in: true, points: 2 },
];
const event = { id: eventId, name: 'Filter Conference', company: 'APPE', is_active: true, start_date: '2026-11-01', end_date: '2026-11-01', num_registrations: 4, num_checked_in_registrations: 2, num_sessions: 0, num_speakers: 1 };
const layouts = [{ id: 'l1', event_id: eventId, name: 'Default', is_default: true, page_width_mm: 100, page_height_mm: 70, created_at: 'x', updated_at: 'x', elements: [{ id: 't1', type: 'text', x: 8, y: 8, width: 60, height: 12, rotation: 0, content: 'attendee_name', text: '', font: 'Open Sans', font_size: 14, line_height: 1.2, color: '#000', bold: false, italic: false, align_h: 'left', align_v: 'middle', transform: 'none' }] }];
async function openAdmin(page: Page, view: 'Contacts' | 'Registrations') {
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'r', expires_in: 3600, token_type: 'bearer' };
await page.route('**/auth/v1/**', (r) => r.fulfill({ json: new URL(r.request().url()).pathname.endsWith('/user') ? user : session }));
await page.route('**/rest/v1/**', (r) => {
const u = new URL(r.request().url());
const t = u.pathname.split('/').pop();
if (t === 'contacts') return r.fulfill({ json: u.searchParams.has('email') ? contacts[0] : contacts });
if (t === 'registrations') return r.fulfill({ json: registrations });
if (t === 'badge_layouts') return r.fulfill({ json: layouts });
if (t === 'events') return r.fulfill({ json: u.searchParams.has('is_active') ? event : [event] });
return r.fulfill({ json: [] });
});
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=r&type=magiclink`);
await page.locator('.nav').getByRole('button', { name: new RegExp(view) }).click();
}
// Open the portalled filter popover for a column header and pick an option.
// (Checkbox names include the live count, e.g. "Yes 2", hence the \b regex.)
async function pickFilter(page: Page, column: string, option: string) {
await page.getByRole('button', { name: `Filter ${column}` }).click();
await page.getByRole('group', { name: `Filter ${column}` }).getByRole('checkbox', { name: new RegExp(`^${option}\\b`) }).check();
}
const closePopover = (page: Page) => page.mouse.click(700, 860);
test.describe('contacts column filters + search', () => {
test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openAdmin(page, 'Contacts');
await expect(page.getByRole('row').filter({ hasText: '[email protected]' })).toBeVisible();
});
test('search matches first name, last name and email', async ({ page }) => {
await expect(page.locator('table.data tbody tr')).toHaveCount(5);
await page.getByPlaceholder(/Search first name/).fill('jane');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
await expect(page.locator('table.data tbody tr')).toContainText('Jane Doe');
await page.getByPlaceholder(/Search first name/).fill('doe');
await expect(page.locator('table.data tbody tr')).toHaveCount(3); // Jane, John, Amy
await page.getByPlaceholder(/Search first name/).fill('sam.roe@');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
await expect(page.locator('table.data tbody tr')).toContainText('Sam Roe');
});
test('LinkedIn filter narrows to rows with / without a profile', async ({ page }) => {
await pickFilter(page, 'LinkedIn', 'Yes');
await expect(page.locator('table.data tbody tr')).toHaveCount(2); // Jane + Amy
await page.getByRole('group', { name: 'Filter LinkedIn' }).getByRole('checkbox', { name: /^No\b/ }).check();
await expect(page.locator('table.data tbody tr')).toHaveCount(5); // Yes+No = all
await closePopover(page);
await page.getByRole('button', { name: 'Filter LinkedIn' }).click();
await page.getByRole('group', { name: 'Filter LinkedIn' }).getByRole('button', { name: 'Clear' }).click();
await closePopover(page);
await expect(page.locator('table.data tbody tr')).toHaveCount(5);
});
test('Admin filter shows only admins', async ({ page }) => {
await pickFilter(page, 'Admin', 'Yes');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
await expect(page.locator('table.data tbody tr')).toContainText('Admin User');
});
test('Visibility filter matches the shown combination', async ({ page }) => {
await pickFilter(page, 'Visibility', 'None shown');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
await expect(page.locator('table.data tbody tr')).toContainText('John Doe');
});
test('filters combine with the search bar', async ({ page }) => {
await page.getByPlaceholder(/Search first name/).fill('doe');
await pickFilter(page, 'LinkedIn', 'Yes');
await expect(page.locator('table.data tbody tr')).toHaveCount(2); // Jane + Amy (not John)
});
test('filter dropdown shows live counts and an active badge on the button', async ({ page }) => {
await page.getByRole('button', { name: 'Filter LinkedIn' }).click();
const pop = page.getByRole('group', { name: 'Filter LinkedIn' });
await expect(pop.getByRole('checkbox', { name: /^Yes\b/ })).not.toBeChecked();
await expect(pop.locator('.cnt').first()).toHaveText('2');
await expect(pop.locator('.cnt').nth(1)).toHaveText('3');
await pop.getByRole('checkbox', { name: /^Yes\b/ }).check();
await closePopover(page);
await expect(page.getByRole('button', { name: 'Filter LinkedIn' })).toContainText('1');
});
test('the popover escapes the table overflow (portalled to body)', async ({ page }) => {
await page.getByRole('button', { name: 'Filter Visibility' }).click();
const pop = page.getByRole('group', { name: 'Filter Visibility' });
await expect(pop).toBeVisible();
await expect(pop.locator('xpath=ancestor::body')).toHaveCount(1);
});
});
test.describe('registrations column filters + search', () => {
test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openAdmin(page, 'Registrations');
await expect(page.getByRole('row').filter({ hasText: '[email protected]' })).toBeVisible();
});
test('search matches name, email and type', async ({ page }) => {
await expect(page.locator('table.data tbody tr')).toHaveCount(4);
await page.getByPlaceholder(/Search first name/).fill('speaker');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
await expect(page.locator('table.data tbody tr')).toContainText('John Doe');
await page.getByPlaceholder(/Search first name/).fill('amy');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
});
test('Type filter narrows rows and supports multiple types', async ({ page }) => {
await pickFilter(page, 'Type', 'attendee');
await expect(page.locator('table.data tbody tr')).toHaveCount(2);
await page.getByRole('group', { name: 'Filter Type' }).getByRole('checkbox', { name: /^staff\b/ }).check();
await expect(page.locator('table.data tbody tr')).toHaveCount(3);
});
test('Ticket filter separates rows with and without QR', async ({ page }) => {
await pickFilter(page, 'Ticket', 'No');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
await expect(page.locator('table.data tbody tr')).toContainText('[email protected]');
});
test('Checked-in filter matches the toggle state', async ({ page }) => {
await pickFilter(page, 'Checked in', 'Yes');
await expect(page.locator('table.data tbody tr')).toHaveCount(2);
const body = page.locator('table.data tbody');
await expect(body).toContainText('[email protected]');
await expect(body).toContainText('[email protected]');
});
test('filters combine with each other and the search', async ({ page }) => {
await pickFilter(page, 'Type', 'attendee');
await closePopover(page);
await pickFilter(page, 'Checked in', 'Yes');
await expect(page.locator('table.data tbody tr')).toHaveCount(1);
await expect(page.locator('table.data tbody tr')).toContainText('Jane Doe');
await closePopover(page);
await page.getByPlaceholder(/Search first name/).fill('sam');
await expect(page.locator('table.data tbody tr')).toHaveCount(0);
await expect(page.getByText('No registrations yet')).toBeVisible();
});
test('type counts reflect the other active filters (Excel-style)', async ({ page }) => {
await pickFilter(page, 'Checked in', 'Yes');
await closePopover(page);
await page.getByRole('button', { name: 'Filter Type' }).click();
const pop = page.getByRole('group', { name: 'Filter Type' });
// Only checked-in rows count: attendee 1, staff 1, speaker 0 (hidden).
await expect(pop.getByRole('checkbox', { name: /^attendee\b/ })).toBeVisible();
await expect(pop.locator('.cnt').first()).toHaveText('1');
await expect(pop.getByRole('checkbox', { name: /^speaker\b/ })).toHaveCount(0);
});
});