diff --git a/backend/src/db/migrate.ts b/backend/src/db/migrate.ts index 816543f..c450579 100644 --- a/backend/src/db/migrate.ts +++ b/backend/src/db/migrate.ts @@ -209,6 +209,9 @@ async function migrate() { try { await (db as any).run(sql`ALTER TABLE payments ADD COLUMN payer_name TEXT`); } catch (e) { /* column may already exist */ } + try { + await (db as any).run(sql`ALTER TABLE payments ADD COLUMN reminder_sent_at TEXT`); + } catch (e) { /* column may already exist */ } // Invoices table await (db as any).run(sql` @@ -577,6 +580,9 @@ async function migrate() { try { await (db as any).execute(sql`ALTER TABLE payments ADD COLUMN payer_name VARCHAR(255)`); } catch (e) { /* column may already exist */ } + try { + await (db as any).execute(sql`ALTER TABLE payments ADD COLUMN reminder_sent_at TIMESTAMP`); + } catch (e) { /* column may already exist */ } // Invoices table await (db as any).execute(sql` diff --git a/backend/src/db/schema.ts b/backend/src/db/schema.ts index 0e72ab5..1d4e2f3 100644 --- a/backend/src/db/schema.ts +++ b/backend/src/db/schema.ts @@ -115,6 +115,7 @@ export const sqlitePayments = sqliteTable('payments', { paidAt: text('paid_at'), paidByAdminId: text('paid_by_admin_id'), adminNote: text('admin_note'), // Internal admin notes + reminderSentAt: text('reminder_sent_at'), // When payment reminder email was sent createdAt: text('created_at').notNull(), updatedAt: text('updated_at').notNull(), }); @@ -405,6 +406,7 @@ export const pgPayments = pgTable('payments', { paidAt: timestamp('paid_at'), paidByAdminId: uuid('paid_by_admin_id'), adminNote: pgText('admin_note'), + reminderSentAt: timestamp('reminder_sent_at'), // When payment reminder email was sent createdAt: timestamp('created_at').notNull(), updatedAt: timestamp('updated_at').notNull(), }); diff --git a/backend/src/lib/email.ts b/backend/src/lib/email.ts index eaa0185..7c949ae 100644 --- a/backend/src/lib/email.ts +++ b/backend/src/lib/email.ts @@ -980,6 +980,106 @@ export const emailService = { }); }, + /** + * Send payment reminder email + * This email is sent when admin wants to remind attendee about pending payment + */ + async sendPaymentReminder(paymentId: string): Promise<{ success: boolean; error?: string }> { + // Get payment + const payment = await dbGet( + (db as any) + .select() + .from(payments) + .where(eq((payments as any).id, paymentId)) + ); + + if (!payment) { + return { success: false, error: 'Payment not found' }; + } + + // Only send for pending/pending_approval payments + if (!['pending', 'pending_approval'].includes(payment.status)) { + return { success: false, error: 'Payment reminder can only be sent for pending payments' }; + } + + // Get ticket + const ticket = await dbGet( + (db as any) + .select() + .from(tickets) + .where(eq((tickets as any).id, payment.ticketId)) + ); + + if (!ticket) { + return { success: false, error: 'Ticket not found' }; + } + + // Get event + const event = await dbGet( + (db as any) + .select() + .from(events) + .where(eq((events as any).id, ticket.eventId)) + ); + + if (!event) { + return { success: false, error: 'Event not found' }; + } + + const locale = ticket.preferredLanguage || 'en'; + const eventTitle = locale === 'es' && event.titleEs ? event.titleEs : event.title; + const attendeeFullName = `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim(); + + // Calculate total price for multi-ticket bookings + let totalPrice = event.price; + let ticketCount = 1; + + if (ticket.bookingId) { + const bookingTickets = await dbAll( + (db as any) + .select() + .from(tickets) + .where(eq((tickets as any).bookingId, ticket.bookingId)) + ); + ticketCount = bookingTickets.length; + totalPrice = event.price * ticketCount; + } + + // Generate the booking URL for returning to payment page + const frontendUrl = process.env.FRONTEND_URL || 'https://spanglish.com'; + const bookingUrl = `${frontendUrl}/booking/${ticket.id}?step=payment`; + + // Format amount with ticket count info for multi-ticket bookings + const amountDisplay = ticketCount > 1 + ? `${this.formatCurrency(totalPrice, event.currency)} (${ticketCount} tickets)` + : this.formatCurrency(totalPrice, event.currency); + + // Get site timezone for proper date/time formatting + const timezone = await this.getSiteTimezone(); + + console.log(`[Email] Sending payment reminder email to ${ticket.attendeeEmail}`); + + return this.sendTemplateEmail({ + templateSlug: 'payment-reminder', + to: ticket.attendeeEmail, + toName: attendeeFullName, + locale, + eventId: event.id, + variables: { + attendeeName: attendeeFullName, + attendeeEmail: ticket.attendeeEmail, + ticketId: ticket.bookingId || ticket.id, + eventTitle, + eventDate: this.formatDate(event.startDatetime, locale, timezone), + eventTime: this.formatTime(event.startDatetime, locale, timezone), + eventLocation: event.location, + eventLocationUrl: event.locationUrl || '', + paymentAmount: amountDisplay, + bookingUrl, + }, + }); + }, + /** * Send custom email to event attendees */ diff --git a/backend/src/lib/emailTemplates.ts b/backend/src/lib/emailTemplates.ts index dcc3584..6340aba 100644 --- a/backend/src/lib/emailTemplates.ts +++ b/backend/src/lib/emailTemplates.ts @@ -991,6 +991,118 @@ Spanglish`, ], isSystem: true, }, + { + name: 'Payment Reminder', + slug: 'payment-reminder', + subject: 'Reminder: Complete your payment for Spanglish', + subjectEs: 'Recordatorio: Completa tu pago para Spanglish', + bodyHtml: ` +

Payment Reminder

+

Hi {{attendeeName}},

+

We wanted to follow up on your booking for {{eventTitle}}.

+

We haven't been able to locate your payment yet. To receive your ticket and confirm your spot, please complete your payment.

+ +
+

📅 Event Details

+
Event: {{eventTitle}}
+
Date: {{eventDate}}
+
Time: {{eventTime}}
+
Location: {{eventLocation}}
+
Amount Due: {{paymentAmount}}
+
+ +

+ Complete Payment +

+ +
+ Already paid?
+ If you have already completed your payment and believe this is an error, please reply to this email with your payment details (date, amount, and method used) and we'll be happy to look into it. +
+ +

We hope to see you at the event!

+

The Spanglish Team

+ `, + bodyHtmlEs: ` +

Recordatorio de Pago

+

Hola {{attendeeName}},

+

Queríamos dar seguimiento a tu reserva para {{eventTitle}}.

+

Aún no hemos podido localizar tu pago. Para recibir tu entrada y confirmar tu lugar, por favor completa tu pago.

+ +
+

📅 Detalles del Evento

+
Evento: {{eventTitle}}
+
Fecha: {{eventDate}}
+
Hora: {{eventTime}}
+
Ubicación: {{eventLocation}}
+
Monto a Pagar: {{paymentAmount}}
+
+ +

+ Completar Pago +

+ +
+ ¿Ya pagaste?
+ Si ya completaste tu pago y crees que esto es un error, por favor responde a este correo con los detalles de tu pago (fecha, monto y método utilizado) y con gusto lo revisaremos. +
+ +

¡Esperamos verte en el evento!

+

El Equipo de Spanglish

+ `, + bodyText: `Payment Reminder + +Hi {{attendeeName}}, + +We wanted to follow up on your booking for {{eventTitle}}. + +We haven't been able to locate your payment yet. To receive your ticket and confirm your spot, please complete your payment. + +Event Details: +- Event: {{eventTitle}} +- Date: {{eventDate}} +- Time: {{eventTime}} +- Location: {{eventLocation}} +- Amount Due: {{paymentAmount}} + +Complete your payment here: {{bookingUrl}} + +Already paid? +If you have already completed your payment and believe this is an error, please reply to this email with your payment details (date, amount, and method used) and we'll be happy to look into it. + +We hope to see you at the event! +The Spanglish Team`, + bodyTextEs: `Recordatorio de Pago + +Hola {{attendeeName}}, + +Queríamos dar seguimiento a tu reserva para {{eventTitle}}. + +Aún no hemos podido localizar tu pago. Para recibir tu entrada y confirmar tu lugar, por favor completa tu pago. + +Detalles del Evento: +- Evento: {{eventTitle}} +- Fecha: {{eventDate}} +- Hora: {{eventTime}} +- Ubicación: {{eventLocation}} +- Monto a Pagar: {{paymentAmount}} + +Completa tu pago aquí: {{bookingUrl}} + +¿Ya pagaste? +Si ya completaste tu pago y crees que esto es un error, por favor responde a este correo con los detalles de tu pago (fecha, monto y método utilizado) y con gusto lo revisaremos. + +¡Esperamos verte en el evento! +El Equipo de Spanglish`, + description: 'Sent to remind attendees to complete their pending payment', + variables: [ + ...commonVariables, + ...bookingVariables, + { name: 'paymentAmount', description: 'Payment amount with currency', example: '50,000 PYG' }, + { name: 'bookingUrl', description: 'URL to complete payment', example: 'https://spanglish.com/booking/abc123?step=payment' }, + ], + isSystem: true, + }, { name: 'Payment Rejected', slug: 'payment-rejected', diff --git a/backend/src/routes/payments.ts b/backend/src/routes/payments.ts index eae3ea4..ca8dbd4 100644 --- a/backend/src/routes/payments.ts +++ b/backend/src/routes/payments.ts @@ -17,10 +17,12 @@ const updatePaymentSchema = z.object({ const approvePaymentSchema = z.object({ adminNote: z.string().optional(), + sendEmail: z.boolean().optional().default(true), }); const rejectPaymentSchema = z.object({ adminNote: z.string().optional(), + sendEmail: z.boolean().optional().default(true), }); // Get all payments (admin) - with ticket and event details @@ -266,7 +268,7 @@ paymentsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json // Approve payment (admin) - specifically for pending_approval payments paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValidator('json', approvePaymentSchema), async (c) => { const id = c.req.param('id'); - const { adminNote } = c.req.valid('json'); + const { adminNote, sendEmail } = c.req.valid('json'); const user = (c as any).get('user'); const payment = await dbGet( @@ -329,13 +331,17 @@ paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValida .where(eq((tickets as any).id, (t as any).id)); } - // Send confirmation emails asynchronously - Promise.all([ - emailService.sendBookingConfirmation(payment.ticketId), - emailService.sendPaymentReceipt(id), - ]).catch(err => { - console.error('[Email] Failed to send confirmation emails:', err); - }); + // Send confirmation emails asynchronously (if sendEmail is true, which is the default) + if (sendEmail !== false) { + Promise.all([ + emailService.sendBookingConfirmation(payment.ticketId), + emailService.sendPaymentReceipt(id), + ]).catch(err => { + console.error('[Email] Failed to send confirmation emails:', err); + }); + } else { + console.log('[Payment] Skipping confirmation emails per admin request'); + } const updated = await dbGet( (db as any) @@ -350,7 +356,7 @@ paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValida // Reject payment (admin) paymentsRouter.post('/:id/reject', requireAuth(['admin', 'organizer']), zValidator('json', rejectPaymentSchema), async (c) => { const id = c.req.param('id'); - const { adminNote } = c.req.valid('json'); + const { adminNote, sendEmail } = c.req.valid('json'); const user = (c as any).get('user'); const payment = await dbGet( @@ -390,11 +396,13 @@ paymentsRouter.post('/:id/reject', requireAuth(['admin', 'organizer']), zValidat }) .where(eq((tickets as any).id, payment.ticketId)); - // Send rejection email asynchronously (for manual payment methods only) - if (['bank_transfer', 'tpago'].includes(payment.provider)) { + // Send rejection email asynchronously (for manual payment methods only, if sendEmail is true) + if (sendEmail !== false && ['bank_transfer', 'tpago'].includes(payment.provider)) { emailService.sendPaymentRejectionEmail(id).catch(err => { console.error('[Email] Failed to send payment rejection email:', err); }); + } else if (sendEmail === false) { + console.log('[Payment] Skipping rejection email per admin request'); } const updated = await dbGet( @@ -407,6 +415,51 @@ paymentsRouter.post('/:id/reject', requireAuth(['admin', 'organizer']), zValidat return c.json({ payment: updated, message: 'Payment rejected and booking cancelled' }); }); +// Send payment reminder email +paymentsRouter.post('/:id/send-reminder', requireAuth(['admin', 'organizer']), async (c) => { + const id = c.req.param('id'); + + const payment = await dbGet( + (db as any) + .select() + .from(payments) + .where(eq((payments as any).id, id)) + ); + + if (!payment) { + return c.json({ error: 'Payment not found' }, 404); + } + + // Only allow sending reminders for pending payments + if (!['pending', 'pending_approval'].includes(payment.status)) { + return c.json({ error: 'Payment reminder can only be sent for pending payments' }, 400); + } + + try { + const result = await emailService.sendPaymentReminder(id); + + if (result.success) { + const now = getNow(); + + // Record when reminder was sent + await (db as any) + .update(payments) + .set({ + reminderSentAt: now, + updatedAt: now, + }) + .where(eq((payments as any).id, id)); + + return c.json({ message: 'Payment reminder sent successfully', reminderSentAt: now }); + } else { + return c.json({ error: result.error || 'Failed to send payment reminder' }, 500); + } + } catch (err: any) { + console.error('[Payment] Failed to send payment reminder:', err); + return c.json({ error: 'Failed to send payment reminder' }, 500); + } +}); + // Update admin note paymentsRouter.post('/:id/note', requireAuth(['admin', 'organizer']), async (c) => { const id = c.req.param('id'); diff --git a/frontend/src/app/(public)/book/[eventId]/page.tsx b/frontend/src/app/(public)/book/[eventId]/page.tsx index d15b3ad..5b00a69 100644 --- a/frontend/src/app/(public)/book/[eventId]/page.tsx +++ b/frontend/src/app/(public)/book/[eventId]/page.tsx @@ -473,8 +473,8 @@ export default function BookingPage() { paymentMethods.push({ id: 'tpago', icon: CreditCardIcon, - label: locale === 'es' ? 'TPago / Tarjeta Internacional' : 'TPago / International Card', - description: locale === 'es' ? 'Paga con tarjeta de crédito o débito' : 'Pay with credit or debit card', + 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', }); } @@ -483,8 +483,8 @@ export default function BookingPage() { paymentMethods.push({ id: 'bank_transfer', icon: BuildingLibraryIcon, - label: locale === 'es' ? 'Transferencia Bancaria' : 'Bank Transfer', - description: locale === 'es' ? 'Transferencia bancaria local' : 'Local bank transfer', + 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', }); } diff --git a/frontend/src/app/admin/payments/page.tsx b/frontend/src/app/admin/payments/page.tsx index da18b7a..e9fcceb 100644 --- a/frontend/src/app/admin/payments/page.tsx +++ b/frontend/src/app/admin/payments/page.tsx @@ -19,6 +19,7 @@ import { BanknotesIcon, BuildingLibraryIcon, CreditCardIcon, + EnvelopeIcon, } from '@heroicons/react/24/outline'; import toast from 'react-hot-toast'; @@ -38,6 +39,8 @@ export default function AdminPaymentsPage() { const [selectedPayment, setSelectedPayment] = useState(null); const [noteText, setNoteText] = useState(''); const [processing, setProcessing] = useState(false); + const [sendEmail, setSendEmail] = useState(true); + const [sendingReminder, setSendingReminder] = useState(false); // Export state const [showExportModal, setShowExportModal] = useState(false); @@ -77,10 +80,11 @@ export default function AdminPaymentsPage() { const handleApprove = async (payment: PaymentWithDetails) => { setProcessing(true); try { - await paymentsApi.approve(payment.id, noteText); + await paymentsApi.approve(payment.id, noteText, sendEmail); 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'); @@ -92,10 +96,11 @@ export default function AdminPaymentsPage() { const handleReject = async (payment: PaymentWithDetails) => { setProcessing(true); try { - await paymentsApi.reject(payment.id, noteText); + await paymentsApi.reject(payment.id, noteText, sendEmail); toast.success(locale === 'es' ? 'Pago rechazado' : 'Payment rejected'); setSelectedPayment(null); setNoteText(''); + setSendEmail(true); loadData(); } catch (error: any) { toast.error(error.message || 'Failed to reject payment'); @@ -104,6 +109,24 @@ export default function AdminPaymentsPage() { } }; + const handleSendReminder = async (payment: PaymentWithDetails) => { + setSendingReminder(true); + try { + const result = await paymentsApi.sendReminder(payment.id); + toast.success(locale === 'es' ? 'Recordatorio enviado' : 'Reminder sent'); + // Update the selected payment with the new reminderSentAt timestamp + if (result.reminderSentAt) { + setSelectedPayment({ ...payment, reminderSentAt: result.reminderSentAt }); + } + // Also refresh the data to update the lists + loadData(); + } catch (error: any) { + toast.error(error.message || 'Failed to send reminder'); + } finally { + setSendingReminder(false); + } + }; + const handleConfirmPayment = async (id: string) => { try { await paymentsApi.approve(id); @@ -317,7 +340,7 @@ export default function AdminPaymentsPage() { const modalBookingInfo = getBookingInfo(selectedPayment); return (
- +

{locale === 'es' ? 'Verificar Pago' : 'Verify Payment'}

@@ -374,6 +397,13 @@ export default function AdminPaymentsPage() {
)} + {selectedPayment.reminderSentAt && ( +
+ + {locale === 'es' ? 'Recordatorio enviado:' : 'Reminder sent:'} {formatDate(selectedPayment.reminderSentAt)} +
+ )} + {selectedPayment.payerName && (

@@ -395,6 +425,19 @@ export default function AdminPaymentsPage() { placeholder={locale === 'es' ? 'Agregar nota...' : 'Add a note...'} />

+ +
+ setSendEmail(e.target.checked)} + className="w-4 h-4 text-primary-yellow border-gray-300 rounded focus:ring-primary-yellow" + /> + +
@@ -417,8 +460,20 @@ export default function AdminPaymentsPage() {
+
+ +
+