Kaynağa Gözat

uso de sistema de notificaciones con emision al websocket. Estado: funcional; frontend recibe notificación.

EmilianoOrtiz 2 ay önce
ebeveyn
işleme
ef5fbf5f5d

+ 31 - 0
sistema-mantenimiento-back/app/Http/Controllers/AsyncValidateLoadArchivesController.php

@@ -9,6 +9,8 @@ use ZipArchive;
 use Illuminate\Support\Str;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
+use ElephantIO\Client;
+
 
 /**
  * Async Controller for validating Excel and ZIP files for equipment documentation loading
@@ -20,6 +22,8 @@ class AsyncValidateLoadArchivesController extends Controller
     private $encryptionController;
     private $documentManagementController;
     private $functionsController;
+    private $notificationsController;
+    private $socketClient;
     
     // Expected headers in row 7 of Excel file with their corresponding column letters
     private $expectedHeaders = [
@@ -72,6 +76,33 @@ class AsyncValidateLoadArchivesController extends Controller
         $this->encryptionController = new EncryptionController();
         $this->documentManagementController = new DocumentManagementController();
         $this->functionsController = new FunctionsController();
+        $this->notificationsController = new NotificationsController();
+
+        $url = 'http://localhost:3200';
+        $this->socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
+        $this->socketClient->initialize();
+        $this->socketClient->of('/');
+    }
+
+
+    /**
+     * EmitNotification use  
+     */
+    public function emitNotification(Request $request):bool{
+        $module = $request['module'];
+        $title = $request['title'];
+        $content = $request['content'];
+        $actions = is_string($request['actions']) ? json_decode($request['actions'], true) : $request['actions'];
+        $audience = [$request['audience']];
+        $idUser = $request['idUser'] ?? $request['audience'];
+        $line = $request['line'] ?? 1;
+        $idOrder = $request['idOrder'] ?? null;
+        $orderType = $request['orderType'] ?? null;
+
+        $this->notificationsController->emitNotification($module, $title, $content, $actions, $audience, $idUser, $line, $this->socketClient ,$idOrder, $orderType);
+
+        return true;
+
     }
 
 

+ 33 - 58
sistema-mantenimiento-back/bash/validateLoadArchives.php

@@ -90,9 +90,6 @@ try {
     }
 
     echo "Procesando Job ID: {$job['VAJO_IDJO']}\n";
-    
-    // Enviar notificación WebSocket de inicio
-    sendWebSocketNotification($job['VAJO_IDUS'], 'processing', $job['VAJO_IDJO']);
 
     // 4. Determinar archivos ya procesados
     $results = json_decode($job['VAJO_RESU'], true) ?? ['processed_files' => []];
@@ -209,11 +206,6 @@ try {
                 WHERE VAJO_IDJO = ?
             ");
             $stmt->execute([json_encode($results), $progress, $job['VAJO_IDJO']]);
-            
-            // Enviar notificación de progreso
-            sendWebSocketNotification($job['VAJO_IDUS'], 'progress', $job['VAJO_IDJO'], $progress);
-
-            //echo "Progreso: {$progress}%\n";
         } else {
             echo "Error al procesar archivo {$nombreArchivo}: HTTP {$httpCode}\n";
             throw new Exception("Error al procesar archivo: {$nombreArchivo}");
@@ -233,24 +225,29 @@ try {
     ");
     $stmt->execute([$job['VAJO_IDJO']]);
     
-    // Enviar notificación de completado con archivos temporales
-    $completionData = [
+    // Enviar notificación de completado
+    $parameters = [
         'temp_files' => $tempFiles,
         'individual_temp_files' => $individualTempFiles
     ];
-
-    sendWebSocketNotification($job['VAJO_IDUS'], 'completed', $job['VAJO_IDJO'], 100, $completionData);
+    
+    emitNotification(
+        'S002V01M15IDUE',
+        'Carga de archivos temporales completada',
+        'Los archivos del submodulo Carga de documentos han sido subidos al servidor y están listos para completar el proceso.',
+        [['BOTON' => 'Completar proceso', 'FUNCION' => 'processLoadArchives', 'PARAMETROS' => json_encode($parameters)]],
+        [$job['VAJO_IDUS']]
+    );
 
     echo "Job completado: {$job['VAJO_IDJO']}\n";
 
 } catch (Exception $e) {
     echo "ERROR: " . $e->getMessage() . "\n";
     
-    // Enviar notificación de error si hay job activo
+    // Marcar job como fallido si hay job activo
     if (isset($job)) {
         $stmt = $pdo->prepare("UPDATE S002V01TVAJO SET VAJO_ESTA = 'failed', VAJO_ERME = ? WHERE VAJO_IDJO = ?");
         $stmt->execute([$e->getMessage(), $job['VAJO_IDJO']]);
-        sendWebSocketNotification($job['VAJO_IDUS'], 'failed', $job['VAJO_IDJO']);
     }
 } finally {
     // 8. Limpiar y eliminar lock global
@@ -268,51 +265,7 @@ try {
     }
 }
 
-function sendWebSocketNotification($userId, $status, $jobId, $progress = 0, $completionData = []) {
-    try {
-        require_once __DIR__ . '/../vendor/autoload.php';
-        
-        $client = new \ElephantIO\Client(\ElephantIO\Client::engine(\ElephantIO\Client::CLIENT_4X, 'http://localhost:3200'));
-        $client->initialize();
-        $client->of('/');
-        
-        $data = [
-            'jobId' => $jobId,
-            'status' => $status,
-            'message' => getStatusMessage($status)
-        ];
-        
-        if ($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";
-    } catch (Exception $e) {
-        echo "WebSocket error: " . $e->getMessage() . "\n";
-    }
-}
 
-function getStatusMessage($status) {
-    $messages = [
-        'queued' => 'En cola de validación',
-        'processing' => 'Procesando archivos',
-        'progress' => 'Validando archivos',
-        'completed' => 'Validación completada',
-        'failed' => 'Error en validación'
-    ];
-    return $messages[$status] ?? 'Estado desconocido';
-}
 
 function getEncrypt($value){
     $ch = curl_init('http://192.168.2.21:8000/api/encrypt');
@@ -325,3 +278,25 @@ function getEncrypt($value){
     $responseData = json_decode($response, true);
     return $responseData['response']['encrypted'];
 }
+
+function emitNotification($module, $title, $content, $actions, $audience) {
+    $ch = curl_init('http://192.168.2.21:8000/api/emitNotification');
+    curl_setopt($ch, CURLOPT_POST, true);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, [
+        'module' => $module,
+        'title' => $title,
+        'content' => $content,
+        'actions' => json_encode($actions),
+        'audience' => $audience
+    ]);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    $response = curl_exec($ch);
+    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+    curl_close($ch);
+    
+    if ($httpCode >= 200 && $httpCode < 300) {
+        echo "Notificación enviada exitosamente\n";
+    } else {
+        echo "Error al enviar notificación: HTTP $httpCode\n";
+    }
+}

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

@@ -552,10 +552,9 @@ Route::get("/print-order-details/{idOrder}/{idUser}/{line}",
     // Módulo de carga de archivos 
     Route::post("process-load-archives",                                                           "App\Http\Controllers\AsyncValidateLoadArchivesController@processLoadArchives");
     Route::post("async-validate-load-archives",                                                    "App\Http\Controllers\AsyncValidateLoadArchivesController@validateFilesWithBat");
-
     //api para encriptar
     Route::post("encrypt",                                                                          "App\Http\Controllers\AsyncValidateLoadArchivesController@encrypt");
-
+    Route::post("emitNotification", "App\Http\Controllers\AsyncValidateLoadArchivesController@emitNotification");
     //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');