// Test exact UI workflow with authentication const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); async function testUIExactWorkflow() { console.log('๐Ÿ” TESTING EXACT UI WORKFLOW'); console.log('='.repeat(50)); try { // 1. Get data like UI would console.log('1๏ธโƒฃ Getting clinic data...'); const clinic = await prisma.clinic.findFirst(); console.log(` Clinic: ${clinic.name} (WAHA: ${clinic.wahaStatus})`); // 2. Get treatments like UI would console.log('2๏ธโƒฃ Getting treatments...'); const treatments = await prisma.treatment.findMany({ where: { clinicId: clinic.id, isActive: true } }); console.log(` Available treatments: ${treatments.length}`); // 3. Get leads like UI would console.log('3๏ธโƒฃ Getting leads...'); const leads = await prisma.lead.findMany({ where: { clinicId: clinic.id } }); console.log(` Available leads: ${leads.length}`); if (treatments.length === 0 || leads.length === 0) { console.log('โŒ Missing data for test'); return; } // 4. Check reminder templates console.log('4๏ธโƒฃ Checking reminder templates...'); const templates = await prisma.reminderTemplate.findMany({ where: { clinicId: clinic.id, isActive: true } }); console.log(` Active templates: ${templates.length}`); if (templates.length === 0) { console.log('โŒ NO ACTIVE TEMPLATES! This is the problem.'); console.log('๐Ÿ”ง Running fix...'); const { execSync } = require('child_process'); execSync('node fix-templates.js'); console.log('โœ… Templates fixed, retesting...'); return; } templates.forEach(t => { console.log(` - ${t.trigger} (offset: ${t.offsetMinutes} min)`); }); // 5. Login exactly like UI console.log('5๏ธโƒฃ Logging in like UI...'); const loginResponse = await fetch('http://localhost:3000/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'admin@clinera.com', password: 'admin123' }) }); if (!loginResponse.ok) { console.log('โŒ Login failed'); return; } const cookies = loginResponse.headers.get('set-cookie'); console.log('โœ… Authenticated'); // 6. Create appointment exactly like UI console.log('6๏ธโƒฃ Creating appointment via API...'); const appointmentData = { leadId: leads[0].id, treatmentId: treatments[0].id, dateTime: new Date(Date.now() + 30 * 60 * 1000).toISOString(), // 30 min from now notes: 'UI Test Appointment' }; console.log(` Lead: ${leads[0].name} (${leads[0].phone})`); console.log(` Treatment: ${treatments[0].name}`); console.log(` DateTime: ${appointmentData.dateTime}`); const beforeCounts = { appointments: await prisma.appointment.count(), reminders: await prisma.scheduledReminder.count(), messages: await prisma.messageLog.count() }; const appointmentResponse = await fetch('http://localhost:3000/api/appointments', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cookie': cookies }, body: JSON.stringify(appointmentData) }); if (!appointmentResponse.ok) { const error = await appointmentResponse.text(); console.log('โŒ Appointment creation failed:', appointmentResponse.status, error); return; } const appointment = await appointmentResponse.json(); console.log(`โœ… Appointment created: ${appointment.id}`); // 7. Check what changed immediately console.log('7๏ธโƒฃ Checking immediate changes...'); await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds const afterCounts = { appointments: await prisma.appointment.count(), reminders: await prisma.scheduledReminder.count(), messages: await prisma.messageLog.count() }; console.log(` Appointments: ${beforeCounts.appointments} โ†’ ${afterCounts.appointments}`); console.log(` Reminders: ${beforeCounts.reminders} โ†’ ${afterCounts.reminders}`); console.log(` Messages: ${beforeCounts.messages} โ†’ ${afterCounts.messages}`); // 8. Get appointment details const fullAppointment = await prisma.appointment.findUnique({ where: { id: appointment.id }, include: { lead: true, treatment: true, clinic: true, scheduledReminders: { include: { template: true } } } }); console.log('8๏ธโƒฃ Appointment details:'); console.log(` Confirm Token: ${fullAppointment.confirmToken ? 'โœ…' : 'โŒ'}`); console.log(` Reminders: ${fullAppointment.scheduledReminders.length}`); if (fullAppointment.scheduledReminders.length === 0) { console.log('โŒ NO REMINDERS SCHEDULED!'); console.log('๐Ÿ” Investigating...'); // Test reminder scheduling manually console.log('๐Ÿงช Testing scheduleReminders function manually...'); try { // Import and test the function directly const { scheduleReminders } = await import('./src/lib/reminders.js'); await scheduleReminders(appointment.id); console.log('โœ… Manual reminder scheduling completed'); // Check again const updatedAppointment = await prisma.appointment.findUnique({ where: { id: appointment.id }, include: { scheduledReminders: { include: { template: true } } } }); console.log(` Now has ${updatedAppointment.scheduledReminders.length} reminders`); } catch (error) { console.log(`โŒ Manual scheduling failed: ${error.message}`); } } else { console.log('โœ… Reminders properly scheduled:'); fullAppointment.scheduledReminders.forEach(r => { console.log(` - ${r.template.trigger} at ${r.scheduledFor} (${r.status})`); }); } // 9. Test cron console.log('9๏ธโƒฃ Testing cron...'); const cronResponse = await fetch('http://localhost:3000/api/cron/send-reminders?key=dev-cron-key', { method: 'POST' }); if (cronResponse.ok) { const cronResult = await cronResponse.json(); console.log(`โœ… Cron result: sent=${cronResult.sent}, failed=${cronResult.failed}, skipped=${cronResult.skipped}`); } else { console.log('โŒ Cron failed'); } // 10. Final status const finalCounts = { appointments: await prisma.appointment.count(), reminders: await prisma.scheduledReminder.count(), messages: await prisma.messageLog.count() }; console.log('\n๐Ÿ“Š FINAL RESULTS:'); console.log(` Appointments: ${beforeCounts.appointments} โ†’ ${finalCounts.appointments}`); console.log(` Reminders: ${beforeCounts.reminders} โ†’ ${finalCounts.reminders}`); console.log(` Messages: ${beforeCounts.messages} โ†’ ${finalCounts.messages}`); if (finalCounts.messages > beforeCounts.messages) { console.log('๐ŸŽ‰ SUCCESS! Messages were sent!'); } else { console.log('โŒ FAILURE! No messages sent!'); } } catch (error) { console.error('โŒ Test failed:', error); } finally { await prisma.$disconnect(); } } testUIExactWorkflow().catch(console.error);