Преглед изворни кода

uso de encriptado y emisión de la data con el formato requerido. Hay un error al mandar o recibir la data pero ahorita lo encuentro

EmilianoOrtiz пре 3 месеци
родитељ
комит
b5614aa48d

+ 39 - 22
sistema-mantenimiento-back/app/Http/Controllers/AsyncValidateLoadArchivesController.php

@@ -75,6 +75,20 @@ class AsyncValidateLoadArchivesController extends Controller
         $this->functionsController = new FunctionsController();
     }
 
+
+    /***
+     * Encryption endpoint
+     *
+     */
+
+    public function encrypt(Request $request){
+        $encryptString = $this->encryptionController->encrypt($request['value']);
+         if(!$encryptString){
+             return $this->responseController->makeResponse(true, "La cadena no fue encriptada correctamente", [], 400);
+         }
+         return $this->responseController->makeResponse(false, "Cadena encriptada correctamente", ['encrypted' => $encryptString], 200);
+    }
+
     /**
      * Validation endpoint that dispatches file process to bat job
      */
@@ -153,33 +167,36 @@ class AsyncValidateLoadArchivesController extends Controller
 
         // Log::info($tempFiles);
 
-        $idFileZip = $this->encryptionController->decrypt($tempFiles['files']['zip']);
-        if(!$idFileZip){
-            return $this->responseController->makeResponse(true, "El id del archivo que desea eliminar no fue encriptado correctamente", [], 400);
-        }
+         $idFileZip = $this->encryptionController->decrypt($tempFiles['files']['zip']);
+         if(!$idFileZip){
+             return $this->responseController->makeResponse(true, "El id del archivo que desea eliminar no fue encriptado correctamente", [], 400);
+         }
 
-        Log::info($idFileZip);
+        // Log::info($idFileZip);
 
-        //Recuperar objeto del registro del zip
-         $zipFile = DB::table('S002V01TARTE')->where([
-            ['ARTE_IDAR', '=', $idFileZip],
-            ['ARTE_NULI', '=', $request['linea']]
-        ])->first();
+        // //Recuperar objeto del registro del zip
+        //  $zipFile = DB::table('S002V01TARTE')->where([
+        //     ['ARTE_IDAR', '=', $idFileZip],
+        //     ['ARTE_NULI', '=', $request['linea']]
+        // ])->first();
 
-        //hay que usar la funcion de registerActivity para registrar en bd los movimiento  como el de registrar un nuevo archivo en tmep
+        // //hay que usar la funcion de registerActivity para registrar en bd los movimiento  como el de registrar un nuevo archivo en tmep
         
-        $idFileExcel = $this->encryptionController->decrypt($tempFiles['files']['excel']);
-        if(!$idFileExcel){
-            return $this->responseController->makeResponse(true, "El id del archivo que desea eliminar no fue encriptado correctamente", [], 400);
+         $idFileExcel = $this->encryptionController->decrypt($tempFiles['files']['excel']);
+         if(!$idFileExcel){
+             return $this->responseController->makeResponse(true, "El id del archivo que desea eliminar no fue encriptado correctamente", [], 400);
         }
 
-        Log::info($idFileExcel);
+        // Log::info($idFileExcel);
+
+        // //Recuperar objeto del registro del excel
+        //  $excelFile = DB::table('S002V01TARTE')->where([
+        //     ['ARTE_IDAR', '=', $idFileExcel],
+        //     ['ARTE_NULI', '=', $request['linea']]
+        // ])->first();
 
-        //Recuperar objeto del registro del excel
-         $excelFile = DB::table('S002V01TARTE')->where([
-            ['ARTE_IDAR', '=', $idFileExcel],
-            ['ARTE_NULI', '=', $request['linea']]
-        ])->first();
+        Log::info($idFileExcel);
+        Log::info($idFileZip);
         
 
         // Guardar en bd::validation_jobs 
@@ -187,8 +204,8 @@ class AsyncValidateLoadArchivesController extends Controller
             'job_id' => $jobId,
             'user_id' => $userId,
             'linea' => $request->input('linea'),
-            'excel_temp_path' => $excelFile->ARTE_UBTE,
-            'zip_temp_path' => $zipFile->ARTE_UBTE,
+            'excel_temp_id' => $idFileExcel,
+            'zip_temp_id' => $idFileZip,
             'created_at' => now(),
             'updated_at' => now()
         ]);

+ 56 - 9
sistema-mantenimiento-back/bash/validateLoadArchives.php

@@ -1,5 +1,6 @@
 <?php
 // Configuración de BD
+
 $host = 'localhost';
 $port = 3306;
 $database = 'samqa';
@@ -97,11 +98,27 @@ try {
     $results = json_decode($job['results'], true) ?? ['processed_files' => []];
     $procesados = $results['processed_files'] ?? [];
 
-    // 5. Abrir ZIP y obtener lista completa de archivos
-    $zipPath = $job['zip_temp_path'];
+    // 5. Buscar ruta del ZIP en base de datos
+    $stmt = $pdo->prepare("SELECT ARTE_UBTE FROM s002v01tarte WHERE ARTE_IDAR = ?");
+    $stmt->execute([$job['zip_temp_id']]);
+    $zipData = $stmt->fetch(PDO::FETCH_ASSOC);
+    
+    if (!$zipData) {
+        throw new Exception("ZIP ID no encontrado: {$job['zip_temp_id']}");
+    }
+    
+    $zipPath = $zipData['ARTE_UBTE'];
     if (!file_exists($zipPath)) {
         throw new Exception("ZIP no encontrado: {$zipPath}");
     }
+    
+    // Guardar IDs de archivos temporales
+    $tempFiles = [
+        'excel' => getEncrypt($job['excel_temp_id']),
+        'zip' => getEncrypt($job['zip_temp_id'])
+    ];
+    
+    $individualTempFiles = [];
 
     $zip = new ZipArchive();
     if ($zip->open($zipPath) !== TRUE) {
@@ -173,8 +190,15 @@ try {
         unlink($archivoExtraido);
         
         // Solo marcar como procesado si el endpoint respondió exitosamente
-        echo "response: {$response}\n";
         if ($httpCode >= 200 && $httpCode < 300) {
+            $responseData = json_decode($response, true);
+            if (isset($responseData['response']['idArchivo'])) {
+                $individualTempFiles[] = [
+                    'original_name' => $nombreArchivo,
+                    'temp_id' => $responseData['response']['idArchivo']
+                ];
+            }
+            
             $procesados[] = $nombreArchivo;
             $progress = intval((count($procesados) / $totalArchivos) * 100);
 
@@ -189,7 +213,7 @@ try {
             // Enviar notificación de progreso
             sendWebSocketNotification($job['user_id'], 'progress', $job['id'], $progress);
 
-            echo "Progreso: {$progress}%\n";
+            //echo "Progreso: {$progress}%\n";
         } else {
             echo "Error al procesar archivo {$nombreArchivo}: HTTP {$httpCode}\n";
             throw new Exception("Error al procesar archivo: {$nombreArchivo}");
@@ -209,8 +233,14 @@ try {
     ");
     $stmt->execute([$job['id']]);
     
-    // Enviar notificación de completado
-    sendWebSocketNotification($job['user_id'], 'completed', $job['id'], 100);
+    // Enviar notificación de completado con archivos temporales
+    $completionData = [
+        'temp_files' => $tempFiles,
+        'individual_temp_files' => $individualTempFiles
+    ];
+
+    echo ("completionData: " . json_encode($completionData) . "\n");
+    sendWebSocketNotification($job['user_id'], 'completed', $job['id'], 100, $completionData);
 
     echo "Job completado: {$job['id']}\n";
 
@@ -239,7 +269,7 @@ try {
     }
 }
 
-function sendWebSocketNotification($userId, $status, $jobId, $progress = null) {
+function sendWebSocketNotification($userId, $status, $jobId, $progress = 0, $completionData = []) {
     try {
         require_once __DIR__ . '/../vendor/autoload.php';
         
@@ -257,14 +287,19 @@ function sendWebSocketNotification($userId, $status, $jobId, $progress = null) {
             $data['progress'] = $progress;
         }
         
+        if (!empty($completionData)) {
+            $data = array_merge($data, $completionData);
+        }
+        
         $client->emit('laravel_emit', [
             'event' => 'validation_status',
             'data' => $data,
+            'completionData' => $completionData,
             'userId' => (string)$userId
         ]);
         
         $client->close();
-        echo "WebSocket: $status enviado a usuario $userId\n";
+        //echo "WebSocket: $status enviado a usuario $userId\n";
     } catch (Exception $e) {
         echo "WebSocket error: " . $e->getMessage() . "\n";
     }
@@ -279,4 +314,16 @@ function getStatusMessage($status) {
         'failed' => 'Error en validación'
     ];
     return $messages[$status] ?? 'Estado desconocido';
-}
+}
+
+function getEncrypt($value){
+    $ch = curl_init('http://192.168.2.21:8000/api/encrypt');
+    curl_setopt($ch, CURLOPT_POST, true);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, ['value' => $value]);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    $response = curl_exec($ch);
+    curl_close($ch);
+    
+    $responseData = json_decode($response, true);
+    return $responseData['response']['encrypted'];
+}

+ 2 - 2
sistema-mantenimiento-back/database/migrations/2024_01_01_000001_create_validation_jobs_table.php

@@ -17,8 +17,8 @@ return new class extends Migration
             $table->integer('progress_percentage')->default(0);
             $table->json('results')->nullable();
             $table->text('error_message')->nullable();
-            $table->string('excel_temp_path')->nullable();
-            $table->string('zip_temp_path')->nullable();
+            $table->string('excel_temp_id')->nullable();
+            $table->string('zip_temp_id')->nullable();
             $table->timestamps();
             $table->timestamp('completed_at')->nullable();
         });

+ 3 - 0
sistema-mantenimiento-back/routes/api.php

@@ -554,6 +554,9 @@ Route::get("/print-order-details/{idOrder}/{idUser}/{line}",
     Route::post("process-load-archives",                                                           "App\Http\Controllers\ValidateLoadArchivesController@processLoadArchives");
     Route::post("async-validate-load-archives",                                                    "App\Http\Controllers\AsyncValidateLoadArchivesController@validateFilesWithBat");
 
+    //api para encriptar
+    Route::post("encrypt",                                                                          "App\Http\Controllers\AsyncValidateLoadArchivesController@encrypt");
+
     //subida de archivo de equipamientos
     Route::post('equipment-data/verify-template',                                                   'App\Http\Controllers\TemplatesManagementController@validateAndProcessExcelTemplate');
     Route::post('equipment-data/upload-template',                                                   'App\Http\Controllers\TemplatesManagementController@processExcelEquipment');