Pagination and search on long lists (1.50.1)

Audit log: search (person, target, IP), role filter, every action in the
filter, inclusive To date. Data requests: search and paging (was cut at
200). Webhook deliveries: status filter and Load older. Supervisor Payments
loads only what it needs (unpaid registrations, recent/today/donation
payments, a person's own for refunds) instead of everything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
2026-10-29 06:53:54 +02:00
co-authored by Claude Opus 5.5
parent 0ffbb13a1f
commit 4c066e67d9
26 changed files with 460 additions and 147 deletions
@@ -53,6 +53,19 @@ type ProviderTx = {
note?: string | null;
};
// What each registration still owes. The backend attaches a tranche-aware totalDueComputed
// (exact even when a line spans multiple early-bird prices); otherwise estimate it here.
function computeOutstanding(list: Registration[]): Outstanding {
const now = new Date();
const map: Outstanding = {};
for (const r of list) {
const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => sum + registrationOptionUnitPrice(opt, null, now) * (opt.quantity || 0), 0);
const totalPaid = (r.payments || []).reduce((sum, p) => sum + (p.amount || 0), 0);
map[r.id] = { totalDue, totalPaid, outstanding: Math.max(0, totalDue - totalPaid) };
}
return map;
}
function RegistrationOptions({ regs, regOutstanding }: {
regs: Registration[];
regOutstanding: Record<string, { totalDue: number; totalPaid: number; outstanding: number }>;
@@ -161,7 +174,11 @@ function PaymentsContent() {
if (!user) router.replace("/login");
}, [user, loading, router]);
const [payments, setPayments] = useState<Payment[]>([]);
// Not every payment ever made: the latest few for "Recent payments", today's for the totals,
// and donations with the legs that apply them (for assigning and the assigned list).
const [recentPayments, setRecentPayments] = useState<Payment[]>([]);
const [todayPayments, setTodayPayments] = useState<Payment[]>([]);
const [donationPayments, setDonationPayments] = useState<Payment[]>([]);
const [loadingList, setLoadingList] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const [info, setInfo] = useDismissingState<string | null>(null);
@@ -173,8 +190,15 @@ function PaymentsContent() {
if (!token) return;
try {
setLoadingList(true);
const list = await fetchAllPayments(token);
setPayments(list.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()));
const start = new Date(); start.setHours(0, 0, 0, 0);
const [recent, today, donations] = await Promise.all([
apiFetch<{ data: Payment[] }>("/api/payments?page=1&limit=40", { authToken: token }),
fetchAllPayments(token, { from: start.toISOString() }),
fetchAllPayments(token, { donations: "1" }),
]);
setRecentPayments(recent?.data || []);
setTodayPayments(today);
setDonationPayments(donations);
} catch (e) {
setError(errorMessage(e) || "Failed to load payments");
} finally {
@@ -184,25 +208,16 @@ function PaymentsContent() {
useEffect(() => { loadPayments(); }, [loadPayments]);
// Load registrations for dropdowns.
// GET /api/registrations already embeds each registration's `payments`, so outstanding
// balances are computed from that in one pass — no per-registration follow-up requests.
// Registrations still owing (not paid or cancelled), for the dropdowns. GET /api/registrations
// embeds each registration's `payments`, so balances come from that in one pass. Refunds load
// the chosen person's own registrations (including paid ones) when needed.
const loadRegistrations = useCallback(async () => {
if (!token) return;
try {
setLoadingRegs(true);
const regs = await apiFetch<Registration[]>("/api/registrations", { authToken: token });
const regs = await apiFetch<Registration[]>("/api/registrations?unpaid=1", { authToken: token });
const list = Array.isArray(regs) ? regs : [];
const now = new Date();
const map: Outstanding = {};
for (const r of list) {
// Backend attaches a tranche-aware totalDueComputed (exact even when a line spans
// multiple early-bird prices) — fall back to the old client-side estimate otherwise.
const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => sum + registrationOptionUnitPrice(opt, null, now) * (opt.quantity || 0), 0);
const totalPaid = (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0);
map[r.id] = { totalDue, totalPaid, outstanding: Math.max(0, totalDue - totalPaid) };
}
setRegOutstanding(map);
setRegOutstanding(computeOutstanding(list));
// Sort by createdAt desc
const sorted = list.sort((a,b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
setRegistrations(sorted);
@@ -420,11 +435,11 @@ function PaymentsContent() {
const todayTotals = useMemo(() => {
const start = new Date(); start.setHours(0,0,0,0);
// Exclude donation-application legs — that money was already counted once, as the donation.
const today = payments.filter(p => new Date(p.createdAt).getTime() >= start.getTime() && !isDonationLeg(p));
const today = todayPayments.filter(p => new Date(p.createdAt).getTime() >= start.getTime() && !isDonationLeg(p));
const revenue = today.reduce((s,p)=> s + (p.amount||0), 0);
const donations = today.filter(p => p.isDonation).length;
return { revenue, donations, count: today.length };
}, [payments]);
}, [todayPayments]);
const [mode, setMode] = useState<'payment'|'refund'|'donation'|'reconcile'|'link'>("payment");
@@ -741,10 +756,7 @@ function PaymentsContent() {
{mode === 'refund' && (
<>
<RefundSection
payments={payments}
allUsers={allUsers}
regsForUser={(uid:string)=> registrations.filter((r)=> String(r.user?.id||r.userId)===String(uid))}
regOutstanding={regOutstanding}
onDone={async()=>{ await Promise.all([loadPayments(), loadRegistrations()]); setInfo('Refund recorded'); }}
/>
{loadingUsers && <div className="text-xs text-gray-500">Loading users…</div>}
@@ -754,7 +766,7 @@ function PaymentsContent() {
{mode === 'donation' && (
<>
<DonationAssignSection
payments={payments}
payments={donationPayments}
allUsers={allUsers}
registrations={registrations}
regOutstanding={regOutstanding}
@@ -762,7 +774,7 @@ function PaymentsContent() {
/>
{loadingUsers && <div className="text-xs text-gray-500">Loading users…</div>}
<AssignedDonationsList
payments={payments}
payments={donationPayments}
onDone={async()=>{ await Promise.all([loadPayments(), loadRegistrations()]); setInfo('Donation unassigned'); }}
/>
</>
@@ -815,7 +827,7 @@ function PaymentsContent() {
{loadingList && <span className="text-xs text-gray-500">Loading…</span>}
</div>
<ul className="text-sm space-y-2 max-h-[520px] overflow-auto pr-2">
{payments.filter(p => !isDonationLeg(p)).slice(0, 25).map(p => {
{recentPayments.filter(p => !isDonationLeg(p)).slice(0, 25).map(p => {
const amt = p.amount || 0;
const isRefund = amt < 0;
return (
@@ -834,7 +846,7 @@ function PaymentsContent() {
</li>
);
})}
{payments.length === 0 && <li className="text-gray-500">No payments yet.</li>}
{recentPayments.length === 0 && <li className="text-gray-500">No payments yet.</li>}
</ul>
</div>
</div>
@@ -864,14 +876,13 @@ function PaymentsContent() {
}
type RefundSectionProps = {
payments: Payment[];
allUsers: User[];
regsForUser: (userId: string) => Registration[];
regOutstanding: Outstanding;
onDone: () => void | Promise<void>;
};
function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone }: RefundSectionProps) {
// The chosen person's own payments and registrations (paid ones too) are loaded when they're
// picked, rather than every payment and registration up front.
function RefundSection({ allUsers, onDone }: RefundSectionProps) {
const { token } = useAuth();
const [userId, setUserId] = useState<string>("");
const [target, setTarget] = useState<'payment'|'registration'>('payment');
@@ -883,10 +894,28 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
const [submitting, setSubmitting] = useState(false);
const [err, setErr] = useState<string | null>(null);
const paymentsForUser = useMemo(() => {
if (!userId) return [];
return payments.filter(p => String(p.userId) === String(userId) && (p.amount || 0) > 0);
}, [payments, userId]);
const [payments, setPayments] = useState<Payment[]>([]);
const [regs, setRegs] = useState<Registration[]>([]);
const [loadingUser, setLoadingUser] = useState(false);
useEffect(() => {
setPayments([]); setRegs([]);
if (!userId || !token) return;
let cancelled = false;
setLoadingUser(true);
Promise.all([
fetchAllPayments(token, { userId }),
apiFetch<Registration[]>(`/api/registrations?userId=${encodeURIComponent(userId)}`, { authToken: token }),
]).then(([p, r]) => {
if (cancelled) return;
setPayments(p);
setRegs((Array.isArray(r) ? r : []).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()));
}).catch((e) => { if (!cancelled) setErr(errorMessage(e) || "Couldn't load this person's payments"); })
.finally(() => { if (!cancelled) setLoadingUser(false); });
return () => { cancelled = true; };
}, [userId, token]);
const regOutstanding = useMemo(() => computeOutstanding(regs), [regs]);
const paymentsForUser = useMemo(() => payments.filter(p => (p.amount || 0) > 0), [payments]);
useEffect(() => {
// Reset dependent fields on changes
@@ -907,7 +936,6 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
}
}, [paymentId, target, payments]);
const regs = useMemo(() => regsForUser(userId), [regsForUser, userId]);
const submitRefund = async () => {
if (!token) return;
@@ -948,6 +976,7 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
<div className="grid gap-2">
<label className="text-xs text-gray-600">User</label>
<UserSearchField allUsers={allUsers} value={userId} onChange={uid => setUserId(uid)} />
{loadingUser && <div className="text-xs text-gray-500" role="status">Loading their payments…</div>}
<label className="text-xs text-gray-600 mt-2">Refund target</label>
<div className="flex gap-4 text-sm">
<label className="flex items-center gap-2"><input type="radio" name="refundTarget" checked={target==='payment'} onChange={()=>setTarget('payment')} /> Payment</label>