Browse Source

Controlador para manejar la validacion y procesamiento de archivos del modulo de carga de archivos SAM con api fuera de middleware para acceso publico mientras se desarrolla

EmilianoOrtiz 3 tháng trước cách đây
mục cha
commit
43cf1ff372

+ 273 - 0
sistema-mantenimiento-back/app/Http/Controllers/ValidateLoadArchivesController.php

@@ -0,0 +1,273 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Support\Facades\Log;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use ZipArchive;
+
+/**
+ * Controller for validating Excel and ZIP files for equipment documentation loading
+ * Validates Excel headers structure and compares file listings with ZIP contents
+ */
+class ValidateLoadArchivesController extends Controller
+{
+    private $responseController;
+    
+    // Expected headers in row 7 of Excel file with their corresponding column letters
+    private $expectedHeaders = [
+        ['letter' => 'D', 'category' => 'CÓDIGO DE EQUIPO'],
+        ['letter' => 'H', 'category' => 'FICHA DE SEGURIDAD DE PRODUCTOS QUÍMICOS'],
+        ['letter' => 'J', 'category' => 'FICHA TÉCNICA'],
+        ['letter' => 'L', 'category' => 'FOTOGRAFÍAS - DIAGRAMAS'],
+        ['letter' => 'N', 'category' => 'DATOS DEL PROVEEDOR'],
+        ['letter' => 'P', 'category' => 'MANUALES DE OPERACIÓN'],
+        ['letter' => 'R', 'category' => 'MANUALES DE MANTENIMIENTO PREVENTIVO'],
+        ['letter' => 'T', 'category' => 'MANUALES DE MANTENIMIENTO CORRECTIVO'],
+        ['letter' => 'V', 'category' => 'DOCUMENTOS ADICIONALES']
+    ];
+    
+    // Mapping of file extensions to their types for validation
+    private $extensionTypes = [
+        'pdf' => 'PDF',
+        'jpg' => 'IMG', 'jpeg' => 'IMG', 'png' => 'IMG', 'gif' => 'IMG', 'bmp' => 'IMG',
+        'xlsx' => 'EXCEL', 'xls' => 'EXCEL'
+    ];
+
+    public function __construct()
+    {
+        $this->responseController = new ResponseController();
+    }
+        
+    /**
+     * Main validation endpoint that validates both Excel and ZIP files
+     * Checks Excel headers, ZIP integrity, file listings, and compares them
+     */
+    public function validateFiles(Request $request)
+    {
+        Log::info('=== INICIANDO VALIDACIÓN DE ARCHIVOS ===');
+        
+        // Validate request inputs
+        Log::info('Paso 1: Validando tipos de archivo');
+        $validator = Validator::make($request->all(), [
+            'excel_file' => 'required|file|mimes:xlsx,xls',
+            'zip_file' => 'required|file|mimes:zip'
+        ]);
+
+        if ($validator->fails()) {
+            Log::error('Error en validación de tipos de archivo', $validator->errors()->toArray());
+            return $this->responseController->makeResponse(
+                true,
+                'Se encontraron uno o más errores.',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
+        }
+        Log::info('✓ Tipos de archivo válidos');
+
+        // Validate Excel file headers structure
+        Log::info('Paso 2: Validando encabezados de Excel');
+        $excelValidation = $this->validateExcelHeaders($request->file('excel_file'));
+        if ($excelValidation['error']) {
+            Log::error('Error en encabezados Excel: ' . $excelValidation['message']);
+            return $this->responseController->makeResponse(true, $excelValidation['message'], [], 400);
+        }
+        Log::info('✓ Encabezados de Excel válidos');
+        
+        // Extract and validate file listings from Excel
+        Log::info('Paso 3: Extrayendo listado de archivos del Excel');
+        $filesValidation = $this->extractAndValidateFiles($request->file('excel_file'));
+        if ($filesValidation['error']) {
+            Log::error('Error extrayendo archivos Excel: ' . $filesValidation['message']);
+            return $this->responseController->makeResponse(true, $filesValidation['message'], [], 400);
+        }
+        Log::info('✓ Archivos extraídos: ' . count($filesValidation['files']) . ' archivos encontrados');
+
+        // Validate ZIP file integrity
+        Log::info('Paso 4: Validando integridad del archivo ZIP');
+        $zipValidation = $this->validateZipFile($request->file('zip_file'));
+        if ($zipValidation['error']) {
+            Log::error('Error validando ZIP: ' . $zipValidation['message']);
+            return $this->responseController->makeResponse(true, $zipValidation['message'], [], 400);
+        }
+        Log::info('✓ Archivo ZIP válido');
+
+        // Compare Excel file listings with ZIP contents
+        Log::info('Paso 5: Comparando listados Excel vs ZIP');
+        $comparison = $this->compareExcelWithZip($filesValidation['files'], $request->file('zip_file'));
+        
+        Log::info('✓ Comparación completada', [
+            'valid' => $comparison['valid'],
+            'missing_in_zip' => count($comparison['missing_in_zip']),
+            'extra_in_zip' => count($comparison['extra_in_zip'])
+        ]);
+        
+        Log::info('=== VALIDACIÓN COMPLETADA EXITOSAMENTE ===');
+        return $this->responseController->makeResponse(false, 'Validación completada.', $comparison);
+    }
+
+    /**
+     * Validates that Excel file has the correct headers in row 7
+     * Each column must match the expected category name exactly
+     */
+    private function validateExcelHeaders($file)
+    {
+        try {
+            Log::info('  - Cargando archivo Excel: ' . $file->getClientOriginalName());
+            $spreadsheet = IOFactory::load($file->getPathname());
+            $worksheet = $spreadsheet->getActiveSheet();
+            Log::info('  - Excel cargado, validando encabezados en fila 7');
+            
+            // Check each expected header in row 7
+            foreach ($this->expectedHeaders as $header) {
+                $cellValue = $worksheet->getCell($header['letter'] . '7')->getValue();
+                if (trim($cellValue) !== $header['category']) {
+                    return [
+                        'error' => true,
+                        'message' => "El encabezado en la columna {$header['letter']} no coincide. Se esperaba: '{$header['category']}', se encontró: '{$cellValue}'"
+                    ];
+                }
+            }
+            
+            return ['error' => false];
+        } catch (\Exception $e) {
+            return ['error' => true, 'message' => 'Error al procesar el archivo Excel: ' . $e->getMessage()];
+        }
+    }
+
+    /**
+     * Validates ZIP file integrity and ensures it's not empty
+     */
+    private function validateZipFile($file)
+    {
+        Log::info('  - Abriendo archivo ZIP: ' . $file->getClientOriginalName());
+        $zip = new ZipArchive();
+        $result = $zip->open($file->getPathname());
+        
+        if ($result !== TRUE) {
+            return ['error' => true, 'message' => 'No se pudo abrir el archivo ZIP.'];
+        }
+        
+        if ($zip->numFiles === 0) {
+            $zip->close();
+            return ['error' => true, 'message' => 'El archivo ZIP está vacío.'];
+        }
+        
+        Log::info('  - ZIP contiene ' . $zip->numFiles . ' archivos');
+        $zip->close();
+        return ['error' => false];
+    }
+    
+    /**
+     * Extracts file listings from Excel starting from row 8
+     * Validates file extensions and creates structured file list
+     * Only processes rows with equipment code (column D)
+     */
+    private function extractAndValidateFiles($file)
+    {
+        try {
+            $spreadsheet = IOFactory::load($file->getPathname());
+            $worksheet = $spreadsheet->getActiveSheet();
+            $highestRow = $worksheet->getHighestRow();
+            Log::info('  - Procesando ' . ($highestRow - 7) . ' filas de datos (filas 8-' . $highestRow . ')');
+            $files = [];
+            
+            // Process each row starting from row 8 (data rows)
+            for ($row = 8; $row <= $highestRow; $row++) {
+                $equipmentCode = trim($worksheet->getCell('D' . $row)->getValue());
+                if (empty($equipmentCode)) continue; // Skip rows without equipment code
+                
+                $hasFiles = false;
+                $rowFiles = [];
+                
+                // Check each file category column (excluding equipment code column D)
+                foreach ($this->expectedHeaders as $header) {
+                    if ($header['letter'] === 'D') continue;
+                    
+                    $cellValue = trim($worksheet->getCell($header['letter'] . $row)->getValue());
+                    if (empty($cellValue)) continue;
+                    
+                    // Handle multiple files separated by commas
+                    $fileNames = explode(',', $cellValue);
+                    foreach ($fileNames as $fileName) {
+                        $fileName = trim($fileName);
+                        if (empty($fileName)) continue;
+                        
+                        // Validate file extension
+                        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
+                        if (!isset($this->extensionTypes[$extension])) {
+                            return [
+                                'error' => true,
+                                'message' => "Extensión inválida '{$extension}' en archivo '{$fileName}' para equipo '{$equipmentCode}'"
+                            ];
+                        }
+                        
+                        $rowFiles[] = [
+                            'equipment_code' => $equipmentCode,
+                            'category' => $header['category'],
+                            'file_name' => $fileName,
+                            'type' => $this->extensionTypes[$extension]
+                        ];
+                        $hasFiles = true;
+                    }
+                }
+                
+                if ($hasFiles) {
+                    $files = array_merge($files, $rowFiles);
+                }
+            }
+            
+            return ['error' => false, 'files' => $files];
+        } catch (\Exception $e) {
+            return ['error' => true, 'message' => 'Error al extraer archivos del Excel: ' . $e->getMessage()];
+        }
+    }
+    
+    /**
+     * Compares file listings from Excel with actual files in ZIP
+     * Returns validation status and lists of missing/extra files
+     */
+    private function compareExcelWithZip($excelFiles, $zipFile)
+    {
+        $zip = new ZipArchive();
+        $zip->open($zipFile->getPathname());
+        
+        // Extract all file names from ZIP
+        Log::info('  - Extrayendo nombres de archivos del ZIP');
+        $zipFiles = [];
+        for ($i = 0; $i < $zip->numFiles; $i++) {
+            $fullPath = $zip->getNameIndex($i);
+            
+            // Skip directories (entries ending with /)
+            if (substr($fullPath, -1) === '/') {
+                continue;
+            }
+            
+            // Extract only filename without path
+            $fileName = basename($fullPath);
+            if (!empty($fileName)) {
+                $zipFiles[] = $fileName;
+            }
+        }
+        $zip->close();
+        Log::info('  - ZIP contiene ' . count($zipFiles) . ' archivos (excluyendo directorios)');
+        
+        // Get file names from Excel listings
+        $excelFileNames = array_column($excelFiles, 'file_name');
+        Log::info('  - Excel lista ' . count($excelFileNames) . ' archivos');
+        
+        // Find discrepancies between Excel and ZIP
+        $missingInZip = array_diff($excelFileNames, $zipFiles);
+        $extraInZip = array_diff($zipFiles, $excelFileNames);
+        Log::info('  - Archivos faltantes en ZIP: ' . count($missingInZip));
+        Log::info('  - Archivos extra en ZIP: ' . count($extraInZip));
+        
+        return [
+            'valid' => empty($missingInZip) && empty($extraInZip),
+            'missing_in_zip' => array_values($missingInZip),
+            'extra_in_zip' => array_values($extraInZip)
+        ];
+    }
+}

+ 4 - 2
sistema-mantenimiento-back/routes/api.php

@@ -549,7 +549,9 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::post('budget-management/update-payment-method/{idPayment}',                              "App\Http\Controllers\BudgetManagementController@updatePaymentMethod");
     Route::post('budget-management/delete-payment-method/{idPayment}',                              "App\Http\Controllers\BudgetManagementController@deletePaymentMethod");
 
-});
-
 
+        
+});
 
+// Endpoint for file validation - outside middleware for public access
+Route::post("/validate-load-archives", "App\Http\Controllers\ValidateLoadArchivesController@validateFiles");