瀏覽代碼

Actualización de avances API mantenimiento correctivo y contadores y activadores

Jose Brito 2 年之前
父節點
當前提交
79814a9c1b

+ 787 - 43
sistema-mantenimiento-back/app/Http/Controllers/CatalogMeasuresController.php

@@ -68,12 +68,16 @@ class CatalogMeasuresController extends Controller
     }
 
     public function registerMeasures(Request $request) {
+        DB::enableQueryLog();
+
         $validator = Validator::make($request->all(), [
             'NOMBRE_MEDIDA' => 'required|string',
             'ACRONIMO_MEDIDA' => 'required|string',
-            'NUMERO_LINEA' => 'required|string',
+            'NUMERO_LINEA' => 'required|integer',
             'USUARIO' => 'required|string',
+            'ID_MAGNITUD' =>  'required|string',
         ]);
+
         if ($validator->fails()) {
             return $this->responseController->makeResponse(
                 true,
@@ -83,50 +87,88 @@ class CatalogMeasuresController extends Controller
             );
         }
 
-        DB::beginTransaction();
         $requestData = $request->all();
 
         try {
-            $user = $this->encController->decrypt($requestData['USUARIO']);
+            $idUser = $this->encController->decrypt($requestData['USUARIO']);
         } catch (\Throwable $th) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: No se pudo obtener el usuario.", $th->getMessage(), 500);
         }
 
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $requestData['NUMERO_LINEA']],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        try {
+            $idMagnitude = $this->encController->decrypt($requestData['ID_MAGNITUD']);
+        } catch (\Throwable $th) {
+            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la magnitud relacionada no fe encriptado correctamente.", $th->getMessage(), 500);
+        }
+
+        $magnitude = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $requestData['NUMERO_LINEA']],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
         $now = $this->functionsController->now();
         $currentDate = $now->toDateTimeString();
 
         try {
-            $validateRegister = DB::table('S002V01TLIME')->insert([
+            $validateRegister = DB::table('S002V01TLIME')->insertGetId([
+                'LIME_NULI' => $requestData['NUMERO_LINEA'],
+                'LIME_MAGN' => $idMagnitude,
                 'LIME_NOME' => $requestData['NOMBRE_MEDIDA'],
                 'LIME_ACME' => $requestData['ACRONIMO_MEDIDA'],
-                'LIME_NULI' => $requestData['NUMERO_LINEA'],
-                'LIME_USRE' => $user,
+                'LIME_USRE' => $idUser,
                 'LIME_FERE' => $currentDate,
-                'LIME_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
             ]);
         } catch (\Throwable $th) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_REG001: Ocurrió un error al insertar el formulario en la base de datos.", $th->getMessage(), 500);
         }
 
         if (!$validateRegister) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_REG002: No se pudo insertar el formulario en la base de datos.", [], 500);
         }
 
-        DB::commit();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $requestData['NUMERO_LINEA'],
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró la unidad $requestData[NOMBRE_MEDIDA] ($validateRegister).",
+            $idUser,
+            $currentDate
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $currentDate, $idac, $requestData['NUMERO_LINEA']);
         return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
     }
 
     public function updateMeasures(Request $request) {
+        DB::enableQueryLog();
+
         $validator = Validator::make($request->all(), [
             'ID_MEDIDA' => 'required|string',
             'NOMBRE_MEDIDA' => 'required|string',
             'ACRONIMO_MEDIDA' => 'required|string',
-            'NUMERO_LINEA' => 'required|string',
+            'NUMERO_LINEA' => 'required|integer',
             'USUARIO' => 'required|string',
+            'ID_MAGNITUD' =>  'required|string',
         ]);
+
         if ($validator->fails()) {
             return $this->responseController->makeResponse(
                 true,
@@ -136,61 +178,108 @@ class CatalogMeasuresController extends Controller
             );
         }
 
-        DB::beginTransaction();
         $requestData = $request->all();
 
         try {
-            $user = $this->encController->decrypt($request['USUARIO']);
+            $idUser = $this->encController->decrypt($request['USUARIO']);
         } catch (\Throwable $th) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD001: No se pudo obtener el usuario.", $th->getMessage(), 500);
         }
 
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $requestData['NUMERO_LINEA']],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
         try {
-            $validateExists = DB::table('S002V01TLIME')->where('LIME_IDME', '=', $requestData['ID_MEDIDA'])->exists();
+            $idMagnitude = $this->encController->decrypt($requestData['ID_MAGNITUD']);
         } catch (\Throwable $th) {
-            DB::rollBack();
-            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD002: Ocurrió un error al consultar en la base de datos.", $th->getMessage(), 500);
+            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la magnitud relacionada no fe encriptado correctamente.", $th->getMessage(), 500);
+        }
+
+        $magnitude = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $requestData['NUMERO_LINEA']],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
+        try {
+            $idUnit = $this->encController->decrypt($requestData['ID_MEDIDA']);
+        } catch (\Throwable $th) {
+            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la unidad seleccionada no fe encriptado correctamente.", $th->getMessage(), 500);
         }
-        if (!$validateExists) {
-            DB::rollBack();
-            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD003: No se pudo encontrar el registro dentro de la base de datos.", [], 500);
+
+        try {
+          $validateExists = DB::table('S002V01TLIME')->where([
+              ['LIME_IDME', '=', $idUnit],
+              ['LIME_NULI', '=', $requestData['NUMERO_LINEA']],
+              ['LIME_MAGN', '=', $idMagnitude]
+          ])->first();
+        } catch (\Throwable $th) {
+            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD002: Ocurrió un error al consultar en la base de datos.", $th->getMessage(), 500);
         }
 
+        if(is_null($validateExists)){
+          return $this->responseController->makeResponse(true, 'La unidad de medición seleccionada no está registrada.', [], 404);
+      }
+
         $now = $this->functionsController->now();
         $currentDate = $now->toDateTimeString();
 
         try {
             $validateUpdate = DB::table('S002V01TLIME')
-                ->where('LIME_IDME', '=', $requestData['ID_MEDIDA'])
+                ->where('LIME_IDME', '=', $idUnit)
                 ->where('LIME_NULI', '=', $requestData['NUMERO_LINEA'])
+                ->where('LIME_MAGN', '=', $idMagnitude)
                 ->update([
                     'LIME_NOME' => $requestData['NOMBRE_MEDIDA'],
                     'LIME_ACME' => $requestData['ACRONIMO_MEDIDA'],
-                    'LIME_USMO' => $user,
+                    'LIME_USMO' => $idUser,
                     'LIME_FEMO' => $currentDate,
-                    'LIME_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                 ]);
         } catch (\Throwable $th) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD004: Ocurrió un error al modificar el formulario en la base de datos.", $th, 500);
         }
 
         if ( !$validateUpdate ) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD005: No se pudo modificar el formulario en la base de datos.", [], 500);
         }
 
-        DB::commit();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $requestData['NUMERO_LINEA'],
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la unidad de medida #$idUnit.",
+            $idUser,
+            $currentDate
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $currentDate, $idac, $requestData['NUMERO_LINEA']);
         return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
     }
 
     public function deleteMeasures(Request $request) {
+        DB::enableQueryLog();
+
         $validator = Validator::make($request->all(), [
-            'ID_MEDIDA' => 'required|integer',
+            'ID_MEDIDA' => 'required|string',
             'NUMERO_LINEA' => 'required|integer',
             'USUARIO' => 'required|string',
+            'ID_MAGNITUD' =>  'required|string',
         ]);
+
         if ($validator->fails()) {
             return $this->responseController->makeResponse(
                 true,
@@ -200,25 +289,56 @@ class CatalogMeasuresController extends Controller
             );
         }
 
-        DB::beginTransaction();
         $requestData = $request->all();
 
         try {
-            $user = $this->encController->decrypt($request['USUARIO']);
+          $idUser = $this->encController->decrypt($request['USUARIO']);
         } catch (\Throwable $th) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL001: No se pudo obtener el usuario.", [], 500);
         }
 
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $requestData['NUMERO_LINEA']],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
         try {
-            $validateExists = DB::table('S002V01TLIME')->where('LIME_IDME', '=', $requestData['ID_MEDIDA'])->exists();
+            $idMagnitude = $this->encController->decrypt($requestData['ID_MAGNITUD']);
         } catch (\Throwable $th) {
-            DB::rollBack();
-            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL002: Ocurrió un error al consultar en la base de datos.", $th->getMessage(), 500);
+            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la magnitud relacionada no fe encriptado correctamente.", $th->getMessage(), 500);
         }
-        if (!$validateExists) {
-            DB::rollBack();
-            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL003: La medida no existe.", [], 500);
+
+        $magnitude = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $requestData['NUMERO_LINEA']],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
+        try {
+            $idUnit = $this->encController->decrypt($requestData['ID_MEDIDA']);
+        } catch (\Throwable $th) {
+            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la unidad seleccionada no fe encriptado correctamente.", $th->getMessage(), 500);
+        }
+
+        try {
+          $validateExists = DB::table('S002V01TLIME')->where([
+              ['LIME_IDME', '=', $idUnit],
+              ['LIME_NULI', '=', $requestData['NUMERO_LINEA']],
+              ['LIME_MAGN', '=', $idMagnitude]
+          ])->first();
+        } catch (\Throwable $th) {
+            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD002: Ocurrió un error al consultar en la base de datos.", $th->getMessage(), 500);
+        }
+
+        if(is_null($validateExists)){
+            return $this->responseController->makeResponse(true, 'La unidad de medición seleccionada no está registrada.', [], 404);
         }
 
         $now = $this->functionsController->now();
@@ -226,25 +346,649 @@ class CatalogMeasuresController extends Controller
 
         try {
             $validateDelete = DB::table('S002V01TLIME')
-                ->where('LIME_IDME', '=', $requestData['ID_MEDIDA'])
+                ->where('LIME_IDME', '=', $idUnit)
                 ->where('LIME_NULI', '=', $requestData['NUMERO_LINEA'])
+                ->where('LIME_MAGN', '=', $idMagnitude)
                 ->update([
                     'LIME_ESTA' => 'Eliminado',
-                    'LIME_USMO' => $user,
+                    'LIME_USMO' => $idUser,
                     'LIME_FEMO' => $currentDate,
-                    'LIME_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                 ]);
         } catch (\Throwable $th) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL004: Ocurrió un error al eliminar la medida base de datos.", $th, 500);
         }
         if (!$validateDelete) {
-            DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL005: No se pudo eliminar la medida en la base de datos..", [], 500);
         }
 
-        DB::commit();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $requestData['NUMERO_LINEA'],
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la unidad de medida #$idUnit.",
+            $idUser,
+            $currentDate
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $currentDate, $idac, $requestData['NUMERO_LINEA']);
         return $this->responseController->makeResponse(false, "ÉXITO: Eliminación Exitosa");
     }
 
+    public function registerMagnitude(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'magnitude' => 'required|string|max:50',
+        ]);
+
+        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->encController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $magnitudes = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $form['linea']],
+            ['MAGN_MAGN', '=', $form['magnitude']]
+        ])->get()->all();
+
+        if(count($magnitudes) > 0){
+            return $this->responseController->makeResponse(true, "La magnitud $form[magnitude] ya ha sido registrada.", [], 400);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $idMagnitude = DB::table('S002V01TMAGN')->insertGetId([
+            'MAGN_NULI' => $form['linea'],
+            'MAGN_MAGN' => $form['magnitude'],
+            'MAGN_USRE' => $idUser,
+            'MAGN_FERE' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró la magnitud $form[magnitude] ($idMagnitude).",
+            $idUser,
+            $nowStr
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getMagnitudes($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $magnitudes = DB::table('S002V01TMAGN')->select([
+            'MAGN_IDMA AS ID_MAGNITUD',
+            'MAGN_MAGN AS MAGNITUD',
+            'MAGN_ESTA AS ESTADO',
+            'MAGN_USRE AS USRREG',
+            'MAGN_FERE AS FECREG',
+            'MAGN_USMO AS USRMOD',
+            'MAGN_FEMO AS FECMOD'
+        ])->get()->all();
+
+        foreach($magnitudes as $key=>$magnitude){
+            $units = DB::table('S002V01TLIME')->where([
+                ['LIME_NULI', '=', $line],
+                ['LIME_MAGN', '=', $magnitude->ID_MAGNITUD]
+            ])->get()->all();
+
+            $magnitude->ID_MAGNITUD = $this->encController->encrypt($magnitude->ID_MAGNITUD);
+            $magnitude->UNIDADES_RELACIONADAS = count($units);
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $magnitude->USRREG],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+
+            $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $magnitude->USRREG = $nameUsrReg . " (" . $magnitude->USRREG . ")";
+
+            if(!is_null($magnitude->USRMOD)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_IDUS', '=', $magnitude->USRMOD],
+                    ['USUA_NULI', '=', $line]
+                ])->first();
+    
+                $nameUsrMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+                $magnitude->USRMOD = $nameUsrMod . " (" . $magnitude->USRMOD . ")";
+            }
+
+            $magnitudes[$key] = $magnitude;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las magnitudes registradas.",
+            $idUser,
+            $nowStr
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $magnitudes);
+    }
+
+    public function getUnitsByMagnitude($idMagnitude, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idMagnitude = $this->encController->decrypt($idMagnitude);
+        if(!$idMagnitude){
+            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+        }
+
+        $magnitude = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $line],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
+        $units = DB::table('S002V01TLIME')->select([
+            'LIME_IDME AS ID_UNIDAD',
+            'LIME_MAGN AS ID_MAGNITUD',
+            'LIME_NOME AS NOMBRE_UNIDAD',
+            'LIME_ACME AS ACRONIMO_UNIDAD',
+            'LIME_ESTA AS ESTADO',
+            'LIME_USRE AS USRREG',
+            'LIME_FERE AS FECREG',
+            'LIME_USMO AS USRMOD',
+            'LIME_FEMO AS FECMOD'
+        ])->where([
+            ['LIME_NULI', '=', $line],
+            ['LIME_MAGN', '=', $idMagnitude],
+        ])->get()->all();
+
+        foreach($units as $key=>$unit){
+            $unit->ID_UNIDAD = $this->encController->encrypt($unit->ID_UNIDAD);
+            $unit->ID_MAGNITUD = $this->encController->encrypt($unit->ID_MAGNITUD);
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $unit->USRREG],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+
+            $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $unit->USRREG = $nameUsrReg . " (" . $unit->USRREG . ")";
+
+            if(!is_null($unit->USRMOD)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_IDUS', '=', $unit->USRMOD],
+                    ['USUA_NULI', '=', $line]
+                ])->first();
+    
+                $nameUsrMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+                $unit->USRMOD = $nameUsrMod . " (" . $unit->USRMOD . ")";
+            }
+
+            $units[$key] = $unit;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las unidades relacionadas a la magnitud #$idMagnitude.",
+            $idUser,
+            $nowStr
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $units);
+    }
+    
+    public function getMagnitude($idMagnitude, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idMagnitude = $this->encController->decrypt($idMagnitude);
+        if(!$idMagnitude){
+            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+        }
+
+        $magnitude = DB::table('S002V01TMAGN')->select([
+            'MAGN_IDMA AS ID_MAGNITUD',
+            'MAGN_MAGN AS MAGNITUD',
+            'MAGN_ESTA AS ESTADO',
+            'MAGN_USRE AS USRREG',
+            'MAGN_FERE AS FECREG',
+            'MAGN_USMO AS USRMOD',
+            'MAGN_FEMO AS FECMOD'
+        ])->where([
+            ['MAGN_NULI', '=', $line],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_IDUS', '=', $magnitude->USRREG],
+            ['USUA_NULI', '=', $line]
+        ])->first();
+
+        $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $magnitude->USRREG = $nameUsrReg . " (" . $magnitude->USRREG . ")";
+
+        if(!is_null($magnitude->USRMOD)){
+            $usrMod = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $magnitude->USRMOD],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+
+            $nameUsrMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+            $magnitude->USRMOD = $nameUsrMod . " (" . $magnitude->USRMOD . ")";
+        }
+
+        $units = DB::table('S002V01TLIME')->select([
+            'LIME_IDME AS ID_UNIDAD',
+            'LIME_MAGN AS ID_MAGNITUD',
+            'LIME_NOME AS NOMBRE_UNIDAD',
+            'LIME_ACME AS ACRONIMO_UNIDAD',
+            'LIME_ESTA AS ESTADO',
+            'LIME_USRE AS USRREG',
+            'LIME_FERE AS FECREG',
+            'LIME_USMO AS USRMOD',
+            'LIME_FEMO AS FECMOD'
+        ])->where([
+            ['LIME_NULI', '=', $line],
+            ['LIME_MAGN', '=', $idMagnitude],
+        ])->get()->all();
+
+        foreach($units as $key=>$unit){
+            $unit->ID_UNIDAD = $this->encController->encrypt($unit->ID_UNIDAD);
+            $unit->ID_MAGNITUD = $this->encController->encrypt($unit->ID_MAGNITUD);
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $unit->USRREG],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+
+            $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $unit->USRREG = $nameUsrReg . " (" . $unit->USRREG . ")";
+
+            if(!is_null($unit->USRMOD)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_IDUS', '=', $unit->USRMOD],
+                    ['USUA_NULI', '=', $line]
+                ])->first();
+    
+                $nameUsrMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+                $unit->USRMOD = $nameUsrMod . " (" . $unit->USRMOD . ")";
+            }
+
+            $units[$key] = $unit;
+        }
+
+        $magnitude->UNIDADES = $units;
+        $magnitude->ID_MAGNITUD = $this->encController->encrypt($magnitude->ID_MAGNITUD);
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la magnitud #$idMagnitude.",
+            $idUser,
+            $nowStr
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $magnitude);
+    }
+
+    public function updateMagnitude(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'magnitude' => 'required|string|max:50',
+            'id_magnitude' => 'required|string',
+        ]);
+
+        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->encController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idMagnitude = $this->encController->decrypt($form['id_magnitude']);
+        if(!$idMagnitude){
+            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+        }
+
+        $magnitude = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $form['linea']],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $form['linea']],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->update([
+            'MAGN_MAGN' => $form['magnitude'],
+            'MAGN_USMO' => $idUser,
+            'MAGN_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la magnitud $form[magnitude] ($idMagnitude).",
+            $idUser,
+            $nowStr
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function deleteMagnitude(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_magnitude' => 'required|string',
+        ]);
+
+        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->encController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idMagnitude = $this->encController->decrypt($form['id_magnitude']);
+        if(!$idMagnitude){
+            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+        }
+
+        $magnitude = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $form['linea']],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $form['linea']],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->update([
+            'MAGN_ESTA' => 'Eliminado',
+            'MAGN_USMO' => $idUser,
+            'MAGN_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la magnitud #$idMagnitude.",
+            $idUser,
+            $nowStr
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getUnit($idMagnitude, $idUnit, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idMagnitude = $this->encController->decrypt($idMagnitude);
+        if(!$idMagnitude){
+            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+        }
+
+        $magnitude = DB::table('S002V01TMAGN')->where([
+            ['MAGN_NULI', '=', $line],
+            ['MAGN_IDMA', '=', $idMagnitude]
+        ])->first();
+
+        if(is_null($magnitude)){
+            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
+        }
+
+        $idUnit = $this->encController->decrypt($idUnit);
+        if(!$idUnit){
+            return $this->responseController->makeResponse(true, 'El ID de la unidad seleccionada no está encriptado correctamente.', [], 400);
+        }
+
+        $unit = DB::table('S002V01TLIME')->select([
+            'LIME_IDME AS ID_UNIDAD',
+            'LIME_MAGN AS ID_MAGNITUD',
+            'LIME_NOME AS NOMBRE_UNIDAD',
+            'LIME_ACME AS ACRONIMO_UNIDAD',
+            'LIME_ESTA AS ESTADO',
+            'LIME_USRE AS USRREG',
+            'LIME_FERE AS FECREG',
+            'LIME_USMO AS USRMOD',
+            'LIME_FEMO AS FECMOD'
+        ])->where([
+            ['LIME_NULI', '=', $line],
+            ['LIME_MAGN', '=', $idMagnitude],
+            ['LIME_IDME', '=', $idUnit],
+        ])->first();
+
+        if(is_null($unit)){
+            return $this->responseController->makeResponse(true, 'La unidad seleccionada no está registrada.', [], 404);
+        }
+
+        $unit->ID_UNIDAD = $this->encController->encrypt($unit->ID_UNIDAD);
+        $unit->ID_MAGNITUD = $this->encController->encrypt($unit->ID_MAGNITUD);
+
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_IDUS', '=', $unit->USRREG],
+            ['USUA_NULI', '=', $line]
+        ])->first();
+
+        $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $unit->USRREG = $nameUsrReg . " (" . $unit->USRREG . ")";
+
+        if(!is_null($unit->USRMOD)){
+            $usrMod = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $unit->USRMOD],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+
+            $nameUsrMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+            $unit->USRMOD = $nameUsrMod . " (" . $unit->USRMOD . ")";
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M01ADSI',
+            'S002V01F11PASI',
+            'S002V01P09MAUN',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la unidad de medida #$idUnit.",
+            $idUser,
+            $nowStr
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $unit);
+    }
 }

+ 3295 - 0
sistema-mantenimiento-back/app/Http/Controllers/CorrectiveMaintenanceController.php

@@ -0,0 +1,3295 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Support\Facades\DB;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Support\Carbon;
+use Carbon\Exceptions\InvalidFormatException;
+use ElephantIO\Client;
+use Illuminate\Validation\Rule;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Http\File;
+
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Style\Fill;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+
+class CorrectiveMaintenanceController extends Controller{
+    private $responseController;
+    private $encryptionController;
+    private $functionsController;
+    private $documentManagementController;
+    private $notificationsController;
+    private $socketClient;
+
+    public function __construct(){
+        $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->functionsController = new FunctionsController();
+        $this->documentManagementController = new DocumentManagementController();
+        $this->notificationsController = new NotificationsController();
+
+        $url = 'http://localhost:3200';
+        $this->socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
+        $this->socketClient->initialize();
+        $this->socketClient->of('/');
+    }
+
+    public function registerWorkOrder(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_responsible' => 'required|string',
+            'type_responsible' => 'required|string|in:U,S',
+            'description' => 'required|string|min:15',
+            'equipment' => 'required|string',
+            'start_date_time' => 'required|date',
+            'solution_time' => 'required|numeric',
+            'priority' => 'required|string',
+            'id_counter' => 'required|string',
+            'id_last_measure' => 'required|string',
+            'clasification' => 'required|string|max:50',
+            'staff' => 'required|json',
+            'security_management' => 'required|string',
+            'activation_type' => 'required|string|in:Manual,Automática',
+            'resources' => 'required|json',
+            'attached' => '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);
+        }
+        
+        $idUserResponsible = $this->encryptionController->decrypt($form['id_responsible']);
+        if(!$idUserResponsible){
+            return $this->responseController->makeResponse(true, 'El ID del usuario responsable no fue encriptado correctamente.', [], 400);
+        }
+
+        $usrResponsible = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUserResponsible]
+        ])->first();
+        
+        if(is_null($usrResponsible)){
+            return $this->responseController->makeResponse(true, 'El usuario responsable de atender la solicitud no existe.', [], 404);
+        }
+
+        $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
+        if(!$equipmentCode){
+            return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
+        }
+
+        $equipment = DB::table('S002V01TEQUI')->where([
+            ['EQUI_NULI', '=', $form['linea']],
+            ['EQUI_COEQ', '=', $equipmentCode],
+        ])->first();
+        
+        if(is_null($equipment)){
+            return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404);
+        }
+
+        if(floatval($form['solution_time']) <= 0){
+            return $this->responseController->makeResponse(true, 'El tiempo de solución estimado debe ser mayor a cero.', [], 400);
+        }
+
+        $priority = $this->encryptionController->decrypt($form['priority']);
+        if(!$priority){
+            return $this->responseController->makeResponse(true, 'La prioridad relacionada no fue encriptada correctamente.', [], 400);
+        }
+
+        $validPriorities = ['1', '2', '3', '4'];
+        if(!in_array($priority, $validPriorities)){
+            return $this->responseController->makeResponse(true, 'La prioridad relacionada es inválida.', [], 400);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($form['id_counter']);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador relacionado no fue encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $form['linea']]
+        ])->first();
+        
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador relacionado no existe.', [], 404);
+        }
+
+        $idLastMeasure = $this->encryptionController->decrypt($form['id_last_measure']);
+        if(!$idLastMeasure){
+            return $this->responseController->makeResponse(true, 'El ID de la última medida del contador relacionado no fue encriptado correctamente.', [], 400);
+        }
+
+        $lastMeasure = DB::table('S002V01TMEDI')->select([
+            'MEDI_IDME AS ID_MEDIDA',
+            'MEDI_CORE AS CONTADOR',
+            'MEDI_VALO AS VALOR',
+            'MEDI_WSRE AS ID_SERVICIO_WEB',
+            'LSWE_URLX AS URL_SERVICIO_WEB',
+            'MEDI_HORE AS HORA_REGISTRO',
+        ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([
+            ['MEDI_IDME', '=', $idLastMeasure],
+            ['MEDI_NULI', '=', $form['linea']],
+            ['MEDI_CORE', '=', $idCounter]
+        ])->orderBy('MEDI_HORE', 'desc')->first();
+        
+        if(is_null($lastMeasure)){
+            return $this->responseController->makeResponse(true, 'La última medida del contador relacionado no existe.', [], 404);
+        }
+
+        $staffArr = json_decode($form['staff'], true);
+        if(count($staffArr) == 0){
+            return $this->responseController->makeResponse(true, 'El arreglo del personal está vacío.', [], 400);
+        }
+
+        $staffArrFn = [];
+        foreach($staffArr as $key=>$item){
+            $itemArr = explode('-', $item);
+            $idDec = $this->encryptionController->decrypt($itemArr[0]);
+            if(!$idDec){
+                return $this->responseController->makeResponse(true, "El ID en la posición $key del arreglo del personal no fue encriptado correctamente.", [], 400);
+            }
+
+            if($itemArr[1] == 'EQ'){
+                $workTeam = DB::table('S002V01TEQMA')->where([
+                    ['EQMA_IDEQ', '=', $idDec],
+                    ['EQMA_NULI', '=', $form['linea']]
+                ])->first();
+
+                if(is_null($workTeam)){
+                    return $this->responseController->makeResponse(true, "El equipo de trabajo en la posición $key del arreglo del personal no existe.", [], 404);
+                }else if($workTeam->EQMA_ESTA == 'Eliminado'){
+                    return $this->responseController->makeResponse(true, "El equipo de trabajo en la posición $key del arreglo del personal está eliminado.", [], 404);
+                }
+
+                $staffArrFn[] = [
+                    'ID' => $idDec,
+                    'TYPE' => $itemArr[1]
+                ];
+            }else if($itemArr[1] == 'SU'){
+                $subcontratist = DB::table('S002V01TPESU')->where([
+                    ['PESU_IDPS', '=', $idDec],
+                    ['PESU_NULI', '=', $form['linea']]
+                ])->first();
+
+                if(is_null($subcontratist)){
+                    return $this->responseController->makeResponse(true, "El subcontratista en la posición $key del arreglo del personal no existe.", [], 404);
+                }else if($subcontratist->PESU_ESTA == 'Eliminado'){
+                    return $this->responseController->makeResponse(true, "El subcontratista en la posición $key del arreglo del personal está eliminado.", [], 404);
+                }
+
+                $staffArrFn[] = [
+                    'ID' => $idDec,
+                    'TYPE' => $itemArr[1]
+                ];
+            }else if($itemArr[1] == 'EM'){
+                $employee = DB::table('S002V01TPERS')->where([
+                    ['PERS_IDPE', '=', $idDec],
+                    ['PERS_NULI', '=', $form['linea']]
+                ])->first();
+
+                if(is_null($employee)){
+                    return $this->responseController->makeResponse(true, "El empleado en la posición $key del arreglo del personal no existe.", [], 404);
+                }else if($employee->PERS_ESTA == 'Eliminado'){
+                    return $this->responseController->makeResponse(true, "El empleado en la posición $key del arreglo del personal está eliminado.", [], 404);
+                }
+
+                $staffArrFn[] = [
+                    'ID' => $idDec,
+                    'TYPE' => $itemArr[1]
+                ];
+            }
+        }
+
+        $staffStrFn = json_encode($staffArrFn);
+        $idManagement = $this->encryptionController->decrypt($form['security_management']);
+        if(!$idManagement){
+            return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
+        }
+
+        $management = DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_IDGS', '=', $idManagement]
+        ])->first();
+
+        if(is_null($management)){
+            return $this->responseController->makeResponse(true, 'La gerencia de seguridad seleccionada no está registrada.', [], 404);
+        }
+        //PENDIENTE REVISAR LOS RECURSOS
+
+        $attachedArrFn = [];
+        if(isset($form['attached'])){
+            $attachedArr = json_decode($form['attached'], true);
+            foreach($attachedArr as $key=>$attached){
+                $idDec = $this->encryptionController->decrypt($attached['id']);
+                if(!$idDec){
+                    return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
+                }
+
+                if($attached['type'] == 'Existente'){
+                    $codeArr = explode('=', $idDec);
+                    $codeArr0 = explode('-', $codeArr[0]);
+
+                    $file = DB::table('S002V01TAFAL')->where([
+                        ['AFAL_NULI', '=', $form['linea']],
+                        ['AFAL_COMO', '=', $codeArr0[1]],
+                        ['AFAL_CLDO', '=', $codeArr0[2]],
+                        ['AFAL_FECR', '=', $codeArr0[3]],
+                        ['AFAL_NUSE', '=', $codeArr0[4]],
+                        ['AFAL_NUVE', '=', $codeArr[1]],
+                    ])->first();
+
+                    if(is_null($file)){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
+                    }else if($file->AFAL_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
+                    }
+
+                    $attachedArrFn[] = $idDec;
+                }else if($attached['type'] == 'Nuevo'){
+                    $tempFile = DB::table('S002V01TARTE')->where([
+                        ['ARTE_IDAR', '=', $idDec],
+                        ['ARTE_NULI', '=', $form['linea']]
+                    ])->first();
+
+                    if(is_null($tempFile)){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
+                    }else if($tempFile->ARTE_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
+                    }
+
+                    $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser);
+                    if(!$finalFile){
+                        return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
+                    }else{
+                        $attachedArrFn[] = $finalFile[1];
+                    }
+                }
+            }
+        }
+
+        $activationType = $form['activation_type'][0];
+        $attachedStrFn = json_encode($attachedArrFn);
+        $lastMeasureStr = json_encode($lastMeasure);
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        $statusHistoryStr = json_encode([
+            ['USUARIO' => $idUser, 'ESTADO' => 'PE', 'FECHA' => $nowStr]
+        ]);
+
+        $orderID = DB::table('S002V01TOTCO')->insertGetId([
+            'OTCO_NULI' => $form['linea'],
+            'OTCO_IDUR' => $idUserResponsible,
+            'OTCO_TURE' => $form['type_responsible'],
+            'OTCO_DEIN' => $form['description'],
+            'OTCO_EQIN' => $equipmentCode,
+            'OTCO_FIFA' => $form['start_date_time'],
+            'OTCO_TESO' => $form['solution_time'],
+            'OTCO_CORE' => $idCounter,
+            'OTCO_DRCO' => $lastMeasureStr,
+            'OTCO_PRIO' => $priority,
+            'OTCO_RHUT' => $form['resources'],
+            'OTCO_PEIN' => $staffStrFn,
+            'OTCO_TIAC' => $activationType,
+            'OTCO_DORE' => $attachedStrFn,
+            'OTCO_CLAS' => $form['clasification'],
+            'OTCO_GESE' => $idManagement,
+            'OTCO_HIES' => $statusHistoryStr,
+            'OTCO_ESOR' => 'PE',
+            'OTCO_USRE' => $idUser,
+            'OTCO_FERE' => $nowStr
+        ]);
+
+        $this->notificationsController->emitNotification(
+            'S002V01M09GMCO',
+            "Orden de mantenimiento correctivo #$orderID",
+            "Su usuario ha sido asignado como responsable de atender la orden de mantenimiento #$orderID.",
+            [[
+                'BOTON' => 'Ver detalles',
+                'FUNCION' => 'openCorrectiveWorkOrderDetails',
+                'PARAMETROS' => json_encode([$this->encryptionController->encrypt($orderID)])
+            ], [
+                'BOTON' => 'Validar orden',
+                'FUNCION' => 'validateCorrectiveWorkOrder',
+                'PARAMETROS' => json_encode([$this->encryptionController->encrypt($orderID)])
+            ], [
+                'BOTON' => 'Ir al módulo',
+                'FUNCION' => 'openModule',
+                'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
+            ]],
+            [$idUserResponsible],
+            $idUser, 
+            $form['linea'],
+            $this->socketClient,
+            $orderID,
+            'Correctivo'
+        );
+
+        $idOrderEnc = $this->encryptionController->encrypt($orderID);
+        $socketData = ['idOrder' => $idOrderEnc];
+        $this->socketClient->emit('new_corrective_work_order', $socketData);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F04GEOT',
+            'S002V01P01GEOT',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró la orden de trabajo correctivo #$orderID.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getWorkOrders($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $orders = DB::table('S002V01TOTCO')->select([
+            'OTCO_IDOT AS ID_ORDEN',
+            'OTCO_EQIN AS CODIGO_EQUIPAMIENTO',
+            'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
+            'EQUI_MODE AS MODELO_EQUIPAMIENTO',
+            'EQUI_IDEQ AS ID_EQUIPAMIENTO',
+            'OTCO_FIFA AS FECHA_INICIO',
+            'OTCO_CORE AS CONTADOR',
+            'OTCO_FTIN AS FECHA_FIN',
+            'OTCO_TIAC AS TIPO_ACTIVACION',
+            'OTCO_IDUR AS ID_RESPONSABLE',
+            'OTCO_TURE AS TIPO_RESPONSABLE',
+            'OTCO_PRIO AS PRIORIDAD',
+            'OTCO_ESOR AS ESTADO'
+        ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTCO_EQIN')
+        ->where('OTCO_NULI', '=', $line)
+        ->orderBy('OTCO_IDOT', 'desc')->get()->all();
+
+        $subcontratistTypes = ['S' => 'Subcontratista', 'U' => 'Usuario'];
+        $activationTypes = ['M' => 'Manual', 'A' => 'Automática'];
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+
+        foreach($orders as $key=>$order){
+            if($order->TIPO_RESPONSABLE == 'U'){
+                $userResponsible = DB::table('S002V01TUSUA')->where([
+                    ['USUA_IDUS', '=', $order->ID_RESPONSABLE],
+                    ['USUA_NULI', '=', $line]
+                ])->first();
+
+                $userResponsibleName = $this->functionsController->joinName($userResponsible->USUA_NOMB, $userResponsible->USUA_APPA, $userResponsible->USUA_APMA);
+                $order->ID_RESPONSABLE = $userResponsibleName . " (" . $order->ID_RESPONSABLE . ")";
+            }else{
+                $subcontratistResponsible = DB::table('S002V01TPESU')->where([
+                    ['PESU_NULI', '=', $line],
+                    ['PESU_IDPS', '=', $order->ID_RESPONSABLE]
+                ])->first();
+
+                $order->ID_RESPONSABLE = $subcontratistResponsible->PESU_RASO . " (" . $subcontratistResponsible->PESU_REFI . ") (" . $order->ID_RESPONSABLE . ")";
+            }
+
+            $order->TIPO_RESPONSABLE = $subcontratistTypes[$order->TIPO_RESPONSABLE];
+            $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN);
+            $order->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($order->CODIGO_EQUIPAMIENTO);
+            $order->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($order->ID_EQUIPAMIENTO);
+            $order->CONTADOR = $this->encryptionController->encrypt($order->CONTADOR);
+            $order->TIPO_ACTIVACION = $activationTypes[$order->TIPO_ACTIVACION];
+            $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
+            $order->ESTADO = $orderStates[$order->ESTADO];
+
+            $orders[$key] = $order;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F01GEOP',
+            'S002V01P01COOP',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de mantenimiento correctivo registradas.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $orders);
+    }
+
+    public function getWorkOrder($idOrder, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($idOrder);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->select([
+            'OTCO_IDOT AS ID_ORDEN',
+            'OTCO_DEIN AS DESCRIPCION',
+            'OTCO_EQIN AS CODIGO_EQUIPAMIENTO',
+            'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
+            'EQUI_MODE AS MODELO_EQUIPAMIENTO',
+            'EQUI_IDEQ AS ID_EQUIPAMIENTO',
+            'OTCO_FIFA AS FECHA_INICIO',
+            'OTCO_TESO AS TIEMPO_ESTIMADO',
+            'OTCO_CORE AS CONTADOR',
+            'OTCO_DRCO AS MEDIDAS',
+            'OTCO_PRIO AS PRIORIDAD',
+            'OTCO_FTIN AS FECHA_FINAL',
+            'OTCO_DTIN AS DURACION_TOTAL',
+            'OTCO_RHUT AS RECURSOS',
+            'OTCO_PEIN AS PERSONAL',
+            'OTCO_TIAC AS TIPO_ACTIVACION',
+            'OTCO_IDUR AS ID_RESPONSABLE',
+            'OTCO_TURE AS TIPO_RESPONSABLE',
+            'OTCO_ANCO AS ANALISIS_COSTOS',
+            'OTCO_DORE AS DOCUMENTOS_RELACIONADOS',
+            'OTCO_CLAS AS CLASIFICACION',
+            'OTCO_COME AS COMENTARIOS',
+            'OTCO_GESE AS GERENCIA_SEGURIDAD',
+            'OTCO_CAEX AS CAMPOS_EXTRA',
+            'OTCO_ESOR AS ESTADO',
+            'OTCO_USRE AS USUREG',
+            'OTCO_FERE AS FECREG',
+            'OTCO_USMO AS USUMOD',
+            'OTCO_FEMO AS FECMOD'
+        ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTCO_EQIN')
+        ->where([
+            ['OTCO_IDOT', '=', $idOrder],
+            ['OTCO_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
+        }
+        
+        $subcontratistTypes = ['S' => 'Subcontratista', 'U' => 'Usuario'];
+        if($order->TIPO_RESPONSABLE == 'U'){
+            $userResponsible = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $order->ID_RESPONSABLE],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+
+            $userResponsibleName = $this->functionsController->joinName($userResponsible->USUA_NOMB, $userResponsible->USUA_APPA, $userResponsible->USUA_APMA);
+            $order->ID_RESPONSABLE = $userResponsibleName . " (" . $order->ID_RESPONSABLE . ")";
+        }else{
+            $subcontratistResponsible = DB::table('S002V01TPESU')->where([
+                ['PESU_NULI', '=', $line],
+                ['PESU_IDPS', '=', $order->ID_RESPONSABLE]
+            ])->first();
+
+            $order->ID_RESPONSABLE = $subcontratistResponsible->PESU_RASO . " (" . $subcontratistResponsible->PESU_REFI . ") (" . $order->ID_RESPONSABLE . ")";
+        }
+
+        $order->TIPO_RESPONSABLE = $subcontratistTypes[$order->TIPO_RESPONSABLE];
+        $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN);
+        $order->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($order->CODIGO_EQUIPAMIENTO);
+        $order->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($order->ID_EQUIPAMIENTO);
+        $order->CONTADOR = $this->encryptionController->encrypt($order->CONTADOR);
+
+        $measureArr = json_decode($order->MEDIDAS, true);
+        $measureArr['CONTADOR'] = $this->encryptionController->encrypt($measureArr['CONTADOR']);
+        $measureArr['ID_MEDIDA'] = $this->encryptionController->encrypt($measureArr['ID_MEDIDA']);
+        $measureArr['ID_SERVICIO_WEB'] = $this->encryptionController->encrypt($measureArr['ID_SERVICIO_WEB']);
+
+        $order->MEDIDAS = json_encode($measureArr);
+        $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
+        $order->GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($order->GERENCIA_SEGURIDAD);
+        
+        $staffArr = json_decode($order->PERSONAL, true);
+        foreach($staffArr as $key=>$val){
+            if($val['TYPE'] == 'EQ'){
+                $workTeam = DB::table('S002V01TEQMA')->where([
+                    ['EQMA_NULI', '=', $line],
+                    ['EQMA_IDEQ', '=', $val['ID']]
+                ])->first();
+
+                $val['NAME'] = $workTeam->EQMA_NOMB . " (" . $val['ID'] . ")";
+            }else if($val['TYPE'] == 'SU'){
+                $subcontratist = DB::table('S002V01TPESU')->where([
+                    ['PESU_NULI', '=', $line],
+                    ['PESU_IDPS', '=', $val['ID']]
+                ])->first();
+
+                $val['NAME'] = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $val['ID'] . ")";
+            }else if($val['TYPE'] == 'EM'){
+                $employee = DB::table('S002V01TPERS')
+                ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
+                ->where([
+                    ['PERS_NULI', '=', $line],
+                    ['PERS_IDPE', '=', $val['ID']]
+                ])->first();
+
+                $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
+                $val['NAME'] = $employeeName . " (" . $employee->PERS_IDUS . ") (" . $val['ID'] . ")";;
+            }
+            $val['ID'] = $this->encryptionController->encrypt($val['ID']);
+            $staffArr[$key] = $val;
+        }
+        
+        $activationTypes = ['M' => 'Manual', 'A' => 'Automática'];
+        $order->PERSONAL = json_encode($staffArr);
+        $order->TIPO_ACTIVACION = $activationTypes[$order->TIPO_ACTIVACION];
+        
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+        $order->ESTADO = $orderStates[$order->ESTADO];
+
+        $documentsArr = json_decode($order->DOCUMENTOS_RELACIONADOS, true);
+        $documentsFn = [];
+        foreach($documentsArr as $document){
+            $documentArr = explode('=', $document);
+            $codeArr = explode('-', $documentArr[0]);
+            $file = DB::table('S002V01TAFAL')->where([
+                ['AFAL_NULI', '=', $line],
+                ['AFAL_COMO', '=', $codeArr[1]],
+                ['AFAL_CLDO', '=', $codeArr[2]],
+                ['AFAL_FECR', '=', $codeArr[3]],
+                ['AFAL_NUSE', '=', $codeArr[4]],
+                ['AFAL_NUVE', '=', $documentArr[1]]
+            ])->first();
+
+            $documentsFn[] = [
+                'id' => $this->encryptionController->encrypt($document),
+                'name' => $file->AFAL_NOAR . '.' . $file->AFAL_EXTE,
+                'size' => $file->AFAL_TAMA,
+                'type' => 'Existente'
+            ];
+        }
+
+        $order->DOCUMENTOS_RELACIONADOS = json_encode($documentsFn);
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_IDUS', '=', $order->USUREG],
+            ['USUA_NULI', '=', $line]
+        ])->first();
+
+        $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $order->USUREG = $nameReg . " (" . $order->USUREG . ")";
+
+        if(!is_null($order->USUMOD)){
+            $usrMod = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $order->USUMOD],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+    
+            $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+            $order->USUMOD = $nameMod . " (" . $order->USUMOD . ")";
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F01GEOP',
+            'S002V01P01COOP',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles de la orden #$idOrder de mantenimiento correctivo registradas.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $order);
+    }
+
+    public function updateWorkOrder(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'description' => 'required|string|min:15',
+            'equipment' => 'required|string',
+            'start_date_time' => 'required|date',
+            'solution_time' => 'required|numeric',
+            'priority' => 'required|string',
+            'id_counter' => 'required|string',
+            'id_last_measure' => 'required|string',
+            'clasification' => 'required|string|max:50',
+            'staff' => 'required|json',
+            'security_management' => 'required|string',
+            'activation_type' => 'required|string|in:Manual,Automática',
+            'resources' => 'required|json',
+            'attached' => 'json',
+            'id_order' => 'required|string'
+        ]);
+ 
+        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);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($form['id_order']);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_IDOT', '=', $idOrder]
+        ])->first();
+        
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
+        }
+
+        $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
+        if(!$equipmentCode){
+            return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
+        }
+
+        $equipment = DB::table('S002V01TEQUI')->where([
+            ['EQUI_NULI', '=', $form['linea']],
+            ['EQUI_COEQ', '=', $equipmentCode],
+        ])->first();
+        
+        if(is_null($equipment)){
+            return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404);
+        }
+
+        if(floatval($form['solution_time']) <= 0){
+            return $this->responseController->makeResponse(true, 'El tiempo de solución estimado debe ser mayor a cero.', [], 400);
+        }
+
+        $priority = $this->encryptionController->decrypt($form['priority']);
+        if(!$priority){
+            return $this->responseController->makeResponse(true, 'La prioridad relacionada no fue encriptada correctamente.', [], 400);
+        }
+
+        $validPriorities = ['1', '2', '3', '4'];
+        if(!in_array($priority, $validPriorities)){
+            return $this->responseController->makeResponse(true, 'La prioridad relacionada es inválida.', [], 400);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($form['id_counter']);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador relacionado no fue encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $form['linea']]
+        ])->first();
+        
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador relacionado no existe.', [], 404);
+        }
+
+        $idLastMeasure = $this->encryptionController->decrypt($form['id_last_measure']);
+        if(!$idLastMeasure){
+            return $this->responseController->makeResponse(true, 'El ID de la última medida del contador relacionado no fue encriptado correctamente.', [], 400);
+        }
+
+        $lastMeasure = DB::table('S002V01TMEDI')->select([
+            'MEDI_IDME AS ID_MEDIDA',
+            'MEDI_CORE AS CONTADOR',
+            'MEDI_VALO AS VALOR',
+            'MEDI_WSRE AS ID_SERVICIO_WEB',
+            'LSWE_URLX AS URL_SERVICIO_WEB',
+            'MEDI_HORE AS HORA_REGISTRO',
+        ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([
+            ['MEDI_IDME', '=', $idLastMeasure],
+            ['MEDI_NULI', '=', $form['linea']],
+            ['MEDI_CORE', '=', $idCounter]
+        ])->orderBy('MEDI_HORE', 'desc')->first();
+        
+        if(is_null($lastMeasure)){
+            return $this->responseController->makeResponse(true, 'La última medida del contador relacionado no existe.', [], 404);
+        }
+
+        $staffArr = json_decode($form['staff'], true);
+        if(count($staffArr) == 0){
+            return $this->responseController->makeResponse(true, 'El arreglo del personal está vacío.', [], 400);
+        }
+
+        $staffArrFn = [];
+        foreach($staffArr as $key=>$item){
+            $itemArr = explode('-', $item);
+            $idDec = $this->encryptionController->decrypt($itemArr[0]);
+            if(!$idDec){
+                return $this->responseController->makeResponse(true, "El ID en la posición $key del arreglo del personal no fue encriptado correctamente.", [], 400);
+            }
+
+            if($itemArr[1] == 'EQ'){
+                $workTeam = DB::table('S002V01TEQMA')->where([
+                    ['EQMA_IDEQ', '=', $idDec],
+                    ['EQMA_NULI', '=', $form['linea']]
+                ])->first();
+
+                if(is_null($workTeam)){
+                    return $this->responseController->makeResponse(true, "El equipo de trabajo en la posición $key del arreglo del personal no existe.", [], 404);
+                }else if($workTeam->EQMA_ESTA == 'Eliminado'){
+                    return $this->responseController->makeResponse(true, "El equipo de trabajo en la posición $key del arreglo del personal está eliminado.", [], 404);
+                }
+
+                $staffArrFn[] = [
+                    'ID' => $idDec,
+                    'TYPE' => $itemArr[1]
+                ];
+            }else if($itemArr[1] == 'SU'){
+                $subcontratist = DB::table('S002V01TPESU')->where([
+                    ['PESU_IDPS', '=', $idDec],
+                    ['PESU_NULI', '=', $form['linea']]
+                ])->first();
+
+                if(is_null($subcontratist)){
+                    return $this->responseController->makeResponse(true, "El subcontratista en la posición $key del arreglo del personal no existe.", [], 404);
+                }else if($subcontratist->PESU_ESTA == 'Eliminado'){
+                    return $this->responseController->makeResponse(true, "El subcontratista en la posición $key del arreglo del personal está eliminado.", [], 404);
+                }
+
+                $staffArrFn[] = [
+                    'ID' => $idDec,
+                    'TYPE' => $itemArr[1]
+                ];
+            }else if($itemArr[1] == 'EM'){
+                $employee = DB::table('S002V01TPERS')->where([
+                    ['PERS_IDPE', '=', $idDec],
+                    ['PERS_NULI', '=', $form['linea']]
+                ])->first();
+
+                if(is_null($employee)){
+                    return $this->responseController->makeResponse(true, "El empleado en la posición $key del arreglo del personal no existe.", [], 404);
+                }else if($employee->PERS_ESTA == 'Eliminado'){
+                    return $this->responseController->makeResponse(true, "El empleado en la posición $key del arreglo del personal está eliminado.", [], 404);
+                }
+
+                $staffArrFn[] = [
+                    'ID' => $idDec,
+                    'TYPE' => $itemArr[1]
+                ];
+            }
+        }
+
+        $staffStrFn = json_encode($staffArrFn);
+        $idManagement = $this->encryptionController->decrypt($form['security_management']);
+        if(!$idManagement){
+            return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
+        }
+
+        $management = DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_IDGS', '=', $idManagement]
+        ])->first();
+
+        if(is_null($management)){
+            return $this->responseController->makeResponse(true, 'La gerencia de seguridad seleccionada no está registrada.', [], 404);
+        }
+        //PENDIENTE REVISAR LOS RECURSOS
+
+        $attachedArrFn = [];
+        if(isset($form['attached'])){
+            $attachedArr = json_decode($form['attached'], true);
+            foreach($attachedArr as $key=>$attached){
+                $idDec = $this->encryptionController->decrypt($attached['id']);
+                if(!$idDec){
+                    return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
+                }
+
+                if($attached['type'] == 'Existente'){
+                    $codeArr = explode('=', $idDec);
+                    $codeArr0 = explode('-', $codeArr[0]);
+
+                    $file = DB::table('S002V01TAFAL')->where([
+                        ['AFAL_NULI', '=', $form['linea']],
+                        ['AFAL_COMO', '=', $codeArr0[1]],
+                        ['AFAL_CLDO', '=', $codeArr0[2]],
+                        ['AFAL_FECR', '=', $codeArr0[3]],
+                        ['AFAL_NUSE', '=', $codeArr0[4]],
+                        ['AFAL_NUVE', '=', $codeArr[1]],
+                    ])->first();
+
+                    if(is_null($file)){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
+                    }else if($file->AFAL_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
+                    }
+
+                    $attachedArrFn[] = $idDec;
+                }else if($attached['type'] == 'Nuevo'){
+                    $tempFile = DB::table('S002V01TARTE')->where([
+                        ['ARTE_IDAR', '=', $idDec],
+                        ['ARTE_NULI', '=', $form['linea']]
+                    ])->first();
+
+                    if(is_null($tempFile)){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
+                    }else if($tempFile->ARTE_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
+                    }
+
+                    $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser);
+                    if(!$finalFile){
+                        return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
+                    }else{
+                        $attachedArrFn[] = $finalFile[1];
+                    }
+                }
+            }
+        }
+
+        $activationType = $form['activation_type'][0];
+        $attachedStrFn = json_encode($attachedArrFn);
+        $lastMeasureStr = json_encode($lastMeasure);
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        DB::table('S002V01TOTCO')->where([
+            ['OTCO_IDOT', '=', $idOrder],
+            ['OTCO_NULI', '=', $form['linea']]
+        ])->update([
+            'OTCO_DEIN' => $form['description'],
+            'OTCO_EQIN' => $equipmentCode,
+            'OTCO_FIFA' => $form['start_date_time'],
+            'OTCO_TESO' => $form['solution_time'],
+            'OTCO_CORE' => $idCounter,
+            'OTCO_DRCO' => $lastMeasureStr ,
+            'OTCO_PRIO' => $priority,
+            'OTCO_FTIN' => $order->OTCO_FTIN,
+            'OTCO_DTIN' => $order->OTCO_DTIN,
+            'OTCO_RHUT' => $form['resources'],
+            'OTCO_PEIN' => $staffStrFn,
+            'OTCO_TIAC' => $activationType,
+            'OTCO_ANCO' => $order->OTCO_ANCO,
+            'OTCO_DORE' => $attachedStrFn,
+            'OTCO_CLAS' => $form['clasification'],
+            'OTCO_COME' => $order->OTCO_COME,
+            'OTCO_GESE' => $idManagement,
+            'OTCO_CAEX' => $order->OTCO_CAEX,
+            'OTCO_ESOR' => $order->OTCO_ESOR,
+            'OTCO_USMO' => $idUser,
+            'OTCO_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F04GEOT',
+            'S002V01P01GEOT',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo correctivo #$idOrder.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function deleteWorkOrder(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_order' => 'required|string'
+        ]);
+ 
+        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);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($form['id_order']);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_IDOT', '=', $idOrder]
+        ])->first();
+        
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        $statusHistoryArr = json_decode($order->OTCO_HIES, true);
+        $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'EL', 'FECHA' => $nowStr];
+        $statusHistoryStr = json_encode($statusHistoryArr);
+
+        DB::table('S002V01TOTCO')->where([
+            ['OTCO_IDOT', '=', $idOrder],
+            ['OTCO_NULI', '=', $form['linea']]
+        ])->update([
+            'OTCO_ESOR' => 'EL',
+            'OTCO_HIES' => $statusHistoryStr,
+            'OTCO_USMO' => $idUser,
+            'OTCO_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F04GEOT',
+            'S002V01P01GEOT',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la orden de trabajo correctivo #$idOrder.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function approveWorkOrder(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_order' => 'required|string'
+        ]);
+ 
+        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);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($form['id_order']);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_IDOT', '=', $idOrder]
+        ])->first();
+        
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+        
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
+        }else if($order->OTCO_ESOR == 'EL'){
+            return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
+        }else if($order->OTCO_ESOR != 'PE'){
+            $status = $orderStates[$order->OTCO_ESOR];
+            return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
+        }
+
+        $staffArr = json_decode($order->OTCO_PEIN, true);
+        $audience = [];
+
+        foreach($staffArr as $item){
+            if($item['TYPE'] == 'EQ'){
+                $employees = DB::table('S002V01TPERS')->where([
+                    ['PERS_NULI', '=', $form['linea']],
+                    ['PERS_EQTR', '=', $item['ID']]
+                ])->get()->all();
+
+                foreach($employees as $employee){
+                    if(!in_array($employee->PERS_IDUS, $audience)){
+                        $audience[] = $employee->PERS_IDUS;
+                    }
+                }
+            }else if($item['TYPE'] == 'SU'){
+                $employees = DB::table('S002V01TPERS')->where([
+                    ['PERS_NULI', '=', $form['linea']],
+                    ['PERS_IDPS', '=', $item['ID']]
+                ])->get()->all();
+
+                foreach($employees as $employee){
+                    if(!in_array($employee->PERS_IDUS, $audience)){
+                        $audience[] = $employee->PERS_IDUS;
+                    }
+                }
+            }else if($item['TYPE'] == 'EM'){
+                $employee = DB::table('S002V01TPERS')->where([
+                    ['PERS_NULI', '=', $form['linea']],
+                    ['PERS_IDPE', '=', $item['ID']]
+                ])->first();
+
+                if(!in_array($employee->PERS_IDUS, $audience)){
+                    $audience[] = $employee->PERS_IDUS;
+                }
+            }
+        }
+
+        $this->notificationsController->emitNotification(
+            'S002V01M09GMCO',
+            "Orden de mantenimiento correctivo #$idOrder",
+            "Se ha generado la orden de mantenimiento correctivo #$idOrder y requiere su atención.",
+            [],
+            $audience,
+            $idUser, 
+            $form['linea'],
+            $this->socketClient,
+            $idOrder,
+            'Correctivo'
+        );
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        $statusHistoryArr = json_decode($order->OTCO_HIES, true);
+        $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'VA', 'FECHA' => $nowStr];
+        $statusHistoryStr = json_encode($statusHistoryArr);
+
+        DB::table('S002V01TOTCO')->where([
+            ['OTCO_IDOT', '=', $idOrder],
+            ['OTCO_NULI', '=', $form['linea']]
+        ])->update([
+            'OTCO_ESOR' => 'VA',
+            'OTCO_HIES' => $statusHistoryStr,
+            'OTCO_USMO' => $idUser,
+            'OTCO_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F04GEOT',
+            'S002V01P01GEOT',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") validó la orden de trabajo correctivo #$idOrder.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function startWorkOrder(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_order' => 'required|string'
+        ]);
+ 
+        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);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($form['id_order']);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_IDOT', '=', $idOrder]
+        ])->first();
+        
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+        
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
+        }else if($order->OTCO_ESOR == 'EL'){
+            return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
+        }else if($order->OTCO_ESOR != 'VA'){
+            $status = $orderStates[$order->OTCO_ESOR];
+            return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        $statusHistoryArr = json_decode($order->OTCO_HIES, true);
+        $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'EP', 'FECHA' => $nowStr];
+        $statusHistoryStr = json_encode($statusHistoryArr);
+
+        DB::table('S002V01TOTCO')->where([
+            ['OTCO_IDOT', '=', $idOrder],
+            ['OTCO_NULI', '=', $form['linea']]
+        ])->update([
+            'OTCO_ESOR' => 'EP',
+            'OTCO_HIES' => $statusHistoryStr,
+            'OTCO_USMO' => $idUser,
+            'OTCO_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F04GEOT',
+            'S002V01P01GEOT',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") inició la orden de trabajo correctivo #$idOrder.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function updateWorkOrderStatus(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_order' => 'required|string',
+            'status' => 'required|string|in:RE,CE,CA',
+            'comments' => 'required|string|min:15'
+        ]);
+ 
+        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);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($form['id_order']);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_IDOT', '=', $idOrder]
+        ])->first();
+        
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+        
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
+        }else if($order->OTCO_ESOR == 'EL'){
+            return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
+        }
+        
+        $status = $form['status'];
+        switch($status){
+            case 'RE': 
+                if($order->OTCO_ESOR != 'PE'){
+                    $status = $orderStates[$order->OTCO_ESOR];
+                    return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
+                }
+            break;
+            case 'CE':
+                if($order->OTCO_ESOR != 'EP' && $order->OTCO_ESOR != 'CP'){
+                    $status = $orderStates[$order->OTCO_ESOR];
+                    return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
+                }
+            break;
+            case 'CA':
+                if($order->OTCO_ESOR != 'VA'){
+                    $status = $orderStates[$order->OTCO_ESOR];
+                    return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
+                }
+            break;
+        }
+
+        $message = '';
+        if($status == 'CE' && is_null($order->OTCO_ANCO)){
+            $status = 'CP';
+            $message = 'La orden no puede cerrarse complentamente hasta asignar el análisis de costos.';
+        }else{
+            $message = 'Actualización correcta.';
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        $ftin = null;
+        $dtin = null;
+        if(($status == 'CE' || $status == 'CP') && is_null($order->OTCO_FTIN)){
+            $ftin = $nowStr;
+            $startDate = new Carbon($order->OTCO_FIFA);
+
+            $diffInSecs = $now->diffInSeconds($startDate);
+            $diffInMins = $this->functionsController->floatDiv($diffInSecs, 60);
+            $dtin = $this->functionsController->floatDiv($diffInMins, 60);
+        }else{
+            $ftin = $order->OTCO_FTIN;
+            $dtin = $order->OTCO_DTIN;
+        }
+
+        $statusHistoryArr = json_decode($order->OTCO_HIES, true);
+        $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => $status, 'FECHA' => $nowStr];
+        $statusHistoryStr = json_encode($statusHistoryArr);
+
+        DB::table('S002V01TOTCO')->where([
+            ['OTCO_IDOT', '=', $idOrder],
+            ['OTCO_NULI', '=', $form['linea']]
+        ])->update([
+            'OTCO_ESOR' => $status,
+            'OTCO_COME' => $form['comments'],
+            'OTCO_HIES' => $statusHistoryStr,
+            'OTCO_FTIN' => $ftin,
+            'OTCO_DTIN' => $dtin,
+            'OTCO_USMO' => $idUser,
+            'OTCO_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F04GEOT',
+            'S002V01P01GEOT',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden de trabajo correctivo #$idOrder.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, "EXITO: $message");
+    }
+
+    public function getWorkOrderClasifications($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $clasifications = DB::table('S002V01TOTCO')->select([
+            DB::raw('DISTINCT(OTCO_CLAS) AS CLASIFICACION')
+        ])->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F01GEOP',
+            'S002V01P01COOP',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las clasificaciones registradas.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $clasifications);
+    }
+
+    public function getResponsibleUsers($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $profiles = DB::table('S002V01TPERF')->where('PERF_NULI', '=', $line)->get()->all();
+        $profilesWithAccess = [];
+        foreach($profiles as $profile){
+            $permissions = json_decode($profile->PERF_PERM, true);
+            $permissionsArr = $permissions['permissions'];
+            $correctiveMaintenanceFilt = array_filter($permissionsArr, function($v, $k) {
+                return $v['id'] == 'S002V01M09GMCO';
+            }, ARRAY_FILTER_USE_BOTH);
+            
+            $correctiveMaintenance = end($correctiveMaintenanceFilt);
+            if(intval($correctiveMaintenance['access']) > 0){
+                $submodules = $correctiveMaintenance['children'];
+                $workOrdersFilt = array_filter($submodules, function($v, $k) {
+                    return $v['id'] == 'S002V01S01ORTR';
+                }, ARRAY_FILTER_USE_BOTH);
+
+                $workOrders = end($workOrdersFilt);
+                if(intval($workOrders['access']) > 0){
+                    $functions = $workOrders['children'];
+                    $operationsManagementFilt = array_filter($functions, function($v, $k) {
+                        return $v['id'] == 'S002V01F01GEOP';
+                    }, ARRAY_FILTER_USE_BOTH);
+
+                    $operationsManagement = end($operationsManagementFilt);
+                    if(intval($operationsManagement['access']) > 0){
+                        $profilesWithAccess[] = $profile->PERF_IDPE;
+                    }
+                }
+            }
+        }
+
+        $usersWithAccess = [];
+        foreach($profilesWithAccess as $idProfile){
+            $users = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_PERF', '=', $idProfile],
+                ['USUA_ESTA', '=', 'Activo']
+            ])->get()->all();
+
+            foreach($users as $user){
+                $userName = $this->functionsController->joinName($user->USUA_NOMB, $user->USUA_APPA, $user->USUA_APMA);
+                $usersWithAccess[] = [
+                    'ID' => $this->encryptionController->encrypt($user->USUA_IDUS),
+                    'NOMBRE' => $userName,
+                ];
+            }
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F01GEOP',
+            'S002V01P01COOP',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los usuarios con acceso a la gestión de las operaciones.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $usersWithAccess);
+    }
+
+    public function transferWorkOrder(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_order' => 'required|string',
+            'id_new_user' => 'required|string',
+            'type' => 'required|string|in:U,S'
+        ]);
+ 
+        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);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($form['id_order']);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_IDOT', '=', $idOrder]
+        ])->first();
+        
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+        
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
+        }else if($order->OTCO_ESOR == 'EL'){
+            return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
+        }else if($order->OTCO_ESOR != 'PE'){
+            $status = $orderStates[$order->OTCO_ESOR];
+            return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
+        }
+
+        if($order->OTCO_TURE == 'U' && $order->OTCO_IDUR != $idUser){
+            return $this->responseController->makeResponse(true, "El usuario que realizó la solicitud no es el responsable de atenderla.", [], 401);
+        }else if($order->OTCO_TURE == 'S'){
+            $users = DB::table('S002V01TPERS')->where([
+                ['PERS_NULI', '=', $form['linea']],
+                ['PERS_TICO', '=', 'Subcontratista'],
+                ['PERS_IDPS', '=', $order->OTCO_IDUR],
+            ])->get()->all();
+
+            $enabledUsers = [];
+            foreach($users as $user){
+                $enabledUsers[] = $user->PERS_IDUS;
+            }
+
+            if(!in_array($idUser, $enabledUsers)){
+                return $this->responseController->makeResponse(true, "El usuario que realizó la solicitud no es el responsable de atenderla.", [], 401);
+            }
+        }
+
+        $audience = [];
+        $idNewUser = $this->encryptionController->decrypt($form['id_new_user']);
+        if(!$idNewUser){
+            return $this->responseController->makeResponse(true, 'El ID del nuevo encargado no fue encriptado correctamente.', [], 400);
+        }
+
+        if($form['type'] == 'U'){
+            $newUser = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $form['linea']],
+                ['USUA_IDUS', '=', $idNewUser]
+            ])->first();
+        
+            if(is_null($newUser)){
+                return $this->responseController->makeResponse(true, 'El usuario seleccionado no existe.', [], 404);
+            }
+            
+            $audience[] = $idNewUser;
+        }else if($form['type'] == 'S'){
+            $subcontratist = DB::table('S002V01TPESU')->where([
+                ['PESU_IDPS', '=', $idNewUser],
+                ['PESU_NULI', '=', $form['linea']]
+            ])->first();
+        
+            if(is_null($subcontratist)){
+                return $this->responseController->makeResponse(true, 'El subcontratista seleccionado no existe.', [], 404);
+            }
+            
+            $users = DB::table('S002V01TPERS')->where([
+                ['PERS_NULI', '=', $form['linea']],
+                ['PERS_TICO', '=', 'Subcontratista'],
+                ['PERS_IDPS', '=', $idNewUser],
+            ])->get()->all();
+
+            foreach($users as $user){
+                $audience[] = $user->PERS_IDUS;
+            }
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TOTCO')->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_IDOT', '=', $idOrder]
+        ])->update([
+            'OTCO_IDUR' => $idNewUser,
+            'OTCO_TURE' => $form['type'],
+            'OTCO_USMO' => $idUser,
+            'OTCO_FEMO' => $nowStr
+        ]);
+
+        $this->notificationsController->emitNotification(
+            'S002V01M09GMCO',
+            "Orden de mantenimiento correctivo #$idOrder",
+            "Su usuario ha sido asignado como responsable de atender la orden de mantenimiento #$idOrder.",
+            [[
+                'BOTON' => 'Ver detalles',
+                'FUNCION' => 'openCorrectiveWorkOrderDetails',
+                'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
+            ], [
+                'BOTON' => 'Validar orden',
+                'FUNCION' => 'validateCorrectiveWorkOrder',
+                'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
+            ], [
+                'BOTON' => 'Ir al módulo',
+                'FUNCION' => 'openModule',
+                'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
+            ]],
+            $audience,
+            $idUser, 
+            $form['linea'],
+            $this->socketClient,
+            $idOrder,
+            'Correctivo'
+        );
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F06TROT',
+            '-',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") traspasó la orden de trabajo correctivo al usuario o subcontratista #$idNewUser.",
+            $idUser,
+            $nowStr,
+            'S002V01S01ORTR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function registerSecurityManagement(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'lada1' => 'required|string|max:8',
+            'phone1' => 'required|string|min:10|max:11',
+            'ext1' => 'string|max:5',
+            'lada2' =>'string|max:8',
+            'phone2' => 'string|min:10|max:11',
+            'ext2' => 'string|max:5',
+            'email' => 'required|string|max:150',
+            'id_manager' => 'required|string',
+        ]);
+ 
+        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);
+        }
+
+        $idManager = $this->encryptionController->decrypt($form['id_manager']);
+        if(!$idManager){
+            return $this->responseController->makeResponse(true, 'El ID del gerente no fue encriptado correctamente.', [], 400);
+        }
+
+        $manager = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idManager]
+        ])->first();
+        
+        if(is_null($manager)){
+            return $this->responseController->makeResponse(true, 'El usuario seleccionado como gerente no existe.', [], 404);
+        }
+
+        $email = $form['email'];
+        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
+            return $this->responseController->makeResponse(true, 'El formato del correo electrónico enviado es inválido.', [], 400);
+        }
+
+        $emailVerified = DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_COEL', '=', $email]
+        ])->get()->all();
+
+        if(count($emailVerified) > 0){
+            return $this->responseController->makeResponse(true, 'El correo electrónico enviado ya ha sido registrado.', [], 400);
+        }
+
+        $lada1 = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $form['linea']],
+            ['PAIS_LADA', '=', $form['lada1']]
+        ])->first();
+        
+        if(is_null($lada1)){
+            return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono principal es inválida.', [], 400);
+        }else if(!$this->functionsController->validPhoneNumber($form['phone1'])){
+            return $this->responseController->makeResponse(true, 'El número de teléfono principal es inválido.', [], 400);
+        }else if(isset($form['ext1']) && !is_numeric($form['ext1'])){
+            return $this->responseController->makeResponse(true, 'La extensión de teléfono principal es inválida.', [], 400);
+        }
+
+        $ext1 = isset($form['ext1']) ? $form['ext1']: null;
+        $lad2 = null;
+        $tel2 = null;
+        $ext2 = null;
+        if(isset($form['lada2']) || isset($form['phone2'])){
+            if(!isset($form['lada2']) || !isset($form['phone2'])){
+                if(!isset($form['lada2'])){
+                    return $this->responseController->makeResponse(true, 'La lada del teléfono secundario es obligatoria cuando se envía el teléfono o la extensión secundarios', [], 400);
+                }
+
+                if(!isset($form['phone2'])){
+                    return $this->responseController->makeResponse(true, 'El teléfono secundario es obligatorio cuando se envía la lada o la extensión secundarias', [], 400);
+                }
+            }
+
+            $lada2 = DB::table('S002V01TPAIS')->where([
+                ['PAIS_NULI', '=', $form['linea']],
+                ['PAIS_LADA', '=', $form['lada2']]
+            ])->first();
+        
+            if(is_null($lada2)){
+                return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono secundario es inválida.', [], 400);
+            }else if(!$this->functionsController->validPhoneNumber($form['phone2'])){
+                return $this->responseController->makeResponse(true, 'El número de teléfono secundario es inválido.', [], 400);
+            }else if(isset($form['ext2']) && !is_numeric($form['ext2'])){
+                return $this->responseController->makeResponse(true, 'La extensión de teléfono secundario es inválida.', [], 400);
+            }
+
+            $lad2 = $form['lada2'];
+            $tel2 = $form['phone2'];
+            $ext2 = isset($form['ext2']) ? $form['ext2'] : null;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $idManagement = DB::table('S002V01TGESE')->insertGetId([
+            'GESE_NULI' => $form['linea'],
+            'GESE_LAD1' => $form['lada1'],
+            'GESE_TEL1' => $form['phone1'],
+            'GESE_EXT1' => $ext1,
+            'GESE_LAD2' => $lad2,
+            'GESE_TEL2' => $tel2,
+            'GESE_EXT2' => $ext2,
+            'GESE_COEL' => $email,
+            'GESE_GERE' => $idManager,
+            'GESE_USRE' => $idUser,
+            'GESE_FERE' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P02GSAU',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró la gerencia de seguridad #$idManagement.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getSegurityManagements($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $securityManagements = DB::table('S002V01TGESE')->select([
+            'GESE_IDGS AS ID_GERENCIA_SEGURIDAD',
+            'GESE_LAD1 AS LADA_TELEFONO_PRINCIPAL',
+            'GESE_TEL1 AS TELEFONO_PRINCIPAL',
+            'GESE_EXT1 AS EXTENSION_TELEFONO_PRINCIPAL',
+            'GESE_LAD2 AS LADA_TELEFONO_SECUNDARIO',
+            'GESE_TEL2 AS TELEFONO_SECUNDARIO',
+            'GESE_EXT2 AS EXTENSION_TELEFONO_SECUNDARIO',
+            'GESE_COEL AS CORREO_GERENCIA',
+            'GESE_GERE AS GERENTE',
+            'GESE_ESTA AS ESTADO',
+            'GESE_USRE AS USUREG',
+            'GESE_FERE AS FECREG',
+            'GESE_USMO AS USUMOD',
+            'GESE_FEMO AS FECMOD'
+        ])->where('GESE_NULI', '=', $line)->get()->all();
+
+        foreach($securityManagements as $key=>$item){
+            $workOrders = DB::table('S002V01TOTCO')->where([
+                ['OTCO_NULI', '=', $line],
+                ['OTCO_GESE', '=', $item->ID_GERENCIA_SEGURIDAD]
+            ])->get()->all();
+            
+            $item->NUMERO_ORDENES = count($workOrders);
+            $item->ID_GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($item->ID_GERENCIA_SEGURIDAD);
+            $manager = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $item->GERENTE]
+            ])->first();
+
+            $managerName = $this->functionsController->joinName($manager->USUA_NOMB, $manager->USUA_APPA, $manager->USUA_APMA);
+            $item->GERENTE = $managerName . " (" . $item->GERENTE . ")";
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $item->USUREG]
+            ])->first();
+
+            $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $item->USUREG = $usrRegName . " (" . $item->USUREG . ")";
+
+            if(!is_null($item->USUMOD)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_NULI', '=', $line],
+                    ['USUA_IDUS', '=', $item->USUMOD]
+                ])->first();
+
+                $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+                $item->USUMOD = $usrModName . " (" . $item->USUMOD . ")";
+            }
+
+            $securityManagements[$key] = $item;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P02GSAU',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las gerencias de seguridad registradas.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $securityManagements);
+    }
+
+    public function getSecurityManagement($idManagement, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $idManagement = $this->encryptionController->decrypt($idManagement);
+        if(!$idManagement){
+            return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
+        }
+
+        $management = DB::table('S002V01TGESE')->select([
+            'GESE_IDGS AS ID_GERENCIA_SEGURIDAD',
+            'GESE_LAD1 AS LADA_TELEFONO_PRINCIPAL',
+            'GESE_TEL1 AS TELEFONO_PRINCIPAL',
+            'GESE_EXT1 AS EXTENSION_TELEFONO_PRINCIPAL',
+            'GESE_LAD2 AS LADA_TELEFONO_SECUNDARIO',
+            'GESE_TEL2 AS TELEFONO_SECUNDARIO',
+            'GESE_EXT2 AS EXTENSION_TELEFONO_SECUNDARIO',
+            'GESE_COEL AS CORREO_GERENCIA',
+            'GESE_GERE AS GERENTE',
+            'GESE_ESTA AS ESTADO',
+            'GESE_USRE AS USUREG',
+            'GESE_FERE AS FECREG',
+            'GESE_USMO AS USUMOD',
+            'GESE_FEMO AS FECMOD'
+        ])->where([
+            ['GESE_NULI', '=', $line],
+            ['GESE_IDGS', '=', $idManagement]
+        ])->first();
+
+        if(is_null($management)){
+            return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404);
+        }
+
+        $workOrders = DB::table('S002V01TOTCO')->select([
+            'OTCO_IDOT AS ID_ORDEN'
+        ])->where([
+            ['OTCO_NULI', '=', $line],
+            ['OTCO_GESE', '=', $idManagement]
+        ])->get()->all();
+
+        foreach($workOrders as $key=>$order){
+            $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN);
+            $workOrders[$key] = $order;
+        }
+
+        $management->ORDENES_TRABAJO = $workOrders;
+        $management->ID_GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($management->ID_GERENCIA_SEGURIDAD);
+        $manager = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $management->GERENTE]
+        ])->first();
+
+        $managerName = $this->functionsController->joinName($manager->USUA_NOMB, $manager->USUA_APPA, $manager->USUA_APMA);
+        $management->GERENTE = $managerName . " (" . $management->GERENTE . ")";
+
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $management->USUREG]
+        ])->first();
+
+        $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $management->USUREG = $usrRegName . " (" . $management->USUREG . ")";
+
+        if(!is_null($management->USUMOD)){
+            $usrMod = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $management->USUMOD]
+            ])->first();
+
+            $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+            $management->USUMOD = $usrModName . " (" . $management->USUMOD . ")";
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P02GSAU',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la gerencias de seguridad #$idManagement.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $management);
+    }
+
+    public function updateSecurityManagement(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'lada1' => 'required|string|max:8',
+            'phone1' => 'required|string|min:10|max:11',
+            'ext1' => 'string|max:5',
+            'lada2' =>'string|max:8',
+            'phone2' => 'string|min:10|max:11',
+            'ext2' => 'string|max:5',
+            'email' => 'required|string|max:150',
+            'id_manager' => 'required|string',
+            'id_management' => 'required|string',
+        ]);
+ 
+        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);
+        }
+
+        $idManagement = $this->encryptionController->decrypt($form['id_management']);
+        if(!$idManagement){
+            return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
+        }
+
+        $management = DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_IDGS', '=', $idManagement]
+        ])->first();
+
+        if(is_null($management)){
+            return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404);
+        }
+
+        $idManager = $this->encryptionController->decrypt($form['id_manager']);
+        if(!$idManager){
+            return $this->responseController->makeResponse(true, 'El ID del gerente no fue encriptado correctamente.', [], 400);
+        }
+
+        $manager = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idManager]
+        ])->first();
+        
+        if(is_null($manager)){
+            return $this->responseController->makeResponse(true, 'El usuario seleccionado como gerente no existe.', [], 404);
+        }
+
+        $email = $form['email'];
+        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
+            return $this->responseController->makeResponse(true, 'El formato del correo electrónico enviado es inválido.', [], 400);
+        }
+
+        $emailVerified = DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_COEL', '=', $email],
+            ['GESE_IDGS', '!=', $idManagement]
+        ])->get()->all();
+
+        if(count($emailVerified) > 0){
+            return $this->responseController->makeResponse(true, 'El correo electrónico enviado ya ha sido registrado.', [], 400);
+        }
+
+        $lada1 = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $form['linea']],
+            ['PAIS_LADA', '=', $form['lada1']]
+        ])->first();
+        
+        if(is_null($lada1)){
+            return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono principal es inválida.', [], 400);
+        }else if(!$this->functionsController->validPhoneNumber($form['phone1'])){
+            return $this->responseController->makeResponse(true, 'El número de teléfono principal es inválido.', [], 400);
+        }else if(isset($form['ext1']) && !is_numeric($form['ext1'])){
+            return $this->responseController->makeResponse(true, 'La extensión de teléfono principal es inválida.', [], 400);
+        }
+
+        $ext1 = isset($form['ext1']) ? $form['ext1']: null;
+        $lad2 = null;
+        $tel2 = null;
+        $ext2 = null;
+        if(isset($form['lada2']) || isset($form['phone2'])){
+            if(!isset($form['lada2']) || !isset($form['phone2'])){
+                if(!isset($form['lada2'])){
+                    return $this->responseController->makeResponse(true, 'La lada del teléfono secundario es obligatoria cuando se envía el teléfono o la extensión secundarios', [], 400);
+                }
+
+                if(!isset($form['phone2'])){
+                    return $this->responseController->makeResponse(true, 'El teléfono secundario es obligatorio cuando se envía la lada o la extensión secundarias', [], 400);
+                }
+            }
+
+            $lada2 = DB::table('S002V01TPAIS')->where([
+                ['PAIS_NULI', '=', $form['linea']],
+                ['PAIS_LADA', '=', $form['lada2']]
+            ])->first();
+        
+            if(is_null($lada2)){
+                return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono secundario es inválida.', [], 400);
+            }else if(!$this->functionsController->validPhoneNumber($form['phone2'])){
+                return $this->responseController->makeResponse(true, 'El número de teléfono secundario es inválido.', [], 400);
+            }else if(isset($form['ext2']) && !is_numeric($form['ext2'])){
+                return $this->responseController->makeResponse(true, 'La extensión de teléfono secundario es inválida.', [], 400);
+            }
+
+            $lad2 = $form['lada2'];
+            $tel2 = $form['phone2'];
+            $ext2 = isset($form['ext2']) ? $form['ext2'] : null;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_IDGS', '=', $idManagement]
+        ])->update([
+            'GESE_LAD1' => $form['lada1'],
+            'GESE_TEL1' => $form['phone1'],
+            'GESE_EXT1' => $ext1,
+            'GESE_LAD2' => $lad2,
+            'GESE_TEL2' => $tel2,
+            'GESE_EXT2' => $ext2,
+            'GESE_COEL' => $email,
+            'GESE_GERE' => $idManager,
+            'GESE_USMO' => $idUser,
+            'GESE_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P02GSAU',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la gerencia de seguridad #$idManagement.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function deleteSecurityManagement(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_management' => 'required|string',
+        ]);
+ 
+        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);
+        }
+
+        $idManagement = $this->encryptionController->decrypt($form['id_management']);
+        if(!$idManagement){
+            return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
+        }
+
+        $management = DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_IDGS', '=', $idManagement]
+        ])->first();
+
+        if(is_null($management)){
+            return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404);
+        }
+
+        $workOrders = DB::table('S002V01TOTCO')->select([
+            'OTCO_IDOT AS ID_ORDEN'
+        ])->where([
+            ['OTCO_NULI', '=', $form['linea']],
+            ['OTCO_GESE', '=', $idManagement],
+            ['OTCO_ESOR', '!=', 'EL'],
+        ])->get()->all();
+
+        if(count($workOrders) > 0){
+            return $this->responseController->makeResponse(true, 'La gerencia no se puede eliminar porque tiene órdenes de trabajo relacionadas.', [], 401);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TGESE')->where([
+            ['GESE_NULI', '=', $form['linea']],
+            ['GESE_IDGS', '=', $idManagement]
+        ])->update([
+            'GESE_ESTA' => 'Eliminado',
+            'GESE_USMO' => $idUser,
+            'GESE_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P02GSAU',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la gerencia de seguridad #$idManagement.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function registerBlock(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'blocked' => 'required|string',
+            'type' => 'required|string|in:USR,SUB'
+        ]);
+ 
+        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);
+        }
+
+        $idBlocked = $this->encryptionController->decrypt($form['blocked']);
+        if(!$idBlocked){
+            return $this->responseController->makeResponse(true, 'El ID que desea bloquear no fue encriptado correctamente.', [], 400);
+        }
+
+        $blockedTypes = ['USR' => 'Empleado', 'SUB' => 'Subcontratista'];
+        $blockedType = $blockedTypes[$form['type']];
+
+        if($blockedType == 'Empleado'){
+            $employee = DB::table('S002V01TPERS')->where([
+                ['PERS_IDPE', '=', $idBlocked],
+                ['PERS_NULI', '=', $form['linea']]
+            ])->first();
+        
+            if(is_null($employee)){
+                return $this->responseController->makeResponse(true, 'El empleado que desea bloquear no está registrado.', [], 404);
+            }
+        }else{
+            $subcontratist = DB::table('S002V01TPESU')->where([
+                ['PESU_NULI', '=', $form['linea']],
+                ['PESU_IDPS', '=', $idBlocked]
+            ])->first();
+        
+            if(is_null($subcontratist)){
+                return $this->responseController->makeResponse(true, 'El subcontratista que desea bloquear no está registrado.', [], 404);
+            }
+        }
+
+        $checkStatus = DB::table('S002V01TBIBL')->where([
+            ['BIBL_NULI', '=', $form['linea']],
+            ['BIBL_BLOQ', '=', $idBlocked],
+            ['BIBL_TIBL', '=', $blockedType],
+            ['BIBL_ESTA', '=', 'Activo']
+        ])->get()->all();
+
+        if(count($checkStatus)){
+            return $this->responseController->makeResponse(true, "El $blockedType que desea bloquear ya se encuentra bloqueado.", [], 401);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TBIBL')->insert([
+            'BIBL_NULI' => $form['linea'],
+            'BIBL_BLOQ' => $idBlocked,
+            'BIBL_TIBL' => $blockedType,
+            'BIBL_USRE' => $idUser,
+            'BIBL_FERE' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P04REBL',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") bloqueó al $blockedType #$idBlocked.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getBlockRegisters($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $blockRegisters = DB::table('S002V01TBIBL')->select([
+            'BIBL_IDBL AS ID_BLOQUEO',
+            'BIBL_BLOQ AS BLOQUEADO',
+            'BIBL_TIBL AS TIPO_BLOQUEADO',
+            'BIBL_ESTA AS ESTADO',
+            'BIBL_USRE AS USUREG',
+            'BIBL_FERE AS FECREG',
+            'BIBL_USMO AS USUMOD',
+            'BIBL_FEMO AS FECMOD'
+        ])->where('BIBL_NULI', '=', $line)->get()->all();
+
+        foreach($blockRegisters as $key=>$register){
+            $register->ID_BLOQUEO = $this->encryptionController->encrypt($register->ID_BLOQUEO);
+            if($register->TIPO_BLOQUEADO == 'Subcontratista'){
+                $subcontratist = DB::table('S002V01TPESU')->where([
+                    ['PESU_NULI', '=', $line],
+                    ['PESU_IDPS', '=', $register->BLOQUEADO]
+                ])->first();
+
+                $register->BLOQUEADO = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $register->BLOQUEADO . ")";
+            }else{
+                $employee = DB::table('S002V01TPERS')->where([
+                    ['PERS_NULI', '=', $line],
+                    ['PERS_IDPE', '=', $register->BLOQUEADO]
+                ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->first();
+
+                $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
+                $register->BLOQUEADO = $employeeName . " (" . $register->BLOQUEADO . ")";
+            }
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $register->USUREG]
+            ])->first();
+
+            $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $register->USUREG = $usrRegName . " (" . $register->USUREG . ")";
+
+            if(!is_null($register->USUMOD)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_NULI', '=', $line],
+                    ['USUA_IDUS', '=', $register->USUMOD]
+                ])->first();
+
+                $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+                $register->USUMOD = $usrModName . " (" . $register->USUMOD . ")";
+            }
+
+            $blockRegisters[$key] = $register;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P03BLOQ',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los bloqueos registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $blockRegisters);
+    }
+
+    public function unblockRegister(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_register' => 'required|string',
+        ]);
+ 
+        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);
+        }
+
+        $idBlocked = $this->encryptionController->decrypt($form['id_register']);
+        if(!$idBlocked){
+            return $this->responseController->makeResponse(true, 'El ID del bloqueo no fue encriptado correctamente.', [], 400);
+        }
+
+        $register = DB::table('S002V01TBIBL')->where([
+            ['BIBL_NULI', '=', $form['linea']],
+            ['BIBL_IDBL', '=', $idBlocked]
+        ])->first();
+        
+        if(is_null($register)){
+            return $this->responseController->makeResponse(true, 'El bloqueo que desea revocar no está registrado.', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TBIBL')->where([
+            ['BIBL_NULI', '=', $form['linea']],
+            ['BIBL_IDBL', '=', $idBlocked]
+        ])->update([
+            'BIBL_ESTA' => 'Anulado',
+            'BIBL_USMO' => $idUser,
+            'BIBL_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F03GESE',
+            'S002V01P04REBL',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") anuló el bloqueo #$idBlocked.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEME'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getWorkOrderStatusHistory($idOrder, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idOrder = $this->encryptionController->decrypt($idOrder);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente', [], 400);
+        }
+
+        $order = DB::table('S002V01TOTCO')->select([
+            'OTCO_HIES AS HISTORIAL',
+        ])->where([
+            ['OTCO_IDOT', '=', $idOrder],
+            ['OTCO_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
+        }
+        
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+
+        $statusHistoryArr = json_decode($order->HISTORIAL, true);
+        foreach($statusHistoryArr as $key=>$item){
+            $item['ESTADO'] = $orderStates[$item['ESTADO']];
+            $usrSta = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $item['USUARIO']]
+            ])->first();
+
+            $usrStaName = $this->functionsController->joinName($usrSta->USUA_NOMB, $usrSta->USUA_APPA, $usrSta->USUA_APMA);
+            $item['USUARIO'] = $usrStaName . " (" . $item['USUARIO'] . ")";
+            $statusHistoryArr[$key] = $item;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F01GEOT',
+            '-',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el historial de estados de la orden #$idOrder de mantenimiento correctivo.",
+            $idUser,
+            $nowStr,
+            'S002V01S03PRIN'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $statusHistoryArr);
+    }
+
+    public function generateReport(Request $request) {
+        DB::enableQueryLog();
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'report_type' => 'required|string|in:TODAS,MANUA,AUTOM,ESTAD',
+            'start_date' => 'date',
+            'end_date' => 'date',
+            'order_state' => 'required_if:report_type,=,ESTAD|string', 
+        ]);
+ 
+        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);
+        }
+
+        $systemParamsExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        if(!$systemParamsExists){
+            return $this->responseController->makeResponse(true, 'El archivo de parámetros del sistema no fue encontrado.', [], 500);
+        }
+
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+
+        $ordersBuilder = DB::table('S002V01TOTCO')->select([
+            'OTCO_IDOT AS ID_ORDEN',
+            'OTCO_IDUR AS USUARIO_RESPONSABLE',
+            'OTCO_TURE AS TIPO_USUARIO_RESPONSABLE',
+            'OTCO_DEIN AS DESCRIPCION',
+            'OTCO_EQIN AS EQUIPAMIENTO',
+            'OTCO_FIFA AS FECHA_REGISTRO_FALLA',
+            'OTCO_TESO AS TIEMPO_ESTIMADO',
+            'OTCO_CORE AS CONTADOR',
+            'OTCO_DRCO AS MEDIDA_REGISTRADA',
+            'OTCO_PRIO AS PRIORIDAD',
+            'OTCO_FTIN AS FECHA_FINALIZACION',
+            'OTCO_DTIN AS DURACION_TOTAL',
+            'OTCO_RHUT AS RECURSOS',
+            'OTCO_PEIN AS PERSONAL',
+            'OTCO_TIAC AS TIPO_ACTIVACION',
+            'OTCO_ANCO AS ANALISIS_COSTOS',
+            'OTCO_DORE AS DOCUMENTOS',
+            'OTCO_CLAS AS CLASIFICACION',
+            'OTCO_COME AS COMENTARIOS',
+            'OTCO_GESE AS GERENCIA_SGURIDAD',
+            'OTCO_HIES AS HISTORIAL_ESTADOS',
+            'OTCO_ESOR AS ESTADO',
+            'OTCO_USRE AS USUREG',
+            'OTCO_FERE AS FECREG',
+            'OTCO_USMO AS USUMOD',
+            'OTCO_FEMO AS FECMOD'
+        ])->where('OTCO_NULI', '=', $form['linea']);
+        if(isset($form['start_date'])){
+            $ordersBuilder->where('OTCO_FERE', '>=', $form['start_date']);
+        }
+
+        if(isset($form['end_date'])){
+            $ordersBuilder->where('OTCO_FERE', '<=', $form['end_date']);
+        }
+        
+        $orderStates = [
+            'PE' => 'Pendiente',   'VA' => 'Validado', 'RE' => 'Rechazado', 
+            'EP' => 'En progreso', 'CE' => 'Cerrado',  'CP' => 'Cerrado pendiente',
+            'CA' => 'Cancelado',   'EL' => 'Eliminado'
+        ];
+
+        if(isset($form['order_state']) && !array_key_exists($form['order_state'], $orderStates)){
+            return $this->responseController->makeResponse(true, 'El estado solicitado para las órdenes de mantenimiento correctivo es inválido.', [], 400);
+        }else if(isset($form['order_state']) && array_key_exists($form['order_state'], $orderStates)){
+            $ordersBuilder->where('OTCO_ESOR', '=', $form['order_state']);
+        }
+
+        if($form['report_type'] == 'MANUA'){
+            $ordersBuilder->where('OTCO_TIAC', '=', 'M');
+        }
+
+        if($form['report_type'] == 'AUTOM'){
+            $ordersBuilder->where('OTCO_TIAC', '=', 'A');
+        }
+
+        $workOrders = $ordersBuilder->get()->all();
+        foreach($workOrders as $order){
+            $order->ID_ORDEN = "#" . $order->ID_ORDEN;
+
+            if($order->TIPO_USUARIO_RESPONSABLE == 'S'){
+                $subcontratist = DB::table('S002V01TPESU')->where([
+                    ['PESU_NULI', '=', $form['linea']],
+                    ['PESU_IDPS', '=', $order->USUARIO_RESPONSABLE]
+                ])->first();
+
+                $order->USUARIO_RESPONSABLE = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $subcontratist->PESU_IDPS . ")";
+                $order->TIPO_USUARIO_RESPONSABLE = 'Subcontratista';
+            }else if($order->TIPO_USUARIO_RESPONSABLE == 'U'){
+                $usrResp = DB::table('S002V01TUSUA')->where([
+                    ['USUA_NULI', '=', $form['linea']],
+                    ['USUA_IDUS', '=', $order->USUARIO_RESPONSABLE]
+                ])->first();
+    
+                $nameUsrResp = $this->functionsController->joinName($usrResp->USUA_NOMB, $usrResp->USUA_APPA, $usrResp->USUA_APMA);
+                $order->USUARIO_RESPONSABLE = $nameUsrResp . " (" . $order->USUARIO_RESPONSABLE . ")";
+                $order->TIPO_USUARIO_RESPONSABLE = 'Empleado';
+            }
+
+            $equipment = DB::table('S002V01TEQUI')->where([
+                ['EQUI_NULI', '=', $form['linea']],
+                ['EQUI_COEQ', '=', $order->EQUIPAMIENTO]
+            ])->first();
+
+            $order->EQUIPAMIENTO = $order->EQUIPAMIENTO . ' - ' . $equipment->EQUI_TIPO . ' - ' . $equipment->EQUI_MODE . ' (' . $equipment->EQUI_IDEQ . ')';
+            $order->FECHA_REGISTRO_FALLA = $this->functionsController->formatDateTime($order->FECHA_REGISTRO_FALLA);
+            $order->TIEMPO_ESTIMADO = $order->TIEMPO_ESTIMADO . "h";
+
+            $counterActivator = DB::table('S002V01TACTI')->where([
+                ['ACTI_NULI', '=', $form['linea']],
+                ['ACTI_CORE', '=', $order->CONTADOR]
+            ])->first();
+
+            $measureArr = json_decode($order->MEDIDA_REGISTRADA, true);
+            $activationConfig = json_decode($counterActivator->ACTI_COAC, true);
+            if($counterActivator->ACTI_TIAC == 'Medida' || $counterActivator->ACTI_TIAC == 'Valor'){
+                $unit = DB::table('S002V01TLIME')->where([
+                    ['LIME_IDME', '=', $activationConfig['unit']],
+                    ['LIME_MAGN', '=', $activationConfig['magnitude']],
+                ])->first();
+
+                $order->MEDIDA_REGISTRADA = "Medida #" . $measureArr['ID_MEDIDA'] . ". Valor registrado: " . $measureArr['VALOR'] . 
+                ' ' . $unit->LIME_ACME . ". Fecha de registro: " . $this->functionsController->formatDateTime($measureArr['HORA_REGISTRO']) . 
+                ". Servicio web de recepción: " . $measureArr['URL_SERVICIO_WEB'] . " (" . $measureArr['ID_SERVICIO_WEB'] . ")";
+            }else if($counterActivator->ACTI_TIAC == 'Sintoma'){
+                $symptom = DB::table('S002V01TLISI')->where([
+                    ['LISI_IDSI', '=', $activationConfig['sign']],
+                    ['LISI_NULI', '=', $form['linea']]
+                ])->first();
+
+                $unit = DB::table('S002V01TLIME')->where([
+                    ['LIME_IDME', '=', $symptom->LISI_IDME],
+                    ['LIME_MAGN', '=', $activationConfig['magnitude']],
+                ])->first();
+
+                $order->MEDIDA_REGISTRADA = "Medida #" . $measureArr['ID_MEDIDA'] . ". Valor registrado: " . $measureArr['VALOR'] . 
+                ' ' . $unit->LIME_ACME . ". Fecha de registro: " . $this->functionsController->formatDateTime($measureArr['HORA_REGISTRO']) . 
+                ". Servicio web de recepción: " . $measureArr['URL_SERVICIO_WEB'] . " (" . $measureArr['ID_SERVICIO_WEB'] . ")";
+            }else{
+                $order->MEDIDA_REGISTRADA = 'No aplica';
+            }
+
+            $order->CONTADOR = "#" . $order->CONTADOR;
+            $orderPriorities = $paramsArr['order_priorities'];
+            $priorityFilt = array_filter($orderPriorities, function($v, $k) use($order) {
+                return $v['value'] == $order->PRIORIDAD;
+            }, ARRAY_FILTER_USE_BOTH);
+
+            if(count($priorityFilt) < 1){
+                $order->PRIORIDAD = 'Desconocido';
+            }else{
+                $priority = end($priorityFilt);
+                $order->PRIORIDAD = $priority['label'] . " (" . $order->PRIORIDAD . ")";
+            }
+
+            if(is_null($order->FECHA_FINALIZACION)) {
+                $order->FECHA_FINALIZACION = '-';
+            }else{
+                $order->FECHA_FINALIZACION = $this->functionsController->formatDateTime($order->FECHA_FINALIZACION);
+            }
+
+            if(is_null($order->DURACION_TOTAL)) {
+                $order->DURACION_TOTAL = '-';
+            }else{
+                $order->DURACION_TOTAL = $order->DURACION_TOTAL . "h";
+            }
+
+            $resourcesArr = json_decode($order->RECURSOS, true);
+            if(count($resourcesArr) < 1){
+                $order->RECURSOS = 'Ninguno';
+            }else{
+                //Pendiente procesar los recursos
+            }
+
+            $staffArr = json_decode($order->PERSONAL, true);
+            $staffStr = "";
+            foreach($staffArr as $item){
+                if($item['TYPE'] == 'EQ'){
+                    $workTeam = DB::table('S002V01TEQMA')->where([
+                        ['EQMA_IDEQ', '=', $item['ID']],
+                        ['EQMA_NULI', '=', $form['linea']]
+                    ])->first();
+
+                    $staffStr .= "equipo de trabajo " . $workTeam->EQMA_NOMB . " (" . $item['ID'] . "), ";
+                }else if($item['TYPE'] == 'SU'){
+                    $subcontratist = DB::table('S002V01TPESU')->where([
+                        ['PESU_IDPS', '=', $item['ID']],
+                        ['PESU_NULI', '=', $form['linea']]
+                    ])->first();
+
+                    $staffStr .= "subcontratista " . $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $item['ID'] . "), ";
+                }else if($item['TYPE'] == 'EM'){
+                    $employee = DB::table('S002V01TPERS')->where([
+                        ['PERS_IDPE', '=', $item['ID']],
+                        ['PERS_NULI', '=', $form['linea']]
+                    ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->first();
+
+                    $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
+                    $staffStr .= "empleado " . $employeeName . " (" . $item['ID'] . "), ";
+                }
+            }
+
+            $staffStr = substr($staffStr, 0, -2);
+            $staffStr = ucfirst($staffStr);
+            
+            $order->PERSONAL = $staffStr;
+            $order->TIPO_ACTIVACION = $order->TIPO_ACTIVACION == 'M' ? 'Manual' : 'Automática';
+
+            if(is_null($order->ANALISIS_COSTOS)){
+                $order->ANALISIS_COSTOS = 'Sin asignar';
+            }else{
+                //Pendiente revisar el análisis de costos
+            }
+
+            $documentsArr = json_decode($order->DOCUMENTOS, true);
+            $documentsStr = "";
+
+            if(count($documentsArr) < 1){
+                $documentsStr = 'Ninguno';
+            }else{
+                foreach($documentsArr as $document){
+                    $documentsStr .= $document . ", ";
+                }
+
+                $documentsStr = substr($documentsStr, 0, -2);
+            }
+
+            $order->DOCUMENTOS = $documentsStr;
+            if(is_null($order->COMENTARIOS)){
+                $order->COMENTARIOS = 'Sin comentarios';
+            }
+
+            $order->GERENCIA_SGURIDAD = "Gerencia #" . $order->GERENCIA_SGURIDAD;
+            $statusHistoryArr = json_decode($order->HISTORIAL_ESTADOS, true);
+            $statusHistoryStr = "";
+            foreach($statusHistoryArr as $item){
+                $statusHistoryStr .= $orderStates[$item['ESTADO']] . ' - ' . $this->functionsController->formatDateTime($item['FECHA']);
+                $usrState = DB::table('S002V01TUSUA')->where([
+                    ['USUA_IDUS', '=', $item['USUARIO']],
+                    ['USUA_NULI', '=', $form['linea']]
+                ])->first();
+
+                $usrStateName = $this->functionsController->joinName($usrState->USUA_NOMB, $usrState->USUA_APPA, $usrState->USUA_APMA);
+                $statusHistoryStr .= ' - ' . $usrStateName . ' (' . $item['USUARIO'] . '), ';
+            }
+
+            $statusHistoryStr = substr($statusHistoryStr, 0, -2);
+            $order->HISTORIAL_ESTADOS = $statusHistoryStr;
+            $order->ESTADO = $orderStates[$order->ESTADO];
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $order->USUREG],
+                ['USUA_NULI', '=', $form['linea']]
+            ])->first();
+
+            $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $order->USUREG = $usrRegName . " (" . $order->USUREG . ")";
+            $order->FECREG = $this->functionsController->formatDateTime($order->FECREG);
+
+            if(!is_null($order->USUMOD)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_IDUS', '=', $order->USUMOD],
+                    ['USUA_NULI', '=', $form['linea']]
+                ])->first();
+    
+                $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+                $order->USUMOD = $usrModName . " (" . $order->USUMOD . ")";
+                $order->FECMOD = $this->functionsController->formatDateTime($order->FECMOD);
+            }else{
+                $order->USUMOD = "-";
+                $order->FECMOD = "-";
+            }
+        }
+
+        $document = $this->reportWorkOrders($workOrders);
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        
+        $dateTimeArr = explode(" ", $nowStr);
+        $dateArr = explode("-", $dateTimeArr[0]);
+        $year = substr($dateArr[0], 2);
+        $como = 'GMCO';
+        $cldo = 'IN';
+        $fecr = $year . $dateArr[1] . $dateArr[2];
+
+        $sec = DB::table('S002V01TAFAL')->where([
+            ['AFAL_NULI', '=', $form['linea']],
+            ['AFAL_COMO', '=', $como],
+            ['AFAL_CLDO', '=', $cldo],
+        ])->orderBy('AFAL_NUSE', 'desc')->first();
+
+        $nuse = "";
+        if(is_null($sec)){
+            $nuse = '000001';
+        }else{
+            $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
+            $nuse = "";
+
+            for($i = strlen($secu); $i < 6; $i++){
+                $nuse .= "0";
+            }
+
+            $nuse = $nuse . $secu;
+        }
+
+        $timestamp = $now->timestamp;
+        $noar = "informe_ordenes_mantenimiento_correctivo_$timestamp";
+        $exte = "xlsx";
+
+        $ver = DB::table('S002V01TAFAL')->where([
+            ['AFAL_NULI', '=', $form['linea']],
+            ['AFAL_COMO', '=', $como],
+            ['AFAL_CLDO', '=', $cldo],
+            ['AFAL_NOAR', '=', $noar],
+            ['AFAL_EXTE', '=', $exte],
+        ])->orderBy('AFAL_NUVE', 'desc')->first();
+
+        $nuve = "";
+        if(is_null($ver)){
+            $nuve = "01";
+        }else{
+            $vers = intval($ver->AFAL_NUVE) + 1;
+            $nuve = $vers < 10 ? "0$vers" : "$vers";
+        }
+
+        $line = $form['linea'] < 10 ? "0$form[linea]" : "$form[linea]";
+        $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';
+        $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
+        
+        $tempFile = $filePath . $fileName;
+        if(file_exists($tempFile)){
+            unlink($tempFile);
+        }
+
+        $writer = IOFactory::createWriter($document, 'Xlsx');
+        $writer->save($tempFile);
+        $ubic = Storage::putFile('files', new File($tempFile));
+        $ubic = str_replace("/", "\\", $ubic);
+        $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
+        $tama = filesize($ubic);
+        $usac = json_encode([$idUser]);
+        unlink($tempFile);
+
+        DB::table('S002V01TAFAL')->insert([
+            'AFAL_NULI' => $line,
+            'AFAL_COMO' => $como,
+            'AFAL_CLDO' => $cldo,
+            'AFAL_FECR' => $fecr,
+            'AFAL_NUSE' => $nuse,
+            'AFAL_NUVE' => $nuve,
+            'AFAL_NOAR' => $noar,
+            'AFAL_EXTE' => $exte,
+            'AFAL_TAMA' => $tama,
+            'AFAL_UBIC' => $ubic,
+            'AFAL_USAC' => $usac,
+            'AFAL_USRE' => $idUser,
+            'AFAL_FERE' => $nowStr,
+        ]);
+
+        $idReport = DB::table('S002V01TIMCO')->insertGetId([
+            'IMCO_NULI' => $form['linea'],
+            'IMCO_TIIN' => $form['report_type'],
+            'IMCO_DORE' => $fileName,
+            'IMCO_USRE' => $idUser,
+            'IMCO_FERE' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M09GMCO',
+            'S002V01F02PRIN',
+            'S002V01P01REIN',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró el informe #$idReport.",
+            $idUser,
+            $nowStr,
+            'S002V01S03PRIN'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.', ['report' => $this->encryptionController->encrypt($fileName)]);
+    }
+
+    private function reportWorkOrders($workOrders) : Spreadsheet {
+        $spreadsheet = new Spreadsheet;
+        $spreadsheet->getProperties()
+            ->setCreator('STC')
+            ->setTitle('Historial de órdenes de trabajo de mantenimiento correctivo.')
+            ->setSubject('Historial documento')
+            ->setKeywords('Historial Órdenes Mantenimiento Correctivo')
+            ->setCategory('Historial archivo');
+
+        $worksheet = $spreadsheet->getActiveSheet();
+        $worksheet->setTitle('ÓRDENES DE MANT CORRECTIVO');
+
+        $columns = ['# ORDEN', 'RESPONSABLE', 'TIPO DE USUARIO RESPONSABLE', 'DESCRIPCIÓN', 'EQUIPAMIENTO', 'FECHA Y HORA DE REGISTRO DE LA FALLA', 
+        'TIEMPO ESTIMADO DE DURACIÓN DE LA INTERVENCIÓN', 'CONTADOR RELACIONADO', 'MEDIDA REGISTRADA AL MOMENTO DE LA FALLA', 'PRIORIDAD', 
+        'FECHA DE FINALIZACIÓN DE LA INTERVENCIÓN', 'DURACIÓN TOTAL DE LA INTERVENCIÓN', 'CONSUMIBLES UTILIZADOS', 'PERSONAL INVOLUCRADO', 
+        'TIPO DE ACTIVACIÓN', 'ANÁLISIS DE COSTOS', 'DOCUMENTOS REQUERIDOS', 'CLASIFICACIÓN', 'COMENTARIOS REALIZADOS DURANTE LA INTERVENCIÓN', 
+        'GERENCIA DE SEGURIDAD RELACIONADA', 'HISTORIAL DE ESTADOS', 'ESTADO DE LA ORDEN', 'USUARIO DE REGISTRO', 'FECHA DE REGISTRO', 'USUARIO DE ACTIALIZACIÓN', 
+        'FECHA DE ACTUALIZACIÓN'];
+        
+        $startRow = 2;
+        $startCol = 2;
+        $maxRow = $startRow + count($workOrders) + 1;
+        $maxCol = $startCol + count($columns) - 1;
+
+        for($row = $startRow; $row <= $maxRow; $row++){
+            $startColStr = Coordinate::stringFromColumnIndex($startCol);
+            $maxColStr = Coordinate::stringFromColumnIndex($maxCol);
+
+            if($row == 2){
+                $worksheet->mergeCells($startColStr . $row . ':' . $maxColStr . $row);
+                $worksheet->setCellValue($startColStr . $row, 'INFORME DE ÓRDENES DE MANTENIMIENTO CORRECTIVO')->getStyle($startColStr . $row)->getFill()
+                    ->setFillType(Fill::FILL_SOLID)
+                    ->getStartColor()->setRGB('B7BCC4');
+                $worksheet->getStyle($startColStr . $row)->getFont()->setBold(true);
+                $worksheet->getStyle($startColStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
+            }else if($row == 3){
+                for($col = $startCol; $col <= $maxCol; $col++){
+                    $colStr = Coordinate::stringFromColumnIndex($col);
+                    $colInd = $col - 2;
+
+                    $column = $columns[$colInd]; 
+                    $worksheet->setCellValue($colStr . $row, $column);
+                    $worksheet->getStyle($colStr . $row)->getFont()->setBold(true);
+                    $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
+                }
+            }else if($row > 3){
+                $rowInd = $row - 4;
+                $order = (array) $workOrders[$rowInd];
+                $keys = array_keys($order);
+
+                for($col = $startCol; $col <= $maxCol; $col++){
+                    $colInd = $col - 2;
+                    $key = $keys[$colInd];
+                    $value = $order[$key];
+                    $colStr = Coordinate::stringFromColumnIndex($col);
+
+                    if($key == 'ID_ORDEN' || $key == 'TIEMPO_ESTIMADO' || $key == 'CONTADOR' || 
+                    $key == 'DURACION_TOTAL' || $key == 'GERENCIA_SGURIDAD'){
+                        $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
+                        $worksheet->getColumnDimension($colStr)->setAutoSize(true);
+                    }else if($key == 'EQUIPAMIENTO' || $key == 'DESCRIPCION' || $key == 'MEDIDA_REGISTRADA' || 
+                    $key == 'PERSONAL' || $key == 'DOCUMENTOS' || $key == 'COMENTARIOS' || $key == 'HISTORIAL_ESTADOS'){
+                        $worksheet->getColumnDimension($colStr)->setWidth(48);
+                        $worksheet->getStyle($colStr . $row)->getAlignment()->setWrapText(true);
+                    }else{
+                        $worksheet->getColumnDimension($colStr)->setAutoSize(true);
+                    }
+
+                    $worksheet->getStyle($colStr . $row)->getAlignment()->setVertical(Alignment::HORIZONTAL_CENTER);
+                    $worksheet->setCellValue($colStr . $row, $value);
+                }
+            }
+        }
+
+        return $spreadsheet;
+    }
+
+    public function getReports($type, $startDate, $endDate, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $reportsBuilder = DB::table('S002V01TIMCO')->select([
+            'IMCO_IDIN AS ID_INFORME',
+            'IMCO_TIIN AS TIPO_INFORME',
+            'IMCO_DORE AS DOCUMENTO',
+            'IMCO_USRE AS USUREG',
+            'IMCO_FERE AS FECREG'
+        ])->where('IMCO_NULI', '=', $line);
+
+        if($type != '-'){
+            $validReports = ['TODAS','MANUA','AUTOM','ESTAD'];
+            if(!in_array($type, $validReports)){
+                return $this->responseController->makeResponse(true, "El tipo de reportes solicitado es inválido.", [], 400);
+            }
+
+            $reportsBuilder->where('IMCO_TIIN', '=', $type);
+        }
+
+        if($startDate != '-'){
+            $startDateArr = explode('-', $startDate);
+            if(count($startDateArr) != 3){
+                return $this->responseController->makeResponse(true, 'La fecha de inicio tiene un formato inválido.', [], 400);
+            }
+    
+            try{
+                $startDateObj = new Carbon($startDate);
+            }catch(InvalidFormatException $e){
+                return $this->responseController->makeResponse(true, "La fecha de inicio tiene un formato inválido: " . $e->getMessage(), [], 400);
+            }
+    
+            $startDate = $startDateObj->toDateTimeString();
+            $reportsBuilder->where('IMCO_FERE', '>=', $startDate);
+        }
+
+        if($endDate != '-'){
+            $endDateArr = explode('-', $endDate);
+            if(count($endDateArr) != 3){
+                return $this->responseController->makeResponse(true, 'La fecha final tiene un formato inválido.', [], 400);
+            }
+    
+            try{
+                $endDateObj = new Carbon($endDate);
+                
+                $endDateObj->addDay();
+                $endDateObj->subSecond();
+            }catch(InvalidFormatException $e){
+                return $this->responseController->makeResponse(true, "La fecha final tiene un formato inválido: " . $e->getMessage(), [], 400);
+            }
+            
+            $endDate = $endDateObj->toDateTimeString();
+            $reportsBuilder->where('IMCO_FERE', '<=', $endDate);
+        }
+
+        $reports = $reportsBuilder->get()->all();
+        foreach($reports as $key=>$report){
+            $report->ID_INFORME = $this->encryptionController->encrypt($report->ID_INFORME);
+            $report->DOCUMENTO = $this->encryptionController->encrypt($report->DOCUMENTO);
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $report->USUREG],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+
+            $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $report->USUREG = $usrRegName . " (" . $report->USUREG . ")";
+
+            $reports[$key] = $report;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M09GMCO',
+            'S002V01F02PRIN',
+            '-',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los informes de tipo $type.",
+            $idUser,
+            $nowStr,
+            'S002V01S03PRIN'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $reports);
+    }
+}

+ 1596 - 6
sistema-mantenimiento-back/app/Http/Controllers/CountersActivatorsController.php

@@ -18,6 +18,59 @@ class CountersActivatorsController extends Controller{
         $this->functionsController = new FunctionsController();
     }
 
+    public function getActivators($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+        
+        $activators = DB::table('S002V01TACTI')->select([
+            'ACTI_IDAC AS ID_ACTIVADOR',
+            'ACTI_PRIO AS PRIORIDAD',
+            'ACTI_TIAC AS TIPO_ACTIVADOR',
+            'ACTI_CORE AS ID_CONTADOR',
+            'ACTI_ESTA AS ESTADO'
+        ])->get()->all();
+
+        foreach($activators as $key=>$activator){
+            $activator->ID_ACTIVADOR = $this->encryptionController->encrypt($activator->ID_ACTIVADOR);
+            $activator->ID_CONTADOR = $this->encryptionController->encrypt($activator->ID_CONTADOR);
+
+            $activators[$key] = $activator;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M06COAC',
+            'S002V01F01GEAC',
+            'S002V01P01COAC',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los activadores registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S02ACTI'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", $activators);
+    }
+
     public function getActivatorsByType($type, $idUser, $line){
         DB::enableQueryLog();
 
@@ -36,7 +89,7 @@ class CountersActivatorsController extends Controller{
         }
         
         $activators = DB::table('S002V01TACTI')->select([
-            'ACTI_IDCO AS IDCONTADOR',
+            'ACTI_IDAC AS IDACTIVADOR',
             'ACTI_PRIO AS PRIORIDAD',
             'ACTI_TIAC AS TIPOACTIVACION',
             'ACTI_COAC AS CONDICIONES'
@@ -75,6 +128,7 @@ class CountersActivatorsController extends Controller{
             'priority' => 'required|string|in:1,2,3,4',
             'type' => 'required|string|in:CA,SI,ME,VA',
             'condition' => 'required|json',
+            'counter' => 'required|string'
         ]);
 
         if($validator->fails()){
@@ -106,15 +160,181 @@ class CountersActivatorsController extends Controller{
             return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
         }
 
+        $idCounter = $this->encryptionController->decrypt($form['counter']);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador relacionado no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_NULI', '=', $form['linea']],
+            ['CONA_IDCO', '=', $idCounter]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador relacionado no está registrado.', [], 404);
+        }
+
         $priority = $form['priority'];
         $type = $types[$form['type']];
-        
-        $nowStr = Carbon::now('America/Guatemala')->toDateTimeString();
+        $conditionArr = json_decode($form['condition'], true);
+
+        if(count($conditionArr) == 0){
+            return $this->responseController->makeResponse(true, 'El arreglo de la condición de activación está vació.', [], 400);
+        }else{
+            switch($form['type']){
+                case 'CA': 
+                    if(count($conditionArr) != 5){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysCA = ['startDate', 'startHour', 'repeat', 'customRepeat', 'color'];
+                    foreach($keysCA as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+                break;
+                case 'SI':
+                    if(count($conditionArr) != 6){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysSI = ['sign', 'startDate', 'startHour', 'repeat', 'customRepeat', 'color'];
+                    foreach($keysSI as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+
+                    $idSymptom = $this->encryptionController->decrypt($conditionArr['sign']);
+                    if(!$idSymptom){
+                        return $this->responseController->makeResponse(true, 'El ID del síntoma relacionado no está encriptado correctamente.', [], 400);
+                    }
+
+                    $symptom = DB::table('S002V01TLISI')->where([
+                        ['LISI_IDSI', '=', $idSymptom],
+                        ['LISI_NULI', '=', $form['linea']]
+                    ])->first();
+
+                    if(is_null($symptom)){
+                        return $this->responseController->makeResponse(true, 'El síntoma relacionado no está registrado.', [], 404);
+                    }else if($symptom->LISI_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'El síntoma relacionado está eliminado.', [], 404);
+                    }
+
+                    $conditionArr['sign'] = $idSymptom;
+                break;
+                case 'ME':
+                    if(count($conditionArr) != 7){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysSI = ['minValue', 'maxValue', 'magnitude', 'customMagnitude', 'unit', 'customUnit', 'color'];
+                    foreach($keysSI as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+
+                    $idMagnitude = $this->encryptionController->decrypt($conditionArr['magnitude']);
+                    if(!$idMagnitude){
+                        return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $magnitude = DB::table('S002V01TMAGN')->where([
+                        ['MAGN_NULI', '=', $form['linea']],
+                        ['MAGN_IDMA', '=', $idMagnitude]
+                    ])->first();
+
+                    if(is_null($magnitude)){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrado.', [], 404);
+                    }else if($magnitude->MAGN_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada está eliminada.', [], 404);
+                    }
+
+                    $idUnit = $this->encryptionController->decrypt($conditionArr['unit']);
+                    if(!$idUnit){
+                        return $this->responseController->makeResponse(true, 'El ID de la unidad relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $unit = DB::table('S002V01TLIME')->where([
+                        ['LIME_IDME', '=', $idUnit],
+                        ['LIME_NULI', '=', $form['linea']],
+                        ['LIME_MAGN', '=', $idMagnitude],
+                    ])->first();
+
+                    if(is_null($unit)){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada no está registrado.', [], 404);
+                    }else if($unit->LIME_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada está eliminada.', [], 404);
+                    }
+
+                    $conditionArr['magnitude'] = $idMagnitude ;
+                    $conditionArr['unit'] = $idUnit;
+                break;
+                case 'VA':
+                    if(count($conditionArr) != 7){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysVA = ['comparison', 'limitValue', 'magnitude', 'customMagnitude', 'unit', 'customUnit', 'color'];
+                    foreach($keysVA as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+
+                    $idMagnitude = $this->encryptionController->decrypt($conditionArr['magnitude']);
+                    if(!$idMagnitude){
+                        return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $magnitude = DB::table('S002V01TMAGN')->where([
+                        ['MAGN_NULI', '=', $form['linea']],
+                        ['MAGN_IDMA', '=', $idMagnitude]
+                    ])->first();
+
+                    if(is_null($magnitude)){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrado.', [], 404);
+                    }else if($magnitude->MAGN_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada está eliminada.', [], 404);
+                    }
+
+                    $idUnit = $this->encryptionController->decrypt($conditionArr['unit']);
+                    if(!$idUnit){
+                        return $this->responseController->makeResponse(true, 'El ID de la unidad relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $unit = DB::table('S002V01TLIME')->where([
+                        ['LIME_IDME', '=', $idUnit],
+                        ['LIME_NULI', '=', $form['linea']],
+                        ['LIME_MAGN', '=', $idMagnitude],
+                    ])->first();
+
+                    if(is_null($unit)){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada no está registrado.', [], 404);
+                    }else if($unit->LIME_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada está eliminada.', [], 404);
+                    }
+
+                    $conditionArr['magnitude'] = $idMagnitude ;
+                    $conditionArr['unit'] = $idUnit;
+                break;
+                default:
+                    return $this->responseController->makeResponse(true, 'El tipo de contador es inválido.', [], 400);
+                break;
+            }
+        }
+
+        $conditionStr = json_encode($conditionArr);
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
         $idCont = DB::table('S002V01TACTI')->insertGetId([
             'ACTI_NULI' => $form['linea'],
             'ACTI_PRIO' => $priority,
             'ACTI_TIAC' => $type,
-            'ACTI_COAC' => $form['condition'],
+            'ACTI_COAC' => $conditionStr,
+            'ACTI_CORE' => $idCounter,
             'ACTI_USRE' => $idUser,
             'ACTI_FERE' => $nowStr
         ]);
@@ -161,16 +381,18 @@ class CountersActivatorsController extends Controller{
         }
         
         $activator = DB::table('S002V01TACTI')->select([
-            'ACTI_IDCO AS IDACTIVADOR',
+            'ACTI_IDAC AS IDACTIVADOR',
             'ACTI_PRIO AS PRIORIDAD',
             'ACTI_TIAC AS TIPOACTIVADOR',
             'ACTI_COAC AS CONDICIONES',
+            'ACTI_CORE AS CONTADOR',
+            'ACTI_ESTA AS ESTADO',
             'ACTI_USRE AS USRREG',
             'ACTI_FERE AS FECREG',
             'ACTI_USMO AS USRMOD',
             'ACTI_FEMO AS FECMOD',
         ])->where([
-            ['ACTI_IDCO', '=', $idActivator],
+            ['ACTI_IDAC', '=', $idActivator],
             ['ACTI_NULI', '=', $line],
         ])->first();
 
@@ -178,6 +400,61 @@ class CountersActivatorsController extends Controller{
             return $this->responseController->makeResponse(true, 'El activador solicitado no está registrado.', [], 404);
         }
 
+        $activator->IDACTIVADOR = $this->encryptionController->encrypt($activator->IDACTIVADOR);
+        $activator->CONTADOR = $this->encryptionController->encrypt($activator->CONTADOR);
+        
+        $conditionsArr = json_decode($activator->CONDICIONES, true);
+        foreach($conditionsArr as $key=>$val){
+            $encryptedParams = ['sign', 'magnitude', 'unit'];
+            if(in_array($key, $encryptedParams)){
+                switch($key){
+                    case 'sign':
+                        $symptom = DB::table('S002V01TLISI')->where([
+                            ['LISI_NULI', '=', $line],
+                            ['LISI_IDSI', '=', $val]
+                        ])->first();
+
+                        $conditionsArr[$key] = $symptom->LISI_NOSI . " (" . $val . ")";
+                    break;
+                    case 'magnitude':
+                        $magnitude = DB::table('S002V01TMAGN')->where([
+                            ['MAGN_NULI', '=', $line],
+                            ['MAGN_IDMA', '=', $val]
+                        ])->first();
+
+                        $conditionsArr[$key] = $magnitude->MAGN_MAGN . " (" . $val . ")";
+                    break;
+                    case 'unit':
+                        $unit = DB::table('S002V01TLIME')->where([
+                            ['LIME_NULI', '=', $line],
+                            ['LIME_IDME', '=', $val]
+                        ])->first();
+
+                        $conditionsArr[$key] = $unit->LIME_NOME . " (" . $val . ") - " . $unit->LIME_ACME;
+                    break;
+                }
+            }
+        }
+
+        $activator->CONDICIONES = json_encode($conditionsArr);
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $activator->USRREG]
+        ])->first();
+
+        $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $activator->USRREG = $nameReg . " (" . $activator->USRREG . ")";
+
+        if(!is_null($activator->USRMOD)){
+            $usrMod = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $activator->USRMOD]
+            ])->first();
+    
+            $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+            $activator->USRMOD = $nameMod . " (" . $activator->USRMOD . ")";
+        }
+
         $now = $this->functionsController->now();
         $nowStr = $now->toDateTimeString();
         $actions = DB::getQueryLog();
@@ -198,4 +475,1317 @@ class CountersActivatorsController extends Controller{
         $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
         return $this->responseController->makeresponse(false, "EXITO", $activator);
     }
+
+    public function registerCounter(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'scada' => 'required|string',
+            'equipment' => 'required|string',
+            'time_interval' => 'required|numeric',
+            'time_interval_unit' => 'required|string|in:seg,min,hor,dia',
+            'time_interval_tolerance' => 'required|numeric',
+            'time_interval_tolerance_unit' => 'required|string|in:seg,min,hor,dia'
+        ]);
+
+        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 del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idSCADA = $this->encryptionController->decrypt($form['scada']);
+        if(!$idSCADA){
+            return $this->responseController->makeResponse(true, 'El ID del SCADA relacionado no está encriptado correctamente.', [], 400);
+        }
+
+        $scada = DB::table('S002V01TLISC')->where([
+            ['LISC_IDSC', '=', $idSCADA],
+            ['LISC_NULI', '=', $form['linea']],
+        ])->first();
+
+        if(is_null($scada)){
+            return $this->responseController->makeResponse(true, 'El SCADA relacionado no está registrado.', [], 404);
+        }
+
+        $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
+        if(!$equipmentCode){
+            return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no está encriptado correctamente.', [], 400);
+        }
+
+        $equipment = DB::table('S002V01TEQUI')->where([
+            ['EQUI_NULI', '=', $form['linea']],
+            ['EQUI_COEQ', '=', $equipmentCode],
+        ])->first();
+
+        if(is_null($equipment)){
+            return $this->responseController->makeResponse(true, 'El equipamiento relacionado no está registrado.', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $idCont = DB::table('S002V01TCONA')->insertGetId([
+            'CONA_NULI' => $form['linea'],
+            'CONA_INLE' => $form['time_interval'],
+            'CONA_UTIL' => $form['time_interval_unit'],
+            'CONA_TOIN' => $form['time_interval_tolerance'],
+            'CONA_UTTI' => $form['time_interval_tolerance_unit'],
+            'CONA_IDSC' => $idSCADA,
+            'CONA_COEQ' => $equipmentCode,
+            'CONA_USRE' => $idUser,
+            'CONA_FERE' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P02RECO',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró el contador #$idCont.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getCounters($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $counters = DB::table('S002V01TCONA')->select([
+            'CONA_IDCO AS ID_CONTADOR',
+            'CONA_IDSC AS ID_SCADA',
+            'LISC_NOSC AS SCADA',
+            'CONA_COEQ AS CODIGO_EQUIPAMIENTO',
+            'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
+            'EQUI_MODE AS MODELO_EQUIPAMIENTO',
+            'EQUI_IDEQ AS ID_EQUIPAMIENTO',
+            'CONA_ESTA AS ESTADO',
+        ])->join('S002V01TLISC', 'LISC_IDSC', '=', 'CONA_IDSC')
+        ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'CONA_COEQ')
+        ->get()->all();
+
+        foreach($counters as $key=>$counter){
+            $activators = DB::table('S002V01TACTI')->where([
+                ['ACTI_NULI', '=', $line],
+                ['ACTI_CORE', '=', $counter->ID_CONTADOR]
+            ])->get()->all();
+
+            $counter->ID_CONTADOR = $this->encryptionController->encrypt($counter->ID_CONTADOR);
+            $counter->ID_SCADA = $this->encryptionController->encrypt($counter->ID_SCADA);
+            $counter->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($counter->CODIGO_EQUIPAMIENTO);
+            $counter->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($counter->ID_EQUIPAMIENTO);
+            $counter->TIENE_ACTIVADOR = count($activators) > 0;
+            $counter->ACTIVADOR = count($activators) > 0 ? $this->encryptionController->encrypt($activators[0]->ACTI_IDAC) : null;
+
+            $counters[$key] = $counter;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P01COCO',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contadores registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", $counters);
+    }
+
+    public function getCounter($idCounter, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($idCounter);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->select([
+            'CONA_IDCO AS ID_CONTADOR',
+            'CONA_IDSC AS ID_SCADA',
+            'LISC_NOSC AS SCADA',
+            'CONA_COEQ AS CODIGO_EQUIPAMIENTO',
+            'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
+            'EQUI_MODE AS MODELO_EQUIPAMIENTO',
+            'EQUI_IDEQ AS ID_EQUIPAMIENTO',
+            'CONA_INLE AS INTERVALO',
+            'CONA_UTIL AS UNIDAD_INTERVALO',
+            'CONA_TOIN AS TOLERANCIA_INTERVALO',
+            'CONA_UTTI AS UNIDAD_TOLERANCIA_INTERVALO',
+            'CONA_COVI AS CONTADORES_VINCULADOS',
+            'CONA_ESTA AS ESTADO',
+            'CONA_USRE AS USRREG',
+            'CONA_FERE AS FECREG',
+            'CONA_USMO AS USRMOD',
+            'CONA_FEMO AS FECMOD',
+        ])->join('S002V01TLISC', 'LISC_IDSC', '=', 'CONA_IDSC')
+        ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'CONA_COEQ')
+        ->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador solicitado no está registrado.', [], 404);
+        }
+
+        $counter->ID_CONTADOR = $this->encryptionController->encrypt($counter->ID_CONTADOR);
+        $counter->ID_SCADA = $this->encryptionController->encrypt($counter->ID_SCADA);
+        $counter->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($counter->CODIGO_EQUIPAMIENTO);
+        $counter->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($counter->ID_EQUIPAMIENTO);
+
+        $relatedCountersArr = json_decode($counter->CONTADORES_VINCULADOS, true);
+        foreach($relatedCountersArr as $key=>$counterStr){
+            $counterStr = $this->encryptionController->encrypt($counterStr);
+            $relatedCountersArr[$key] = $counterStr;
+        }
+
+        $relatedCountersStr = json_encode($relatedCountersArr);
+        $counter->CONTADORES_VINCULADOS = $relatedCountersStr;
+
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_IDUS', '=', $counter->USRREG],
+            ['USUA_NULI', '=', $line]
+        ])->first();
+
+        $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $counter->USRREG = $nameReg . " (" . $counter->USRREG . ")";
+
+        if(!is_null($counter->USRMOD)){
+            $usrMod = DB::table('S002V01TUSUA')->where([
+                ['USUA_IDUS', '=', $counter->USRMOD],
+                ['USUA_NULI', '=', $line]
+            ])->first();
+    
+            $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+            $counter->USRMOD = $nameMod . " (" . $counter->USRMOD . ")";
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P01COCO',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el contador #$idCounter.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", $counter);
+    }
+
+    public function updateCounter(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'scada' => 'required|string',
+            'equipment' => 'required|string',
+            'id_counter' => 'required|string',
+            'time_interval' => 'required|numeric',
+            'time_interval_unit' => 'required|string|in:seg,min,hor,dia',
+            'time_interval_tolerance' => 'required|numeric',
+            'time_interval_tolerance_unit' => 'required|string|in:seg,min,hor,dia'
+        ]);
+
+        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 del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idSCADA = $this->encryptionController->decrypt($form['scada']);
+        if(!$idSCADA){
+            return $this->responseController->makeResponse(true, 'El ID del SCADA relacionado no está encriptado correctamente.', [], 400);
+        }
+
+        $scada = DB::table('S002V01TLISC')->where([
+            ['LISC_IDSC', '=', $idSCADA],
+            ['LISC_NULI', '=', $form['linea']],
+        ])->first();
+
+        if(is_null($scada)){
+            return $this->responseController->makeResponse(true, 'El SCADA relacionado no está registrado.', [], 404);
+        }
+
+        $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
+        if(!$equipmentCode){
+            return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no está encriptado correctamente.', [], 400);
+        }
+
+        $equipment = DB::table('S002V01TEQUI')->where([
+            ['EQUI_NULI', '=', $form['linea']],
+            ['EQUI_COEQ', '=', $equipmentCode],
+        ])->first();
+
+        if(is_null($equipment)){
+            return $this->responseController->makeResponse(true, 'El equipamiento relacionado no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($form['id_counter']);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador seleccionado no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_NULI', '=', $form['linea']],
+            ['CONA_IDCO', '=', $idCounter]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador seleccionado no está registrado.', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $form['linea']]
+        ])->update([
+            'CONA_INLE' => $form['time_interval'],
+            'CONA_UTIL' => $form['time_interval_unit'],
+            'CONA_TOIN' => $form['time_interval_tolerance'],
+            'CONA_UTTI' => $form['time_interval_tolerance_unit'],
+            'CONA_IDSC' => $idSCADA,
+            'CONA_USMO' => $idUser,
+            'CONA_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P02RECO',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el contador #$idCounter.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function deleteCounter(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_counter' => 'required|string'
+        ]);
+
+        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 del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($form['id_counter']);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador seleccionado no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_NULI', '=', $form['linea']],
+            ['CONA_IDCO', '=', $idCounter]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador seleccionado no está registrado.', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $form['linea']]
+        ])->update([
+            'CONA_ESTA' => 'Eliminado',
+            'CONA_USMO' => $idUser,
+            'CONA_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M06COAC',
+            'S002V01F02ELCO',
+            '-',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el contador #$idCounter.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function updateActivator(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'priority' => 'required|string|in:1,2,3,4',
+            'type' => 'required|string|in:CA,SI,ME,VA',
+            'condition' => 'required|json',
+            'counter' => 'required|string',
+            'id_activator' => 'required|string'
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                true,
+                "Se encontraron uno o más errores.",
+                $this->responseController->makeErrors(
+                    $validator->errors()->messages()
+                ),
+                401
+            );
+        }
+
+        //$priorities = ['MA' => '1', 'AL' => '2', 'ME' => '3', 'BA' => '4'];
+        $types = ['CA' => 'Calendario', 'SI' => 'Sintoma', 'ME' => 'Medida', 'VA' => 'Valor'];
+        $form = $request->all();
+
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($form['counter']);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador relacionado no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_NULI', '=', $form['linea']],
+            ['CONA_IDCO', '=', $idCounter]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador relacionado no está registrado.', [], 404);
+        }
+
+        $idActivator = $this->encryptionController->decrypt($form['id_activator']);
+        if(!$idActivator){
+            return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no está encriptado correctamente.', [], 400);
+        }
+
+        $activator = DB::table('S002V01TACTI')->where([
+            ['ACTI_IDAC', '=', $idActivator],
+            ['ACTI_NULI', '=', $form['linea']]
+        ])->first();
+
+        if(is_null($activator)){
+            return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
+        }
+
+        $priority = $form['priority'];
+        $type = $types[$form['type']];
+        $conditionArr = json_decode($form['condition'], true);
+
+        if(count($conditionArr) == 0){
+            return $this->responseController->makeResponse(true, 'El arreglo de la condición de activación está vació.', [], 400);
+        }else{
+            switch($form['type']){
+                case 'CA': 
+                    if(count($conditionArr) != 5){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysCA = ['startDate', 'startHour', 'repeat', 'customRepeat', 'color'];
+                    foreach($keysCA as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+                break;
+                case 'SI':
+                    if(count($conditionArr) != 6){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysSI = ['sign', 'startDate', 'startHour', 'repeat', 'customRepeat', 'color'];
+                    foreach($keysSI as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+
+                    $idSymptom = $this->encryptionController->decrypt($conditionArr['sign']);
+                    if(!$idSymptom){
+                        return $this->responseController->makeResponse(true, 'El ID del síntoma relacionado no está encriptado correctamente.', [], 400);
+                    }
+
+                    $symptom = DB::table('S002V01TLISI')->where([
+                        ['LISI_IDSI', '=', $idSymptom],
+                        ['LISI_NULI', '=', $form['linea']]
+                    ])->first();
+
+                    if(is_null($symptom)){
+                        return $this->responseController->makeResponse(true, 'El síntoma relacionado no está registrado.', [], 404);
+                    }else if($symptom->LISI_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'El síntoma relacionado está eliminado.', [], 404);
+                    }
+
+                    $conditionArr['sign'] = $idSymptom;
+                break;
+                case 'ME':
+                    if(count($conditionArr) != 7){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysSI = ['minValue', 'maxValue', 'magnitude', 'customMagnitude', 'unit', 'customUnit', 'color'];
+                    foreach($keysSI as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+
+                    $idMagnitude = $this->encryptionController->decrypt($conditionArr['magnitude']);
+                    if(!$idMagnitude){
+                        return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $magnitude = DB::table('S002V01TMAGN')->where([
+                        ['MAGN_NULI', '=', $form['linea']],
+                        ['MAGN_IDMA', '=', $idMagnitude]
+                    ])->first();
+
+                    if(is_null($magnitude)){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrado.', [], 404);
+                    }else if($magnitude->MAGN_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada está eliminada.', [], 404);
+                    }
+
+                    $idUnit = $this->encryptionController->decrypt($conditionArr['unit']);
+                    if(!$idUnit){
+                        return $this->responseController->makeResponse(true, 'El ID de la unidad relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $unit = DB::table('S002V01TLIME')->where([
+                        ['LIME_IDME', '=', $idUnit],
+                        ['LIME_NULI', '=', $form['linea']],
+                        ['LIME_MAGN', '=', $idMagnitude],
+                    ])->first();
+
+                    if(is_null($unit)){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada no está registrado.', [], 404);
+                    }else if($unit->LIME_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada está eliminada.', [], 404);
+                    }
+
+                    $conditionArr['magnitude'] = $idMagnitude ;
+                    $conditionArr['unit'] = $idUnit;
+                break;
+                case 'VA':
+                    if(count($conditionArr) != 7){
+                        return $this->responseController->makeResponse(true, 'El arreglo de la condición tiene un formato inválido.', [], 400);
+                    }
+
+                    $keysVA = ['comparison', 'limitValue', 'magnitude', 'customMagnitude', 'unit', 'customUnit', 'color'];
+                    foreach($keysVA as $key){
+                        if(!array_key_exists($key, $conditionArr)){
+                            return $this->responseController->makeResponse(true, "El arreglo de la condición no contiene el elemento '$key'.", [], 400);
+                        }
+                    }
+
+                    $idMagnitude = $this->encryptionController->decrypt($conditionArr['magnitude']);
+                    if(!$idMagnitude){
+                        return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $magnitude = DB::table('S002V01TMAGN')->where([
+                        ['MAGN_NULI', '=', $form['linea']],
+                        ['MAGN_IDMA', '=', $idMagnitude]
+                    ])->first();
+
+                    if(is_null($magnitude)){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrado.', [], 404);
+                    }else if($magnitude->MAGN_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La magnitud relacionada está eliminada.', [], 404);
+                    }
+
+                    $idUnit = $this->encryptionController->decrypt($conditionArr['unit']);
+                    if(!$idUnit){
+                        return $this->responseController->makeResponse(true, 'El ID de la unidad relacionada no está encriptado correctamente.', [], 400);
+                    }
+
+                    $unit = DB::table('S002V01TLIME')->where([
+                        ['LIME_IDME', '=', $idUnit],
+                        ['LIME_NULI', '=', $form['linea']],
+                        ['LIME_MAGN', '=', $idMagnitude],
+                    ])->first();
+
+                    if(is_null($unit)){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada no está registrado.', [], 404);
+                    }else if($unit->LIME_ESTA == 'Eliminado'){
+                        return $this->responseController->makeResponse(true, 'La unidad relacionada está eliminada.', [], 404);
+                    }
+
+                    $conditionArr['magnitude'] = $idMagnitude ;
+                    $conditionArr['unit'] = $idUnit;
+                break;
+                default:
+                    return $this->responseController->makeResponse(true, 'El tipo de contador es inválido.', [], 400);
+                break;
+            }
+        }
+
+        $conditionStr = json_encode($conditionArr);
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TACTI')->where([
+            ['ACTI_IDAC', '=', $idActivator],
+            ['ACTI_NULI', '=', $form['linea']]
+        ])->update([
+            'ACTI_PRIO' => $priority,
+            'ACTI_TIAC' => $type,
+            'ACTI_COAC' => $conditionStr,
+            'ACTI_CORE' => $idCounter,
+            'ACTI_USMO' => $idUser,
+            'ACTI_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M06COAC',
+            'S002V01F01GEAC',
+            'S002V01P02REAC',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el activador #$idActivator.",
+            $idUser,
+            $nowStr,
+            'S002V01S02ACTI'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function deleteActivator(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_activator' => 'required|string'
+        ]);
+
+        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 del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idActivator = $this->encryptionController->decrypt($form['id_activator']);
+        if(!$idActivator){
+            return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no está encriptado correctamente.', [], 400);
+        }
+
+        $activator = DB::table('S002V01TACTI')->where([
+            ['ACTI_IDAC', '=', $idActivator],
+            ['ACTI_NULI', '=', $form['linea']]
+        ])->first();
+
+        if(is_null($activator)){
+            return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
+        }
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TACTI')->where([
+            ['ACTI_IDAC', '=', $idActivator],
+            ['ACTI_NULI', '=', $form['linea']]
+        ])->update([
+            'ACTI_ESTA' => 'Eliminado',
+            'ACTI_USMO' => $idUser,
+            'ACTI_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M06COAC',
+            'S002V01F01GEAC',
+            'S002V01P02REAC',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el activador #$idActivator.",
+            $idUser,
+            $nowStr,
+            'S002V01S02ACTI'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+
+    public function getCountersByEquipment($equipmentCode, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $equipmentCode = $this->encryptionController->decrypt($equipmentCode);
+        if(!$equipmentCode){
+            return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no está encriptado correctamente.', [], 400);
+        }
+
+        $equipment = DB::table('S002V01TEQUI')->where([
+            ['EQUI_COEQ', '=', $equipmentCode],
+            ['EQUI_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($equipment)){
+            return $this->responseController->makeResponse(true, 'El equipamiento relacionado no está registrado.', [], 404);
+        }
+
+        $counters = DB::table('S002V01TCONA')->select([
+            'CONA_IDCO AS ID_CONTADOR',
+            'ACTI_IDAC AS ID_ACTIVADOR',
+            'ACTI_PRIO AS PRIORIDAD',
+            'CONA_ESTA AS ESTADO',
+            'CONA_FERE AS FECREG',
+            'CONA_USRE AS USRREG',
+            'CONA_FEMO AS FECMOD',
+            'CONA_USMO AS USRMOD'
+        ])->join('S002V01TACTI', 'ACTI_CORE', '=', 'CONA_IDCO')->where([
+            ['CONA_NULI', '=', $line],
+            ['CONA_COEQ', '=', $equipmentCode]
+        ])->orderBy('CONA_IDCO', 'asc')->get()->all();
+
+        foreach($counters as $key=>$counter){
+            $counter->ID_CONTADOR = $this->encryptionController->encrypt($counter->ID_CONTADOR);
+            if(!is_null($counter->ID_ACTIVADOR)){
+                $counter->ID_ACTIVADOR = $this->encryptionController->encrypt($counter->ID_ACTIVADOR);
+            }
+
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $counter->USRREG]
+            ])->first();
+
+            $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $counter->USRREG = $nameReg . " (" . $counter->USRREG . ")";
+
+            if(!is_null($counter->USRMOD)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_NULI', '=', $line],
+                    ['USUA_IDUS', '=', $counter->USRMOD]
+                ])->first();
+
+                $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+                $counter->USRMOD = $nameMod . " (" . $counter->USRMOD . ")";
+            }
+
+            $counters[$key] = $counter;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P01COCO',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contadores relacionados al equipamiento $equipmentCode.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", $counters);
+    }
+
+    public function getCounterLastMeasure($idCounter, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($idCounter);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador solicitado no está registrado.', [], 404);
+        }
+
+        $measure = DB::table('S002V01TMEDI')->select([
+            'MEDI_IDME AS ID_MEDIDA',
+            'MEDI_CORE AS CONTADOR',
+            'MEDI_VALO AS VALOR',
+            'MEDI_WSRE AS ID_SERVICIO_WEB',
+            'LSWE_URLX AS URL_SERVICIO_WEB',
+            'MEDI_HORE AS HORA_REGISTRO',
+        ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([
+            ['MEDI_NULI', '=', $line],
+            ['MEDI_CORE', '=', $idCounter]
+        ])->orderBy('MEDI_HORE', 'desc')->first();
+
+        if(!is_null($measure)){
+            $measure->ID_MEDIDA = $this->encryptionController->encrypt($measure->ID_MEDIDA);
+            $measure->CONTADOR = $this->encryptionController->encrypt($measure->CONTADOR);
+            $measure->ID_SERVICIO_WEB = $this->encryptionController->encrypt($measure->ID_SERVICIO_WEB);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P01COCO',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las medidas relacionadas al contador #$idCounter.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", is_null($measure) ? [] : [$measure]);
+    }
+
+    public function getCounterMeasures($idCounter, $order, $direction, $limit, $offset, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($idCounter);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador solicitado no está registrado.', [], 404);
+        }
+        
+        $enabledOrders = [
+            'ID_MEDIDA' => 'MEDI_IDME',
+            'VALOR' => 'MEDI_VALO',
+            'FECREG' => 'MEDI_HORE'
+        ];
+
+        if(!isset($enabledOrders[$order])){
+            return $this->responseController->makeResponse(true, 'El orden solicitado para los registros es inválido.', [], 404);
+        }
+
+        $orderDB = $enabledOrders[$order];
+        $enbaledDirections = [
+            'D' => 'desc',
+            'A' => 'asc'
+        ];
+
+        if(!isset($enbaledDirections[$direction])){
+            return $this->responseController->makeResponse(true, 'La dirección del orden solicitado para los registros es inválida.', [], 404);
+        }
+
+        $directionDB = $enbaledDirections[$direction];
+        $limit = intval($limit);
+        $offset = intval($offset);
+
+        $measures = DB::table('S002V01TMEDI')->select([
+            'MEDI_IDME AS ID_MEDIDA',
+            'MEDI_CORE AS CONTADOR',
+            'MEDI_VALO AS VALOR',
+            'MEDI_WSRE AS ID_SERVICIO_WEB',
+            'LSWE_URLX AS URL_SERVICIO_WEB',
+            'MEDI_HORE AS HORA_REGISTRO',
+        ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([
+            ['MEDI_NULI', '=', $line],
+            ['MEDI_CORE', '=', $idCounter]
+        ])->orderBy($orderDB, $directionDB)
+        ->offset($offset)->limit($limit)->get()->all();
+
+        foreach($measures as $key=>$measure){
+            $measure->ID_MEDIDA = $this->encryptionController->encrypt($measure->ID_MEDIDA);
+            $measure->CONTADOR = $this->encryptionController->encrypt($measure->CONTADOR);
+            $measure->ID_SERVICIO_WEB = $this->encryptionController->encrypt($measure->ID_SERVICIO_WEB);
+
+            $measures[$key];
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P01COCO',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las medidas relacionadas al contador #$idCounter.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", $measures);
+    }
+
+    public function getCounterMeasuresLength($idCounter, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($idCounter);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador solicitado no está registrado.', [], 404);
+        }
+
+        $measures = DB::table('S002V01TMEDI')->select([
+            'MEDI_IDME AS ID_MEDIDA',
+            'MEDI_CORE AS CONTADOR',
+            'MEDI_VALO AS VALOR',
+            'MEDI_WSRE AS ID_SERVICIO_WEB',
+            'LSWE_URLX AS URL_SERVICIO_WEB',
+            'MEDI_HORE AS HORA_REGISTRO',
+        ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([
+            ['MEDI_NULI', '=', $line],
+            ['MEDI_CORE', '=', $idCounter]
+        ])->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P01COCO',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las medidas relacionadas al contador #$idCounter.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", ['MEASURES_LENGTH' => count($measures)]);
+    }
+
+    public function getRelatedCounters($idCounter, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está encriptado correctamente.', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($idCounter);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $line]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador solicitado no está registrado.', [], 404);
+        }
+        var_dump($idCounter);
+    }
+
+    public function relateCounters(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_counter' => 'required|string',
+            'related_counters' => '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 del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
+        }
+
+        $idCounter = $this->encryptionController->decrypt($form['id_counter']);
+        if(!$idCounter){
+            return $this->responseController->makeResponse(true, 'El ID del contador seleccionado no está encriptado correctamente.', [], 400);
+        }
+
+        $counter = DB::table('S002V01TCONA')->where([
+            ['CONA_NULI', '=', $form['linea']],
+            ['CONA_IDCO', '=', $idCounter]
+        ])->first();
+
+        if(is_null($counter)){
+            return $this->responseController->makeResponse(true, 'El contador seleccionado no está registrado.', [], 404);
+        }
+
+        $relatedCountersRegisteredArr = json_decode($counter->CONA_COVI, true);
+        $relatedCountersArr = json_decode($form['related_counters'], true);
+
+        if(!is_array($relatedCountersArr)){
+            return $this->responseController->makeResponse(true, 'El campo de contadores vinculados no es un arreglo.', [], 400);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $relatedCountersArrDec = [];
+        foreach($relatedCountersArr as $relatedCounterEnc){
+            $relatedCounterDec = $this->encryptionController->decrypt($relatedCounterEnc);
+            $relatedCounter = DB::table('S002V01TCONA')->where([
+                ['CONA_IDCO', '=', $relatedCounterDec],
+                ['CONA_NULI', '=', $form['linea']]
+            ])->first();
+
+            if(is_null($relatedCounter)){
+                return $this->responseController->makeResponse(true, "El contador #$relatedCounterDec no está registrado.", [], 404);
+            }
+
+            if(!in_array($relatedCounter, $relatedCountersRegisteredArr)){
+                $relatedCountersRegisteredArr[] = $relatedCounterDec;
+            }
+
+            $relatedCounterRelatedCountersArr = json_decode($relatedCounter->CONA_COVI);
+            if(!in_array($idCounter, $relatedCounterRelatedCountersArr)){
+                $relatedCounterRelatedCountersArr[] = $idCounter;
+            }
+
+            $relatedCounterCOVI = json_encode($relatedCounterRelatedCountersArr);
+            DB::table('S002V01TCONA')->where([
+                ['CONA_IDCO', '=', $relatedCounterDec],
+                ['CONA_NULI', '=', $form['linea']]
+            ])->update([
+                'CONA_COVI' => $relatedCounterCOVI,
+                'CONA_USMO' => $idUser,
+                'CONA_FEMO' => $nowStr
+            ]);
+
+            $relatedCountersArrDec[] = $relatedCounterDec;
+        }
+
+        $countersWithRelation = DB::table('S002V01TCONA')->where('CONA_NULI', '=', $form['linea'])
+        ->whereJsonContains('CONA_COVI', $idCounter)->get()->all();
+        foreach($countersWithRelation as $counterWithRelation){
+            if(!in_array($counterWithRelation->CONA_IDCO, $relatedCountersArrDec)){
+                $counterWithRelationRelatedCounters = json_decode($counterWithRelation->CONA_COVI, true);
+                $counterWithRelationRelatedCountersFn = [];
+                
+                foreach($counterWithRelationRelatedCounters as $counterWithRelationRelatedCounter){
+                    if($idCounter != $counterWithRelationRelatedCounter){
+                        $counterWithRelationRelatedCountersFn[] = $counterWithRelationRelatedCounter;
+                    }
+                }
+
+                $counterWithRelationCOVI = json_encode($counterWithRelationRelatedCountersFn);
+                DB::table('S002V01TCONA')->where([
+                    ['CONA_IDCO', '=', $counterWithRelation->CONA_IDCO],
+                    ['CONA_NULI', '=', $form['linea']]
+                ])->update([
+                    'CONA_COVI' => $counterWithRelationCOVI,
+                    'CONA_USMO' => $idUser,
+                    'CONA_FEMO' => $nowStr
+                ]);
+            }
+        }
+
+        $relatedCountersFn = [];
+        foreach($relatedCountersRegisteredArr as $relatedCounterRegistered){
+            if(in_array($relatedCounterRegistered, $relatedCountersArrDec) && !in_array($relatedCounterRegistered, $relatedCountersFn)){
+                $relatedCountersFn[] = $relatedCounterRegistered;
+            }
+        }
+
+        $covi = json_encode($relatedCountersFn);
+        DB::table('S002V01TCONA')->where([
+            ['CONA_IDCO', '=', $idCounter],
+            ['CONA_NULI', '=', $form['linea']]
+        ])->update([
+            'CONA_COVI' => $covi,
+            'CONA_USMO' => $idUser,
+            'CONA_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M06COAC',
+            'S002V01F01GECO',
+            'S002V01P02RECO',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó los contadores vinculados al contador #$idCounter.",
+            $idUser,
+            $nowStr,
+            'S002V01S01CONT'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
 }

+ 3 - 6
sistema-mantenimiento-back/app/Http/Controllers/DocumentManagementController.php

@@ -836,17 +836,14 @@ class DocumentManagementController extends Controller{
 
       
       $ubicArr = explode('storage', $file->AFAL_UBIC);
-        // $publicUbi = "$ubicArr[0]public_files\\$id";
-        $publicUbi = "$ubicArr[0]public\public_files\\$id";                                                                        // PRUEBAS JEAN
+      $publicUbi = "$ubicArr[0]public_files\\$id";
 
       if(!file_exists($publicUbi)){
           copy($file->AFAL_UBIC, $publicUbi);
       }
 
-      // $apiURI = $this->functionsController->getApiURI();
-      $apiURI = 'http://192.168.100.105:8000/';                                                                                        // PRUEBAS JEAN
-      // $publicUbiStr = str_replace('C:\inetpub\wwwroot\\', $apiURI, $publicUbi);  
-      $publicUbiStr = str_replace('C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public\\', $apiURI, $publicUbi);   // PRUEBAS JEAN
+      $apiURI = $this->functionsController->getApiURI();
+      $publicUbiStr = str_replace('C:\inetpub\wwwroot\\', $apiURI, $publicUbi);
       $publicUbiStr = str_replace('\\', '/', $publicUbiStr);
 
       $now = $this->functionsController->now();

File diff suppressed because it is too large
+ 404 - 463
sistema-mantenimiento-back/app/Http/Controllers/EmployeeController.php


+ 6 - 24
sistema-mantenimiento-back/app/Http/Controllers/EquipmentManagementController.php

@@ -18,11 +18,7 @@ class EquipmentManagementController extends Controller{
         $this->responseController = new ResponseController();
         $this->encryptionController = new EncryptionController();
         $this->functionsController = new FunctionsController();
-        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
-            $this->templatesUbic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\public\pdf_templates\\01_05_GEEQ\\";
-        } else {
-            $this->templatesUbic = "C:\inetpub\wwwroot\sam\storage\app\public\pdf_templates\\01_05_GEEQ\\";
-        }
+        $this->templatesUbic = "C:\inetpub\wwwroot\sam\storage\app\public\pdf_templates\\01_05_GEEQ\\";
         $this->documentManagementController = new DocumentManagementController();
     }
 
@@ -740,6 +736,7 @@ class EquipmentManagementController extends Controller{
 
         $ubic = $this->templatesUbic;
         $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
+
         $locationsEnc = file_get_contents($ubic . "locations.sam");
         $locationsDec = $this->encryptionController->decrypt($locationsEnc);
         $locationsArr = json_decode($locationsDec, true);
@@ -1287,44 +1284,37 @@ class EquipmentManagementController extends Controller{
         }
 
         $form = $request->all();
-        
-        // Desencriptación del usuario
         $idUser = $this->encryptionController->decrypt($form['id_user']);
         if(!$idUser){
             return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
         }
-        // Obtención del usuario
+
         $usr = DB::table('S002V01TUSUA')->where([
             ['USUA_NULI', '=', $form['linea']],
             ['USUA_IDUS', '=', $idUser]
         ])->first();
 
-        // Verificación de la existencia del usuario
         if(is_null($usr)){
             return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
         }
 
-        // El código del equipo padre se inicializa
         $eqpa = null;
-        // Si la jerarquía es de tipo "Hijo", Entonces
         if($form['hierarchy'] == 'Hijo'){
-            // Se desencripta el código del equipamiento padre
             $eqpa = $this->encryptionController->decrypt($form['parent_equipment']);
             if(!$eqpa){
                 return $this->responseController->makeResponse(true, 'El ID del equipamiento padre no fue encriptado correctamente.', [], 400);
             }
-            // Se obtiene la información del equipo padre
+
             $parentEquipment = DB::table('S002V01TEQUI')->where([
                 ['EQUI_NULI', '=', $form['linea']],
                 ['EQUI_COEQ', '=', $eqpa],
             ])->first();
-            // Se verifica que el equipo padre exista
+            
             if(is_null($parentEquipment)){
                 return $this->responseController->makeResponse(true, 'El equipamiento padre no existe.', [], 404);
             }
         }
         
-        // Se obtiene la ubicación de las plantillas
         $ubic = $this->templatesUbic;
         $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
 
@@ -1342,7 +1332,6 @@ class EquipmentManagementController extends Controller{
             ];
         }
 
-
         $originLocation = null;
         $originLevel = null;
         $originOccupationStr = null;
@@ -1378,6 +1367,7 @@ class EquipmentManagementController extends Controller{
             for($i = 5; $i > 0; $i--){
                 $supportedLevels[] = "S0$i";
             }
+
             for($i = 0; $i <= 15; $i++){
                 $tag = $i < 10 ? "P0$i" : "P$i";
                 $supportedLevels[] = $tag;
@@ -1479,8 +1469,6 @@ class EquipmentManagementController extends Controller{
                 return $this->responseController->makeResponse(true, 'El almacen no existe.', [], 500);
             }
         }
-        
-
 
         // Se desencripta la familia 
         $familyCode = $this->encryptionController->decrypt($form['family']);
@@ -1498,7 +1486,6 @@ class EquipmentManagementController extends Controller{
             return $this->responseController->makeResponse(true, 'La familia seleccionada no existe.', [], 404);
         }
 
-
         // Se desencripta la subfamilia
         $subfamilyCode = $this->encryptionController->decrypt($form['subfamily']);
         if(!$subfamilyCode){
@@ -1620,7 +1607,6 @@ class EquipmentManagementController extends Controller{
             return $this->responseController->makeResponse(true, 'La fecha de término de la grantía no puede ser menor o igual a la fecha de inicio de la garantía.', [], 400);
         }
 
-
         // Se desencripta el numero del proveedor
         $providerID = $this->encryptionController->decrypt($form['equipment_provider']);
         if(!$providerID){
@@ -1635,7 +1621,6 @@ class EquipmentManagementController extends Controller{
         if(is_null($provider)){
             return $this->responseController->makeResponse(true, 'La proveedor seleccionada no existe.', [], 404);
         }
-
         
         // Se desencripta el número de serie
         $serialNumer = $this->encryptionController->decrypt($form['serial_number']);
@@ -1706,7 +1691,6 @@ class EquipmentManagementController extends Controller{
         $now = $this->functionsController->now();
         $nowStr = $now->toDateTimeString();
         
-
         $numberItems = intval($form['number_items']);
         for ($i=0; $i < $numberItems; $i++) { 
             // Se ingresa la información a la tabla de los precódigos de los equipamientos
@@ -2456,12 +2440,10 @@ class EquipmentManagementController extends Controller{
                 'EQUI_NIOR' => $pendingEquipment->PCEQ_NIOR,
                 'EQUI_OCOR' => $pendingEquipment->PCEQ_OCOR,
                 'EQUI_ELOR' => $pendingEquipment->PCEQ_ELOR,
-
                 'EQUI_ALMA' => $pendingEquipment->PCEQ_ALMA,
                 'EQUI_AREA' => $pendingEquipment->PCEQ_AREA,
                 'EQUI_NIVE' => $pendingEquipment->PCEQ_NIVE,
                 'EQUI_ZONA' => $pendingEquipment->PCEQ_ZONA,
-
                 'EQUI_IPCC' => $pendingEquipment->PCEQ_IPCC,
                 'EQUI_PPCC' => $pendingEquipment->PCEQ_PPCC,
                 'EQUI_KIOR' => $pendingEquipment->PCEQ_KIOR,

+ 18 - 1
sistema-mantenimiento-back/app/Http/Controllers/FunctionsController.php

@@ -327,6 +327,24 @@ class FunctionsController extends Controller{
       return "http://git.ittec.mx/";
     }
 
+    public function validPhoneNumber(string $number) : bool {
+        if(intval($number) <= 0) return false;
+
+        $validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
+        $numberArr = str_split($number);
+        $validNumber = '';
+
+        foreach($numberArr as $char){
+            if(in_array($char, $validChars)) $validNumber .= $char;
+        }
+
+        if(strlen($validNumber) >= 10 && strlen($validNumber) <= 11){
+            return true;
+        }else{
+            return false;
+        }
+    }
+
     public function unaccent(string $value): string{
         $transliteration = array(
         'IJ' => 'I', 'Ö' => 'O','Œ' => 'O','Ü' => 'U','ä' => 'a','æ' => 'a',
@@ -426,5 +444,4 @@ class FunctionsController extends Controller{
         $str = str_replace( array_keys( $transliteration ),  array_values( $transliteration ), $value);
         return $str;
     }
-
 }

+ 277 - 0
sistema-mantenimiento-back/app/Http/Controllers/NotificationsController.php

@@ -0,0 +1,277 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Support\Facades\DB;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Support\Carbon;
+use ElephantIO\Client;
+
+class NotificationsController extends Controller{
+    private $responseController;
+    private $encryptionController;
+    private $functionsController;
+    private $documentManagementController;
+
+    public function __construct(){
+        $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->functionsController = new FunctionsController();
+        $this->documentManagementController = new DocumentManagementController();
+    }
+
+    public function emitNotification(
+        string $module,
+        string $title,
+        string $content,
+        array $actions,
+        array $audience,
+        string $idUser,
+        int $line,
+        object $socket,
+        int $idOrder = null,
+        string $orderType = null
+    ) : bool {
+        $moduleObj = DB::table('S002V01TMODU')->where([
+            ['MODU_NULI', '=', $line],
+            ['MODU_IDMO', '=', $module]
+        ])->first();
+
+        if(is_null($moduleObj)) return false;
+        if(strlen($title) < 1 || strlen($title) > 150) return false;
+
+        $scope = [];
+        foreach($audience as $user){
+            $scope[] = [
+                'USUARIO' => $user,
+                'ESTADO' => 'No leído'
+            ];
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $audienceStr = json_encode($audience);
+        $idNotification = DB::table('S002V01TNOTI')->insertGetId([
+            'NOTI_NULI' => $line,
+            'NOTI_IDMO' => $module,
+            'NOTI_ASUN' => $title,
+            'NOTI_CONT' => $content,
+            'NOTI_IDOT' => $idOrder,
+            'NOTI_TIOR' => $orderType,
+            'NOTI_ACCI' => json_encode($actions),
+            'NOTI_AUDI' => $audienceStr,
+            'NOTI_ALCA' => json_encode($scope),
+            'NOTI_USRE' => $idUser,
+            'NOTI_FERE' => $nowStr,
+        ]);
+
+        $idNotificationEnc = $this->encryptionController->encrypt($idNotification);
+        $audienceEnc = $this->encryptionController->encrypt($audienceStr);
+
+        $notificationData = ['idNotification' => $idNotificationEnc, 'audience' => $audienceEnc];
+        $socket->emit('new_notification', $notificationData);
+
+        return true;
+    }
+
+    public function getNotification($idNotification, $setRead, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $idNotification = $this->encryptionController->decrypt($idNotification);
+        if(!$idNotification){
+            return $this->responseController->makeResponse(true, 'El ID de la notificación solicitada no está encriptado correctamente', [], 400);
+        }
+
+        $notification = DB::table('S002V01TNOTI')->select([
+            'NOTI_IDNO AS ID_NOTIFICACION',
+            'NOTI_IDMO AS ID_MODULO',
+            'MODU_NOMO AS MODULO',
+            'NOTI_ASUN AS TITULO',
+            'NOTI_CONT AS CUERPO_NOTIFICACION',
+            'NOTI_IDOT AS ID_ORDEN',
+            'NOTI_TIOR AS TIPO_ORDEN',
+            'NOTI_ACCI AS ACCIONES',
+            'NOTI_AUDI AS AUDIENCIA',
+            'NOTI_ALCA AS ALCANCE',
+            'NOTI_USRE AS USRREG',
+            'NOTI_FERE AS FECREG',
+        ])->join('S002V01TMODU', 'MODU_IDMO', '=', 'NOTI_IDMO')->where([
+            ['NOTI_NULI', '=', $line],
+            ['NOTI_IDNO', '=', $idNotification]
+        ])->first();
+
+        if(is_null($notification)){
+            return $this->responseController->makeResponse(true, 'La notificación consultada no está registrada.', [], 404);
+        }
+
+        $notification->ID_NOTIFICACION = $this->encryptionController->encrypt($notification->ID_NOTIFICACION);
+        $notification->ID_MODULO = $this->encryptionController->encrypt($notification->ID_MODULO);
+
+        if(!is_null($notification->ID_ORDEN)){
+            $notification->ID_ORDEN = $this->encryptionController->encrypt($notification->ID_ORDEN);
+        }
+
+        $audienceArr = json_decode($notification->AUDIENCIA, true);
+        if(!in_array($idUser, $audienceArr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no puede leer la notificación.', [], 401);
+        }
+
+        foreach($audienceArr as $key=>$user){
+            $audienceArr[$key] = $this->encryptionController->encrypt($user);
+        }
+
+        $notification->AUDIENCIA = json_encode($audienceArr);
+        $scopeArr = json_decode($notification->ALCANCE, true);
+        foreach($scopeArr as $key=>$item){
+            $item['USUARIO'] = $this->encryptionController->encrypt($item['USUARIO']);
+            $scopeArr[$key] = $item;
+        }
+
+        if($setRead == 'S'){
+            $scopeArrUpd = json_decode($notification->ALCANCE, true);
+
+            foreach($scopeArrUpd as $key=>$item){
+                if($item['USUARIO'] == $idUser){
+                    $item['ESTADO'] = 'Leído';
+                    $scopeArrUpd[$key] = $item;
+                }
+            }
+
+            $scopeStrUpd = json_encode($scopeArrUpd);
+            DB::table('S002V01TNOTI')->where([
+                ['NOTI_NULI', '=', $line],
+                ['NOTI_IDNO', '=', $idNotification]
+            ])->update([
+                'NOTI_ALCA' => $scopeStrUpd,
+            ]);
+        }
+
+        $notification->ALCANCE = json_encode($scopeArr);
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $notification->USRREG]
+        ])->first();
+
+        $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $notification->USRREG = $nameReg . ' (' . $notification->USRREG . ')';
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            '-',
+            '-',
+            '-',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la notificación #$idNotification.",
+            $idUser,
+            $nowStr,
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $notification);
+    }
+
+    public function getNotificationsByUser($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $notifications = DB::table('S002V01TNOTI')->select([
+            'NOTI_IDNO AS ID_NOTIFICACION',
+            'NOTI_IDMO AS ID_MODULO',
+            'MODU_NOMO AS MODULO',
+            'NOTI_ASUN AS TITULO',
+            'NOTI_CONT AS CUERPO_NOTIFICACION',
+            'NOTI_IDOT AS ID_ORDEN',
+            'NOTI_TIOR AS TIPO_ORDEN',
+            'NOTI_AUDI AS AUDIENCIA',
+            'NOTI_ALCA AS ALCANCE',
+            'NOTI_USRE AS USRREG',
+            'NOTI_FERE AS FECREG',
+        ])->join('S002V01TMODU', 'MODU_IDMO', '=', 'NOTI_IDMO')
+        ->where('NOTI_NULI', '=', $line)
+        ->whereJsonContains('NOTI_AUDI', $idUser)
+        ->orderBy('NOTI_FERE', 'desc')->get()->all();
+
+        foreach($notifications as $key=>$notification){
+            $notification->ID_NOTIFICACION = $this->encryptionController->encrypt($notification->ID_NOTIFICACION);
+            $notification->ID_MODULO = $this->encryptionController->encrypt($notification->ID_MODULO);
+
+            if(!is_null($notification->ID_ORDEN)){
+                $notification->ID_ORDEN = $this->encryptionController->encrypt($notification->ID_ORDEN);
+            }
+
+            $audienceArr = json_decode($notification->AUDIENCIA, true);
+            foreach($audienceArr as $k=>$v){
+                $audienceArr[$k] = $this->encryptionController->encrypt($v);
+            }
+
+            $notification->AUDIENCIA = json_encode($audienceArr);
+            $scopeArr = json_decode($notification->ALCANCE, true);
+            foreach($scopeArr as $k=>$v){
+                $v['USUARIO'] = $this->encryptionController->encrypt($v['USUARIO']);
+                $scopeArr[$k] = $v;
+            }
+
+            $notification->ALCANCE = json_encode($scopeArr);
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $notification->USRREG]
+            ])->first();
+
+            $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+            $notification->USRREG = $nameReg . " (" . $notification->USRREG . ")";
+            $notifications[$key] = $notification;
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            '-',
+            '-',
+            '-',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó su feed de notificaciones.",
+            $idUser,
+            $nowStr,
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $notifications);
+    }
+}

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

@@ -85,7 +85,7 @@ class PreventiveMaintenanceController extends Controller{
 
         $activator = DB::table('S002V01TACTI')->where([
             ['ACTI_NULI', '=', $form['linea']],
-            ['ACTI_IDCO', '=', $form['activator']]
+            ['ACTI_IDAC', '=', $form['activator']]
         ])->first();
         
         if(is_null($activator)){
@@ -332,7 +332,7 @@ class PreventiveMaintenanceController extends Controller{
             if($order->OTPR_ACAS > 0){
                 $acti = DB::table('S002V01TACTI')->where([
                     ['ACTI_NULI', '=', $line],
-                    ['ACTI_IDCO', '=', $order->OTPR_ACAS]
+                    ['ACTI_IDAC', '=', $order->OTPR_ACAS]
                 ])->first();
 
                 if(!is_null($acti)){
@@ -1059,7 +1059,7 @@ class PreventiveMaintenanceController extends Controller{
         $activatorTypes = ['Calendario' => 'CA', 'Sintoma' => 'SI', 'Medida' => 'ME', 'Valor' => 'VA'];
         $activator = DB::table('S002V01TACTI')->where([
             ['ACTI_NULI', '=', $line],
-            ['ACTI_IDCO', '=', $workOrder->OTPR_ACAS],
+            ['ACTI_IDAC', '=', $workOrder->OTPR_ACAS],
         ])->first();
 
         $startDateTimeArr = explode(' ', $workOrder->OTPR_FIAP);
@@ -2304,7 +2304,7 @@ class PreventiveMaintenanceController extends Controller{
             'OTPR_ACAS AS ACTIVADOR',
             'ACTI_PRIO AS PRIORIDAD',
             'ACTI_TIAC AS TIPOACTIVADOR'
-        ])->join('S002V01TACTI', 'ACTI_IDCO', '=', 'OTPR_ACAS')->where([
+        ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([	
             ['OTPR_NULI', '=', $line],
             ['OTPR_ESTA', '=', 'A']
         ])->get()->all();
@@ -2358,7 +2358,7 @@ class PreventiveMaintenanceController extends Controller{
         $fecIniObj = new Carbon($fecIni . ' 00:00:00');
         $fecFinObj = new Carbon($fecFin . ' 23:59:59');
 
-        $workOrders = DB::table('S002V01TOTPR')->join('S002V01TACTI', 'ACTI_IDCO', '=', 'OTPR_ACAS')->where([
+        $workOrders = DB::table('S002V01TOTPR')->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
             ['OTPR_NULI', '=', $line],
             ['OTPR_ESTA', '=', 'A'],
         ])->get()->all();
@@ -3277,7 +3277,7 @@ class PreventiveMaintenanceController extends Controller{
             'ACTI_PRIO AS PRIORIDAD',
             'ACTI_TIAC AS TIPOACTIVADOR',
             'ACTI_COAC AS CONFIGACTI'
-        ])->join('S002V01TACTI', 'ACTI_IDCO', '=', 'OTPR_ACAS')->where([
+        ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
             ['OTPR_NULI', '=', $line],
             ['OTPR_IDOT', '=', $idOrder]
         ])->first();
@@ -3450,7 +3450,7 @@ class PreventiveMaintenanceController extends Controller{
             'ACTI_PRIO AS PRIORIDAD',
             'ACTI_TIAC AS TIPOACTIVADOR',
             'ACTI_COAC AS CONFIGACTIVADOR',
-        ])->join('S002V01TACTI', 'ACTI_IDCO', '=', 'OTPR_ACAS')->where([
+        ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
             ['OTPR_NULI', '=', $line],
             ['OTPR_IDOT', '=', $idOrder],
         ])->first();
@@ -3541,7 +3541,7 @@ class PreventiveMaintenanceController extends Controller{
         }
 
         $activator = DB::table('S002V01TACTI')->where([
-            ['ACTI_IDCO', '=', $idActivator],
+            ['ACTI_IDAC', '=', $idActivator],
             ['ACTI_NULI', '=', $form['linea']]
         ])->first();
 
@@ -3564,7 +3564,7 @@ class PreventiveMaintenanceController extends Controller{
         ]);
 
         DB::table('S002V01TACTI')->where([
-            ['ACTI_IDCO', '=', $idActivator],
+          ['ACTI_IDAC', '=', $idActivator],
             ['ACTI_NULI', '=', $form['linea']]
         ])->update([
             'ACTI_PRIO' => $form['priority'],
@@ -3957,7 +3957,7 @@ class PreventiveMaintenanceController extends Controller{
         }
 
         $order = DB::table('S002V01TOTPR')->join(
-            'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDCO',
+            'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC',
         )->where([
             ['OTPR_NULI', '=', $line],
             ['OTPR_IDOT', '=', $idOrder]
@@ -4229,7 +4229,7 @@ class PreventiveMaintenanceController extends Controller{
         }
 
         $order = DB::table('S002V01TOTPR')->join(
-            'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDCO',
+            'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC',
         )->where([
             ['OTPR_NULI', '=', $line],
             ['OTPR_IDOT', '=', $idOrder]

+ 59 - 39
sistema-mantenimiento-back/routes/api.php

@@ -64,6 +64,8 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::get("/get-module-functions/{idMod}/{id}/{line}",                             "App\Http\Controllers\SystemAdministratorController@getModuleFunctions");           //Obtiene las funciones de un módulo
     Route::get("/get-submodules/{idMod}/{id}/{line}",                                   "App\Http\Controllers\SystemAdministratorController@getSubmodules");                //Obtiene todos los submódulos pertenecientes a algún módulo
     Route::get("/get-submodule-functions/{idMod}/{idSub}/{id}/{line}",                  "App\Http\Controllers\SystemAdministratorController@getSubmoduleFunctions");        //Obtiene todos los submódulos pertenecientes a algún módulo
+    Route::get("/get-notification/{idNotification}/{setRead}/{idUser}/{line}",          "App\Http\Controllers\NotificationsController@getNotification");        //Obtiene todos los submódulos pertenecientes a algún módulo
+    Route::get("/get-notifications-by-user/{idUser}/{line}",                            "App\Http\Controllers\NotificationsController@getNotificationsByUser");        //Obtiene todos los submódulos pertenecientes a algún módulo
     //Módulo de usuarios y perfiles
     Route::post("/create-user",                                                         "App\Http\Controllers\UsersProfilesController@createUser");                         //Registra nuevos usuarios en la base de datos
     Route::post("/delete-user",                                                         "App\Http\Controllers\UsersProfilesController@deleteUser");                         //Cambia el estado de los usuarios a Eliminado
@@ -205,9 +207,23 @@ Route::middleware(['jwt.auth'])->group(function(){
     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
     //Módulo contadores y activadores
+    Route::get("/activator/consult/{idUser}/{line}",                                    "App\Http\Controllers\CountersActivatorsController@getActivators");
     Route::get("/get-activators-by-type/{type}/{idUser}/{line}",                        "App\Http\Controllers\CountersActivatorsController@getActivatorsByType");
     Route::get("/get-activator/{idActi}/{idUser}/{line}",                               "App\Http\Controllers\CountersActivatorsController@getActivator");
+    Route::get("/counter/consult/{idUser}/{line}",                                      "App\Http\Controllers\CountersActivatorsController@getCounters");
+    Route::get("/counter/consult/only/{idCounter}/{idUser}/{line}",                     "App\Http\Controllers\CountersActivatorsController@getCounter");
+    Route::get("/counter/consult/by-equipment/{equipment}/{idUser}/{line}",             "App\Http\Controllers\CountersActivatorsController@getCountersByEquipment");
+    Route::get("/counter/consult/last-measure/{idCounter}/{idUser}/{line}",             "App\Http\Controllers\CountersActivatorsController@getCounterLastMeasure");
+    Route::get("/counter/consult/measures/{idCo}/{ord}/{dir}/{lim}/{off}/{idUs}/{lin}", "App\Http\Controllers\CountersActivatorsController@getCounterMeasures");
+    Route::get("/counter/consult/measures-length/{idCounter}/{idUser}/{line}",          "App\Http\Controllers\CountersActivatorsController@getCounterMeasuresLength");
+    Route::get("/counter/consult/related-counters/{idCounter}/{idUser}/{line}",         "App\Http\Controllers\CountersActivatorsController@getRelatedCounters");
     Route::post("/register-activator",                                                  "App\Http\Controllers\CountersActivatorsController@registerActivator");
+    Route::post("/activator/update",                                                    "App\Http\Controllers\CountersActivatorsController@updateActivator");
+    Route::post("/activator/delete",                                                    "App\Http\Controllers\CountersActivatorsController@deleteActivator");
+    Route::post("/counter/register",                                                    "App\Http\Controllers\CountersActivatorsController@registerCounter");
+    Route::post("/counter/update",                                                      "App\Http\Controllers\CountersActivatorsController@updateCounter");
+    Route::post("/counter/delete",                                                      "App\Http\Controllers\CountersActivatorsController@deleteCounter");
+    Route::post("/counter/relate-counters",                                             "App\Http\Controllers\CountersActivatorsController@relateCounters");
     //Módulo gestión del personal de mantenimiento
     Route::get("/employee/consult/{idUser}/{line}",                                     "App\Http\Controllers\EmployeeController@getConsultOfEmployees");
     Route::get("/employee/consult-for-leader/{idEmployee}/{idUser}/{line}",             "App\Http\Controllers\EmployeeController@getConsultOfEmployeesForLeader");
@@ -215,6 +231,7 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::get("/employee/contracts/employees/{idUser}/{line}",                         "App\Http\Controllers\EmployeeController@getContractsOfEveryEmployee");
     Route::get("/employee/contracts/history/{idEmployee}/{idUser}/{line}",              "App\Http\Controllers\EmployeeController@getDetailsOfContractsByEmployee");
     Route::get("/employee/orders/{idEmployee}/{idUser}/{line}",                         "App\Http\Controllers\EmployeeController@getInterventionsByEmployee");
+    Route::get("/employee/consult-for-leader/{idEmployee}/{idUser}/{line}",             "App\Http\Controllers\EmployeeController@getConsultOfEmployeesForLeader");
     Route::get("/subcontract/consult/{idUser}/{line}",                                  "App\Http\Controllers\SubcontractController@getConsultOfSubcontratists");
     Route::get("/subcontract/only/{idSub}/{idUser}/{line}",                             "App\Http\Controllers\SubcontractController@getSubcontratistById");
     Route::get("/subcontract/contracts/subcontratists/{idUser}/{line}",                 "App\Http\Controllers\SubcontractController@getContractsOfEverySubcontratist");
@@ -262,6 +279,29 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::post("/occupation/delete",                                                   "App\Http\Controllers\EquipmentManagementController@deleteOccupation");
     Route::post("/equipment/pre-codification",                                          "App\Http\Controllers\EquipmentManagementController@saveEquipmentPreCodified");
     Route::post("/equipment/pre-codification/status/update",                            "App\Http\Controllers\EquipmentManagementController@changePreCodedEquipmentStatus");
+    //Módulo gestión de mantenimiento correctivo
+    Route::get("corrective-maintenance/get-work-orders/{idUser}/{line}",                "App\Http\Controllers\CorrectiveMaintenanceController@getWorkOrders");
+    Route::get("corrective-maintenance/get-work-order/{idOrder}/{idUser}/{line}",       "App\Http\Controllers\CorrectiveMaintenanceController@getWorkOrder");
+    Route::get("corrective-maintenance/get-work-order-clasifications/{idUser}/{line}",  "App\Http\Controllers\CorrectiveMaintenanceController@getWorkOrderClasifications");
+    Route::get("corrective-maintenance/get-responsibe-users/{idUser}/{line}",           "App\Http\Controllers\CorrectiveMaintenanceController@getResponsibleUsers");
+    Route::get("corrective-maintenance/get-security-managements/{idUser}/{line}",       "App\Http\Controllers\CorrectiveMaintenanceController@getSegurityManagements");
+    Route::get("corrective-maintenance/get-security-management/{idMan}/{idUs}/{line}",  "App\Http\Controllers\CorrectiveMaintenanceController@getSecurityManagement");
+    Route::get("corrective-maintenance/get-block-registers/{idUser}/{line}",            "App\Http\Controllers\CorrectiveMaintenanceController@getBlockRegisters");
+    Route::get("corrective-maintenance/get-work-order-status-history/{ord}/{usr}/{li}", "App\Http\Controllers\CorrectiveMaintenanceController@getWorkOrderStatusHistory");
+    Route::get("corrective-maintenance/get-reports/{type}/{sd}/{ed}/{idUser}/{line}",   "App\Http\Controllers\CorrectiveMaintenanceController@getReports");
+    Route::post("corrective-maintenance/register-work-order",                           "App\Http\Controllers\CorrectiveMaintenanceController@registerWorkOrder");
+    Route::post("corrective-maintenance/update-work-order",                             "App\Http\Controllers\CorrectiveMaintenanceController@updateWorkOrder");
+    Route::post("corrective-maintenance/delete-work-order",                             "App\Http\Controllers\CorrectiveMaintenanceController@deleteWorkOrder");
+    Route::post("corrective-maintenance/approve-work-order",                            "App\Http\Controllers\CorrectiveMaintenanceController@approveWorkOrder");
+    Route::post("corrective-maintenance/start-work-order",                              "App\Http\Controllers\CorrectiveMaintenanceController@startWorkOrder");
+    Route::post("corrective-maintenance/update-work-order-status",                      "App\Http\Controllers\CorrectiveMaintenanceController@updateWorkOrderStatus");
+    Route::post("corrective-maintenance/transfer-work-order",                           "App\Http\Controllers\CorrectiveMaintenanceController@transferWorkOrder");
+    Route::post("corrective-maintenance/register-security-management",                  "App\Http\Controllers\CorrectiveMaintenanceController@registerSecurityManagement");
+    Route::post("corrective-maintenance/update-security-management",                    "App\Http\Controllers\CorrectiveMaintenanceController@updateSecurityManagement");
+    Route::post("corrective-maintenance/delete-security-management",                    "App\Http\Controllers\CorrectiveMaintenanceController@deleteSecurityManagement");
+    Route::post("corrective-maintenance/register-block",                                "App\Http\Controllers\CorrectiveMaintenanceController@registerBlock");
+    Route::post("corrective-maintenance/unblock-register",                              "App\Http\Controllers\CorrectiveMaintenanceController@unblockRegister");
+    Route::post("corrective-maintenance/generate-report",                               "App\Http\Controllers\CorrectiveMaintenanceController@generateReport");
 });
 
 // Module (FUNCIONALES)
@@ -379,13 +419,13 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::post('acquisition-management/invoice/compare-invoice',                             [InvoiceControlController::class, 'compareInvoice']);
 
     // Module: ANFA
-    Route::get ('failure-analysis/get-list-failure/{user}/{line}',                                      [FailureListController::class,  'getFailures']);
-    Route::get ('failure-analysis/get-list-failure-actives/{user}/{line}',                              [FailureListController::class,  'getFailuresActives']);
-    Route::get ('failure-analysis/get-list-failure-by-id/{idFailure}/{user}/{line}',                    [FailureListController::class,  'getFailureById']);
+    Route::get ('failure-analysis/get-list-failure/{user}/{line}',                       [FailureListController::class,  'getFailures']);
+    Route::get ('failure-analysis/get-list-failure-actives/{user}/{line}',               [FailureListController::class,  'getFailuresActives']);
+    Route::get ('failure-analysis/get-list-failure-by-id/{idFailure}/{user}/{line}',     [FailureListController::class,  'getFailureById']);
     Route::get ('failure-analysis/get-list-failure-by-classification/{idFailure}/{user}/{line}',        [FailureListController::class,  'getFailureListByClassification']);
-    Route::post('failure-analysis/register-list-failure',                                               [FailureListController::class,  'registerFailures']);
-    Route::post('failure-analysis/update-list-failure',                                                 [FailureListController::class,  'updateFailures']);
-    Route::post('failure-analysis/delete-list-failure',                                                 [FailureListController::class,  'deleteFailures']);
+    Route::post('failure-analysis/register-list-failure',                                [FailureListController::class,  'registerFailures']);
+    Route::post('failure-analysis/update-list-failure',                                  [FailureListController::class,  'updateFailures']);
+    Route::post('failure-analysis/delete-list-failure',                                  [FailureListController::class,  'deleteFailures']);
 
     Route::get ('failure-analysis/get-symptoms/{user}/{line}',                              [SymptomListController::class,  'getSymptoms']);
     Route::get ('failure-analysis/get-symptoms-actives/{user}/{line}',                      [SymptomListController::class,  'getSymptomsActives']);
@@ -395,8 +435,8 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::post('failure-analysis/update-symptom',                                          [SymptomListController::class,  'updateSymptom']);
     Route::post('failure-analysis/delete-symptom',                                          [SymptomListController::class,  'deleteSymptom']);
 
-    Route::get ('failure-analysis/get-failure-log/{user}/{line}',                                   [FailureLogController::class,  'getFailureLog']);
-    Route::get ('failure-analysis/get-history-failure-equipment/{equipment}/{user}/{line}',         [FailureLogController::class,  'getHistoryFailureEquipment']);
+    Route::get ('failure-analysis/get-failure-log/{user}/{line}',                           [FailureLogController::class,  'getFailureLog']);
+    Route::get ('failure-analysis/get-history-failure-equipment/{equipment}/{user}/{line}', [FailureLogController::class,  'getHistoryFailureEquipment']);
     Route::get ('failure-analysis/get-details-history-failure-equipment/{failure}/{user}/{line}',   [FailureLogController::class,  'getDetailsHistoryFailureEquipment']);
     Route::get ('failure-analysis/get-equipment-by-failure/{failure}/{user}/{line}',                [FailureLogController::class,  'getEquipmentByFailure']);
     Route::get ('failure-analysis/get-alarm-emission-from-failures/{user}/{line}',                                [FailureLogController::class,  'getAlarmEmissionFromFailures']);
@@ -406,46 +446,26 @@ Route::middleware(['jwt.auth'])->group(function(){
     // Module: COAC
     Route::get ('counters-and-triggers/get-catalog-measures/{user}/{line}',                      [CatalogMeasuresController::class, 'getMeasures']);
     Route::get ('counters-and-triggers/get-catalog-measures-actives/{user}/{line}',              [CatalogMeasuresController::class, 'getMeasuresActives']);
+    Route::get ('counters-and-triggers/get-magnitudes/{user}/{line}',                            [CatalogMeasuresController::class, 'getMagnitudes']);
+    Route::get ('counters-and-triggers/get-units-by-magnitude/{idMagnitude}/{user}/{line}',      [CatalogMeasuresController::class, 'getUnitsByMagnitude']);
+    Route::get ('counters-and-triggers/get-magnitude/{idMagnitude}/{user}/{line}',               [CatalogMeasuresController::class, 'getMagnitude']);
+    Route::get ('counters-and-triggers/get-unit/{idMagnitude}/{idUnit}/{user}/{line}',           [CatalogMeasuresController::class, 'getUnit']);
     Route::post('counters-and-triggers/register-catalog-measures',                               [CatalogMeasuresController::class, 'registerMeasures']);
     Route::post('counters-and-triggers/update-catalog-measures',                                 [CatalogMeasuresController::class, 'updateMeasures']);
     Route::post('counters-and-triggers/delete-catalog-measures',                                 [CatalogMeasuresController::class, 'deleteMeasures']);
+    Route::post('counters-and-triggers/register-magnitude',                                      [CatalogMeasuresController::class, 'registerMagnitude']);
+    Route::post('counters-and-triggers/update-magnitude',                                        [CatalogMeasuresController::class, 'updateMagnitude']);
+    Route::post('counters-and-triggers/delete-magnitude',                                        [CatalogMeasuresController::class, 'deleteMagnitude']);
 
     
     // Module: GEIN
-    Route::post('inventory-management/register-artitle-without-order',                  [StockController::class, 'createArtitleWithoutOrder']);
-
-    Route::get ('inventory-management/get-warehouse/{user}/{line}',                         [StockController::class, 'getWarehouse']);
-    Route::get ('inventory-management/get-warehouse-by-id/{idWarehouse}/{user}/{line}',     [StockController::class, 'getWarehouseById']);
-    Route::get ('inventory-management/get-warehouse-actives/{user}/{line}',                 [StockController::class, 'getWarehouseActives']);
-    Route::post('inventory-management/create-warehouse',                                    [StockController::class, 'createWarehouse']);
-    Route::put ('inventory-management/update-warehouse/{idWarehouse}',                      [StockController::class, 'updateWarehouse']);
-    Route::put ('inventory-management/delete-warehouse/{idWarehouse}',                      [StockController::class, 'deleteWarehouse']);
-
-    Route::get ('inventory-management/get-area-by-warehouse/{idWarehouse}/{user}/{line}',           [StockController::class, 'getAreaByWarehouse']);
-    Route::get ('inventory-management/get-area-by-id/{idArea}/{user}/{line}',                       [StockController::class, 'getAreaById']);
-    Route::get ('inventory-management/get-area-by-warehouse-actives/{idWarehouse}/{user}/{line}',   [StockController::class, 'getAreaByWarehouseActives']);
-    Route::post ('inventory-management/register-area',                                              [StockController::class, 'registerArea']);
-    Route::put ('inventory-management/update-area/{idArea}',                                        [StockController::class, 'updateArea']);
-    Route::put ('inventory-management/delete-area/{idArea}',                                        [StockController::class, 'deleteArea']);
-
-    Route::get ('inventory-management/get-level-by-area-warehouse/{idWarehouse}/{idArea}/{user}/{line}',            [StockController::class, 'getLevelByAreaWarehouse']);
-    Route::get ('inventory-management/get-level-by-id/{idLevel}/{user}/{line}',                                     [StockController::class, 'getLevelById']);
-    Route::get ('inventory-management/get-level-by-area-warehouse-actives/{idWarehouse}/{idArea}/{user}/{line}',    [StockController::class, 'getLevelByAreaWarehouseActives']);
-    Route::post('inventory-management/register-level',                                                              [StockController::class, 'registerLevel']);
-    Route::put ('inventory-management/update-level/{idLevel}',                                                      [StockController::class, 'updateLevel']);
-    Route::put ('inventory-management/delete-level/{idLevel}',                                                      [StockController::class, 'deleteLevel']);
-
-    Route::get ('inventory-management/get-zone-by-level-area-warehouse/{idWarehouse}/{idArea}/{idLevel}/{user}/{line}',         [StockController::class, 'getZoneByLevelAreaWarehouse']);
-    Route::get ('inventory-management/get-zone-by-id/{idZone}/{user}/{line}',                                                   [StockController::class, 'getZoneById']);
-    Route::get ('inventory-management/get-zone-by-level-area-warehouse-actives/{idWarehouse}/{idArea}/{idLevel}/{user}/{line}', [StockController::class, 'getZoneByLevelAreaWarehouseActive']);
-    Route::post('inventory-management/register-zone',                                                                           [StockController::class, 'registerZone']);
-    Route::put ('inventory-management/update-zone/{idZone}',                                                                    [StockController::class, 'updateZone']);
-    Route::put ('inventory-management/delete-zone/{idZone}',                                                                    [StockController::class, 'deleteZone']);
+    Route::post('inventory-management/register-artitle-without-order', [StockController::class, 'createArtitleWithoutOrder']);
     
-    Route::post ('inventory-management/register-to-stock', [StockController::class, 'registerToStock']);
+    Route::get ('inventory-management/get-warehouse/{user}/{line}', [StockController::class, 'getWarehouse']);
+    Route::post('inventory-management/create-warehouse', [StockController::class, 'createWarehouse']);
     
+    // Localidad
     
-    // Localidad    
     Route::get ('catalog/get-payment-method-active/{line_number}',            [CatalogController::class, 'getPaymentMethodActive']);
     Route::get ('catalog/get-tax-regime-active/{line}',                       [CatalogController::class, 'getTaxRegimeActive']);
     Route::get ('catalog/get-coins-active/{line}',                            [CatalogController::class, 'getCatalogCoinsActive']);

Some files were not shown because too many files changed in this diff