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

+2 -88
View File
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import {
Copy,
Eye,
@@ -46,30 +45,11 @@ import type {
} from '../lib/types';
import { useToast } from '../context/ToastContext';
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 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).
const ALIGN_H: { v: BadgeTextElement['align_h']; label: string; Icon: typeof 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 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';
const HANDLES: { id: Handle; dir: Vec; css: string }[] = [
{ id: 'nw', dir: { x: -1, y: -1 }, css: 'nw' },
@@ -872,7 +823,7 @@ function BadgeElementView({
style={style}
onPointerDown={interactive ? (e) => onMove(e, el) : undefined}
>
<ElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
<BadgeElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
{selected && interactive && (
<>
{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 -------------------------------------------------------
function Num({ label, value, onChange, step = 0.1, min }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number }) {
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 type { Contact } from '../lib/types';
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() {
const { push } = useToast();
const [contacts, setContacts] = useState<Contact[] | null>(null);
const [error, setError] = useState<string | null>(null);
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 [creating, setCreating] = useState(false);
@@ -41,18 +52,37 @@ export function Contacts() {
load();
}, []);
const filtered = useMemo(() => {
// General search: first name, last name or email address.
const searched = useMemo(() => {
if (!contacts) return [];
const q = query.trim().toLowerCase();
if (!q) return contacts;
return contacts.filter(
(c) =>
c.full_name.toLowerCase().includes(q) ||
c.email.toLowerCase().includes(q) ||
(c.linkedin_url ?? '').toLowerCase().includes(q),
);
return contacts.filter((c) => {
const name = c.full_name.toLowerCase();
return name.split(/\s+/).some((part) => part.includes(q)) || name.includes(q) || c.email.toLowerCase().includes(q);
});
}, [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 (!contacts)
return (
@@ -72,7 +102,7 @@ export function Contacts() {
<input
className="input"
style={{ maxWidth: 260 }}
placeholder="Search name, email…"
placeholder="Search first name, last name, email…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -87,9 +117,9 @@ export function Contacts() {
<thead>
<tr>
<th>Name</th>
<th>LinkedIn</th>
<th>Visibility</th>
<th>Admin</th>
<th>LinkedIn <ColumnFilter label="LinkedIn" options={linkedinOptions} selected={fLinkedin} onChange={setFLinkedin} /></th>
<th>Visibility <ColumnFilter label="Visibility" options={visOptions} selected={fVis} onChange={setFVis} /></th>
<th>Admin <ColumnFilter label="Admin" options={adminOptions} selected={fAdmin} onChange={setFAdmin} /></th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
+154 -13
View File
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import {
createRegistration,
deleteContacts,
getBadgeLayouts,
getAllContacts,
getAllEvents,
getActiveEvent,
@@ -12,12 +13,18 @@ import {
setRegistrationType,
upsertSponsor,
} 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 { 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'];
// 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() {
const { push } = useToast();
@@ -35,12 +42,20 @@ export function Registrations() {
const [busy, setBusy] = useState(false);
const [deletingAll, setDeletingAll] = useState(false);
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);
selectedEventId.current = selectedId;
const event = events.find((e) => e.id === selectedId) ?? null;
const eventRegistrations = registrations.filter((registration) => registration.event_id === selectedId);
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) {
const rows = await getRegistrations(eventId);
@@ -79,6 +94,11 @@ export function Registrations() {
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 () => {
cancelled = true;
};
@@ -114,21 +134,40 @@ export function Registrations() {
const byEmail = useMemo(() => new Map(contacts.map((c) => [c.email, c])), [contacts]);
const filtered = useMemo(() => {
if (!registrations) return [];
// General search: first name, last name, email address or type.
const searched = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return registrations.filter((r) => r.event_id === selectedId);
return registrations.filter((r) => {
if (r.event_id !== selectedId) return false;
const c = byEmail.get(r.contact_email);
const rows = registrations.filter((r) => r.event_id === selectedId);
if (!q) return rows;
return rows.filter((r) => {
const name = (byEmail.get(r.contact_email)?.full_name ?? '').toLowerCase();
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.type.toLowerCase().includes(q)
);
});
}, [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) {
setBusy(true);
try {
@@ -215,7 +254,7 @@ export function Registrations() {
<input
className="input"
style={{ maxWidth: 220 }}
placeholder="Search name, email, type…"
placeholder="Search first name, last name, email, type…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -233,9 +272,9 @@ export function Registrations() {
<thead>
<tr>
<th>Contact</th>
<th>Type</th>
<th>QR token</th>
<th>Checked in</th>
<th>Type <ColumnFilter label="Type" options={typeOptions} selected={fType} onChange={setFType} /></th>
<th>QR token <ColumnFilter label="Ticket" options={ticketOptions} selected={fTicket} onChange={setFTicket} /></th>
<th>Checked in <ColumnFilter label="Checked in" options={checkedInOptions} selected={fCheckedIn} onChange={setFCheckedIn} /></th>
<th style={{ textAlign: 'right' }}>Points</th>
</tr>
</thead>
@@ -277,6 +316,17 @@ export function Registrations() {
{r.qr_token?.trim() && <button className="btn small" onClick={() => setQrFor(r)}>
QR
</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' && (
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
Merge tickets
@@ -348,6 +398,16 @@ export function Registrations() {
</Modal>
)}
{badgeFor && (
<BadgePreviewModal
registration={badgeFor}
contact={byEmail.get(badgeFor.contact_email)}
event={event}
layouts={badgeLayouts}
onClose={() => setBadgeFor(null)}
/>
)}
{sponsorFor && (
<SponsorLookupModal
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 }: {
source: Registration;
contacts: Map<string, Contact>;