Refactor monolithic modules and harden booking, email, and auth infrastructure.

Split oversized frontend API client, email service, and admin/booking pages into focused modules while preserving import surfaces, and add Redis-backed queues, stale booking cleanup, stronger auth, and scale deployment configs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Michilis
2026-06-25 07:12:59 +00:00
co-authored by Cursor
parent f0e2de2834
commit 613bd7be1d
75 changed files with 7702 additions and 5580 deletions
@@ -0,0 +1,83 @@
import { useEffect } from 'react';
import toast from 'react-hot-toast';
import { ticketsApi } from '@/lib/api';
import type { BookingStep } from '../_types';
/**
* Watch for Lightning payment confirmation while on the paying step.
* SSE gives instant updates; a 3s poll runs in parallel as a safety net so a
* buffered/stuck stream (e.g. a proxy that doesn't flush SSE) can't strand the UI.
*/
export function useLightningWatcher(
step: BookingStep,
ticketId: string | undefined,
locale: string,
setPaymentPending: (value: boolean) => void,
setStep: (value: BookingStep) => void
) {
useEffect(() => {
if (step !== 'paying' || !ticketId) return;
let settled = false;
let pollTimer: ReturnType<typeof setTimeout> | null = null;
const confirmPaid = () => {
if (settled) return;
settled = true;
toast.success(locale === 'es' ? '¡Pago confirmado!' : 'Payment confirmed!');
setPaymentPending(false);
setStep('success');
};
const expire = () => {
if (settled) return;
settled = true;
toast.error(locale === 'es' ? 'La factura ha expirado' : 'Invoice has expired');
setPaymentPending(false);
};
// Always same-origin so the streaming proxy route handler is used (it
// bypasses the rewrite, which buffers SSE).
const eventSource = new EventSource(`/api/lnbits/stream/${ticketId}`);
eventSource.addEventListener('payment', (event) => {
try {
const data = JSON.parse((event as MessageEvent).data);
if (data.type === 'paid' || data.type === 'already_paid') {
confirmPaid();
} else if (data.type === 'expired') {
expire();
}
} catch (e) {
console.error('Error parsing payment event:', e);
}
});
eventSource.onerror = () => {
// SSE failed or was closed; the poll below remains the source of truth.
eventSource.close();
};
const poll = async () => {
try {
const status = await ticketsApi.checkPaymentStatus(ticketId);
if (status.isPaid) {
confirmPaid();
return;
}
} catch (error) {
console.error('Error checking payment status:', error);
}
if (!settled) {
pollTimer = setTimeout(poll, 3000);
}
};
pollTimer = setTimeout(poll, 3000);
return () => {
settled = true;
eventSource.close();
if (pollTimer) clearTimeout(pollTimer);
};
}, [step, ticketId, locale]);
}
@@ -0,0 +1,131 @@
import toast from 'react-hot-toast';
import { PaymentOptionsConfig } from '@/lib/api';
import {
CreditCardIcon,
BanknotesIcon,
BoltIcon,
BuildingLibraryIcon,
} from '@heroicons/react/24/outline';
import type { PaymentMethod, BookingResult } from '../_types';
export const rucPattern = /^\d{6,10}$/;
/** Format RUC input: digits only, max 10. */
export function formatRuc(value: string): string {
return value.replace(/\D/g, '').slice(0, 10);
}
/** Truncate a long invoice string for display. */
export function truncateInvoice(invoice: string, chars: number = 20): string {
if (invoice.length <= chars * 2) return invoice;
return `${invoice.slice(0, chars)}...${invoice.slice(-chars)}`;
}
/** Copy a Lightning invoice to the clipboard with localized feedback. */
export function copyInvoiceToClipboard(invoice: string, locale: string): void {
navigator.clipboard.writeText(invoice).then(() => {
toast.success(locale === 'es' ? '¡Copiado!' : 'Copied!');
}).catch(() => {
toast.error(locale === 'es' ? 'Error al copiar' : 'Failed to copy');
});
}
export interface PaymentMethodOption {
id: PaymentMethod;
icon: typeof CreditCardIcon;
label: string;
description: string;
badge?: string;
}
/** Build the list of selectable payment methods from the event config. */
export function buildPaymentMethods(
paymentConfig: PaymentOptionsConfig | null,
locale: string
): PaymentMethodOption[] {
const paymentMethods: PaymentMethodOption[] = [];
if (paymentConfig?.lightningEnabled) {
paymentMethods.push({
id: 'lightning',
icon: BoltIcon,
label: 'Bitcoin Lightning',
description: locale === 'es' ? 'Pago instantáneo con Bitcoin' : 'Instant payment with Bitcoin',
badge: locale === 'es' ? 'Instantáneo' : 'Instant',
});
}
if (paymentConfig?.tpagoEnabled) {
paymentMethods.push({
id: 'tpago',
icon: CreditCardIcon,
label: locale === 'es' ? 'TPago / Tarjetas de Crédito' : 'TPago / Credit Cards',
description: locale === 'es' ? 'Pagá con tarjetas de crédito locales o internacionales' : 'Pay with local or international credit cards',
badge: locale === 'es' ? 'Manual' : 'Manual',
});
}
if (paymentConfig?.bankTransferEnabled) {
paymentMethods.push({
id: 'bank_transfer',
icon: BuildingLibraryIcon,
label: locale === 'es' ? 'Transferencia Bancaria Local' : 'Local Bank Transfer',
description: locale === 'es' ? 'Pago por transferencia bancaria en Paraguay' : 'Pay via Paraguayan bank transfer',
badge: locale === 'es' ? 'Manual' : 'Manual',
});
}
if (paymentConfig?.cashEnabled) {
paymentMethods.push({
id: 'cash',
icon: BanknotesIcon,
label: locale === 'es' ? 'Efectivo en el Evento' : 'Cash at Event',
description: locale === 'es' ? 'Paga cuando llegues al evento' : 'Pay when you arrive at the event',
badge: locale === 'es' ? 'Manual' : 'Manual',
});
}
return paymentMethods;
}
export interface SuccessContent {
title: string;
description: string;
iconColor: string;
iconTextColor: string;
}
/** Resolve the success-screen copy based on the payment method used. */
export function getSuccessContent(
bookingResult: BookingResult | null,
locale: string,
t: (key: string) => string
): SuccessContent {
if (bookingResult?.paymentMethod === 'cash') {
return {
title: locale === 'es' ? '¡Reserva Recibida!' : 'Reservation Received!',
description: locale === 'es'
? 'Tu lugar está reservado. El pago se realizará en el evento.'
: 'Your spot is reserved. Payment will be collected at the event.',
iconColor: 'bg-yellow-100',
iconTextColor: 'text-yellow-600',
};
}
if (bookingResult?.paymentMethod === 'lightning') {
// For Lightning, if we're on success step, payment was confirmed
return {
title: locale === 'es' ? '¡Pago Confirmado!' : 'Payment Confirmed!',
description: locale === 'es'
? '¡Tu reserva está confirmada! Te esperamos en el evento.'
: 'Your booking is confirmed! See you at the event.',
iconColor: 'bg-green-100',
iconTextColor: 'text-green-600',
};
}
return {
title: t('booking.success.title'),
description: t('booking.success.description'),
iconColor: 'bg-green-100',
iconTextColor: 'text-green-600',
};
}
@@ -0,0 +1,447 @@
import Link from 'next/link';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import {
CalendarIcon,
MapPinIcon,
UserGroupIcon,
CurrencyDollarIcon,
ArrowLeftIcon,
CheckCircleIcon,
UserIcon,
} from '@heroicons/react/24/outline';
import { Event } from '@/lib/api';
import { formatPrice } from '@/lib/utils';
import type { AttendeeInfo, BookingFormData } from '../_types';
import type { PaymentMethodOption } from '../_logic/booking';
interface BookingFormStepProps {
event: Event;
locale: string;
t: (key: string) => string;
spotsLeft: number;
isSoldOut: boolean;
ticketQuantity: number;
formData: BookingFormData;
setFormData: React.Dispatch<React.SetStateAction<BookingFormData>>;
errors: Partial<Record<keyof BookingFormData, string>>;
attendees: AttendeeInfo[];
setAttendees: React.Dispatch<React.SetStateAction<AttendeeInfo[]>>;
attendeeErrors: { [key: number]: string };
setAttendeeErrors: React.Dispatch<React.SetStateAction<{ [key: number]: string }>>;
handleRucChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
handleRucBlur: () => void;
paymentMethods: PaymentMethodOption[];
agreedToTerms: boolean;
setAgreedToTerms: (value: boolean) => void;
termsError: string | null;
submitting: boolean;
onSubmit: (e: React.FormEvent) => void;
formatDate: (dateStr: string) => string;
fmtTime: (dateStr: string) => string;
}
export function BookingFormStep({
event,
locale,
t,
spotsLeft,
isSoldOut,
ticketQuantity,
formData,
setFormData,
errors,
attendees,
setAttendees,
attendeeErrors,
setAttendeeErrors,
handleRucChange,
handleRucBlur,
paymentMethods,
agreedToTerms,
setAgreedToTerms,
termsError,
submitting,
onSubmit,
formatDate,
fmtTime,
}: BookingFormStepProps) {
return (
<div className="section-padding bg-secondary-gray min-h-screen">
<div className="container-page max-w-2xl">
<Link
href={`/events/${event.slug}`}
className="inline-flex items-center gap-2 text-gray-600 hover:text-primary-dark mb-6"
>
<ArrowLeftIcon className="w-4 h-4" />
{t('common.back')}
</Link>
{/* Event Summary - Always Visible */}
<Card className="mb-6 overflow-hidden">
<div className="bg-primary-yellow/20 p-4 border-b border-primary-yellow/30">
<h2 className="font-bold text-lg text-primary-dark">
{locale === 'es' && event.titleEs ? event.titleEs : event.title}
</h2>
</div>
<div className="p-4 space-y-2 text-sm">
<div className="flex items-center gap-3">
<CalendarIcon className="w-5 h-5 text-primary-yellow" />
<span>{formatDate(event.startDatetime)} {fmtTime(event.startDatetime)}</span>
</div>
<div className="flex items-center gap-3">
<MapPinIcon className="w-5 h-5 text-primary-yellow" />
<span>{event.location}</span>
</div>
{!event.externalBookingEnabled && (
<div className="flex items-center gap-3">
<UserGroupIcon className="w-5 h-5 text-primary-yellow" />
<span>{spotsLeft} / {event.capacity} {t('events.details.spotsLeft')}</span>
</div>
)}
<div className="flex items-center gap-3">
<CurrencyDollarIcon className="w-5 h-5 text-primary-yellow" />
<span className="font-bold text-lg">
{event.price === 0
? t('events.details.free')
: formatPrice(event.price, event.currency)}
</span>
{event.price > 0 && (
<span className="text-gray-400 text-sm">
{locale === 'es' ? 'por persona' : 'per person'}
</span>
)}
</div>
{/* Ticket quantity and total */}
{ticketQuantity > 1 && (
<div className="mt-3 pt-3 border-t border-secondary-light-gray">
<div className="flex items-center justify-between">
<span className="text-gray-600">
{locale === 'es' ? 'Tickets' : 'Tickets'}: <span className="font-semibold">{ticketQuantity}</span>
</span>
<span className="font-bold text-lg text-primary-dark">
{locale === 'es' ? 'Total' : 'Total'}: {formatPrice(event.price * ticketQuantity, event.currency)}
</span>
</div>
</div>
)}
</div>
</Card>
{isSoldOut ? (
<Card className="p-8 text-center">
<UserGroupIcon className="w-16 h-16 text-gray-300 mx-auto mb-4" />
<h2 className="text-xl font-bold text-gray-700">{t('events.details.soldOut')}</h2>
<p className="text-gray-500 mt-2">{t('booking.form.soldOutMessage')}</p>
</Card>
) : (
<form onSubmit={onSubmit}>
{/* User Information Section */}
<Card className="mb-6 p-6">
<h3 className="font-bold text-lg mb-4 text-primary-dark flex items-center gap-2">
{attendees.length > 0 && (
<span className="w-6 h-6 rounded-full bg-primary-yellow text-primary-dark text-sm font-bold flex items-center justify-center">
1
</span>
)}
{t('booking.form.personalInfo')}
{attendees.length > 0 && (
<span className="text-sm font-normal text-gray-500">
({locale === 'es' ? 'Asistente principal' : 'Primary attendee'})
</span>
)}
</h3>
<div className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Input
label={t('booking.form.firstName')}
value={formData.firstName}
onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
placeholder={t('booking.form.firstNamePlaceholder')}
error={errors.firstName}
required
/>
<div>
<div className="flex items-center gap-2 mb-1">
<label className="block text-sm font-medium text-gray-700">
{t('booking.form.lastName')}
</label>
<span className="text-xs text-gray-400">
({locale === 'es' ? 'Opcional' : 'Optional'})
</span>
</div>
<Input
value={formData.lastName}
onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
placeholder={t('booking.form.lastNamePlaceholder')}
error={errors.lastName}
/>
</div>
</div>
<div>
<Input
label={t('booking.form.email')}
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
placeholder={t('booking.form.emailPlaceholder')}
error={errors.email}
required
/>
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<label className="block text-sm font-medium text-gray-700">
{t('booking.form.phone')}
</label>
<span className="text-xs text-gray-400">
({locale === 'es' ? 'Opcional' : 'Optional'})
</span>
</div>
<Input
type="tel"
value={formData.phone}
onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
placeholder={t('booking.form.phonePlaceholder')}
error={errors.phone}
/>
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<label className="block text-sm font-medium text-gray-700">
{t('booking.form.ruc')}
</label>
<span className="text-xs text-gray-400">
{t('booking.form.rucOptional')}
</span>
</div>
<Input
value={formData.ruc}
onChange={handleRucChange}
onBlur={handleRucBlur}
placeholder={t('booking.form.rucPlaceholder')}
error={errors.ruc}
inputMode="numeric"
maxLength={10}
aria-label={t('booking.form.ruc')}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{t('booking.form.preferredLanguage')}
</label>
<select
value={formData.preferredLanguage}
onChange={(e) => setFormData({ ...formData, preferredLanguage: e.target.value as 'en' | 'es' })}
className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
>
<option value="en">English</option>
<option value="es">Español</option>
</select>
</div>
</div>
</Card>
{/* Additional Attendees Section (for multi-ticket bookings) */}
{attendees.length > 0 && (
<Card className="mb-6 p-6">
<h3 className="font-bold text-lg mb-4 text-primary-dark flex items-center gap-2">
<UserIcon className="w-5 h-5 text-primary-yellow" />
{locale === 'es' ? 'Información de los Otros Asistentes' : 'Other Attendees Information'}
</h3>
<p className="text-sm text-gray-600 mb-4">
{locale === 'es'
? 'Ingresa el nombre de cada asistente adicional. Cada persona recibirá su propio ticket.'
: 'Enter the name for each additional attendee. Each person will receive their own ticket.'}
</p>
<div className="space-y-4">
{attendees.map((attendee, index) => (
<div key={index} className="p-4 bg-gray-50 rounded-lg">
<div className="flex items-center gap-2 mb-3">
<span className="w-6 h-6 rounded-full bg-primary-yellow text-primary-dark text-sm font-bold flex items-center justify-center">
{index + 2}
</span>
<span className="font-medium text-gray-700">
{locale === 'es' ? `Asistente ${index + 2}` : `Attendee ${index + 2}`}
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Input
label={t('booking.form.firstName')}
value={attendee.firstName}
onChange={(e) => {
const newAttendees = [...attendees];
newAttendees[index].firstName = e.target.value;
setAttendees(newAttendees);
if (attendeeErrors[index]) {
const newErrors = { ...attendeeErrors };
delete newErrors[index];
setAttendeeErrors(newErrors);
}
}}
placeholder={t('booking.form.firstNamePlaceholder')}
error={attendeeErrors[index]}
required
/>
<div>
<div className="flex items-center gap-2 mb-1">
<label className="block text-sm font-medium text-gray-700">
{t('booking.form.lastName')}
</label>
<span className="text-xs text-gray-400">
({locale === 'es' ? 'Opcional' : 'Optional'})
</span>
</div>
<Input
value={attendee.lastName}
onChange={(e) => {
const newAttendees = [...attendees];
newAttendees[index].lastName = e.target.value;
setAttendees(newAttendees);
}}
placeholder={t('booking.form.lastNamePlaceholder')}
/>
</div>
</div>
</div>
))}
</div>
</Card>
)}
{/* Payment Selection Section */}
<Card className="mb-6 p-6">
<h3 className="font-bold text-lg mb-4 text-primary-dark">
{t('booking.form.paymentMethod')}
</h3>
<div className="space-y-3">
{paymentMethods.length === 0 ? (
<div className="text-center py-8 text-gray-500">
{locale === 'es'
? 'No hay métodos de pago disponibles para este evento.'
: 'No payment methods available for this event.'}
</div>
) : (
<>
{paymentMethods.map((method) => (
<button
key={method.id}
type="button"
onClick={() => setFormData({ ...formData, paymentMethod: method.id })}
className={`w-full p-4 rounded-lg border-2 transition-all text-left flex items-start gap-4 ${
formData.paymentMethod === method.id
? 'border-primary-yellow bg-primary-yellow/10'
: 'border-secondary-light-gray hover:border-gray-300'
}`}
>
<div className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${
formData.paymentMethod === method.id
? 'bg-primary-yellow'
: 'bg-gray-100'
}`}>
<method.icon className={`w-5 h-5 ${
formData.paymentMethod === method.id
? 'text-primary-dark'
: 'text-gray-500'
}`} />
</div>
<div className="flex-1">
<div className="flex items-center gap-2">
<p className="font-medium text-primary-dark">{method.label}</p>
{method.badge && (
<span className={`text-xs px-2 py-0.5 rounded-full ${
method.badge === 'Instant' || method.badge === 'Instantáneo'
? 'bg-green-100 text-green-700'
: 'bg-gray-100 text-gray-600'
}`}>
{method.badge}
</span>
)}
</div>
<p className="text-sm text-gray-500">{method.description}</p>
</div>
{formData.paymentMethod === method.id && (
<CheckCircleIcon className="w-6 h-6 text-primary-yellow ml-auto flex-shrink-0" />
)}
</button>
))}
</>
)}
</div>
</Card>
{/* Terms & Privacy agreement */}
<Card className="mb-6 p-6">
<div className="flex items-start gap-3">
<input
id="booking-terms-agree"
type="checkbox"
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
aria-required="true"
aria-invalid={termsError ? true : undefined}
aria-describedby={termsError ? 'booking-terms-error' : undefined}
className="h-5 w-5 mt-0.5 flex-shrink-0 accent-primary-yellow rounded focus:outline-none focus:ring-2 focus:ring-primary-yellow focus:ring-offset-2 cursor-pointer"
/>
<label
htmlFor="booking-terms-agree"
className="text-sm text-gray-500 leading-relaxed cursor-pointer select-none"
>
{t('booking.form.termsAgreePart1')}
<Link
href={`/legal/terms-policy${locale === 'es' ? '?locale=es' : ''}`}
target="_blank"
rel="noopener noreferrer"
className="text-secondary-blue hover:text-brand-navy underline"
>
{t('booking.form.termsOfService')}
</Link>
{t('booking.form.termsAgreePart2')}
<Link
href={`/legal/privacy-policy${locale === 'es' ? '?locale=es' : ''}`}
target="_blank"
rel="noopener noreferrer"
className="text-secondary-blue hover:text-brand-navy underline"
>
{t('booking.form.privacyPolicy')}
</Link>
{t('booking.form.termsAgreePart3')}
</label>
</div>
{termsError && (
<p id="booking-terms-error" className="mt-1.5 text-sm text-red-600">
{termsError}
</p>
)}
</Card>
{/* Submit Button */}
<Button
type="submit"
size="lg"
className="w-full"
isLoading={submitting}
disabled={paymentMethods.length === 0 || !agreedToTerms}
>
{formData.paymentMethod === 'cash'
? t('booking.form.reserveSpot')
: formData.paymentMethod === 'lightning'
? t('booking.form.proceedPayment')
: locale === 'es' ? 'Continuar al Pago' : 'Continue to Payment'
}
</Button>
</form>
)}
</div>
</div>
);
}
@@ -0,0 +1,249 @@
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import {
CreditCardIcon,
BuildingLibraryIcon,
CheckCircleIcon,
ArrowTopRightOnSquareIcon,
} from '@heroicons/react/24/outline';
import { Event, PaymentOptionsConfig } from '@/lib/api';
import { formatPrice, getTpagoLink } from '@/lib/utils';
import type { BookingResult } from '../_types';
interface ManualPaymentStepProps {
bookingResult: BookingResult;
event: Event;
paymentConfig: PaymentOptionsConfig;
locale: string;
paidUnderDifferentName: boolean;
setPaidUnderDifferentName: (value: boolean) => void;
payerName: string;
setPayerName: (value: string) => void;
markingPaid: boolean;
onMarkPaymentSent: () => void;
}
export function ManualPaymentStep({
bookingResult,
event,
paymentConfig,
locale,
paidUnderDifferentName,
setPaidUnderDifferentName,
payerName,
setPayerName,
markingPaid,
onMarkPaymentSent,
}: ManualPaymentStepProps) {
const isBankTransfer = bookingResult.paymentMethod === 'bank_transfer';
const isTpago = bookingResult.paymentMethod === 'tpago';
const ticketCount = bookingResult.ticketCount || 1;
const totalAmount = (event?.price || 0) * ticketCount;
const tpagoLink = getTpagoLink(paymentConfig, ticketCount);
return (
<div className="section-padding">
<div className="container-page max-w-xl">
<Card className="p-6">
<div className="text-center mb-6">
<div className={`w-16 h-16 rounded-full ${isBankTransfer ? 'bg-green-100' : 'bg-blue-100'} flex items-center justify-center mx-auto mb-4`}>
{isBankTransfer ? (
<BuildingLibraryIcon className="w-8 h-8 text-green-600" />
) : (
<CreditCardIcon className="w-8 h-8 text-blue-600" />
)}
</div>
<h1 className="text-xl font-bold text-primary-dark mb-2">
{locale === 'es' ? 'Completa tu Pago' : 'Complete Your Payment'}
</h1>
<p className="text-gray-600">
{locale === 'es'
? 'Sigue las instrucciones para completar tu pago'
: 'Follow the instructions to complete your payment'}
</p>
</div>
{/* Amount to pay */}
<div className="bg-gray-50 rounded-lg p-4 mb-6 text-center">
<p className="text-sm text-gray-500 mb-1">
{locale === 'es' ? 'Monto a pagar' : 'Amount to pay'}
</p>
<p className="text-2xl font-bold text-primary-dark">
{event?.price !== undefined ? formatPrice(totalAmount, event.currency) : ''}
</p>
{ticketCount > 1 && (
<p className="text-sm text-gray-500 mt-1">
{ticketCount} tickets × {formatPrice(event?.price || 0, event?.currency || 'PYG')}
</p>
)}
</div>
{/* Bank Transfer Details */}
{isBankTransfer && (
<div className="space-y-4 mb-6">
<h3 className="font-semibold text-gray-900">
{locale === 'es' ? 'Datos Bancarios' : 'Bank Details'}
</h3>
<div className="bg-green-50 border border-green-200 rounded-lg p-4 space-y-3">
{paymentConfig.bankName && (
<div className="flex justify-between">
<span className="text-gray-600">{locale === 'es' ? 'Banco' : 'Bank'}:</span>
<span className="font-medium">{paymentConfig.bankName}</span>
</div>
)}
{paymentConfig.bankAccountHolder && (
<div className="flex justify-between">
<span className="text-gray-600">{locale === 'es' ? 'Titular' : 'Account Holder'}:</span>
<span className="font-medium">{paymentConfig.bankAccountHolder}</span>
</div>
)}
{paymentConfig.bankAccountNumber && (
<div className="flex justify-between">
<span className="text-gray-600">{locale === 'es' ? 'Nro. Cuenta' : 'Account Number'}:</span>
<span className="font-medium font-mono">{paymentConfig.bankAccountNumber}</span>
</div>
)}
{paymentConfig.bankAlias && (
<div className="flex justify-between">
<span className="text-gray-600">Alias:</span>
<span className="font-medium">{paymentConfig.bankAlias}</span>
</div>
)}
{paymentConfig.bankPhone && (
<div className="flex justify-between">
<span className="text-gray-600">{locale === 'es' ? 'Teléfono' : 'Phone'}:</span>
<span className="font-medium">{paymentConfig.bankPhone}</span>
</div>
)}
</div>
{(locale === 'es' ? paymentConfig.bankNotesEs : paymentConfig.bankNotes) && (
<p className="text-sm text-gray-600">
{locale === 'es' ? paymentConfig.bankNotesEs : paymentConfig.bankNotes}
</p>
)}
</div>
)}
{/* TPago Link */}
{isTpago && (
<div className="space-y-4 mb-6">
<h3 className="font-semibold text-gray-900">
{locale === 'es' ? 'Pago con Tarjeta' : 'Card Payment'}
</h3>
{tpagoLink && (
<a
href={tpagoLink}
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-center gap-2 w-full px-6 py-4 bg-blue-600 text-white rounded-btn hover:bg-blue-700 transition-colors font-medium"
>
<ArrowTopRightOnSquareIcon className="w-5 h-5" />
{locale === 'es' ? 'Abrir TPago para Pagar' : 'Open TPago to Pay'}
</a>
)}
{(locale === 'es' ? paymentConfig.tpagoInstructionsEs : paymentConfig.tpagoInstructions) && (
<p className="text-sm text-gray-600">
{locale === 'es' ? paymentConfig.tpagoInstructionsEs : paymentConfig.tpagoInstructions}
</p>
)}
</div>
)}
{/* Reference */}
<div className="bg-gray-100 rounded-lg p-3 mb-6">
<p className="text-xs text-gray-500 mb-1">
{locale === 'es' ? 'Referencia de tu reserva' : 'Your booking reference'}
</p>
<p className="font-mono font-bold text-lg">{bookingResult.qrCode}</p>
</div>
{/* Manual verification notice */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
<div className="flex gap-3">
<div className="flex-shrink-0">
<svg className="w-5 h-5 text-blue-600 mt-0.5" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z" />
</svg>
</div>
<div className="text-sm text-blue-800">
<p className="font-medium mb-1">
{locale === 'es' ? 'Verificación manual' : 'Manual verification'}
</p>
<p className="text-blue-700">
{locale === 'es'
? 'El equipo de Spanglish revisará el pago manualmente. Tu reserva solo será confirmada después de recibir un email de confirmación de nuestra parte.'
: 'The Spanglish team will review the payment manually. Your booking is only confirmed after you receive a confirmation email from us.'}
</p>
</div>
</div>
</div>
{/* Paid under different name option */}
<div className="bg-gray-50 rounded-lg p-4 mb-4">
<label className="flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
checked={paidUnderDifferentName}
onChange={(e) => {
setPaidUnderDifferentName(e.target.checked);
if (!e.target.checked) setPayerName('');
}}
className="mt-1 w-4 h-4 text-primary-yellow border-gray-300 rounded focus:ring-primary-yellow"
/>
<div>
<span className="font-medium text-gray-700">
{locale === 'es'
? 'El pago está a nombre de otra persona'
: 'The payment is under another person\'s name'}
</span>
<p className="text-xs text-gray-500 mt-1">
{locale === 'es'
? 'Marcá esta opción si el pago fue realizado por un familiar o tercero.'
: 'Check this option if the payment was made by a family member or a third party.'}
</p>
</div>
</label>
{paidUnderDifferentName && (
<div className="mt-3 pl-7">
<Input
label={locale === 'es' ? 'Nombre del pagador' : 'Payer name'}
value={payerName}
onChange={(e) => setPayerName(e.target.value)}
placeholder={locale === 'es' ? 'Nombre completo del titular de la cuenta' : 'Full name of account holder'}
required
/>
</div>
)}
</div>
{/* Warning before I Have Paid button */}
<p className="text-sm text-center text-amber-700 font-medium mb-3">
{locale === 'es'
? 'Solo haz clic aquí después de haber completado el pago.'
: 'Only click this after you have actually completed the payment.'}
</p>
{/* I Have Paid Button */}
<Button
onClick={onMarkPaymentSent}
isLoading={markingPaid}
size="lg"
className="w-full"
disabled={paidUnderDifferentName && !payerName.trim()}
>
<CheckCircleIcon className="w-5 h-5 mr-2" />
{locale === 'es' ? 'Ya Realicé el Pago' : 'I Have Paid'}
</Button>
<p className="text-xs text-center text-gray-500 mt-4">
{locale === 'es'
? 'Tu reserva será confirmada una vez que verifiquemos el pago'
: 'Your booking will be confirmed once we verify the payment'}
</p>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,81 @@
import { QRCodeSVG } from 'qrcode.react';
import Card from '@/components/ui/Card';
import { BoltIcon, ClipboardDocumentIcon } from '@heroicons/react/24/outline';
import { copyInvoiceToClipboard, truncateInvoice } from '../_logic/booking';
import type { LightningInvoice } from '../_types';
interface PayingStepProps {
invoice: LightningInvoice;
qrCode: string;
locale: string;
}
export function PayingStep({ invoice, qrCode, locale }: PayingStepProps) {
return (
<div className="section-padding">
<div className="container-page max-w-md">
<Card className="p-6 text-center">
{/* Amount - prominent at top */}
<div className="mb-4">
{invoice.fiatAmount && invoice.fiatCurrency && (
<p className="text-2xl font-bold text-primary-dark">
{invoice.fiatAmount.toLocaleString()} {invoice.fiatCurrency}
</p>
)}
<p className="text-orange-600 font-medium">
{invoice.amount.toLocaleString()} sats
</p>
</div>
{/* QR Code - clickable to copy */}
<div
className="bg-white p-4 rounded-lg shadow-inner inline-block mb-4 cursor-pointer hover:shadow-md transition-shadow"
onClick={() => copyInvoiceToClipboard(invoice.paymentRequest, locale)}
title={locale === 'es' ? 'Clic para copiar' : 'Click to copy'}
>
<QRCodeSVG
value={invoice.paymentRequest.toUpperCase()}
size={200}
level="M"
includeMargin={false}
/>
</div>
{/* Invoice string - truncated, clickable */}
<div
className="bg-secondary-gray rounded-lg p-3 mb-4 cursor-pointer hover:bg-gray-200 transition-colors"
onClick={() => copyInvoiceToClipboard(invoice.paymentRequest, locale)}
>
<p className="font-mono text-xs text-gray-600 flex items-center justify-center gap-2">
<ClipboardDocumentIcon className="w-4 h-4 flex-shrink-0" />
<span className="truncate">{truncateInvoice(invoice.paymentRequest, 16)}</span>
</p>
<p className="text-xs text-gray-400 mt-1">
{locale === 'es' ? 'Toca para copiar' : 'Tap to copy'}
</p>
</div>
{/* Open in Wallet - primary action */}
<a
href={`lightning:${invoice.paymentRequest}`}
className="inline-flex items-center justify-center gap-2 w-full px-6 py-3 bg-orange-500 text-white rounded-btn hover:bg-orange-600 transition-colors font-medium mb-4"
>
<BoltIcon className="w-5 h-5" />
{locale === 'es' ? 'Abrir en Billetera' : 'Open in Wallet'}
</a>
{/* Status indicator */}
<div className="flex items-center justify-center gap-2 text-gray-500 text-sm">
<div className="animate-spin w-3 h-3 border-2 border-orange-400 border-t-transparent rounded-full" />
<span>{locale === 'es' ? 'Esperando pago...' : 'Waiting for payment...'}</span>
</div>
{/* Ticket reference - small */}
<p className="text-xs text-gray-400 mt-3">
{locale === 'es' ? 'Ref' : 'Ref'}: {qrCode}
</p>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,76 @@
import Link from 'next/link';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import { ClockIcon, TicketIcon } from '@heroicons/react/24/outline';
import { Event } from '@/lib/api';
import type { BookingResult } from '../_types';
interface PendingApprovalStepProps {
bookingResult: BookingResult;
event: Event | null;
locale: string;
t: (key: string) => string;
formatDate: (dateStr: string) => string;
fmtTime: (dateStr: string) => string;
}
export function PendingApprovalStep({
bookingResult,
event,
locale,
t,
formatDate,
fmtTime,
}: PendingApprovalStepProps) {
return (
<div className="section-padding">
<div className="container-page max-w-xl">
<Card className="p-8 text-center">
<div className="w-16 h-16 rounded-full bg-yellow-100 flex items-center justify-center mx-auto mb-6">
<ClockIcon className="w-10 h-10 text-yellow-600" />
</div>
<h1 className="text-2xl font-bold text-primary-dark mb-2">
{locale === 'es' ? '¡Pago en Verificación!' : 'Payment Being Verified!'}
</h1>
<p className="text-gray-600 mb-6">
{locale === 'es'
? 'Estamos verificando tu pago. Recibirás un email de confirmación una vez aprobado.'
: 'We are verifying your payment. You will receive a confirmation email once approved.'}
</p>
<div className="bg-secondary-gray rounded-lg p-6 mb-6">
<div className="flex items-center justify-center gap-2 mb-4">
<TicketIcon className="w-6 h-6 text-primary-yellow" />
<span className="font-mono text-lg font-bold">{bookingResult.qrCode}</span>
</div>
<div className="text-sm text-gray-600 space-y-2">
<p><strong>{t('booking.success.event')}:</strong> {event?.title}</p>
<p><strong>{t('booking.success.date')}:</strong> {event && formatDate(event.startDatetime)}</p>
<p><strong>{t('booking.success.time')}:</strong> {event && fmtTime(event.startDatetime)}</p>
<p><strong>{t('booking.success.location')}:</strong> {event?.location}</p>
</div>
</div>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
<p className="text-yellow-800 text-sm">
{locale === 'es'
? 'La verificación del pago puede tomar hasta 24 horas hábiles. Por favor revisa tu email regularmente.'
: 'Payment verification may take up to 24 business hours. Please check your email regularly.'}
</p>
</div>
<div className="flex flex-col sm:flex-row gap-3 justify-center">
<Link href="/events">
<Button variant="outline">{t('booking.success.browseEvents')}</Button>
</Link>
<Link href="/">
<Button>{t('booking.success.backHome')}</Button>
</Link>
</div>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,144 @@
import Link from 'next/link';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import {
CheckCircleIcon,
TicketIcon,
ArrowDownTrayIcon,
} from '@heroicons/react/24/outline';
import { Event } from '@/lib/api';
import { getSuccessContent } from '../_logic/booking';
import type { BookingResult } from '../_types';
interface SuccessStepProps {
bookingResult: BookingResult;
event: Event;
locale: string;
t: (key: string) => string;
formatDate: (dateStr: string) => string;
fmtTime: (dateStr: string) => string;
}
export function SuccessStep({
bookingResult,
event,
locale,
t,
formatDate,
fmtTime,
}: SuccessStepProps) {
const successContent = getSuccessContent(bookingResult, locale, t);
return (
<div className="section-padding">
<div className="container-page max-w-2xl">
<Card className="p-8 text-center">
<div className={`w-16 h-16 rounded-full ${successContent.iconColor} flex items-center justify-center mx-auto mb-6`}>
<CheckCircleIcon className={`w-10 h-10 ${successContent.iconTextColor}`} />
</div>
<h1 className="text-2xl font-bold text-primary-dark mb-2">
{successContent.title}
</h1>
<p className="text-gray-600 mb-6">
{successContent.description}
</p>
<div className="bg-secondary-gray rounded-lg p-6 mb-6">
{/* Multi-ticket indicator */}
{bookingResult.ticketCount && bookingResult.ticketCount > 1 && (
<div className="mb-4 pb-4 border-b border-gray-300">
<p className="text-lg font-semibold text-primary-dark">
{locale === 'es'
? `${bookingResult.ticketCount} tickets reservados`
: `${bookingResult.ticketCount} tickets booked`}
</p>
<p className="text-sm text-gray-500">
{locale === 'es'
? 'Cada asistente recibirá su propio código QR'
: 'Each attendee will receive their own QR code'}
</p>
</div>
)}
<div className="flex items-center justify-center gap-2 mb-4">
<TicketIcon className="w-6 h-6 text-primary-yellow" />
<span className="font-mono text-lg font-bold">{bookingResult.qrCode}</span>
{bookingResult.ticketCount && bookingResult.ticketCount > 1 && (
<span className="text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded-full">
+{bookingResult.ticketCount - 1} {locale === 'es' ? 'más' : 'more'}
</span>
)}
</div>
<div className="text-sm text-gray-600 space-y-2">
<p><strong>{t('booking.success.event')}:</strong> {event.title}</p>
<p><strong>{t('booking.success.date')}:</strong> {formatDate(event.startDatetime)}</p>
<p><strong>{t('booking.success.time')}:</strong> {fmtTime(event.startDatetime)}</p>
<p><strong>{t('booking.success.location')}:</strong> {event.location}</p>
</div>
</div>
{bookingResult.paymentMethod === 'cash' && (
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
<p className="text-yellow-800 text-sm">
<strong>{t('booking.success.cashNote')}:</strong> {t('booking.success.cashDescription')}
</p>
</div>
)}
{bookingResult.paymentMethod === 'bancard' && (
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
<p className="text-blue-800 text-sm">
{t('booking.success.cardNote')}
</p>
</div>
)}
{bookingResult.paymentMethod === 'lightning' && (
<div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
<p className="text-green-800 text-sm flex items-center gap-2">
<CheckCircleIcon className="w-5 h-5" />
{locale === 'es'
? '¡Pago con Bitcoin Lightning recibido exitosamente!'
: 'Bitcoin Lightning payment received successfully!'}
</p>
</div>
)}
<p className="text-sm text-gray-500 mb-6">
{t('booking.success.emailSent')}
</p>
{/* Download Ticket Button - only for instant confirmation (Lightning) */}
{bookingResult.paymentMethod === 'lightning' && (
<div className="mb-6">
<a
href={bookingResult.bookingId
? `/api/tickets/booking/${bookingResult.bookingId}/pdf`
: `/api/tickets/${bookingResult.ticketId}/pdf`
}
download
className="inline-flex items-center gap-2 px-4 py-2 bg-primary-yellow text-primary-dark font-medium rounded-btn hover:bg-primary-yellow/90 transition-colors"
>
<ArrowDownTrayIcon className="w-5 h-5" />
{locale === 'es'
? (bookingResult.ticketCount && bookingResult.ticketCount > 1 ? 'Descargar Tickets' : 'Descargar Ticket')
: (bookingResult.ticketCount && bookingResult.ticketCount > 1 ? 'Download Tickets' : 'Download Ticket')}
</a>
</div>
)}
<div className="flex flex-col sm:flex-row gap-3 justify-center">
<Link href="/events">
<Button variant="outline">{t('booking.success.browseEvents')}</Button>
</Link>
<Link href="/">
<Button>{t('booking.success.backHome')}</Button>
</Link>
</div>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,40 @@
// Shared types for the booking flow.
export interface AttendeeInfo {
firstName: string;
lastName: string;
}
export type PaymentMethod = 'bancard' | 'lightning' | 'cash' | 'bank_transfer' | 'tpago';
export interface BookingFormData {
firstName: string;
lastName: string;
email: string;
phone: string;
preferredLanguage: 'en' | 'es';
paymentMethod: PaymentMethod;
ruc: string;
}
export interface LightningInvoice {
paymentHash: string;
paymentRequest: string; // BOLT11 invoice
amount: number; // Amount in satoshis
fiatAmount?: number; // Original fiat amount
fiatCurrency?: string; // Original fiat currency
expiry?: string;
}
export interface BookingResult {
ticketId: string;
ticketIds?: string[]; // For multi-ticket bookings
bookingId?: string;
qrCode: string;
qrCodes?: string[]; // For multi-ticket bookings
paymentMethod: PaymentMethod;
lightningInvoice?: LightningInvoice;
ticketCount?: number;
}
export type BookingStep = 'form' | 'paying' | 'manual_payment' | 'pending_approval' | 'success';
File diff suppressed because it is too large Load Diff