Files
crosscode-platform/apps/events/frontend/src/components/admin/RegistrationBulkBar.tsx
T
joshuaandClaude Opus 5.5 abd2c36e97 WIP 2.0.0: React Compiler lint rules back to errors; docs
- The 192 places the rules flagged are fixed and the rules are errors
  again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state
  that follows other state, set while rendering), useExternalEffect
  (API loads and browser reads), useNow; lib/navigation.ts hardNavigate
  for full reloads after sign-out or identity switches; other pages use
  the router. Resets moved into the handlers that cause them.
- The banner shows and hides at its times on open pages.
- HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated;
  2.0.0 section drafted in WHATS-NEW.

e2e 102/102 (PayFast sandbox skipped); production build passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:45:25 +02:00

201 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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<Action>("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<BulkResponse | null>(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<AllocationSet[]>([]);
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<string, string> = {
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<typeof action, "">, registrationIds: selected.map(r => r.id), ...params } }) as Promise<BulkResponse>);
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 (
<div className="border border-brand-200 bg-brand-50/60 rounded-xl p-3 mb-3 space-y-3" data-testid="bulk-bar">
<div className="flex flex-wrap items-center gap-2">
<CheckSquare className="w-4 h-4 text-brand-700" />
<span className="text-sm font-medium text-brand-900">{selected.length} selected</span>
<select aria-label="Bulk action" className="border rounded px-2 py-1.5 text-sm bg-white" value={action} onChange={e => { setAction(e.target.value as Action); setResult(null); setError(null); }}>
<option value="">Choose an action…</option>
{ACTIONS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
</select>
<button type="button" onClick={onClear} className="ml-auto inline-flex items-center gap-1 text-xs text-gray-600 hover:text-gray-900"><X className="w-3.5 h-3.5" /> Clear selection</button>
</div>
{needsOneEvent && <p className="text-xs text-amber-800">Tick registrations from one event only (filter by event) to {action === "moveOption" ? "move tickets" : "put people in a group"}.</p>}
{action === "message" && (
<div className="space-y-2">
<div className="flex gap-3 text-sm">
<label className="flex items-center gap-1"><input type="radio" checked={channel === "email"} onChange={() => setChannel("email")} /> Email</label>
<label className="flex items-center gap-1"><input type="radio" checked={channel === "whatsapp"} onChange={() => setChannel("whatsapp")} /> WhatsApp</label>
</div>
{channel === "email" && <input aria-label="Subject" className="w-full border rounded px-3 py-1.5 text-sm" placeholder="Subject" value={subject} onChange={e => setSubject(e.target.value)} />}
<textarea aria-label="Message" rows={4} className="w-full border rounded px-3 py-1.5 text-sm" placeholder="Hi {name}, …" value={text} onChange={e => setText(e.target.value)} />
<p className="text-[11px] text-gray-500">Sent as an event update to the person who registered. You can use {"{name}"}, {"{eventTitle}"} and {"{eventStart}"}.</p>
</div>
)}
{action === "markPaid" && (
<label className="text-sm flex items-center gap-2">Paid by
<select aria-label="Paid by" className="border rounded px-2 py-1.5 text-sm bg-white" value={method} onChange={e => setMethod(e.target.value)}>
<option value="cash">Cash</option><option value="eft">EFT</option><option value="card">Card (card machine)</option><option value="other">Other</option>
</select>
<span className="text-xs text-gray-500">Records what each still owes (about R {totalOwing.toFixed(2)} in all).</span>
</label>
)}
{action === "moveOption" && oneEvent && (
<div className="flex flex-wrap gap-2 items-center text-sm">
<select aria-label="Move from" className="border rounded px-2 py-1.5 bg-white" value={fromOptionId} onChange={e => setFromOptionId(e.target.value)}>
<option value="">From ticket…</option>{options.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
</select>
→
<select aria-label="Move to" className="border rounded px-2 py-1.5 bg-white" value={toOptionId} onChange={e => setToOptionId(e.target.value)}>
<option value="">To ticket…</option>{options.filter(o => o.id !== fromOptionId).map(o => <option key={o.id} value={o.id}>{o.name} (R{Number(o.price).toFixed(0)})</option>)}
</select>
</div>
)}
{action === "allocate" && oneEvent && (
sets.length === 0 ? <p className="text-xs text-gray-600">This event has no rooms or groups yet — set them up under Rooms &amp; groups.</p> : (
<select aria-label="Group" className="border rounded px-2 py-1.5 text-sm bg-white" value={groupKey} onChange={e => setGroupKey(e.target.value)}>
<option value="">Choose a group…</option>
{sets.map(s => <optgroup key={s.id} label={s.name}>{s.groups.map(g => <option key={g.id} value={`${s.id}::${g.id}`}>{g.name}</option>)}</optgroup>)}
</select>
)
)}
{action === "cancel" && <p className="text-xs text-gray-700">Cancelling doesn&apos;t refund anyone — record refunds on the Payments page.</p>}
{action && (
<button type="button" disabled={!ready} onClick={run} className={`inline-flex items-center gap-1.5 px-4 py-1.5 text-sm rounded font-medium disabled:opacity-50 ${action === "cancel" ? "bg-red-600 text-white hover:bg-red-700" : "bg-brand-600 text-white hover:bg-brand-700"}`}>
{action === "export" && <Download className="w-4 h-4" />}
{busy ? "Working…" : `${ACTIONS.find(a => a[0] === action)?.[1]} — ${selected.length}`}
</button>
)}
{error && <div className="p-2 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
{result && (
<div className="p-2 border rounded bg-white text-sm" role="status" data-testid="bulk-result">
<div><strong>{result.done}</strong> done{result.skipped ? `, ${result.skipped} skipped` : ""}{result.failed ? `, ${result.failed} not done` : ""}.</div>
{result.results.filter(r => !r.ok || r.skipped).length > 0 && (
<ul className="mt-1 text-xs text-gray-700 max-h-40 overflow-auto">
{result.results.filter(r => !r.ok || r.skipped).map(r => <li key={r.id}><span className={r.ok ? "text-gray-500" : "text-red-700"}>{nameOf(r.id)}</span>: {r.message}</li>)}
</ul>
)}
</div>
)}
</div>
);
}