Archived
Type payments and user dashboard pages
Moves the duplicated registration-option pricing helper into src/lib/pricing.ts and drops an unused users list from payments. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
||||
import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { apiFetch, fetchAllUsers, fetchAllPayments } from "@/lib/api";
|
||||
@@ -8,13 +8,15 @@ import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { scoreUser } from "@/lib/fuzzyMatch";
|
||||
import { Wallet, RotateCcw, HandHeart, ScanLine, Link2 } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { registrationOptionUnitPrice } from "@/lib/pricing";
|
||||
import type { Event, Payment, Registration, User } from "@/types";
|
||||
|
||||
// A donation is never mutated once created — assigning it to a registration creates a separate
|
||||
// "leg" Payment row (isDonation:false, originalPaymentId -> the donation, amount > 0) instead.
|
||||
// That leg is not new money: it just re-labels part of an already-counted donation as applied
|
||||
// to a registration. Money stats/lists must count each real inflow exactly once, so legs are
|
||||
// excluded — the money was already counted via the original donation row.
|
||||
function isDonationLeg(p: any): boolean {
|
||||
function isDonationLeg(p: Payment): boolean {
|
||||
return !p?.isDonation && !!p?.originalPaymentId && (p?.amount || 0) > 0;
|
||||
}
|
||||
|
||||
@@ -30,13 +32,27 @@ function refundMethodForOriginal(method: string | null | undefined): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
type Outstanding = Record<string, { totalDue: number; totalPaid: number; outstanding: number }>;
|
||||
|
||||
// An unreconciled Yoco transaction (GET /api/yoco-transactions/unreconciled). `raw` is the
|
||||
// webhook as Yoco sent it; its checkout metadata says who/what the payment was for.
|
||||
type YocoTx = {
|
||||
id: string;
|
||||
amount: number;
|
||||
checkoutId?: string | null;
|
||||
externalId?: string | null;
|
||||
methodType?: string | null;
|
||||
createdDate?: string | null;
|
||||
raw?: { payload?: { metadata?: { userId?: string; eventId?: string } } } | null;
|
||||
};
|
||||
|
||||
function RegistrationOptions({ regs, regOutstanding }: {
|
||||
regs: any[];
|
||||
regs: Registration[];
|
||||
regOutstanding: Record<string, { totalDue: number; totalPaid: number; outstanding: number }>;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{regs.map((r: any) => {
|
||||
{regs.map((r) => {
|
||||
const out = regOutstanding[r.id]?.outstanding ?? 0;
|
||||
const label = `${r.event?.title || r.eventId || 'Event'} — ${r.user?.name || r.userId || 'User'} — Outstanding: R ${out.toFixed(2)} — #${String(r.id).slice(0,8)}`;
|
||||
return (
|
||||
@@ -50,7 +66,7 @@ function RegistrationOptions({ regs, regOutstanding }: {
|
||||
}
|
||||
|
||||
function UserSearchField({ allUsers, value, onChange, placeholder = "Search by name, email or phone…", disabled = false }: {
|
||||
allUsers: any[];
|
||||
allUsers: User[];
|
||||
value: string;
|
||||
onChange: (userId: string) => void;
|
||||
placeholder?: string;
|
||||
@@ -137,73 +153,45 @@ function PaymentsContent() {
|
||||
if (!user) router.replace("/login");
|
||||
}, [user, loading, router]);
|
||||
|
||||
const [payments, setPayments] = useState<any[]>([]);
|
||||
const [payments, setPayments] = useState<Payment[]>([]);
|
||||
const [loadingList, setLoadingList] = useState(false);
|
||||
const [error, setError] = useDismissingState<string | null>(null);
|
||||
const [info, setInfo] = useDismissingState<string | null>(null);
|
||||
const [registrations, setRegistrations] = useState<any[]>([]);
|
||||
const [registrations, setRegistrations] = useState<Registration[]>([]);
|
||||
const [loadingRegs, setLoadingRegs] = useState(false);
|
||||
const [regOutstanding, setRegOutstanding] = useState<Record<string, { totalDue: number; totalPaid: number; outstanding: number }>>({});
|
||||
const [regOutstanding, setRegOutstanding] = useState<Outstanding>({});
|
||||
|
||||
const loadPayments = async () => {
|
||||
const loadPayments = useCallback(async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
setLoadingList(true);
|
||||
const list = await fetchAllPayments(token);
|
||||
setPayments(list.sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()));
|
||||
setPayments(list.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()));
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load payments");
|
||||
} finally {
|
||||
setLoadingList(false);
|
||||
}
|
||||
};
|
||||
}, [token, setError]);
|
||||
|
||||
useEffect(() => { loadPayments(); }, [token]);
|
||||
|
||||
// Compute effective unit price for a registration option.
|
||||
// Uses priceSnapshot when available (authoritative backend price, variant-aware).
|
||||
// Falls back to deadline-only early-bird calculation for legacy rows without a snapshot.
|
||||
const optionUnitPrice = (opt: any, referenceTime: any, atTime: Date): number => {
|
||||
if (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) {
|
||||
return Number(opt.priceSnapshot);
|
||||
}
|
||||
const eo = opt.eventOption;
|
||||
const variantId: string | null = opt.variantId || null;
|
||||
const base = (opt.variant?.price !== null && opt.variant?.price !== undefined)
|
||||
? Number(opt.variant.price)
|
||||
: Number(eo?.price || 0);
|
||||
const allTiers = Array.isArray(eo?.earlyBirdTiers) ? eo.earlyBirdTiers.slice() : [];
|
||||
const tiers = variantId
|
||||
? allTiers.filter((t: any) => t.variantId === variantId)
|
||||
: allTiers.filter((t: any) => !t.variantId);
|
||||
if (tiers.length === 0) return base;
|
||||
const t = atTime ? new Date(atTime) : new Date();
|
||||
const ref = referenceTime ? new Date(referenceTime) : t;
|
||||
const applicable = tiers
|
||||
.map((x: any) => ({ ...x, deadline: new Date(x.deadline) }))
|
||||
.filter((x: any) => (ref < x.deadline) && (t < x.deadline))
|
||||
.sort((a: any, b: any) => a.deadline.getTime() - b.deadline.getTime() || (a.order||0) - (b.order||0) || a.price - b.price);
|
||||
if (applicable.length === 0) return base;
|
||||
const price = Number(applicable[0].price);
|
||||
return (price >= 0) ? price : base;
|
||||
};
|
||||
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.
|
||||
const loadRegistrations = async () => {
|
||||
const loadRegistrations = useCallback(async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
setLoadingRegs(true);
|
||||
const regs = await apiFetch<any[]>("/api/registrations", { authToken: token });
|
||||
const regs = await apiFetch<Registration[]>("/api/registrations", { authToken: token });
|
||||
const list = Array.isArray(regs) ? regs : [];
|
||||
const now = new Date();
|
||||
const map: Record<string, { totalDue: number; totalPaid: number; outstanding: number }> = {};
|
||||
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: number, opt: any) => sum + optionUnitPrice(opt, null, now) * (opt.quantity || 0), 0);
|
||||
const totalPaid = (r.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0);
|
||||
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);
|
||||
@@ -215,9 +203,9 @@ function PaymentsContent() {
|
||||
} finally {
|
||||
setLoadingRegs(false);
|
||||
}
|
||||
};
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => { loadRegistrations(); }, [token]);
|
||||
useEffect(() => { loadRegistrations(); }, [loadRegistrations]);
|
||||
|
||||
// Load all users for Refund section
|
||||
useEffect(() => {
|
||||
@@ -241,12 +229,12 @@ function PaymentsContent() {
|
||||
const [registrationId, setRegistrationId] = useState<string>("");
|
||||
const [isDonation, setIsDonation] = useState<boolean>(false);
|
||||
const [eventId, setEventId] = useState<string>("");
|
||||
const [events, setEvents] = useState<any[]>([]);
|
||||
const [events, setEvents] = useState<Event[]>([]);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
// Backdate field
|
||||
const [paidAtLocal, setPaidAtLocal] = useState<string>("");
|
||||
// Users for Refund section (load all users with supervisor rights)
|
||||
const [allUsers, setAllUsers] = useState<any[]>([]);
|
||||
const [allUsers, setAllUsers] = useState<User[]>([]);
|
||||
const [loadingUsers, setLoadingUsers] = useState(false);
|
||||
|
||||
// New: user selection states for split dropdowns
|
||||
@@ -254,33 +242,12 @@ function PaymentsContent() {
|
||||
|
||||
// Derived lists for users and outstanding registrations
|
||||
const outstandingRegs = useMemo(() => {
|
||||
return registrations.filter((r: any) => (r.status !== 'paid') && (r.status !== 'cancelled') && ((regOutstanding[r.id]?.outstanding ?? 0) > 0));
|
||||
return registrations.filter((r) => (r.status !== 'paid') && (r.status !== 'cancelled') && ((regOutstanding[r.id]?.outstanding ?? 0) > 0));
|
||||
}, [registrations, regOutstanding]);
|
||||
|
||||
// Users list for UI dropdowns (use all users if loaded; fallback to outstanding registrations)
|
||||
const usersList = useMemo(() => {
|
||||
if (allUsers && allUsers.length > 0) {
|
||||
return [...allUsers]
|
||||
//.filter(u => u?.isActive !== false)
|
||||
.map(u => ({ id: String(u.id), name: String(u.name || u.email || u.id) }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, undefined as any, { sensitivity: 'base' } as any));
|
||||
}
|
||||
const map = new Map<string, string>();
|
||||
for (const r of outstandingRegs) {
|
||||
const uid = r.user?.id || r.userId;
|
||||
if (!uid) continue;
|
||||
const name = r.user?.name || r.user?.email || String(r.userId || uid);
|
||||
if (!map.has(String(uid))) {
|
||||
map.set(String(uid), String(name));
|
||||
}
|
||||
}
|
||||
return Array.from(map.entries())
|
||||
.map(([id, name]) => ({ id, name }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, undefined as any, { sensitivity: 'base' } as any));
|
||||
}, [allUsers, outstandingRegs]);
|
||||
|
||||
const regsForSelectedUser = useMemo(() => {
|
||||
return outstandingRegs.filter((r: any) => (String(r.user?.id || r.userId) === String(selectedUserId)));
|
||||
return outstandingRegs.filter((r) => (String(r.user?.id || r.userId) === String(selectedUserId)));
|
||||
}, [outstandingRegs, selectedUserId]);
|
||||
|
||||
// Payment link tab state
|
||||
@@ -293,7 +260,7 @@ function PaymentsContent() {
|
||||
const [linkCopied, setLinkCopied] = useState(false);
|
||||
|
||||
const regsForLinkUser = useMemo(() => {
|
||||
return outstandingRegs.filter((r: any) => (String(r.user?.id || r.userId) === String(linkUserId)));
|
||||
return outstandingRegs.filter((r) => (String(r.user?.id || r.userId) === String(linkUserId)));
|
||||
}, [outstandingRegs, linkUserId]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -372,7 +339,7 @@ function PaymentsContent() {
|
||||
// If a registration is preselected via query, infer and set its user
|
||||
useEffect(() => {
|
||||
if (!registrationId) return;
|
||||
const reg = registrations.find((r: any) => String(r.id) === String(registrationId));
|
||||
const reg = registrations.find((r) => String(r.id) === String(registrationId));
|
||||
const uid = reg?.user?.id || reg?.userId;
|
||||
if (uid) setSelectedUserId(String(uid));
|
||||
}, [registrationId, registrations]);
|
||||
@@ -388,7 +355,7 @@ function PaymentsContent() {
|
||||
if (eventsIncludePast) params.set("includePast", "true");
|
||||
if (eventsIncludeInactive) params.set("includeInactive", "true");
|
||||
const qs = params.toString() ? `?${params.toString()}` : "";
|
||||
const evs = await apiFetch<any[]>(`/api/events/all${qs}`, { authToken: token });
|
||||
const evs = await apiFetch<Event[]>(`/api/events/all${qs}`, { authToken: token });
|
||||
setEvents(evs || []);
|
||||
} catch {}
|
||||
})();
|
||||
@@ -455,38 +422,38 @@ function PaymentsContent() {
|
||||
|
||||
// Yoco unreconciled list and actions
|
||||
const [yocoLoading, setYocoLoading] = useState(false);
|
||||
const [yocoTxs, setYocoTxs] = useState<any[]>([]);
|
||||
const loadYocoUnreconciled = async () => {
|
||||
const [yocoTxs, setYocoTxs] = useState<YocoTx[]>([]);
|
||||
const loadYocoUnreconciled = useCallback(async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
setYocoLoading(true);
|
||||
const res = await apiFetch<any>("/api/yoco-transactions/unreconciled", { authToken: token });
|
||||
const items = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : []);
|
||||
const res = await apiFetch<{ data?: YocoTx[] } | YocoTx[]>("/api/yoco-transactions/unreconciled", { authToken: token });
|
||||
const items = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : []);
|
||||
setYocoTxs(items);
|
||||
} catch {
|
||||
// ignore silently, shown on demand via error state if needed
|
||||
} finally {
|
||||
setYocoLoading(false);
|
||||
}
|
||||
};
|
||||
useEffect(() => { loadYocoUnreconciled(); }, [token]);
|
||||
}, [token]);
|
||||
useEffect(() => { loadYocoUnreconciled(); }, [loadYocoUnreconciled]);
|
||||
|
||||
// Inline reconcile form state per-row
|
||||
const [reconcileForm, setReconcileForm] = useState<{ txId: string | null; type: 'reg' | 'don' | null; userId: string; registrationId: string; eventId: string; submitting: boolean }>({ txId: null, type: null, userId: '', registrationId: '', eventId: '', submitting: false });
|
||||
|
||||
const openReconcileToRegistration = (tx: any) => {
|
||||
const openReconcileToRegistration = (tx: YocoTx) => {
|
||||
const metaUser = tx?.raw?.payload?.metadata?.userId ? String(tx.raw.payload.metadata.userId) : '';
|
||||
setReconcileForm({ txId: tx.id, type: 'reg', userId: metaUser, registrationId: '', eventId: '', submitting: false });
|
||||
};
|
||||
|
||||
const openReconcileAsDonation = (tx: any) => {
|
||||
const openReconcileAsDonation = (tx: YocoTx) => {
|
||||
const metaEvent = tx?.raw?.payload?.metadata?.eventId ? String(tx.raw.payload.metadata.eventId) : '';
|
||||
setReconcileForm({ txId: tx.id, type: 'don', userId: '', registrationId: '', eventId: metaEvent, submitting: false });
|
||||
};
|
||||
|
||||
const regsForUser = (uid: string) => registrations
|
||||
.filter((r: any) => String(r.user?.id || r.userId) === String(uid))
|
||||
.filter((r: any) => {
|
||||
.filter((r) => String(r.user?.id || r.userId) === String(uid))
|
||||
.filter((r) => {
|
||||
const out = regOutstanding[r.id]?.outstanding ?? 0;
|
||||
return out > 0.000001; // show only registrations with an outstanding balance
|
||||
});
|
||||
@@ -638,7 +605,7 @@ function PaymentsContent() {
|
||||
<label className="block text-xs text-gray-600 mb-1">Registration</label>
|
||||
<select className="w-full border rounded px-3 py-2 text-sm" value={reconcileForm.registrationId} onChange={e => setReconcileForm(prev => ({ ...prev, registrationId: e.target.value }))} disabled={!reconcileForm.userId}>
|
||||
<option value="">Select registration…</option>
|
||||
{reconcileForm.userId && regsForUser(reconcileForm.userId).map((r: any) => {
|
||||
{reconcileForm.userId && regsForUser(reconcileForm.userId).map((r) => {
|
||||
const out = regOutstanding[r.id]?.outstanding ?? 0;
|
||||
const label = `${r.event?.title || r.eventId || 'Event'} — Outstanding: R ${out.toFixed(2)} — #${String(r.id).slice(0,8)}`;
|
||||
return <option key={r.id} value={r.id} title={label}>{label}</option>;
|
||||
@@ -754,7 +721,7 @@ function PaymentsContent() {
|
||||
<RefundSection
|
||||
payments={payments}
|
||||
allUsers={allUsers}
|
||||
regsForUser={(uid:string)=> registrations.filter((r:any)=> String(r.user?.id||r.userId)===String(uid))}
|
||||
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'); }}
|
||||
/>
|
||||
@@ -875,10 +842,10 @@ function PaymentsContent() {
|
||||
}
|
||||
|
||||
type RefundSectionProps = {
|
||||
payments: any[];
|
||||
allUsers: any[];
|
||||
regsForUser: (userId: string) => any[];
|
||||
regOutstanding: Record<string, { totalDue: number; totalPaid: number; outstanding: number }>;
|
||||
payments: Payment[];
|
||||
allUsers: User[];
|
||||
regsForUser: (userId: string) => Registration[];
|
||||
regOutstanding: Outstanding;
|
||||
onDone: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
@@ -895,7 +862,7 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
const paymentsForUser = useMemo(() => {
|
||||
if (!userId) return [] as any[];
|
||||
if (!userId) return [];
|
||||
return payments.filter(p => String(p.userId) === String(userId) && (p.amount || 0) > 0);
|
||||
}, [payments, userId]);
|
||||
|
||||
@@ -969,7 +936,7 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
|
||||
<label className="text-xs text-gray-600 mt-2">Payment</label>
|
||||
<select className="w-full max-w-full border rounded px-3 py-2 text-sm truncate" value={paymentId} onChange={e => setPaymentId(e.target.value)} disabled={!userId}>
|
||||
<option value="">Select payment…</option>
|
||||
{paymentsForUser.map((p:any)=>{
|
||||
{paymentsForUser.map((p)=>{
|
||||
const label = `R ${(p.amount||0).toFixed(2)} — ${p.registrationId ? `Registration ${String(p.registrationId).slice(0,8)}` : (p.event?.title || p.eventId || 'Event')} — #${String(p.id).slice(0,8)}`;
|
||||
return <option key={p.id} value={p.id} title={label}>{label}</option>;
|
||||
})}
|
||||
@@ -980,7 +947,7 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
|
||||
<label className="text-xs text-gray-600 mt-2">Registration</label>
|
||||
<select className="w-full max-w-full border rounded px-3 py-2 text-sm truncate" value={registrationId} onChange={e => setRegistrationId(e.target.value)} disabled={!userId}>
|
||||
<option value="">Select registration…</option>
|
||||
{regs.map((r:any)=>{
|
||||
{regs.map((r)=>{
|
||||
const out = regOutstanding[r.id]?.outstanding ?? 0;
|
||||
const label = `${r.event?.title || r.eventId || 'Event'} — Outstanding: R ${out.toFixed(2)} — #${String(r.id).slice(0,8)}`;
|
||||
return <option key={r.id} value={r.id} title={label}>{label}</option>;
|
||||
@@ -1018,7 +985,7 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
|
||||
// stats both deliberately filter them out (they're not new money, see isDonationLeg's comment) —
|
||||
// so this is the only place staff can see and reverse an assignment.
|
||||
type AssignedDonationsListProps = {
|
||||
payments: any[];
|
||||
payments: Payment[];
|
||||
onDone: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
@@ -1032,12 +999,12 @@ function AssignedDonationsList({ payments, onDone }: AssignedDonationsListProps)
|
||||
const allLegs = useMemo(() => {
|
||||
return payments
|
||||
.filter(isDonationLeg)
|
||||
.sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
}, [payments]);
|
||||
|
||||
const donationById = useMemo(() => {
|
||||
const m = new Map<string, any>();
|
||||
payments.forEach((p: any) => { if (p.isDonation) m.set(p.id, p); });
|
||||
const m = new Map<string, Payment>();
|
||||
payments.forEach((p) => { if (p.isDonation) m.set(p.id, p); });
|
||||
return m;
|
||||
}, [payments]);
|
||||
|
||||
@@ -1045,7 +1012,7 @@ function AssignedDonationsList({ payments, onDone }: AssignedDonationsListProps)
|
||||
// never shows an event with nothing to filter down to.
|
||||
const eventOptions = useMemo(() => {
|
||||
const m = new Map<string, string>();
|
||||
allLegs.forEach((leg: any) => {
|
||||
allLegs.forEach((leg) => {
|
||||
const ev = leg.registration?.event;
|
||||
if (ev?.id) m.set(String(ev.id), ev.title || String(ev.id));
|
||||
});
|
||||
@@ -1054,10 +1021,10 @@ function AssignedDonationsList({ payments, onDone }: AssignedDonationsListProps)
|
||||
|
||||
const legs = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return allLegs.filter((leg: any) => {
|
||||
return allLegs.filter((leg) => {
|
||||
if (eventFilter && String(leg.registration?.eventId || leg.registration?.event?.id) !== eventFilter) return false;
|
||||
if (!q) return true;
|
||||
const donation = donationById.get(leg.originalPaymentId);
|
||||
const donation = leg.originalPaymentId ? donationById.get(leg.originalPaymentId) : undefined;
|
||||
const haystack = [
|
||||
leg.registration?.user?.name,
|
||||
leg.registration?.user?.email,
|
||||
@@ -1071,7 +1038,7 @@ function AssignedDonationsList({ payments, onDone }: AssignedDonationsListProps)
|
||||
});
|
||||
}, [allLegs, donationById, query, eventFilter]);
|
||||
|
||||
const unassign = async (leg: any) => {
|
||||
const unassign = async (leg: Payment) => {
|
||||
if (!token) return;
|
||||
setErr(null);
|
||||
const ok = window.confirm("Unassign this donation? The registration's balance will increase, and any tickets issued only because this payment completed it may be revoked.");
|
||||
@@ -1119,8 +1086,8 @@ function AssignedDonationsList({ payments, onDone }: AssignedDonationsListProps)
|
||||
<div className="text-sm text-gray-500">No assigned donations match your search.</div>
|
||||
) : (
|
||||
<ul className="text-sm space-y-2 max-h-[420px] overflow-auto pr-2">
|
||||
{legs.map((leg: any) => {
|
||||
const donation = donationById.get(leg.originalPaymentId);
|
||||
{legs.map((leg) => {
|
||||
const donation = leg.originalPaymentId ? donationById.get(leg.originalPaymentId) : undefined;
|
||||
return (
|
||||
<li key={leg.id} className="border rounded p-2">
|
||||
<div className="flex justify-between items-start gap-2">
|
||||
@@ -1152,10 +1119,10 @@ function AssignedDonationsList({ payments, onDone }: AssignedDonationsListProps)
|
||||
}
|
||||
|
||||
type DonationAssignSectionProps = {
|
||||
payments: any[];
|
||||
allUsers: any[];
|
||||
registrations: any[];
|
||||
regOutstanding: Record<string, { totalDue: number; totalPaid: number; outstanding: number }>;
|
||||
payments: Payment[];
|
||||
allUsers: User[];
|
||||
registrations: Registration[];
|
||||
regOutstanding: Outstanding;
|
||||
onDone: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
@@ -1179,8 +1146,8 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
|
||||
// Registrations for the selected user that can actually receive a donation: an outstanding
|
||||
// balance to apply it to, and an event that isn't closed.
|
||||
const regsForUser = useMemo(() => {
|
||||
if (!userId) return [] as any[];
|
||||
return registrations.filter((r: any) => {
|
||||
if (!userId) return [];
|
||||
return registrations.filter((r) => {
|
||||
if (String(r.user?.id || r.userId) !== String(userId)) return false;
|
||||
if (r.status === 'cancelled') return false;
|
||||
if (r.event?.cashupStatus === 'closed') return false;
|
||||
@@ -1190,7 +1157,7 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
|
||||
}, [registrations, regOutstanding, userId]);
|
||||
|
||||
const selectedRegistration = useMemo(
|
||||
() => registrations.find((r: any) => String(r.id) === String(registrationId)),
|
||||
() => registrations.find((r) => String(r.id) === String(registrationId)),
|
||||
[registrations, registrationId]
|
||||
);
|
||||
|
||||
@@ -1203,7 +1170,7 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
|
||||
// adding the refund back on top of what's left to allocate).
|
||||
const legsById = useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
payments.forEach((p: any) => {
|
||||
payments.forEach((p) => {
|
||||
if (p.originalPaymentId && !p.isDonation) {
|
||||
m.set(p.originalPaymentId, (m.get(p.originalPaymentId) || 0) + Math.abs(p.amount || 0));
|
||||
}
|
||||
@@ -1214,9 +1181,9 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
|
||||
// Donations "relevant to that event" — donations logged against the same event as the
|
||||
// chosen registration that still have a remaining, unused balance.
|
||||
const donationsForEvent = useMemo(() => {
|
||||
if (!selectedRegistration) return [] as any[];
|
||||
if (!selectedRegistration) return [];
|
||||
const eventId = selectedRegistration.eventId || selectedRegistration.event?.id;
|
||||
return payments.filter((p: any) => {
|
||||
return payments.filter((p) => {
|
||||
if (!p.isDonation || p.registrationId) return false;
|
||||
if (String(p.eventId) !== String(eventId)) return false;
|
||||
if (sponsorshipsOnly && !p.isSponsorship) return false;
|
||||
@@ -1226,7 +1193,7 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
|
||||
}, [payments, selectedRegistration, legsById, sponsorshipsOnly]);
|
||||
|
||||
const selectedDonation = useMemo(
|
||||
() => payments.find((p: any) => String(p.id) === String(paymentId)),
|
||||
() => payments.find((p) => String(p.id) === String(paymentId)),
|
||||
[payments, paymentId]
|
||||
);
|
||||
|
||||
@@ -1305,7 +1272,7 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
|
||||
disabled={!registrationId}
|
||||
>
|
||||
<option value="">Select donation…</option>
|
||||
{donationsForEvent.map((p: any) => {
|
||||
{donationsForEvent.map((p) => {
|
||||
const remaining = (p.amount || 0) - (legsById.get(p.id) || 0);
|
||||
const donor = p.isSponsorship ? `Sponsorship: ${p.sponsorAnonymous ? 'anonymous' : (p.sponsorName || p.user?.name || 'sponsor')}` : (p.user?.name || p.userId || 'Donor');
|
||||
const label = `R ${remaining.toFixed(2)} of R ${(p.amount || 0).toFixed(2)} left — ${donor} — #${String(p.id).slice(0,8)}`;
|
||||
|
||||
Reference in New Issue
Block a user