Просмотр исходного кода

Merge branch 'develop' of http://209.50.56.224/git/ITTEC/PlataformaEducativaWeb2 into devAldrick

EmilianoChavarria 1 месяц назад
Родитель
Сommit
d832a0086a

+ 127 - 0
Back/backendP-Educativa/app/Http/Controllers/NivelExportController.php

@@ -157,4 +157,131 @@ return response()->streamDownload(function () use ($writer) {
 ]);
 
     }
+
+    public function exportarAlumnosRegistro()
+    {
+        // === Reutilizamos tu lógica para obtener los datos ===
+        $data = DB::table('usuarios')
+            ->leftJoin('registroacademico', 'usuarios.idUsuario', '=', 'registroacademico.idAlumno')
+            ->leftJoin('usuarios as u2', 'u2.idUsuario', '=', 'registroacademico.usuarioRegistro')
+            ->select(
+                DB::raw("CONCAT(COALESCE(usuarios.primerNombre, ''), ' ', COALESCE(usuarios.segundoNombre, ''), ' ', COALESCE(usuarios.apellidoPaterno, ''), ' ', COALESCE(usuarios.apellidoMaterno, '')) AS nombreCompleto"),
+                DB::raw("CONCAT(COALESCE(u2.primerNombre, ''), ' ', COALESCE(u2.segundoNombre, ''), ' ', COALESCE(u2.apellidoPaterno, ''), ' ', COALESCE(u2.apellidoMaterno, '')) AS nombrePadre"),
+                'usuarios.idUsuario',
+                'registroacademico.*'
+            )
+            ->where('usuarios.tipoUsuario', 'AL')
+            ->get()
+            ->map(function($item) {
+                $hasEmptyField = collect($item)->some(fn($v) => $v === null || $v === '');
+                return [
+                    'idUsuario' => $item->idUsuario,
+                    'quienRegistra' => $item->nombrePadre ?: 'No Aplica',
+                    'ultActualizacion' => $item->lastUpdate ?: 'No Aplica',
+                    'nombreCompleto' => $item->nombreCompleto,
+                    'registroAcCompleto' => $hasEmptyField ? 'No' : 'Sí'
+                ];
+            });
+
+        $dataAd = DB::table('usuarios')
+            ->select('usuarios.idUsuario','registroadministrativo.*')
+            ->leftJoin('registroadministrativo', 'usuarios.idUsuario', '=', 'registroadministrativo.idAlumno')
+            ->where('usuarios.tipoUsuario', 'AL')
+            ->get()
+            ->map(function($item) {
+                $hasEmptyField = collect($item)->some(fn($v) => $v === null || $v === '');
+                return [
+                    'idUsuario' => $item->idUsuario,
+                    'registroAdCompleto' => $hasEmptyField ? 'No' : 'Sí'
+                ];
+            });
+
+        $completo = $dataAd->map(function($item) use ($data) {
+            $registro = $data->firstWhere('idUsuario', $item['idUsuario']);
+            return [
+                'idUsuario' => $item['idUsuario'],
+                'quienRegistra' => $registro['quienRegistra'],
+                'ultActualizacion' => $registro['ultActualizacion'],
+                'nombreCompleto' => $registro['nombreCompleto'],
+                'registroAcCompleto' => $registro['registroAcCompleto'],
+                'registroAdCompleto' => $item['registroAdCompleto']
+            ];
+        })->toArray();
+
+        // === Ahora formateamos el Excel ===
+        $spreadsheet = new Spreadsheet();
+        $sheet = $spreadsheet->getActiveSheet();
+
+        $titulo = "REPORTE DE ALUMNOS";
+        $headers = ['ID', 'Alumno', 'Quién Registró', 'Última Actualización', 'Académico Completo', 'Administrativo Completo'];
+
+        // Estilos título
+        $sheet->mergeCells('A1:F2');
+        $sheet->setCellValue('A1', $titulo);
+        $sheet->getStyle('A1:F2')->applyFromArray([
+            'font' => ['bold' => true, 'size' => 18, 'name' => 'Century', 'color' => ['rgb' => 'FFFFFF']],
+            'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
+            'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4F81BD']],
+        ]);
+        $sheet->getRowDimension(1)->setRowHeight(50);
+
+        // Logo
+        $logoPathS3 = DB::table('personalizar')->value('PERLOGO');
+        if ($logoPathS3 && Storage::disk('s3')->exists($logoPathS3)) {
+            $tempLogoPath = tempnam(sys_get_temp_dir(), 'logo');
+            file_put_contents($tempLogoPath, Storage::disk('s3')->get($logoPathS3));
+            $logo = new Drawing();
+            $logo->setPath($tempLogoPath);
+            $logo->setHeight(80);
+            $logo->setCoordinates('A1');
+            $logo->setWorksheet($sheet);
+        }
+
+        // Encabezados
+        $sheet->fromArray($headers, null, 'A4');
+        $sheet->getStyle("A4:F4")->applyFromArray([
+            'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 12],
+            'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4F81BD']],
+            'alignment' => ['horizontal' => 'center'],
+            'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]],
+        ]);
+
+        // Datos
+        $row = 5;
+        foreach ($completo as $index => $item) {
+            $sheet->fromArray([
+                $item['idUsuario'],
+                $item['nombreCompleto'],
+                $item['quienRegistra'],
+                $item['ultActualizacion'],
+                $item['registroAcCompleto'],
+                $item['registroAdCompleto'],
+            ], null, "A$row");
+
+            $fillColor = $index % 2 === 0 ? 'F2F2F2' : 'FFFFFF';
+            $sheet->getStyle("A$row:F$row")->applyFromArray([
+                'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => $fillColor]],
+                'font' => ['name' => 'Calibri', 'size' => 11],
+                'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'BFBFBF']]],
+            ]);
+
+            $row++;
+        }
+
+        foreach (range('A', 'F') as $col) {
+            $sheet->getColumnDimension($col)->setAutoSize(true);
+        }
+
+        $sheet->setAutoFilter("A4:F4");
+
+        $writer = new Xlsx($spreadsheet);
+        $filename = "Alumnos_Registro.xlsx";
+
+        return response()->streamDownload(function () use ($writer) {
+            $writer->save('php://output');
+        }, $filename, [
+            'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+        ]);
+    }
 }
+

+ 2 - 0
Back/backendP-Educativa/routes/api.php

@@ -60,6 +60,8 @@ Route::put('changePassword', [LoginController::class, 'updatePassword']);
 Route::get('personalizarInfo', [PersonalizarController::class, 'show']);
 Route::post('/send-test-email', [MailController::class, 'sendTestEmail']);
 Route::get('/exportar-excel', [NivelExportController::class, 'exportarExcel']);
+Route::get('/exportar-alumnos', [NivelExportController::class, 'exportarAlumnosRegistro']);
+
 
 //protección de rutas
 Route::middleware(['auth:sanctum'])->group(function () {

+ 1 - 13
Front/src/app/modules/Administrador/pages/consultarRegistroAcayAdmi/consultar-registro-acay-admi.component.ts

@@ -51,19 +51,7 @@ url2: string | null = '';
   //exportar toda la data a excel
 
 exportarTodo() {
-  this.exportExcell.getConsultarRegistro().subscribe((response: any) => {
-    const datos = response.data.map((item: any) => ({
-      'ID Usuario': item.idUsuario,
-      'Nombre Completo': item.nombreCompleto,
-      'Quién Registró': item.quienRegistra,
-      'Última Actualización': item.ultActualizacion,
-      'Académico Completo': item.registroAcCompleto,
-      'Administrativo Completo': item.registroAdCompleto
-    }));
-
-    // Aquí sí usas tu servicio ExportExcell
-    this.exportExcell.exportJsonToExcel(datos, 'AlumnosRegistro');
-  });
+  this.exportExcell.exportAlumnos()
 }
 
 

+ 17 - 10
Front/src/app/modules/Administrador/services/export-excell.service.ts

@@ -24,17 +24,14 @@ private URL: string = environments.baseUrl;
 
 
 
- // 🔹 Exportar todo
-exportAll(tabla: string) {
+ exportAll(tabla: string) {
   const url = `${this.URL}/exportar-excel?tabla=${tabla}`;
   this.http.get(url, { responseType: 'blob', withCredentials: true }).subscribe({
     next: (blob) => {
-      console.log('👉 Tipo MIME recibido:', blob.type, 'Tamaño:', blob.size);
 
-      // Si no es Excel, mostrar el contenido como texto
       if (blob.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
         blob.text().then(texto => {
-          console.error('⚠️ El servidor no devolvió Excel, devolvió:', texto);
+          console.error( texto);
           Swal.fire('Error', 'El servidor devolvió un error en lugar del Excel', 'error');
         });
         return;
@@ -46,8 +43,22 @@ exportAll(tabla: string) {
   });
 }
 
+exportAlumnos() {
+  const url = `${this.URL}/exportar-alumnos`;
+  this.http.get(url, { responseType: 'blob', withCredentials: true }).subscribe({
+    next: (blob) => {
+      const a = document.createElement('a');
+      const objectUrl = URL.createObjectURL(blob);
+      a.href = objectUrl;
+      a.download = "Alumnos_Registro.xlsx";
+      a.click();
+      URL.revokeObjectURL(objectUrl);
+    },
+    error: (error) => console.error(error)
+  });
+}
+
 
-  // Helpers
   private nombreArchivo(tabla: string): string {
     switch (tabla) {
       case 'niveles': return 'Niveles_Educativos';
@@ -83,17 +94,13 @@ exportAll(tabla: string) {
   }
 
   exportJsonToExcel(datos: any[], nombreArchivo: string) {
-  // Convertir JSON a hoja Excel
   const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(datos);
 
-  // Crear libro
   const workbook: XLSX.WorkBook = XLSX.utils.book_new();
 
-  // Nombre seguro de la hoja
   let sheetName = nombreArchivo.substring(0, 31);
   XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
 
-  // Descargar archivo
   XLSX.writeFile(workbook, `${nombreArchivo}.xlsx`);
 }