| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273 |
- <?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)
- ];
- }
- }
|