Переглянути джерело

en este punto el endpoint funciona, el job emite mensajes y retorna los arrays, pero no funciona de manera asincrona, solo forzandolo sincrono

EmilianoOrtiz 3 місяців тому
батько
коміт
27147ed2ad

+ 394 - 10
sistema-mantenimiento-back/app/Http/Controllers/AsyncValidateLoadArchivesController.php

@@ -3,40 +3,168 @@
 namespace App\Http\Controllers;
 
 use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use ZipArchive;
 use App\Jobs\ValidateLoadArchives;
 use Illuminate\Support\Str;
 
+/**
+ * Async Controller for validating Excel and ZIP files for equipment documentation loading
+ * Validates Excel headers structure and compares file listings with ZIP contents using queues
+ */
 class AsyncValidateLoadArchivesController extends Controller
 {
     private $responseController;
+    private $encryptionController;
+    private $documentManagementController;
+    private $functionsController;
+    
+    // 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 = [
+        // Archivos de almacenamiento
+        'zip' => 'STORAGE', 'rar' => 'STORAGE', 'tar' => 'STORAGE', '7z' => 'STORAGE',
+        // Formatos de audio
+        'mp3' => 'AUDIO', 'mpeg' => 'AUDIO', 'wav' => 'AUDIO', 'ogg' => 'AUDIO', 'opus' => 'AUDIO',
+        // Archivos de imagen
+        'jpeg' => 'IMG', 'jpg' => 'IMG', 'png' => 'IMG', 'gif' => 'IMG', 'bmp' => 'IMG', 'tiff' => 'IMG', 'svg' => 'IMG',
+        // Archivos de texto
+        'txt' => 'TEXT',
+        // Archivos de video
+        'webm' => 'VIDEO', 'mpeg4' => 'VIDEO', 'mp4' => 'VIDEO', '3gpp' => 'VIDEO', 'mov' => 'VIDEO', 'avi' => 'VIDEO', 'wmv' => 'VIDEO', 'flv' => 'VIDEO',
+        // Planos de Auto CAD
+        'dwg' => 'CAD', 'dxf' => 'CAD',
+        // Modelos de 3D Studio
+        '3ds' => '3D',
+        // Dibujos de Illustrator
+        'ai' => 'ILLUSTRATOR',
+        // Imágenes de Photoshop
+        'psd' => 'PHOTOSHOP',
+        // Formato de documento portátil
+        'pdf' => 'PDF',
+        // Hoja de cálculo en Excel
+        'xls' => 'EXCEL', 'xlsx' => 'EXCEL',
+        // Presentaciones de PowerPoint
+        'ppt' => 'POWERPOINT', 'pptx' => 'POWERPOINT',
+        // Documentos de texto de Word
+        'doc' => 'WORD', 'docx' => 'WORD',
+        // Dibujos de Visio
+        'vsd' => 'VISIO', 'vsdx' => 'VISIO'
+    ];
 
     public function __construct()
     {
         $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->documentManagementController = new DocumentManagementController();
+        $this->functionsController = new FunctionsController();
     }
-
+        
+    /**
+     * Async validation endpoint that dispatches validation to queue
+     */
     public function validateFiles(Request $request)
     {
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'excel_file' => 'required|file|mimes:xlsx,xls',
+            'zip_file' => 'required|file|mimes:zip'
+        ]);
+
+        if ($validator->fails()) {
+            return $this->responseController->makeResponse(
+                true,
+                'Se encontraron uno o más errores.',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
+        }
+        
         $jobId = Str::uuid();
-        $userId = $request->input('id_user', '0000000001');
+        $userId = '0000000001';
+        
+        // $idUser = $this->encryptionController->decrypt($request->input('id_user'));
+        // if(!$idUser){
+        //     return $this->responseController->makeResponse(true, "El id del usuario que realizó la petición no fue encriptado correctamente", [], 400);
+        // }
+
+        // Validate Excel file headers structure
+        $excelValidation = $this->validateExcelHeaders($request->file('excel_file'));
+        if ($excelValidation['error']) {
+            return $this->responseController->makeResponse(true, $excelValidation['message'], [], 400);
+        }
+        Log::info('ValidateFiles: Headers Excel validados correctamente');
+        
+        // Validate ZIP file integrity
+        $zipValidation = $this->validateZipFile($request->file('zip_file'));
+        if ($zipValidation['error']) {
+            return $this->responseController->makeResponse(true, $zipValidation['message'], [], 400);
+        }
+        Log::info('ValidateFiles: Archivo ZIP validado correctamente');
+
+        // Extract and validate file listings from Excel
+        $filesValidation = $this->extractAndValidateFiles($request->file('excel_file'));
+        if ($filesValidation['error']) {
+            return $this->responseController->makeResponse(true, $filesValidation['message'], [], 400);
+        }
+        Log::info('ValidateFiles: Archivos extraídos del Excel', ['count' => count($filesValidation['files'])]);
+
         
-        // Guardar archivos temporalmente
-        $tempPaths = [];
-        if ($request->hasFile('excel_file')) {
-            $tempPaths['excel_file'] = $request->file('excel_file')->store('temp_uploads');
+
+        // Compare Excel file listings with ZIP contents
+        $comparison = $this->compareExcelWithZip($filesValidation['files'], $request->file('zip_file'));
+
+        // Check for file size validation errors
+        if (isset($comparison['error'])) {
+            return $this->responseController->makeResponse(true, $comparison['error'], [], 400);
         }
-        if ($request->hasFile('zip_file')) {
-            $tempPaths['zip_file'] = $request->file('zip_file')->store('temp_uploads');
+        Log::info('ValidateFiles: Comparación Excel-ZIP completada', ['valid' => $comparison['valid']]);
+        
+        if (!$comparison['valid']) {
+            return $this->responseController->makeResponse(
+                true, 
+                'Los archivos no coinciden entre Excel y ZIP', 
+                $comparison, 
+                400
+            );
+        }
+
+        // Upload temp files
+        $tempFiles = $this->uploadTempFiles($request);
+        if ($tempFiles['error']) {
+            return $this->responseController->makeResponse(true, $tempFiles['message'], [], 400);
         }
         
         // Solo pasar datos serializables al job
         $requestData = [
             'id_user' => $userId,
             'linea' => $request->input('linea'),
-            'temp_paths' => $tempPaths
+            'temp_files' => $tempFiles['files']
         ];
+
+        Log::info('ValidateFiles: Datos serializados para el job', $requestData);
+        
+        //make sync the call to the job
         
-        ValidateLoadArchives::dispatch($requestData, $userId, $jobId);
+        // Ejecutar el job sincrónicamente en lugar de despacharlo a la cola
+        (new ValidateLoadArchives($requestData, $userId, $jobId))->handle();                
+        //ValidateLoadArchives::dispatch($requestData, $userId, $jobId);
         
         return $this->responseController->makeResponse(
             false, 
@@ -44,4 +172,260 @@ class AsyncValidateLoadArchivesController extends Controller
             ['job_id' => $jobId, 'status' => 'processing']
         );
     }
+
+    /**
+     * 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 {
+            $spreadsheet = IOFactory::load($file->getPathname());
+            $worksheet = $spreadsheet->getActiveSheet();
+            
+            // 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}'"
+                    ];
+                }
+            }
+            
+            Log::info('ValidateExcelHeaders: Todos los headers validados correctamente');
+            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)
+    {
+        $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('ValidateZipFile: ZIP válido', ['num_files' => $zip->numFiles]);
+        $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();
+            $files = [];
+            
+            Log::info('ExtractAndValidateFiles: Iniciando extracción', ['total_rows' => $highestRow]);
+            
+            // 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,
+                            'file_name' => $fileName,
+                            'type' => $this->getFileType($extension)
+                        ];
+                        $hasFiles = true;
+                    }
+                }
+                
+                if ($hasFiles) {
+                    $files = array_merge($files, $rowFiles);
+                }
+            }
+            
+            Log::info('ExtractAndValidateFiles: Extracción completada', ['files_found' => count($files)]);
+            return ['error' => false, 'files' => $files];
+        } catch (\Exception $e) {
+            Log::error('ExtractAndValidateFiles: Excepción', ['error' => $e->getMessage()]);
+            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());
+        
+        Log::info('CompareExcelWithZip: Iniciando comparación');
+        
+        // Extract all file names and sizes from ZIP
+        $zipFiles = [];
+        $zipFileSizes = [];
+        for ($i = 0; $i < $zip->numFiles; $i++) {
+            $fullPath = $zip->getNameIndex($i);
+            
+            // Skip directories (entries ending with /)
+            if (substr($fullPath, -1) === '/') {
+                continue;
+            }
+            
+            // Extract filename and size
+            $fileName = basename($fullPath);
+            if (!empty($fileName)) {
+                $zipFiles[] = $fileName;
+                $zipFileSizes[$fileName] = $zip->statIndex($i)['size'];
+            }
+        }
+        $zip->close();
+        
+        // Validate file sizes using FunctionsController
+        foreach ($zipFileSizes as $fileName => $size) {
+            $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
+            if (!$this->functionsController->checkFileSize($extension, $size)) {
+                $sizeMB = round($size / (1024 * 1024), 2);
+                return [
+                    'valid' => false,
+                    'error' => "El archivo '{$fileName}' excede el límite de tamaño. Tamaño: {$sizeMB}MB"
+                ];
+            }
+        }
+        
+        // Get file names from Excel listings
+        $excelFileNames = array_column($excelFiles, 'file_name');
+        
+        // Find discrepancies between Excel and ZIP
+        $missingInZip = array_diff($excelFileNames, $zipFiles);
+        $extraInZip = array_diff($zipFiles, $excelFileNames);
+        
+        $isValid = empty($missingInZip) && empty($extraInZip);
+        Log::info('CompareExcelWithZip: Comparación completada', [
+            'valid' => $isValid,
+            'missing_count' => count($missingInZip),
+            'extra_count' => count($extraInZip)
+        ]);
+        
+        return [
+            'valid' => $isValid,
+            'missing_in_zip' => array_values($missingInZip),
+            'extra_in_zip' => array_values($extraInZip)
+        ];
+    }
+
+    /**
+     * Uploads Excel and ZIP files as temporary files using DocumentManagementController
+     */
+    private function uploadTempFiles(Request $request)
+    {
+        try {
+            Log::info('UploadTempFiles: Iniciando subida de archivos temporales');
+            $tempFiles = [];
+            
+            // Upload Excel file
+            $excelRequest = new Request();
+            $excelRequest->files->set('file', $request->file('excel_file'));
+            $excelRequest->merge([
+                'id_user' => $request->input('id_user'),
+                'linea' => $request->input('linea')
+            ]);
+            
+            $excelResponse = $this->documentManagementController->uploadTempFile($excelRequest);
+            $excelData = json_decode($excelResponse->getContent());
+            
+            if ($excelData->error) {
+                $errorMsg = isset($excelData->message) ? $excelData->message : 'Error desconocido subiendo Excel';
+                Log::error('UploadTempFiles: Error subiendo Excel', ['message' => $errorMsg]);
+                return ['error' => true, 'message' => 'Error subiendo Excel: ' . $errorMsg];
+            }
+            
+            $tempFiles['excel'] = $excelData->response->idArchivo;
+            
+            // Upload ZIP file
+            $zipRequest = new Request();
+            $zipRequest->files->set('file', $request->file('zip_file'));
+            $zipRequest->merge([
+                'id_user' => $request->input('id_user'),
+                'linea' => $request->input('linea')
+            ]);
+            
+            $zipResponse = $this->documentManagementController->uploadTempFile($zipRequest);
+            $zipData = json_decode($zipResponse->getContent());
+            
+            if ($zipData->error) {
+                $errorMsg = isset($zipData->message) ? $zipData->message : 'Error desconocido subiendo ZIP';
+                Log::error('UploadTempFiles: Error subiendo ZIP', ['message' => $errorMsg]);
+                return ['error' => true, 'message' => 'Error subiendo ZIP: ' . $errorMsg];
+            }
+            
+            $tempFiles['zip'] = $zipData->response->idArchivo;
+            
+            Log::info('UploadTempFiles: Archivos temporales subidos exitosamente', $tempFiles);
+            return ['error' => false, 'files' => $tempFiles];
+            
+        } catch (\Exception $e) {
+            Log::error('UploadTempFiles: Excepción', ['error' => $e->getMessage()]);
+            return ['error' => true, 'message' => 'Error en uploadTempFiles: ' . $e->getMessage()];
+        }
+    }
+    
+
+
+    /**
+     * Gets file type based on extension
+     */
+    private function getFileType($extension){
+        $typeMap = [
+            'zip' => 'STORAGE', 'rar' => 'STORAGE', 'tar' => 'STORAGE', '7z' => 'STORAGE',
+            'mp3' => 'AUDIO', 'mpeg' => 'AUDIO', 'wav' => 'AUDIO', 'ogg' => 'AUDIO', 'opus' => 'AUDIO',
+            'jpeg' => 'IMG', 'jpg' => 'IMG', 'png' => 'IMG', 'gif' => 'IMG', 'bmp' => 'IMG', 'tiff' => 'IMG', 'svg' => 'IMG',
+            'txt' => 'TEXT',
+            'webm' => 'VIDEO', 'mpeg4' => 'VIDEO', 'mp4' => 'VIDEO', '3gpp' => 'VIDEO', 'mov' => 'VIDEO', 'avi' => 'VIDEO', 'wmv' => 'VIDEO', 'flv' => 'VIDEO',
+            'dwg' => 'CAD', 'dxf' => 'CAD', '3ds' => '3D', 'ai' => 'ILLUSTRATOR', 'psd' => 'PHOTOSHOP',
+            'pdf' => 'PDF', 'xls' => 'EXCEL', 'xlsx' => 'EXCEL', 'ppt' => 'POWERPOINT', 'pptx' => 'POWERPOINT',
+            'doc' => 'WORD', 'docx' => 'WORD', 'vsd' => 'VISIO', 'vsdx' => 'VISIO'
+        ];
+        return $typeMap[$extension] ?? 'UNKNOWN';
+    }
 }

+ 74 - 37
sistema-mantenimiento-back/app/Jobs/ValidateLoadArchives.php

@@ -14,6 +14,7 @@ use App\Http\Controllers\EncryptionController;
 use Illuminate\Http\Request;
 use Illuminate\Http\UploadedFile;
 use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Facades\DB;
 use ZipArchive;
 
 class ValidateLoadArchives implements ShouldQueue
@@ -51,33 +52,15 @@ class ValidateLoadArchives implements ShouldQueue
 
     private function processFiles()
     {
-        // Etapa 1: Subida Excel a temp (30%)
-        $this->broadcastProgress(30, 'processing', 'Subiendo archivo Excel a almacenamiento temporal...');
-        $tempFiles = [];
+        // Archivos ya están en temp (Excel y ZIP)
+        $tempFiles = $this->requestData['temp_files'];
         
-        if (isset($this->requestData['temp_paths']['excel_file'])) {
-            $excelTempId = $this->uploadFileToTemp($this->requestData['temp_paths']['excel_file'], 'excel');
-            if ($excelTempId) {
-                $tempFiles['excel'] = $excelTempId;
-            }
-        }
-        
-        // Etapa 2: Subida ZIP a temp (60%)
-        $this->broadcastProgress(60, 'processing', 'Subiendo archivo ZIP a almacenamiento temporal...');
-        
-        if (isset($this->requestData['temp_paths']['zip_file'])) {
-            $zipTempId = $this->uploadFileToTemp($this->requestData['temp_paths']['zip_file'], 'zip');
-            if ($zipTempId) {
-                $tempFiles['zip'] = $zipTempId;
-            }
-        }
-        
-        // Etapa 3: Extracción archivos individuales (90%)
-        $this->broadcastProgress(90, 'processing', 'Extrayendo y subiendo archivos individuales...');
+        // Etapa 1: Extracción archivos individuales (50%)
+        $this->broadcastProgress(50, 'processing', 'Extrayendo y subiendo archivos individuales...');
         
         $individualFiles = [];
-        if (isset($this->requestData['temp_paths']['zip_file'])) {
-            $individualFiles = $this->extractAndUploadIndividualFiles($this->requestData['temp_paths']['zip_file']);
+        if (isset($tempFiles['zip'])) {
+            $individualFiles = $this->extractAndUploadIndividualFiles($tempFiles['zip']);
         }
         
         return [
@@ -127,7 +110,7 @@ class ValidateLoadArchives implements ShouldQueue
             $data = json_decode($response->getContent());
             
             // Limpiar archivo temporal
-            Storage::delete($tempPath);
+            //Storage::delete($tempPath);
             
             return $data->error ? false : $data->response->idArchivo;
         } catch (\Exception $e) {
@@ -136,13 +119,29 @@ class ValidateLoadArchives implements ShouldQueue
         }
     }
     
-    private function extractAndUploadIndividualFiles($zipTempPath)
+    private function extractAndUploadIndividualFiles($zipTempId)
     {
         try {
-            $zipPath = Storage::path($zipTempPath);
+            // Get ZIP file from temp storage using DocumentManagementController
+            $encryptionController = new EncryptionController();
+            $tempIdDec = $encryptionController->decrypt($zipTempId);
+            
+            if (!$tempIdDec) {
+                Log::error('Error decrypting ZIP temp ID');
+                return [];
+            }
+            
+            $tempFile = DB::table('S002V01TARTE')->where('ARTE_IDAR', $tempIdDec)->first();
+            if (!$tempFile) {
+                Log::error('Temp ZIP file not found in database');
+                return [];
+            }
+            
+            $zipPath = $tempFile->ARTE_UBTE;
             $zip = new ZipArchive();
             
             if ($zip->open($zipPath) !== TRUE) {
+                Log::error('Cannot open ZIP file: ' . $zipPath);
                 return [];
             }
             
@@ -150,20 +149,24 @@ class ValidateLoadArchives implements ShouldQueue
             $tempDir = storage_path('app/temp_extracted_' . time());
             mkdir($tempDir, 0755, true);
             
-            for ($i = 0; $i < min($zip->numFiles, 10); $i++) { // Limitar a 10 archivos
-                $fileName = $zip->getNameIndex($i);
+            for ($i = 0; $i < $zip->numFiles; $i++) {
+                $fullPath = $zip->getNameIndex($i);
+                
+                // Skip directories
+                if (substr($fullPath, -1) === '/') continue;
                 
-                if (substr($fileName, -1) === '/') continue;
+                $fileName = basename($fullPath);
+                if (empty($fileName)) continue;
                 
                 $fileContent = $zip->getFromIndex($i);
                 if ($fileContent !== false) {
-                    $extractPath = $tempDir . '/' . basename($fileName);
+                    $extractPath = $tempDir . '/' . $fileName;
                     
                     if (file_put_contents($extractPath, $fileContent)) {
-                        $tempFileId = $this->uploadExtractedFileToTemp($extractPath, basename($fileName));
+                        $tempFileId = $this->uploadExtractedFileToTemp($extractPath, $fileName);
                         if ($tempFileId) {
                             $tempFiles[] = [
-                                'original_name' => basename($fileName),
+                                'original_name' => $fileName,
                                 'temp_id' => $tempFileId
                             ];
                         }
@@ -173,7 +176,7 @@ class ValidateLoadArchives implements ShouldQueue
             }
             
             $zip->close();
-            rmdir($tempDir);
+            $this->removeDirectory($tempDir);
             
             return $tempFiles;
         } catch (\Exception $e) {
@@ -185,19 +188,23 @@ class ValidateLoadArchives implements ShouldQueue
     private function uploadExtractedFileToTemp($filePath, $fileName)
     {
         try {
+            $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
+            $mimeType = $this->getMimeType($extension);
+            
             $uploadedFile = new UploadedFile(
                 $filePath,
                 $fileName,
-                mime_content_type($filePath),
+                $mimeType,
                 null,
                 true
             );
             
+            $encryptionController = new EncryptionController();
             $request = new Request();
             $request->files->set('file', $uploadedFile);
             $request->merge([
-                'id_user' => $this->requestData['id_user'],
-                'linea' => $this->requestData['linea'] ?? 1
+                'id_user' => $encryptionController->encrypt($this->requestData['id_user']),
+                'linea' => $this->requestData['linea']
             ]);
             
             $documentController = new DocumentManagementController();
@@ -210,4 +217,34 @@ class ValidateLoadArchives implements ShouldQueue
             return false;
         }
     }
+    
+    private function getMimeType($extension)
+    {
+        $mimeTypes = [
+            'pdf' => 'application/pdf',
+            'doc' => 'application/msword',
+            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+            'xls' => 'application/vnd.ms-excel',
+            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+            'ppt' => 'application/vnd.ms-powerpoint',
+            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+            'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
+            'png' => 'image/png', 'gif' => 'image/gif', 'bmp' => 'image/bmp',
+            'txt' => 'text/plain', 'dwg' => 'application/acad', 'dxf' => 'application/dxf'
+        ];
+        
+        return $mimeTypes[$extension] ?? 'application/octet-stream';
+    }
+    
+    private function removeDirectory($dir)
+    {
+        if (!is_dir($dir)) return;
+        
+        $files = array_diff(scandir($dir), ['.', '..']);
+        foreach ($files as $file) {
+            $path = $dir . '/' . $file;
+            is_dir($path) ? $this->removeDirectory($path) : unlink($path);
+        }
+        rmdir($dir);
+    }
 }