"use client"; import React, { useMemo, useState } from "react"; import { CheckSquare, X, Download } from "lucide-react"; import { API_BASE } from "@/lib/api"; import { errorMessage } from "@/lib/utils"; import { downloadReportExcel } from "@/lib/export"; import type { Event, Registration } from "@/types"; import { apiV2Data } from "@/lib/apiV2"; import { useExternalEffect } from "@/lib/hooks"; type Action = "" | "message" | "markPaid" | "moveOption" | "allocate" | "cancel" | "export"; type Result = { id: string; ok: boolean; skipped?: boolean; message: string }; type BulkResponse = { action: string; done: number; skipped: number; failed: number; results: Result[] }; type AllocationSet = { id: string; name: string; groups: { id: string; name: string }[] }; const ACTIONS: [Action, string][] = [ ["message", "Send a message"], ["markPaid", "Mark paid (record the balance)"], ["moveOption", "Move to another ticket"], ["allocate", "Put in a room or group"], ["export", "Export to Excel"], ["cancel", "Cancel"], ]; const owing = (r: Registration) => { const due = Number(r.totalDueComputed ?? 0); const paid = (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0); return Math.max(0, due - paid); }; /** * The bar above the registrations list while some are ticked (1.49.1): one action for all of * them, run through the same rules as doing it one at a time, with a result per registration. */ export function RegistrationBulkBar({ selected, events, token, onClear, onDone }: { selected: Registration[]; events: Event[]; token: string; onClear: () => void; onDone: () => void; }) { const [action, setAction] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [result, setResult] = useState(null); // Per-action inputs. const [channel, setChannel] = useState<"email" | "whatsapp">("email"); const [subject, setSubject] = useState(""); const [text, setText] = useState(""); const [method, setMethod] = useState("cash"); const [fromOptionId, setFromOptionId] = useState(""); const [toOptionId, setToOptionId] = useState(""); const [sets, setSets] = useState([]); const [groupKey, setGroupKey] = useState(""); const eventIds = useMemo(() => [...new Set(selected.map(r => r.eventId))], [selected]); const oneEvent = eventIds.length === 1 ? events.find(e => e.id === eventIds[0]) || null : null; const options = useMemo(() => (oneEvent?.eventOptions || []).filter(o => o.id !== oneEvent?.kidsOptionId && o.id !== oneEvent?.volunteerOptionId), [oneEvent]); const totalOwing = useMemo(() => selected.filter(r => r.status !== "cancelled").reduce((s, r) => s + owing(r), 0), [selected]); useExternalEffect(() => { if (action !== "allocate" || !oneEvent) { setSets([]); return; } (apiV2Data("get", "/events/{id}/allocations", { params: { id: oneEvent.id }, authToken: token }) as Promise<{ sets?: AllocationSet[] }>) .then(b => setSets((b.sets || []).filter(s => s.groups.length))) .catch(() => setSets([])); }, [action, oneEvent, token]); const needsOneEvent = (action === "moveOption" || action === "allocate") && !oneEvent; const exportSelected = async () => { await downloadReportExcel(API_BASE, token, { title: "Registrations", subtitle: `${selected.length} selected · ${new Date().toLocaleString()}`, kind: "table", orientation: "landscape", table: { columns: ["Reference", "Name", "Email", "Phone", "Event", "Status", "Total", "Paid", "Owing", "Tickets"], rows: selected.map(r => { const paid = (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0); return [ String(r.id).slice(0, 8), r.user?.name || "", r.user?.email || "", r.user?.phoneNumber || "", r.event?.title || "", r.status, `R ${Number(r.totalDueComputed ?? 0).toFixed(2)}`, `R ${paid.toFixed(2)}`, `R ${owing(r).toFixed(2)}`, (r.registrationOptions || []).map(o => `${o.quantity} × ${o.eventOption?.name || ""}${o.variant?.name ? ` (${o.variant.name})` : ""}`).join(", "), ]; }), }, }); }; const run = async () => { setError(null); setResult(null); if (action === "export") { setBusy(true); try { await exportSelected(); } catch (e) { setError(errorMessage(e) || "Couldn't export"); } finally { setBusy(false); } return; } const confirmText: Record = { cancel: `Cancel ${selected.length} registration(s)? Cancelling doesn't refund — record refunds on the Payments page. Coupon uses are released and the waitlist is offered the places.`, markPaid: `Record ${method.toUpperCase()} payments for what ${selected.length} registration(s) still owe (about R ${totalOwing.toFixed(2)})? Paid registrations get their tickets by email.`, moveOption: `Move ${selected.length} registration(s) to the other ticket? Tickets already issued move with them (same QR code). The price follows the new ticket, so anything now owing or overpaid shows on each registration.`, message: `Send this ${channel === "email" ? "email" : "WhatsApp"} to the people on ${selected.length} registration(s)?`, allocate: `Put the named people on ${selected.length} registration(s) in this group?`, }; if (!confirm(confirmText[action])) return; const [setId, groupId] = groupKey.split("::"); const params = action === "message" ? { channel, subject, text } : action === "markPaid" ? { method } : action === "moveOption" ? { fromOptionId, toOptionId } : action === "allocate" ? { setId, groupId } : {}; setBusy(true); try { const res = await (apiV2Data("post", "/registrations/bulk", { authToken: token, body: { action: action as Exclude, registrationIds: selected.map(r => r.id), ...params } }) as Promise); setResult(res); onDone(); } catch (e) { setError(errorMessage(e) || "Couldn't do that"); } finally { setBusy(false); } }; const ready = !busy && !needsOneEvent && ( action === "export" || action === "cancel" || (action === "markPaid" && !!method) || (action === "message" && text.trim() && (channel === "whatsapp" || subject.trim())) || (action === "moveOption" && fromOptionId && toOptionId && fromOptionId !== toOptionId) || (action === "allocate" && !!groupKey) ); const nameOf = (id: string) => selected.find(r => r.id === id)?.user?.name || id.slice(0, 8); return (
{selected.length} selected
{needsOneEvent &&

Tick registrations from one event only (filter by event) to {action === "moveOption" ? "move tickets" : "put people in a group"}.

} {action === "message" && (
{channel === "email" && setSubject(e.target.value)} />}