Centralize seat capacity accounting and the payment provider registry.
Replace manualProviders.ts with a paymentProviders.ts registry (automatic vs manual settlement) and move all seat counting into capacity.ts as the single source of truth: only paid/checked-in tickets and pending_approval payments hold a seat, so abandoned checkouts never block sales. Admins can now knowingly approve a payment over capacity (allowOverCapacity), with the booking and admin UIs updated to match. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
c9a600b6d6
commit
71c277045b
@@ -5,7 +5,7 @@ import { useParams, useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import { eventsApi, ticketsApi, paymentOptionsApi, Event, PaymentOptionsConfig } from '@/lib/api';
|
||||
import { formatDateLong, formatTime, formatRucDisplay } from '@/lib/utils';
|
||||
import { formatDateLong, formatTime, formatRucDisplay, eventSpotsLeft, isEventSoldOut } from '@/lib/utils';
|
||||
import { isSafeExternalUrl } from '@/lib/safeRedirect';
|
||||
import toast from 'react-hot-toast';
|
||||
import type {
|
||||
@@ -108,16 +108,15 @@ export default function BookingPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
const bookedCount = eventRes.event.bookedCount ?? 0;
|
||||
const capacity = eventRes.event.capacity ?? 0;
|
||||
const soldOut = bookedCount >= capacity;
|
||||
if (soldOut) {
|
||||
// Server-authoritative availability — same formula the booking API
|
||||
// enforces, so a sold-out event is caught here, not at submit time.
|
||||
if (isEventSoldOut(eventRes.event)) {
|
||||
toast.error(t('events.details.soldOut'));
|
||||
router.push(`/events/${eventRes.event.slug}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const spotsLeft = Math.max(0, capacity - bookedCount);
|
||||
const spotsLeft = eventSpotsLeft(eventRes.event);
|
||||
setEvent(eventRes.event);
|
||||
// Cap quantity by available spots (never allow requesting more than spotsLeft)
|
||||
setTicketQuantity((q) => Math.min(q, Math.max(1, spotsLeft)));
|
||||
@@ -366,6 +365,23 @@ export default function BookingPage() {
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || t('booking.form.errors.bookingFailed'));
|
||||
// Capacity race on the last seats: refresh availability so the page
|
||||
// reflects reality (sold-out block / lower quantity cap) instead of the
|
||||
// stale counts loaded when the form was opened.
|
||||
const message = String(error?.message || '');
|
||||
if (/sold out|seats available/i.test(message)) {
|
||||
try {
|
||||
const { event: freshEvent } = await eventsApi.getById(params.eventId as string);
|
||||
setEvent(freshEvent);
|
||||
const freshSpots = eventSpotsLeft(freshEvent);
|
||||
if (freshSpots > 0) {
|
||||
setTicketQuantity((q) => Math.min(q, freshSpots));
|
||||
setAttendees((prev) => prev.slice(0, Math.max(0, freshSpots - 1)));
|
||||
}
|
||||
} catch {
|
||||
// Keep the stale event state if the refresh fails
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -388,8 +404,8 @@ export default function BookingPage() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount ?? 0));
|
||||
const isSoldOut = (event.bookedCount ?? 0) >= event.capacity;
|
||||
const spotsLeft = eventSpotsLeft(event);
|
||||
const isSoldOut = isEventSoldOut(event);
|
||||
|
||||
// Paying step - waiting for Lightning payment (compact design)
|
||||
if (step === 'paying' && bookingResult && bookingResult.lightningInvoice) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { eventsApi, Event } from '@/lib/api';
|
||||
import { formatPrice, formatDateLong, formatTime } from '@/lib/utils';
|
||||
import { formatPrice, formatDateLong, formatTime, eventSpotsLeft, isEventSoldOut } from '@/lib/utils';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import ShareButtons from '@/components/ShareButtons';
|
||||
@@ -43,9 +43,10 @@ export default function EventDetailClient({ eventId, initialEvent }: EventDetail
|
||||
.catch(console.error);
|
||||
}, [eventId]);
|
||||
|
||||
// Spots left: never negative; sold out when confirmed >= capacity
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount ?? 0));
|
||||
const isSoldOut = (event.bookedCount ?? 0) >= event.capacity;
|
||||
// Server-authoritative availability (paid + claimed seats count; abandoned
|
||||
// pending bookings don't) — matches the booking API's sold-out check exactly.
|
||||
const spotsLeft = eventSpotsLeft(event);
|
||||
const isSoldOut = isEventSoldOut(event);
|
||||
const maxTickets = isSoldOut ? 0 : Math.min(MAX_TICKETS_PER_PERSON, Math.max(1, spotsLeft));
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -117,7 +117,10 @@ function generateEventJsonLd(event: Event) {
|
||||
'@type': 'Offer',
|
||||
price: event.price,
|
||||
priceCurrency: event.currency,
|
||||
availability: Math.max(0, (event.capacity ?? 0) - (event.bookedCount ?? 0)) > 0
|
||||
availability:
|
||||
(typeof event.availableSeats === 'number'
|
||||
? event.availableSeats
|
||||
: Math.max(0, (event.capacity ?? 0) - (event.bookedCount ?? 0))) > 0
|
||||
? 'https://schema.org/InStock'
|
||||
: 'https://schema.org/SoldOut',
|
||||
url: `${siteUrl}/events/${event.slug}`,
|
||||
|
||||
@@ -222,7 +222,14 @@ export default function AdminEventsPage() {
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-600">{formatDate(event.startDatetime)}</td>
|
||||
<td className="px-4 py-3 text-sm">{event.bookedCount || 0} / {event.capacity}</td>
|
||||
<td className="px-4 py-3 text-sm">
|
||||
{(event.bookedCount || 0) + (event.claimedCount || 0)} / {event.capacity}
|
||||
{(event.claimedCount || 0) > 0 && (
|
||||
<span className="block text-[11px] text-yellow-600">
|
||||
{event.claimedCount} pending approval
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{getStatusBadge(event.status)}
|
||||
@@ -332,7 +339,12 @@ export default function AdminEventsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between mt-2 pt-2 border-t border-gray-100">
|
||||
<p className="text-xs text-gray-500">{event.bookedCount || 0} / {event.capacity} spots</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{(event.bookedCount || 0) + (event.claimedCount || 0)} / {event.capacity} spots
|
||||
{(event.claimedCount || 0) > 0 && (
|
||||
<span className="text-yellow-600"> · {event.claimedCount} pending</span>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
|
||||
<Link href={`/admin/events/${event.id}`}
|
||||
className="p-2 hover:bg-primary-yellow/20 text-primary-dark rounded-btn min-h-[36px] min-w-[36px] flex items-center justify-center">
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
UserGroupIcon,
|
||||
ExclamationTriangleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { parseDate } from '@/lib/utils';
|
||||
import { parseDate, eventSpotsLeft, isEventSoldOut } from '@/lib/utils';
|
||||
|
||||
export default function AdminDashboardPage() {
|
||||
const { t, locale } = useLanguage();
|
||||
@@ -112,16 +112,15 @@ export default function AdminDashboardPage() {
|
||||
<Card className="p-6">
|
||||
<h2 className="font-semibold text-lg mb-4">Alerts</h2>
|
||||
<div className="space-y-3">
|
||||
{/* Low capacity warnings */}
|
||||
{/* Low capacity warnings (availableSeats accounts for paid + claimed seats) */}
|
||||
{data?.upcomingEvents
|
||||
.filter(event => {
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount || 0));
|
||||
const percentFull = ((event.bookedCount || 0) / event.capacity) * 100;
|
||||
return percentFull >= 80 && spotsLeft > 0;
|
||||
const spotsLeft = eventSpotsLeft(event);
|
||||
return event.capacity > 0 && spotsLeft > 0 && spotsLeft / event.capacity <= 0.2;
|
||||
})
|
||||
.map(event => {
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount || 0));
|
||||
const percentFull = Math.round(((event.bookedCount || 0) / event.capacity) * 100);
|
||||
const spotsLeft = eventSpotsLeft(event);
|
||||
const percentFull = Math.round(((event.capacity - spotsLeft) / event.capacity) * 100);
|
||||
return (
|
||||
<Link
|
||||
key={event.id}
|
||||
@@ -142,7 +141,7 @@ export default function AdminDashboardPage() {
|
||||
|
||||
{/* Sold out events */}
|
||||
{data?.upcomingEvents
|
||||
.filter(event => Math.max(0, event.capacity - (event.bookedCount || 0)) === 0)
|
||||
.filter(event => isEventSoldOut(event))
|
||||
.map(event => (
|
||||
<Link
|
||||
key={event.id}
|
||||
@@ -160,16 +159,30 @@ export default function AdminDashboardPage() {
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{data && data.stats.pendingPayments > 0 && (
|
||||
<Link
|
||||
{/* Actionable: customer says they paid, needs verification */}
|
||||
{data && (data.stats.awaitingApprovalPayments ?? 0) > 0 && (
|
||||
<Link
|
||||
href="/admin/payments"
|
||||
className="flex items-center justify-between p-3 bg-yellow-50 rounded-btn hover:bg-yellow-100 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<CurrencyDollarIcon className="w-5 h-5 text-yellow-600" />
|
||||
<span className="text-sm">Pending payments</span>
|
||||
<span className="text-sm">Payments awaiting verification</span>
|
||||
</div>
|
||||
<span className="badge badge-warning">{data.stats.pendingPayments}</span>
|
||||
<span className="badge badge-warning">{data.stats.awaitingApprovalPayments}</span>
|
||||
</Link>
|
||||
)}
|
||||
{/* Informational: opened checkouts that never paid — hold no seats */}
|
||||
{data && data.stats.pendingPayments > 0 && (
|
||||
<Link
|
||||
href="/admin/payments"
|
||||
className="flex items-center justify-between p-3 bg-gray-50 rounded-btn hover:bg-gray-100 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<CurrencyDollarIcon className="w-5 h-5 text-gray-400" />
|
||||
<span className="text-sm text-gray-500">Unpaid started bookings</span>
|
||||
</div>
|
||||
<span className="badge badge-info">{data.stats.pendingPayments}</span>
|
||||
</Link>
|
||||
)}
|
||||
{data && data.stats.newContacts > 0 && (
|
||||
@@ -186,10 +199,11 @@ export default function AdminDashboardPage() {
|
||||
)}
|
||||
|
||||
{/* No alerts */}
|
||||
{data &&
|
||||
data.stats.pendingPayments === 0 &&
|
||||
data.stats.newContacts === 0 &&
|
||||
!data.upcomingEvents.some(e => ((e.bookedCount || 0) / e.capacity) >= 0.8) && (
|
||||
{data &&
|
||||
data.stats.pendingPayments === 0 &&
|
||||
(data.stats.awaitingApprovalPayments ?? 0) === 0 &&
|
||||
data.stats.newContacts === 0 &&
|
||||
!data.upcomingEvents.some(e => e.capacity > 0 && eventSpotsLeft(e) / e.capacity <= 0.2) && (
|
||||
<p className="text-gray-500 text-sm text-center py-2">No alerts at this time</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -218,7 +232,12 @@ export default function AdminDashboardPage() {
|
||||
<p className="text-xs text-gray-500">{formatDate(event.startDatetime)}</p>
|
||||
</div>
|
||||
<span className="text-sm text-gray-600">
|
||||
{event.bookedCount || 0}/{event.capacity}
|
||||
{(event.bookedCount || 0) + (event.claimedCount || 0)}/{event.capacity}
|
||||
{(event.claimedCount || 0) > 0 && (
|
||||
<span className="text-xs text-yellow-600 block text-right">
|
||||
{event.claimedCount} pending approval
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { paymentsApi, adminApi, eventsApi, PaymentWithDetails, Event, ExportedPayment, FinancialSummary } from '@/lib/api';
|
||||
import { isManualProvider } from '@/lib/api/payments';
|
||||
import { parseDate, formatRucDisplay } from '@/lib/utils';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
@@ -36,6 +37,9 @@ export default function AdminPaymentsPage() {
|
||||
const { t, locale } = useLanguage();
|
||||
const [payments, setPayments] = useState<PaymentWithDetails[]>([]);
|
||||
const [pendingApprovalPayments, setPendingApprovalPayments] = useState<PaymentWithDetails[]>([]);
|
||||
// Manual-gateway payments still in bare 'pending': the customer may have paid
|
||||
// without clicking "I've paid" — approvable directly from the approval tab.
|
||||
const [unclaimedManualPayments, setUnclaimedManualPayments] = useState<PaymentWithDetails[]>([]);
|
||||
const [events, setEvents] = useState<Event[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<Tab>('pending_approval');
|
||||
@@ -69,17 +73,19 @@ export default function AdminPaymentsPage() {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [pendingRes, allRes, eventsRes] = await Promise.all([
|
||||
const [pendingRes, allRes, unclaimedRes, eventsRes] = await Promise.all([
|
||||
paymentsApi.getPendingApproval(),
|
||||
paymentsApi.getAll({
|
||||
status: statusFilter || undefined,
|
||||
paymentsApi.getAll({
|
||||
status: statusFilter || undefined,
|
||||
provider: providerFilter || undefined,
|
||||
eventIds: eventFilter.length > 0 ? eventFilter : undefined,
|
||||
}),
|
||||
paymentsApi.getAll({ status: 'pending' }),
|
||||
eventsApi.getAll(),
|
||||
]);
|
||||
setPendingApprovalPayments(pendingRes.payments);
|
||||
setPayments(allRes.payments);
|
||||
setUnclaimedManualPayments(unclaimedRes.payments.filter(p => isManualProvider(p.provider)));
|
||||
setEvents(eventsRes.events);
|
||||
} catch (error) {
|
||||
toast.error('Failed to load payments');
|
||||
@@ -88,15 +94,35 @@ export default function AdminPaymentsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Approve with over-capacity confirmation: the backend rejects an approval
|
||||
// that would overbook the event unless the admin explicitly allows it.
|
||||
const approveWithCapacityConfirm = async (id: string, note?: string, email?: boolean) => {
|
||||
try {
|
||||
await paymentsApi.approve(id, note, email);
|
||||
} catch (error: any) {
|
||||
if (error?.code !== 'EVENT_OVER_CAPACITY') throw error;
|
||||
const seatsLeft = error?.data?.availableSeats ?? 0;
|
||||
const requested = error?.data?.requestedSeats ?? 1;
|
||||
const message = locale === 'es'
|
||||
? `El evento está lleno (quedan ${seatsLeft} lugares, esta reserva necesita ${requested}). ¿Aprobar de todas formas y sobrevender?`
|
||||
: `This event is full (${seatsLeft} seat(s) left, this booking needs ${requested}). Approve anyway and overbook?`;
|
||||
if (!confirm(message)) return false;
|
||||
await paymentsApi.approve(id, note, email, true);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleApprove = async (payment: PaymentWithDetails) => {
|
||||
setProcessing(true);
|
||||
try {
|
||||
await paymentsApi.approve(payment.id, noteText, sendEmail);
|
||||
toast.success(locale === 'es' ? 'Pago aprobado' : 'Payment approved');
|
||||
setSelectedPayment(null);
|
||||
setNoteText('');
|
||||
setSendEmail(true);
|
||||
loadData();
|
||||
const approved = await approveWithCapacityConfirm(payment.id, noteText, sendEmail);
|
||||
if (approved) {
|
||||
toast.success(locale === 'es' ? 'Pago aprobado' : 'Payment approved');
|
||||
setSelectedPayment(null);
|
||||
setNoteText('');
|
||||
setSendEmail(true);
|
||||
loadData();
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || 'Failed to approve payment');
|
||||
} finally {
|
||||
@@ -140,11 +166,13 @@ export default function AdminPaymentsPage() {
|
||||
|
||||
const handleConfirmPayment = async (id: string) => {
|
||||
try {
|
||||
await paymentsApi.approve(id);
|
||||
toast.success('Payment confirmed');
|
||||
loadData();
|
||||
} catch (error) {
|
||||
toast.error('Failed to confirm payment');
|
||||
const approved = await approveWithCapacityConfirm(id);
|
||||
if (approved) {
|
||||
toast.success('Payment confirmed');
|
||||
loadData();
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || 'Failed to confirm payment');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -298,6 +326,33 @@ export default function AdminPaymentsPage() {
|
||||
return labels[provider] || provider;
|
||||
};
|
||||
|
||||
// Manual gateways need admin verification; automatic ones confirm themselves.
|
||||
const getProviderKindBadge = (provider: string) => (
|
||||
isManualProvider(provider) ? (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-orange-50 text-orange-600">
|
||||
{locale === 'es' ? 'Manual' : 'Manual'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-blue-50 text-blue-600">
|
||||
{locale === 'es' ? 'Automático' : 'Auto'}
|
||||
</span>
|
||||
)
|
||||
);
|
||||
|
||||
// Age of a claim/booking, e.g. "3h" / "2d"; used to surface rotting approvals.
|
||||
const getAgeInfo = (dateStr?: string | null) => {
|
||||
if (!dateStr) return null;
|
||||
const ms = Date.now() - parseDate(dateStr).getTime();
|
||||
if (ms < 0) return null;
|
||||
const hours = Math.floor(ms / (60 * 60 * 1000));
|
||||
const label = hours < 1
|
||||
? (locale === 'es' ? 'hace <1 h' : '<1h ago')
|
||||
: hours < 48
|
||||
? (locale === 'es' ? `hace ${hours} h` : `${hours}h ago`)
|
||||
: (locale === 'es' ? `hace ${Math.floor(hours / 24)} días` : `${Math.floor(hours / 24)}d ago`);
|
||||
return { hours, label, stale: hours >= 48 };
|
||||
};
|
||||
|
||||
// Helper to get booking info for a payment (ticket count and total)
|
||||
const getBookingInfo = (payment: PaymentWithDetails) => {
|
||||
if (!payment.ticket?.bookingId) {
|
||||
@@ -331,6 +386,22 @@ export default function AdminPaymentsPage() {
|
||||
});
|
||||
})();
|
||||
|
||||
// Manual payments never claimed by the customer — they may have paid and
|
||||
// forgotten to press "I've paid", so they stay directly approvable here.
|
||||
// Hidden once the event has ended (same rule as pending approvals above).
|
||||
const visibleUnclaimedManualPayments = (() => {
|
||||
const now = new Date();
|
||||
return unclaimedManualPayments.filter((payment) => {
|
||||
const eventId = payment.event?.id;
|
||||
const fullEvent = eventId ? events.find((e) => e.id === eventId) : undefined;
|
||||
const endIso = fullEvent?.endDatetime
|
||||
|| fullEvent?.startDatetime
|
||||
|| payment.event?.startDatetime;
|
||||
if (!endIso) return true;
|
||||
return parseDate(endIso).getTime() >= now.getTime();
|
||||
});
|
||||
})();
|
||||
|
||||
// Get booking info for pending approval payments
|
||||
const getPendingBookingInfo = (payment: PaymentWithDetails) => {
|
||||
if (!payment.ticket?.bookingId) {
|
||||
@@ -348,9 +419,15 @@ export default function AdminPaymentsPage() {
|
||||
};
|
||||
};
|
||||
|
||||
// Calculate totals (sum all individual payment amounts)
|
||||
const totalPending = payments
|
||||
.filter(p => p.status === 'pending' || p.status === 'pending_approval')
|
||||
// Calculate totals (sum all individual payment amounts).
|
||||
// Claimed ('pending_approval') money is probably already in the account and
|
||||
// just needs verification; bare 'pending' money may never arrive — keep the
|
||||
// two apart so the totals don't overstate what's owed.
|
||||
const totalAwaitingVerification = payments
|
||||
.filter(p => p.status === 'pending_approval')
|
||||
.reduce((sum, p) => sum + Number(p.amount), 0);
|
||||
const totalUnclaimed = payments
|
||||
.filter(p => p.status === 'pending')
|
||||
.reduce((sum, p) => sum + Number(p.amount), 0);
|
||||
const totalPaid = payments
|
||||
.filter(p => p.status === 'paid')
|
||||
@@ -370,9 +447,6 @@ export default function AdminPaymentsPage() {
|
||||
return count;
|
||||
};
|
||||
|
||||
const pendingBookingsCount = getUniqueBookingsCount(
|
||||
payments.filter(p => p.status === 'pending' || p.status === 'pending_approval')
|
||||
);
|
||||
const paidBookingsCount = getUniqueBookingsCount(
|
||||
payments.filter(p => p.status === 'paid')
|
||||
);
|
||||
@@ -721,9 +795,12 @@ export default function AdminPaymentsPage() {
|
||||
<ClockIcon className="w-5 h-5 text-gray-600" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">{locale === 'es' ? 'Total Pendiente' : 'Total Pending'}</p>
|
||||
<p className="text-xl font-bold">{formatCurrency(totalPending, 'PYG')}</p>
|
||||
<p className="text-xs text-gray-400">{pendingBookingsCount} {locale === 'es' ? 'reservas' : 'bookings'}</p>
|
||||
<p className="text-sm text-gray-500">{locale === 'es' ? 'Por Verificar' : 'Awaiting Verification'}</p>
|
||||
<p className="text-xl font-bold text-yellow-600">{formatCurrency(totalAwaitingVerification, 'PYG')}</p>
|
||||
<p className="text-xs text-gray-400">
|
||||
{locale === 'es' ? 'Sin pagar (sin reclamar): ' : 'Unpaid (unclaimed): '}
|
||||
{formatCurrency(totalUnclaimed, 'PYG')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
@@ -817,13 +894,18 @@ export default function AdminPaymentsPage() {
|
||||
<span className="flex items-center gap-1">
|
||||
{getProviderIcon(payment.provider)}
|
||||
{getProviderLabel(payment.provider)}
|
||||
{getProviderKindBadge(payment.provider)}
|
||||
</span>
|
||||
{payment.userMarkedPaidAt && (
|
||||
<span className="flex items-center gap-1">
|
||||
<ClockIcon className="w-3 h-3" />
|
||||
{locale === 'es' ? 'Marcado:' : 'Marked:'} {formatDate(payment.userMarkedPaidAt)}
|
||||
</span>
|
||||
)}
|
||||
{payment.userMarkedPaidAt && (() => {
|
||||
const age = getAgeInfo(payment.userMarkedPaidAt);
|
||||
return (
|
||||
<span className={clsx('flex items-center gap-1', age?.stale && 'text-amber-600 font-medium')}>
|
||||
<ClockIcon className="w-3 h-3" />
|
||||
{locale === 'es' ? 'Marcado:' : 'Marked:'} {formatDate(payment.userMarkedPaidAt)}
|
||||
{age && <span>({age.label})</span>}
|
||||
</span>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
{payment.payerName && (
|
||||
<p className="text-xs text-amber-600 mt-1 font-medium">
|
||||
@@ -841,6 +923,55 @@ export default function AdminPaymentsPage() {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Manual payments the customer never confirmed — they may have paid
|
||||
(bank transfer / TPago received) without pressing "I've paid".
|
||||
Approving one claims a seat, so it goes through the same
|
||||
over-capacity confirmation as any approval. */}
|
||||
{visibleUnclaimedManualPayments.length > 0 && (
|
||||
<details className="mt-8">
|
||||
<summary className="cursor-pointer text-sm font-medium text-gray-600 select-none">
|
||||
{locale === 'es'
|
||||
? `Pagos manuales sin confirmar por el cliente (${visibleUnclaimedManualPayments.length})`
|
||||
: `Manual payments not yet confirmed by customer (${visibleUnclaimedManualPayments.length})`}
|
||||
<span className="block text-xs font-normal text-gray-400 mt-0.5">
|
||||
{locale === 'es'
|
||||
? 'Puede que hayan pagado sin presionar "Ya pagué". No reservan lugar hasta ser aprobados.'
|
||||
: 'They may have paid without pressing "I\'ve paid". These hold no seat until approved.'}
|
||||
</span>
|
||||
</summary>
|
||||
<div className="space-y-3 mt-4">
|
||||
{visibleUnclaimedManualPayments.map((payment) => {
|
||||
const age = getAgeInfo(payment.createdAt);
|
||||
return (
|
||||
<Card key={payment.id} className="p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center flex-shrink-0">
|
||||
{getProviderIcon(payment.provider)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{payment.ticket?.attendeeFirstName} {payment.ticket?.attendeeLastName}
|
||||
<span className="text-gray-400 font-normal"> · {formatCurrency(payment.amount, payment.currency)}</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 truncate">
|
||||
{payment.event?.title}
|
||||
{' · '}{getProviderLabel(payment.provider)}
|
||||
{age && <span> · {age.label}</span>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={() => setSelectedPayment(payment)} size="sm" variant="outline" className="flex-shrink-0 min-h-[40px]">
|
||||
{locale === 'es' ? 'Revisar' : 'Review'}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1004,6 +1135,7 @@ export default function AdminPaymentsPage() {
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-1.5 text-xs text-gray-600">
|
||||
{getProviderIcon(payment.provider)} {getProviderLabel(payment.provider)}
|
||||
{getProviderKindBadge(payment.provider)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">{getStatusBadge(payment.status)}</td>
|
||||
@@ -1063,7 +1195,7 @@ export default function AdminPaymentsPage() {
|
||||
<div className="mt-2 flex items-center gap-2 text-xs text-gray-500">
|
||||
<span className="font-medium text-gray-700">{formatCurrency(bookingInfo.bookingTotal, payment.currency)}</span>
|
||||
<span className="text-gray-300">|</span>
|
||||
<span className="flex items-center gap-1">{getProviderIcon(payment.provider)} {getProviderLabel(payment.provider)}</span>
|
||||
<span className="flex items-center gap-1">{getProviderIcon(payment.provider)} {getProviderLabel(payment.provider)} {getProviderKindBadge(payment.provider)}</span>
|
||||
{bookingInfo.ticketCount > 1 && (
|
||||
<><span className="text-gray-300">|</span><span className="text-purple-600">{bookingInfo.ticketCount} tickets</span></>
|
||||
)}
|
||||
|
||||
@@ -34,7 +34,12 @@ export async function fetchApi<T>(
|
||||
const errorMessage = typeof errorData.error === 'string'
|
||||
? errorData.error
|
||||
: (errorData.message || JSON.stringify(errorData) || 'Request failed');
|
||||
throw new Error(errorMessage);
|
||||
const error = new Error(errorMessage);
|
||||
// Preserve structured error info (e.g. code: 'EVENT_OVER_CAPACITY') so
|
||||
// callers can react beyond the message text.
|
||||
(error as any).code = errorData.code;
|
||||
(error as any).data = errorData;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res.json();
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { fetchApi } from './client';
|
||||
import type { Payment, PaymentWithDetails } from './types';
|
||||
|
||||
// Mirrors backend/src/lib/paymentProviders.ts: manual gateways need an admin to
|
||||
// verify the money arrived; automatic ones (lightning) confirm themselves.
|
||||
export const MANUAL_PAYMENT_PROVIDERS = ['tpago', 'bank_transfer', 'card', 'cash'];
|
||||
|
||||
export function isManualProvider(provider: string): boolean {
|
||||
return MANUAL_PAYMENT_PROVIDERS.includes(provider);
|
||||
}
|
||||
|
||||
export const paymentsApi = {
|
||||
getAll: (params?: { status?: string; provider?: string; pendingApproval?: boolean; eventId?: string; eventIds?: string[] }) => {
|
||||
const query = new URLSearchParams();
|
||||
@@ -21,10 +29,10 @@ export const paymentsApi = {
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
approve: (id: string, adminNote?: string, sendEmail: boolean = true) =>
|
||||
approve: (id: string, adminNote?: string, sendEmail: boolean = true, allowOverCapacity: boolean = false) =>
|
||||
fetchApi<{ payment: Payment; message: string }>(`/api/payments/${id}/approve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ adminNote, sendEmail }),
|
||||
body: JSON.stringify({ adminNote, sendEmail, allowOverCapacity }),
|
||||
}),
|
||||
|
||||
reject: (id: string, adminNote?: string, sendEmail: boolean = true) =>
|
||||
|
||||
@@ -18,8 +18,9 @@ export interface Event {
|
||||
bannerUrl?: string;
|
||||
externalBookingEnabled?: boolean;
|
||||
externalBookingUrl?: string;
|
||||
bookedCount?: number;
|
||||
availableSeats?: number;
|
||||
bookedCount?: number; // paid seats (confirmed + checked_in)
|
||||
claimedCount?: number; // "I've paid" claims awaiting admin verification (hold seats)
|
||||
availableSeats?: number; // capacity - booked - claimed; the server-authoritative number
|
||||
isFeatured?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -221,7 +222,10 @@ export interface DashboardData {
|
||||
totalEvents: number;
|
||||
totalTickets: number;
|
||||
confirmedTickets: number;
|
||||
/** Checkouts opened but never paid nor claimed — informational, holds no seat */
|
||||
pendingPayments: number;
|
||||
/** Customer says they paid; needs admin verification — actionable */
|
||||
awaitingApprovalPayments: number;
|
||||
totalRevenue: number;
|
||||
newContacts: number;
|
||||
totalSubscribers: number;
|
||||
|
||||
@@ -205,3 +205,33 @@ export function getTpagoLink(
|
||||
const key = (count <= 1 ? 'tpagoLink' : `tpagoLink${count}`) as keyof TpagoLinkConfig;
|
||||
return config[key] || config.tpagoLink || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spots left for an event, trusting the server's `availableSeats` (which uses
|
||||
* the same seat-holding formula the booking API enforces: paid + claimed
|
||||
* seats count, abandoned pending bookings don't). Falls back to deriving it
|
||||
* from the counts for older API responses.
|
||||
*/
|
||||
export function eventSpotsLeft(event: {
|
||||
capacity: number;
|
||||
bookedCount?: number;
|
||||
claimedCount?: number;
|
||||
availableSeats?: number;
|
||||
}): number {
|
||||
if (typeof event.availableSeats === 'number') {
|
||||
return Math.max(0, event.availableSeats);
|
||||
}
|
||||
return Math.max(
|
||||
0,
|
||||
(event.capacity ?? 0) - (event.bookedCount ?? 0) - (event.claimedCount ?? 0)
|
||||
);
|
||||
}
|
||||
|
||||
export function isEventSoldOut(event: {
|
||||
capacity: number;
|
||||
bookedCount?: number;
|
||||
claimedCount?: number;
|
||||
availableSeats?: number;
|
||||
}): boolean {
|
||||
return eventSpotsLeft(event) <= 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user