'use client' import { useState, useEffect } from 'react' import { DashboardLayout } from '@/components/dashboard-layout' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from '@/components/ui/breadcrumb' import { Download, FileText, Calendar, Users } from 'lucide-react' import { format } from 'date-fns' import { es } from 'date-fns/locale' import { toast } from 'sonner' interface Section { id: number name: string className: string classCode: string } export default function ExportReportsPage() { const [sections, setSections] = useState([]) const [selectedDate, setSelectedDate] = useState('') const [selectedSection, setSelectedSection] = useState('all') const [isExporting, setIsExporting] = useState(false) const [loading, setLoading] = useState(true) useEffect(() => { fetchSections() // Establecer fecha actual por defecto const today = new Date() setSelectedDate(format(today, 'yyyy-MM-dd')) }, []) const fetchSections = async () => { try { const response = await fetch('/api/teacher/sections') if (response.ok) { const data = await response.json() setSections(data) } else { toast.error('Error al cargar las secciones') } } catch (error) { console.error('Error:', error) toast.error('Error al cargar las secciones') } finally { setLoading(false) } } const handleExport = async () => { if (!selectedDate) { toast.error('Por favor selecciona una fecha') return } setIsExporting(true) try { const params = new URLSearchParams({ date: selectedDate, sectionId: selectedSection }) const response = await fetch(`/api/teacher/export-attendance?${params}`) if (!response.ok) { const errorData = await response.json() throw new Error(errorData.error || 'Error al exportar') } // Obtener el blob del archivo CSV const blob = await response.blob() // Crear URL para descarga const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url // Obtener nombre del archivo desde los headers o generar uno const contentDisposition = response.headers.get('Content-Disposition') let filename = `asistencia_${selectedDate}.csv` if (contentDisposition) { const filenameMatch = contentDisposition.match(/filename="(.+)"/) if (filenameMatch) { filename = filenameMatch[1] } } link.download = filename document.body.appendChild(link) link.click() // Limpiar document.body.removeChild(link) window.URL.revokeObjectURL(url) toast.success('Reporte exportado exitosamente') } catch (error) { console.error('Error al exportar:', error) toast.error(error instanceof Error ? error.message : 'Error al exportar el reporte') } finally { setIsExporting(false) } } const getSelectedSectionName = () => { if (selectedSection === 'all') return 'Todas las secciones' const section = sections.find(s => s.id.toString() === selectedSection) return section ? `${section.className} - ${section.name}` : 'Sección desconocida' } const formatSelectedDate = () => { if (!selectedDate) return '' return format(new Date(selectedDate), 'dd \\de MMMM \\de yyyy', { locale: es }) } if (loading) { return (

Cargando...

) } return (
{/* Breadcrumb */} Profesor Exportar Reportes {/* Header */}

Exportar Reportes de Asistencia

Genera y descarga reportes de asistencia en formato CSV

{/* Configuración de Exportación */} Configuración del Reporte Selecciona la fecha y sección para exportar {/* Selector de Fecha */}
setSelectedDate(e.target.value)} max={format(new Date(), 'yyyy-MM-dd')} />
{/* Selector de Sección */}
{/* Botón de Exportación */}
{/* Vista Previa de Configuración */} Vista Previa del Reporte Información que se incluirá en el reporte {/* Información del Reporte */}
Fecha: {selectedDate ? formatSelectedDate() : 'No seleccionada'}
Sección: {getSelectedSectionName()}
{/* Columnas del CSV */}

Columnas incluidas:

• Fecha
• Estudiante
• Email
• Clase
• Código de Clase
• Sección
• Estado
• Parcial
• Razón
{/* Información adicional */}

Formato CSV

El archivo incluirá todos los registros de asistencia del día seleccionado, ordenados por fecha y nombre del estudiante.

) }