Bläddra i källkod

try to fix doctor appointments

Matthew Trejo 2 dagar sedan
förälder
incheckning
9d4f212bae
3 ändrade filer med 30 tillägg och 139 borttagningar
  1. 0 131
      scripts/seed.ts
  2. 30 3
      src/app/api/dashboard/stats/route.ts
  3. 0 5
      src/components/sidebar/SidebarNavigation.tsx

+ 0 - 131
scripts/seed.ts

@@ -1,131 +0,0 @@
-import { PrismaClient } from '@prisma/client'
-import bcrypt from 'bcryptjs'
-import { config } from '../src/lib/config'
-
-const prisma = new PrismaClient()
-
-async function main() {
-  console.log('🌱 Iniciando seed de la base de datos...')
-  console.log(`📊 Usando base de datos: ${config.database.url}`)
-  console.log('')
-
-  // Buscar usuario paciente existente
-  const patient = await prisma.user.findUnique({
-    where: { email: 'patient@ani-assistant.com' }
-  })
-
-  if (!patient) {
-    console.log('❌ Usuario paciente no encontrado. Ejecuta "npm run db:setup" primero.')
-    return
-  }
-
-  // Buscar usuario doctor existente
-  const doctor = await prisma.user.findUnique({
-    where: { email: 'admin@ani-assistant.com' }
-  })
-
-  if (!doctor) {
-    console.log('❌ Usuario doctor no encontrado. Ejecuta "npm run db:setup" primero.')
-    return
-  }
-
-  console.log('👤 Usuario Paciente:', patient.email, `(${patient.username})`)
-  console.log('👨‍⚕️ Usuario Doctor:', doctor.email, `(${doctor.username})`)
-  console.log('')
-
-  // Crear algunos reportes de ejemplo
-  const sampleReports = [
-    {
-      userId: patient.id,
-      content: `=== REPORTE MÉDICO ===
-
-Fecha: ${new Date().toLocaleDateString('es-ES')}
-Hora: ${new Date().toLocaleTimeString('es-ES')}
-
-SÍNTOMAS IDENTIFICADOS:
-• Dolor de cabeza
-• Fatiga
-
-RESUMEN DE LA CONSULTA:
-El paciente realizó 3 consulta(s) con el asistente virtual.
-
-TEMAS PRINCIPALES:
-• Medicamentos
-• Tratamiento
-
-RECOMENDACIONES DEL ASISTENTE:
-1. Descansar adecuadamente
-2. Mantener hidratación
-3. Consultar con médico si persisten los síntomas
-
-NOTA: Este es un reporte generado automáticamente por el asistente virtual. Se recomienda consultar con un profesional médico para un diagnóstico completo.
-
-=== FIN DEL REPORTE ===`,
-      messages: [
-        { role: 'user', content: 'Tengo dolor de cabeza desde hace 2 días' },
-        { role: 'assistant', content: 'Entiendo tu preocupación. ¿Has notado algún otro síntoma?' },
-        { role: 'user', content: 'También me siento muy cansado' },
-        { role: 'assistant', content: 'Es importante descansar y mantenerse hidratado' },
-        { role: 'user', content: '¿Qué medicamentos puedo tomar?' },
-        { role: 'assistant', content: 'Te recomiendo consultar con un médico para el tratamiento adecuado' }
-      ]
-    },
-    {
-      userId: patient.id,
-      content: `=== REPORTE MÉDICO ===
-
-Fecha: ${new Date().toLocaleDateString('es-ES')}
-Hora: ${new Date().toLocaleTimeString('es-ES')}
-
-SÍNTOMAS IDENTIFICADOS:
-• Dolor de garganta
-• Tos
-
-RESUMEN DE LA CONSULTA:
-El paciente realizó 3 consulta(s) con el asistente virtual.
-
-TEMAS PRINCIPALES:
-• Prevención
-• Control de síntomas
-
-RECOMENDACIONES DEL ASISTENTE:
-1. Gargar con agua salada
-2. Mantener reposo
-3. Beber abundante líquido
-
-NOTA: Este es un reporte generado automáticamente por el asistente virtual. Se recomienda consultar con un profesional médico para un diagnóstico completo.
-
-=== FIN DEL REPORTE ===`,
-      messages: [
-        { role: 'user', content: 'Me duele la garganta y tengo tos' },
-        { role: 'assistant', content: '¿Cuánto tiempo llevas con estos síntomas?' },
-        { role: 'user', content: 'Desde ayer por la mañana' },
-        { role: 'assistant', content: 'Te recomiendo descansar y beber mucho líquido' }
-      ]
-    }
-  ]
-
-  for (const report of sampleReports) {
-    await prisma.record.upsert({
-      where: { 
-        id: `sample-${Date.now()}-${Math.random().toString(36).substr(2, 9)}` 
-      },
-      update: {},
-      create: report,
-    })
-  }
-
-  console.log('✅ Seed completado exitosamente!')
-  console.log('👤 Usuario Paciente:', patient.email)
-  console.log('👨‍⚕️ Usuario Doctor:', doctor.email)
-  console.log('📊 Reportes de ejemplo creados')
-}
-
-main()
-  .catch((e) => {
-    console.error('❌ Error durante el seed:', e)
-    process.exit(1)
-  })
-  .finally(async () => {
-    await prisma.$disconnect()
-  }) 

+ 30 - 3
src/app/api/dashboard/stats/route.ts

@@ -110,7 +110,19 @@ export async function GET(request: NextRequest) {
         where: { doctorId: userId },
         select: { patientId: true }
       })
-      const patientIds = assignedPatients.map((a: { patientId: string }) => a.patientId)
+      
+      // Pacientes con citas con el doctor
+      const appointmentPatients = await prisma.appointment.findMany({
+        where: { medicoId: userId },
+        select: { pacienteId: true },
+        distinct: ['pacienteId']
+      })
+
+      // Combinar IDs de pacientes (únicos)
+      const patientIds = Array.from(new Set([
+        ...assignedPatients.map((a: { patientId: string }) => a.patientId),
+        ...appointmentPatients.map((a: { pacienteId: string }) => a.pacienteId)
+      ]))
 
       // Total de pacientes asignados
       const totalPatients = patientIds.length
@@ -160,6 +172,14 @@ export async function GET(request: NextRequest) {
         }
       })
 
+      // Citas del doctor (pendientes o aprobadas)
+      const totalAppointments = await prisma.appointment.count({
+        where: {
+          medicoId: userId,
+          estado: { in: ["PENDIENTE", "APROBADA"] }
+        }
+      })
+
       // Tendencias
       let consultsTrend = "+0%"
       let reportsTrend = "+0%"
@@ -177,7 +197,7 @@ export async function GET(request: NextRequest) {
         totalConsults: totalReports,
         totalReports,
         totalPatients,
-        totalAppointments: 0, // Por ahora
+        totalAppointments,
         consultsToday,
         reportsThisWeek,
         activePatients: activePatients.length,
@@ -223,6 +243,13 @@ export async function GET(request: NextRequest) {
         where: { createdAt: { gte: thirtyDaysAgo } }
       })
 
+      // Citas totales en el sistema
+      const totalAppointments = await prisma.appointment.count({
+        where: {
+          estado: { in: ["PENDIENTE", "APROBADA"] }
+        }
+      })
+
       // Tendencias
       let consultsTrend = "+0%"
       let reportsTrend = "+0%"
@@ -240,7 +267,7 @@ export async function GET(request: NextRequest) {
         totalConsults: totalReports,
         totalReports,
         totalPatients,
-        totalAppointments: 0, // Por ahora
+        totalAppointments,
         consultsToday,
         reportsThisWeek,
         activePatients: activePatients.length,

+ 0 - 5
src/components/sidebar/SidebarNavigation.tsx

@@ -128,11 +128,6 @@ export default function SidebarNavigation({ onItemClick, isCollapsed = false }:
               title: "Todos los Reportes",
               href: "/records",
               icon: FileText
-            },
-            {
-              title: "Toast Demo",
-              href: "/toast-demo",
-              icon: Sparkles
             }
           ]
         }