Ver código fonte

funcion assign-operarios-to-visit para asignar operarios a una visita preventiva no programada - funcionando

EmilianoOrtiz 1 semana atrás
pai
commit
2b2bdde7e5

+ 183 - 7
sistema-mantenimiento-back/app/Http/Controllers/PreventiveMaintenanceController.php

@@ -4814,7 +4814,9 @@ class PreventiveMaintenanceController extends Controller
             'RVTN_COME AS COMENTARIOS',
             'RVTN_ESTA AS ESTADO',
             'RVTN_USRE AS USUREG',
-            'RVTN_FERE AS FECREG'
+            'RVTN_FERE AS FECREG',
+            'RVTN_HIES AS HISTORIAL',
+            'RVTN_PEIN AS PERSONAL'
         ])->leftJoin('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')
             ->where([
                 ['RVTN_IDVI', '=', $idVisit],
@@ -4835,6 +4837,21 @@ class PreventiveMaintenanceController extends Controller
         $visit->CONTADOR = $this->encryptionController->encrypt($visit->CONTADOR);
         $visit->PRIORIDAD = $this->encryptionController->encrypt($visit->PRIORIDAD);
 
+        // Procesar PERSONAL
+        $staffArr = json_decode($visit->PERSONAL, true);
+        foreach ($staffArr as $key => $val) {
+            $specialty = DB::table('S002V01TGEES')->where([
+                ['GEES_NULI', '=', $line],
+                ['GEES_COES', '=', $val['ID']]
+            ])->first();
+
+            $val['ID'] = $this->encryptionController->encrypt($val['ID']);
+            $val['NAME'] = $specialty->GEES_NOES;
+
+            $staffArr[$key] = $val;
+        }
+        $visit->PERSONAL = json_encode($staffArr);
+
         // Procesar MEDIDAS_OBJ
         $measureArr = json_decode($visit->MEDIDAS, true);
         if (!empty($measureArr)) {
@@ -4890,11 +4907,10 @@ class PreventiveMaintenanceController extends Controller
 
         // Mapear ESTADO
         $orderStates = [
-            'P' => 'Pendiente',
-            'C' => 'Cancelado',
-            'R' => 'Rechazado',
-            'A' => 'Aprobado',
-            'F' => 'Finalizado'
+            'VA' => 'Validado',
+            'EP' => 'En progreso',
+            'CP' => 'Cerrado pendiente',
+            'CE' => 'Cerrado',
         ];
         $visit->ESTADO = $orderStates[$visit->ESTADO];
 
@@ -4925,7 +4941,167 @@ class PreventiveMaintenanceController extends Controller
         );
 
         $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
-        Log::info(json_encode($visit));
         return $this->responseController->makeResponse(false, 'EXITO.', $visit);
     }
+
+    public function assignOperariosToPreventiveVisit(Request $request)
+    {
+        Log::info(json_encode($request->all()));
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_order' => 'required|string',
+            'config' => 'required|json',
+        ]);
+
+        if ($validator->fails()) {
+            return $this->responseController->makeResponse(
+                true,
+                "Se encontraron uno o más errores.",
+                $this->responseController->makeErrors(
+                    $validator->errors()->messages()
+                ),
+                401
+            );
+        }
+
+        $form = $request->all();
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if (!$idUser) {
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+
+        if (is_null($usr)) {
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
+
+        $idVisit = $this->encryptionController->decrypt($form['id_order']);
+        if (!$idVisit) {
+            return $this->responseController->makeResponse(true, 'El ID de la visita no fue encriptado correctamente.', [], 400);
+        }
+
+        $visit = DB::table('S002V01TRVTN')->where([
+            ['RVTN_NULI', '=', $form['linea']],
+            ['RVTN_IDVI', '=', $idVisit]
+        ])->first();
+
+        if (is_null($visit)) {
+            return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
+        } else if ($visit->RVTN_ESTA != 'PE' && $visit->RVTN_ESTA != 'VA') {
+            return $this->responseController->makeResponse(true, 'La visita no está en un estado válido para asignar operarios.', [], 401);
+        }
+
+        $staffConfigArr = json_decode($form['config'], true);
+        $audience = [];
+        foreach ($staffConfigArr as $key => $val) {
+            if (!array_key_exists('SPECIALTY', $val) || !array_key_exists('STAFF', $val)) {
+                return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
+            }
+
+            $specialtyDec = $this->encryptionController->decrypt($val['SPECIALTY']);
+            if (!$specialtyDec) {
+                return $this->responseController->makeResponse(true, "El identificador de la especialidad en el item $key del arreglo de configuración de operarios no fue encriptado correctamente.", [], 400);
+            }
+
+            if (gettype($val['STAFF']) != 'array') {
+                return $this->responseController->makeResponse(true, "El contenedor de operarios en el item $key del arreglo de configuración de operarios es inválido.", [], 400);
+            }
+
+            foreach ($val['STAFF'] as $key0 => $val0) {
+                if (!array_key_exists('ID', $val0) || !array_key_exists('TYPE', $val0)) {
+                    return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
+                }
+
+                $idDec = $this->encryptionController->decrypt($val0['ID']);
+                $employee = DB::table('S002V01TPERS')->where([
+                    ['PERS_NULI', '=', $form['linea']],
+                    ['PERS_IDPE', '=', $idDec]
+                ])->first();
+
+                if (is_null($employee)) {
+                    return $this->responseController->makeResponse(true, "El operario $key0 de la especialidad $specialtyDec del arreglo de configuración de operarios no existe.", [], 404);
+                }
+
+                $audience[] = $employee->PERS_IDUS;
+            }
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
+
+        // Buscar si ya existe un objeto con estado VA
+        $vaStatusIndex = null;
+        foreach ($statusHistoryArr as $index => $status) {
+            if ($status['ESTADO'] == 'VA') {
+                $vaStatusIndex = $index;
+                break;
+            }
+        }
+
+        // Crear nuevas invitaciones
+        $newInvitations = [];
+        foreach ($audience as $operarioId) {
+            $newInvitations[] = [
+                'ID' => $operarioId,
+                'FIRMA' => null,
+                'RESPUESTA' => '',
+                'COMENTARIOS' => ''
+            ];
+        }
+
+        if ($vaStatusIndex !== null) {
+            // Extender objeto VA existente
+            $statusHistoryArr[$vaStatusIndex]['ATENCION'] = array_merge(
+                $statusHistoryArr[$vaStatusIndex]['ATENCION'],
+                $newInvitations
+            );
+        } else {
+            // Crear nuevo objeto VA
+            $statusHistoryArr[] = [
+                'USUARIO' => $idUser,
+                'ESTADO' => 'VA',
+                'FECHA' => $nowStr,
+                'ATENCION' => $newInvitations,
+                'PERSONAL' => []
+            ];
+        }
+
+        $statusHistoryStr = json_encode($statusHistoryArr);
+
+        // Actualizar la visita
+        DB::table('S002V01TRVTN')->where([
+            ['RVTN_IDVI', '=', $idVisit],
+            ['RVTN_NULI', '=', $form['linea']]
+        ])->update([
+            'RVTN_ESTA' => 'VA',
+            'RVTN_HIES' => $statusHistoryStr,
+            'RVTN_USMO' => $idUser,
+            'RVTN_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M10GMPR',
+            'S002V01F11RVTP',
+            'S002V01P01REVI',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") asignó operarios a la visita preventiva #$idVisit.",
+            $idUser,
+            $nowStr,
+            'S002V01S02AOTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
 }

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

@@ -193,6 +193,7 @@ Route::post("/update-order-status",
 Route::post("/set-budget-analysis",                                                 "App\Http\Controllers\PreventiveMaintenanceController@setBudgetAnalysis");          //Registra una nueva orden de trabajo
 Route::post("/update-order-with-activator",                                         "App\Http\Controllers\PreventiveMaintenanceController@updateOrderWithActivator");   //Registra una nueva orden de trabajo
 Route::post("/save-order-simulation",                                               "App\Http\Controllers\PreventiveMaintenanceController@saveOrderSimulation");        //Registra una nueva orden de trabajo
+Route::post("/assign-operarios-to-visit",                                            "App\Http\Controllers\PreventiveMaintenanceController@assignOperariosToPreventiveVisit");
 
 //Módulo contadores y activadores
 Route::get("/activator/consult/{idUser}/{line}",                                    "App\Http\Controllers\CountersActivatorsController@getActivators");