diff --git a/apps/admin/src/components/BadgeRender.tsx b/apps/admin/src/components/BadgeRender.tsx new file mode 100644 index 0000000..3855235 --- /dev/null +++ b/apps/admin/src/components/BadgeRender.tsx @@ -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 = { + 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 = { + 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 || 'attendee@example.com'; + 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 ( +
+ {text || {CONTENT_LABEL[el.content]}} +
+ ); + } + if (el.type === 'qr') { + const size = Math.round(Math.min(el.width, el.height) * pxPerMm); + return ( +
+ +
+ ); + } + // image + if (!el.src) { + return
Image
; + } + return ; +} + +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 ( +
+ {layout.elements.map((el) => ( +
+ +
+ ))} +
+ ); +} + +/** 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); +} diff --git a/apps/admin/src/components/ui.tsx b/apps/admin/src/components/ui.tsx index 4c8a407..24f5fc1 100644 --- a/apps/admin/src/components/ui.tsx +++ b/apps/admin/src/components/ui.tsx @@ -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'; const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777']; @@ -108,3 +110,139 @@ export function Toggle({ ); } + +/** + * 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(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 ( + + {child} + {pos && createPortal( + , + document.body, + )} + + ); +} + +/** 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(null); + const popRef = useRef(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 ( + + + {open && pos && createPortal( +
+
+ {label} + {active && } +
+ {options.map((o) => ( + + ))} +
, + document.body, + )} +
+ ); +} diff --git a/apps/admin/src/styles.css b/apps/admin/src/styles.css index c2dd3ed..3decb7e 100644 --- a/apps/admin/src/styles.css +++ b/apps/admin/src/styles.css @@ -171,6 +171,34 @@ body { .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 .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 */ .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; } @@ -227,6 +255,31 @@ table.data tr:hover td { background: rgba(244,245,249,.6); } .mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; } .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 ---------- */ .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 { @@ -424,6 +477,11 @@ table.data tr:hover td { background: rgba(244,245,249,.6); } .badge-el-placeholder { color: #cbd5e1; font-style: italic; } .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-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 svg { width: 100%; height: 100%; } .badge-image-body { width: 100%; height: 100%; display: block; } diff --git a/apps/admin/src/views/BadgeEditor.tsx b/apps/admin/src/views/BadgeEditor.tsx index 3ab6835..6e0656e 100644 --- a/apps/admin/src/views/BadgeEditor.tsx +++ b/apps/admin/src/views/BadgeEditor.tsx @@ -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 = { - 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 = { - 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 || 'attendee@example.com'; - 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} > - + {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 ( -
- {text || {CONTENT_LABEL[el.content]}} -
- ); - } - if (el.type === 'qr') { - const size = Math.round(Math.min(el.width, el.height) * pxPerMm); - return ( -
- -
- ); - } - // image - if (!el.src) { - return
Image
; - } - return ; -} - // ---- properties panel ------------------------------------------------------- function Num({ label, value, onChange, step = 0.1, min }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number }) { return ( diff --git a/apps/admin/src/views/Contacts.tsx b/apps/admin/src/views/Contacts.tsx index ac1d54c..e1a18cd 100644 --- a/apps/admin/src/views/Contacts.tsx +++ b/apps/admin/src/views/Contacts.tsx @@ -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 = { 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(null); const [error, setError] = useState(null); const [query, setQuery] = useState(''); + const [fLinkedin, setFLinkedin] = useState([]); + const [fVis, setFVis] = useState([]); + const [fAdmin, setFAdmin] = useState([]); const [editing, setEditing] = useState(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(); + 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 ; if (!contacts) return ( @@ -72,7 +102,7 @@ export function Contacts() { setQuery(e.target.value)} /> @@ -87,9 +117,9 @@ export function Contacts() { Name - LinkedIn - Visibility - Admin + LinkedIn + Visibility + Admin Actions diff --git a/apps/admin/src/views/Registrations.tsx b/apps/admin/src/views/Registrations.tsx index 6c62c1c..1d483d3 100644 --- a/apps/admin/src/views/Registrations.tsx +++ b/apps/admin/src/views/Registrations.tsx @@ -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(null); + const [badgeFor, setBadgeFor] = useState(null); + const [badgeLayouts, setBadgeLayouts] = useState([]); + const [fType, setFType] = useState([]); + const [fTicket, setFTicket] = useState([]); + const [fCheckedIn, setFCheckedIn] = useState([]); 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(); + 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() { setQuery(e.target.value)} /> @@ -233,9 +272,9 @@ export function Registrations() { Contact - Type - QR token - Checked in + Type + QR token + Checked in Points @@ -277,6 +316,17 @@ export function Registrations() { {r.qr_token?.trim() && } + {badgeConfigured ? ( + + ) : ( + + + + )} {!r.qr_token?.trim() && r.import_source === 'sessionize' && ( + } + > + {layouts.length === 0 && ( + + )} + {layouts.length > 0 && !layout && ( + + )} + {layout && ( + <> + {layouts.length > 1 && ( + + )} +
+ {pxPerMm > 0 && } +
+

+ {layout.name} · {layout.page_width_mm} × {layout.page_height_mm} mm +

+ + )} + + ); +} + function MergeTicketsModal({ source, contacts, tickets, onClose, onMerged }: { source: Registration; contacts: Map; diff --git a/docs/backend/tests.md b/docs/backend/tests.md index 7f1b0fd..8742c1b 100644 --- a/docs/backend/tests.md +++ b/docs/backend/tests.md @@ -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 `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 -**company / organizer** field, **align-centre** on the page, and **Shift-click -multi-select** for group alignment. No real attendee data changes. +**company / organizer** field, **align-centre** on the page, **Shift-click** +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). +# 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 After applying `20261015180640_raffle`, run: diff --git a/docs/frontend/admin-app.md b/docs/frontend/admin-app.md index a217427..aafeceb 100644 --- a/docs/frontend/admin-app.md +++ b/docs/frontend/admin-app.md @@ -15,13 +15,13 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container | View | Purpose | |---|---| | **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.) | -| **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). | +| **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), 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**). | | **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. | | **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. | | **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). | @@ -112,13 +112,14 @@ apps/admin/src/ │ ├─ api.ts # typed wrapper: reads + writes (contacts, registrations, sponsors, schedule, points) │ └─ types.ts # TS types mirroring the DB ├─ 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/ │ └─ Login.tsx # email-only magic-link login (admin-only) └─ views/ ├─ Dashboard.tsx # active event + aggregates + top points + activity ├─ 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 ├─ Schedule.tsx # slots + sessions + speakers + material ├─ 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 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) Setting a registration's type to **Sponsor** requires a sponsor lookup. If none diff --git a/e2e/tests/registration-badge-preview.spec.ts b/e2e/tests/registration-badge-preview.spec.ts new file mode 100644 index 0000000..befe40b --- /dev/null +++ b/e2e/tests/registration-badge-preview.spec.ts @@ -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: 'admin@appe.at', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} }; + +const jane = { id: '11111111-1111-4111-8111-111111111111', event_id: eventId, contact_email: 'jane@example.com', 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: 'sam@example.com', 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[]) { + 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 = {}) => ({ + 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[]; 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: 'jane@example.com', full_name: 'Jane Attendee', is_admin: false }, + { email: 'sam@example.com', 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: 'jane@example.com' })).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, 'jane@example.com').getByRole('button', { name: 'Badge', exact: true })).toBeVisible(); + await expect(row(page, 'sam@example.com').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, 'jane@example.com').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, 'sam@example.com').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, 'jane@example.com').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, 'jane@example.com').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, 'jane@example.com').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, 'jane@example.com').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, 'jane@example.com').getByRole('button', { name: 'Badge', exact: true }); + await expect(badge).toBeDisabled(); + // The card is not in the DOM until hover (it is portalled to ). + 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, 'jane@example.com').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, 'jane@example.com')).toBeVisible(); + await expect(row(page, 'sam@example.com')).toBeVisible(); + await expect(row(page, 'jane@example.com').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, 'jane@example.com').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, 'jane@example.com').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, 'sam@example.com').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, 'jane@example.com').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); +}); diff --git a/e2e/tests/table-filters.spec.ts b/e2e/tests/table-filters.spec.ts new file mode 100644 index 0000000..59f10c2 --- /dev/null +++ b/e2e/tests/table-filters.spec.ts @@ -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: 'admin@appe.at', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} }; + +const contacts = [ + { email: 'admin@appe.at', full_name: 'Admin User', linkedin_url: null, show_email: true, show_linkedin: true, is_admin: true, created_at: 'x' }, + { email: 'jane.doe@example.com', full_name: 'Jane Doe', linkedin_url: 'https://linkedin.com/in/janedoe', show_email: true, show_linkedin: false, is_admin: false, created_at: 'x' }, + { email: 'john.doe@example.com', full_name: 'John Doe', linkedin_url: null, show_email: false, show_linkedin: false, is_admin: false, created_at: 'x' }, + { email: 'amy.doe@example.com', full_name: 'Amy Doe', linkedin_url: 'https://linkedin.com/in/amydoe', show_email: true, show_linkedin: true, is_admin: false, created_at: 'x' }, + { email: 'sam.roe@example.com', 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: 'jane.doe@example.com', 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: 'john.doe@example.com', 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: 'amy.doe@example.com', type: 'attendee', qr_token: null, external_id: null, import_source: 'sessionize', checked_in: false, points: 0 }, + { id: 'r4', event_id: eventId, contact_email: 'sam.roe@example.com', 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: 'jane.doe@example.com' })).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: 'jane.doe@example.com' })).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('amy.doe@example.com'); + }); + + 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('jane.doe@example.com'); + await expect(body).toContainText('sam.roe@example.com'); + }); + + 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); + }); +});