// Test with clean lead to avoid conflicts const { PrismaClient } = require('@prisma/client'); const crypto = require('crypto'); const prisma = new PrismaClient(); async function testCleanWorkflow() { console.log('๐Ÿงช TESTING CLEAN WORKFLOW (No Conflicts)'); console.log('='.repeat(60)); try { // 1. Get clinic const clinic = await prisma.clinic.findFirst(); console.log(`โœ… Clinic: ${clinic.name} (WAHA: ${clinic.wahaStatus})`); // 2. Check templates first const templates = await prisma.reminderTemplate.count({ where: { clinicId: clinic.id, isActive: true } }); console.log(`โœ… Active templates: ${templates}`); if (templates === 0) { console.log('๐Ÿ”ง Fixing templates...'); const { execSync } = require('child_process'); execSync('node fix-templates.js'); console.log('โœ… Templates fixed'); } // 3. Create a fresh lead to avoid conflicts console.log('๐Ÿ‘ค Creating fresh test lead...'); // Clean up any existing test leads first await prisma.scheduledReminder.deleteMany({ where: { appointment: { lead: { name: 'CLEAN_TEST_USER' } } } }); await prisma.appointment.deleteMany({ where: { lead: { name: 'CLEAN_TEST_USER' } } }); await prisma.lead.deleteMany({ where: { name: 'CLEAN_TEST_USER' } }); const lead = await prisma.lead.create({ data: { clinicId: clinic.id, name: 'CLEAN_TEST_USER', phone: '+96170774480', // Your number to receive test status: 'new', source: 'test' } }); console.log(`โœ… Created lead: ${lead.name} (${lead.phone})`); // 4. Get treatment const treatment = await prisma.treatment.findFirst({ where: { clinicId: clinic.id, isActive: true } }); console.log(`โœ… Treatment: ${treatment.name}`); // 5. Login console.log('๐Ÿ” Logging in...'); 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('โœ… Login successful'); // 6. Count before creation const before = { appointments: await prisma.appointment.count(), reminders: await prisma.scheduledReminder.count(), messages: await prisma.messageLog.count() }; console.log(`๐Ÿ“Š Before: ${before.appointments} appointments, ${before.reminders} reminders, ${before.messages} messages`); // 7. Create appointment console.log('๐Ÿ“ Creating appointment...'); const appointmentTime = new Date(Date.now() + 60 * 60 * 1000); // 1 hour from now const appointmentData = { leadId: lead.id, treatmentId: treatment.id, dateTime: appointmentTime.toISOString(), notes: 'Clean test appointment' }; console.log(` Time: ${appointmentTime.toLocaleString()}`); const appointmentResponse = await fetch('http://localhost:3000/api/appointments', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cookie': cookies }, body: JSON.stringify(appointmentData) }); console.log(`๐Ÿ“ก API Response: ${appointmentResponse.status}`); if (!appointmentResponse.ok) { const error = await appointmentResponse.text(); console.log('โŒ APPOINTMENT CREATION FAILED:'); console.log(' Status:', appointmentResponse.status); console.log(' Error:', error); return; } const appointment = await appointmentResponse.json(); console.log(`โœ… APPOINTMENT CREATED: ${appointment.id}`); // 8. Wait for background processes console.log('โณ Waiting for reminder scheduling...'); await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds // 9. Check what happened const after = { appointments: await prisma.appointment.count(), reminders: await prisma.scheduledReminder.count(), messages: await prisma.messageLog.count() }; console.log(`๐Ÿ“Š After: ${after.appointments} appointments, ${after.reminders} reminders, ${after.messages} messages`); const changes = { appointments: after.appointments - before.appointments, reminders: after.reminders - before.reminders, messages: after.messages - before.messages }; console.log(`๐Ÿ“ˆ Changes: +${changes.appointments} appointments, +${changes.reminders} reminders, +${changes.messages} messages`); // 10. Get full appointment details const fullAppointment = await prisma.appointment.findUnique({ where: { id: appointment.id }, include: { scheduledReminders: { include: { template: true }, orderBy: { scheduledFor: 'asc' } } } }); console.log('\n๐Ÿ“‹ APPOINTMENT DETAILS:'); console.log(` ID: ${fullAppointment.id}`); console.log(` Status: ${fullAppointment.status}`); console.log(` Confirm Token: ${fullAppointment.confirmToken ? 'YES โœ…' : 'NO โŒ'}`); console.log(` Reminders Scheduled: ${fullAppointment.scheduledReminders.length}`); if (fullAppointment.scheduledReminders.length === 0) { console.log('โŒ NO REMINDERS SCHEDULED - THIS IS THE PROBLEM!'); // Try to schedule them manually console.log('๐Ÿ”ง Attempting manual reminder scheduling...'); try { const { scheduleReminders } = await import('./src/lib/reminders.js'); await scheduleReminders(fullAppointment.id); // Check again const updated = await prisma.appointment.findUnique({ where: { id: fullAppointment.id }, include: { scheduledReminders: { include: { template: true } } } }); console.log(`โœ… Manual scheduling result: ${updated.scheduledReminders.length} reminders`); } catch (error) { console.log(`โŒ Manual scheduling failed: ${error.message}`); console.log(` Stack: ${error.stack}`); } } else { console.log('โœ… REMINDERS FOUND:'); fullAppointment.scheduledReminders.forEach((r, i) => { console.log(` ${i + 1}. ${r.template.trigger} - ${r.scheduledFor} (${r.status})`); }); // Check if any are due now const dueNow = fullAppointment.scheduledReminders.filter(r => r.status === 'pending' && new Date(r.scheduledFor) <= new Date() ); console.log(`โฐ Due now: ${dueNow.length}`); if (dueNow.length > 0) { console.log('๐Ÿš€ Testing cron to send due reminders...'); 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 executed: sent=${cronResult.sent}, failed=${cronResult.failed}, skipped=${cronResult.skipped}`); if (cronResult.sent > 0) { console.log('๐ŸŽ‰ SUCCESS! Reminders were sent!'); console.log('๐Ÿ“ฑ CHECK YOUR WHATSAPP NOW!'); } } } } // 11. Final verdict console.log('\n๐ŸŽฏ FINAL VERDICT:'); if (changes.appointments === 1 && changes.reminders > 0) { console.log('๐ŸŸข WORKING: Appointment created AND reminders scheduled'); } else if (changes.appointments === 1 && changes.reminders === 0) { console.log('๐ŸŸก PARTIAL: Appointment created but NO reminders scheduled'); console.log(' ๐Ÿ” Issue: scheduleReminders() function not working'); } else if (changes.appointments === 0) { console.log('๐Ÿ”ด BROKEN: Appointment not created at all'); console.log(' ๐Ÿ” Issue: API endpoint failing'); } } catch (error) { console.error('โŒ Test completely failed:', error); } finally { await prisma.$disconnect(); } } testCleanWorkflow().catch(console.error);