import type { Ticket as TicketRecord } from "@/types"; import { formatDate } from "@/lib/date"; import { formatSessionWhen, scheduleSummary } from "@/lib/sessions"; // One ticket design for every printed ticket (user dashboard, staff event tickets, at the // door). The emailed/WhatsApp PDF in backend/src/controllers/ticketController.js mirrors it. function esc(s: string): string { return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]!)); } export function ticketTypeLabel(t: TicketRecord): string { const opt = t.registrationOption?.eventOption?.name || "Ticket"; const variant = t.registrationOption?.variant?.name; return variant ? `${opt} — ${variant}` : opt; } /** A ticket card. `buyerName` adds a "Purchased by" line. */ export function ticketCardHtml(t: TicketRecord, buyerName?: string | null): string { const eventTitle = t.event?.title || t.eventId || "Event"; // Multi-day events: "5 sessions · Wed 4 Nov – Wed 2 Dec" — one ticket for every session; // a picked-session ticket shows its own session. const session = t.registrationOption?.session; const dateStr = session ? `${session.label || "Session"} · ${formatSessionWhen(session)}` : (t.event && scheduleSummary(t.event)) || (t.event?.startDate ? formatDate(t.event.startDate) : ""); const qrSrc = `https://api.qrserver.com/v1/create-qr-code/?size=320x320&data=${encodeURIComponent(t.qrCode || t.id)}`; return `
${esc(eventTitle)}
${dateStr ? `
${esc(dateStr)}
` : ""}
${esc(ticketTypeLabel(t))}
${t.attendee?.name ? `
Name: ${esc(t.attendee.name)}
` : `
Qty: ${t.quantity || 1}
`}
QR
Ticket ID: ${esc(t.id)}
${buyerName ? `
Purchased by: ${esc(buyerName)}
` : ""}
`; } /** Opens a print window with the given cards and prints once the QR images have loaded. */ export function openTicketPrintWindow(title: string, cardsHtml: string) { const w = window.open("", "_blank"); if (!w) return; w.document.write(`${esc(title)}
${cardsHtml}
`); w.document.close(); w.focus(); } /** Prints tickets in the shared design. */ export function printTicketCards(tickets: TicketRecord[], buyerName?: (t: TicketRecord) => string | null | undefined) { if (!tickets || tickets.length === 0) return; const cards = tickets.map((t) => ticketCardHtml(t, buyerName?.(t))).join(""); openTicketPrintWindow(tickets.length === 1 ? "Ticket" : `Tickets (${tickets.length})`, cards); }