Browse Source

Actualización de controladores

Jose Brito 1 day ago
parent
commit
38288d3cd0

+ 350 - 306
sistema-mantenimiento-back/app/Http/Controllers/AcquisitionManagementController.php

@@ -34,7 +34,6 @@ class AcquisitionManagementController extends Controller
         $this->processManagementController = new ProcessManagementController();
     }
 
-
     public function getFamiliesAndSubfamilies ($user, $line) {
         try {
             $arrFamilias = DB::table('S002V01TFAMI')
@@ -92,15 +91,16 @@ class AcquisitionManagementController extends Controller
             );
         }
         
-
         return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrFamilias);
     }
+
     public function registerFamily(Request $request){
         $valitador = Validator::make($request->all(), [
             'FAMILIA' => 'required|string|max:50',
             'LINE' => 'required|integer',
             'USER' => 'required|string'
         ]);
+
         if ($valitador->fails()) {
             return $this->responseController->makeResponse(
                 true,
@@ -118,8 +118,8 @@ class AcquisitionManagementController extends Controller
             DB::rollBack();
             return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
         }
-        $usuario = $arrResponseCheckUser['response'];
 
+        $usuario = $arrResponseCheckUser['response'];
         $now = $this->functionsController->now();
         $currentDate = $now->toDateTimeString();
 
@@ -144,6 +144,7 @@ class AcquisitionManagementController extends Controller
         DB::commit();
         return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
     }
+
     public function getUnits($user, $line) {
         try {
             $arrFamilias = DB::table('S002V01TUNID')
@@ -165,10 +166,11 @@ class AcquisitionManagementController extends Controller
                 500
             );
         }
+
         return $this->responseController->makeResponse(false, "ÉXITO: Consulta exitosa", $arrFamilias);
     }
-    public function getUnitsActives($user, $line) {
 
+    public function getUnitsActives($user, $line) {
         $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
         if ($arrResponseCheckUser['error']) {
             DB::rollBack();
@@ -195,14 +197,17 @@ class AcquisitionManagementController extends Controller
                 500
             );
         }
+
         return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrFamilias);
     }
+
     public function registerUnit(Request $request){
         $valitador = Validator::make($request->all(), [
             'UNIDAD' => 'required|string|max:50',
             'LINE' => 'required|integer',
             'USER' => 'required|string'
         ]);
+
         if ($valitador->fails()) {
             return $this->responseController->makeResponse(
                 true,
@@ -220,8 +225,8 @@ class AcquisitionManagementController extends Controller
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'ERR_UNITS_REG001:'.$arrResponseCheckUser['msg'], [], 401);
         }
-        $usuario = $arrResponseCheckUser['response'];
 
+        $usuario = $arrResponseCheckUser['response'];
         $now = $this->functionsController->now();
         $currentDate = $now->toDateTimeString();
 
@@ -252,9 +257,11 @@ class AcquisitionManagementController extends Controller
                 401
             );
         }
+
         DB::commit();
         return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
     }
+
     public function registerSubfamily(Request $request){
         $valitador = Validator::make($request->all(), [
             'ID_FAMILIA' => 'required|integer',
@@ -262,6 +269,7 @@ class AcquisitionManagementController extends Controller
             'LINE' => 'required|integer',
             'USER' => 'required|string'
         ]);
+
         if ($valitador->fails()) {
             return $this->responseController->makeResponse(
                 true,
@@ -304,9 +312,8 @@ class AcquisitionManagementController extends Controller
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'ERR_SUBFAMILY_REG003:'.$arrResponseCheckUser['msg'], [], 401);
         }
-        $user = $arrResponseCheckUser['response'];
-
 
+        $user = $arrResponseCheckUser['response'];
         $now = $this->functionsController->now();
         $currentDate = $now->toDateTimeString();
 
@@ -328,6 +335,7 @@ class AcquisitionManagementController extends Controller
                 401
             );
         }
+
         if (!$validateInsert) {
             DB::rollBack();
             return $this->responseController->makeResponse(
@@ -337,11 +345,12 @@ class AcquisitionManagementController extends Controller
                 401
             );
         }
+
         DB::commit();
         return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
     }
-    public function getArtitles($user, $line) {
 
+    public function getArtitles($user, $line) {
         $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
         if ($arrResponseCheckUser['error']) {
             DB::rollBack();
@@ -415,11 +424,10 @@ class AcquisitionManagementController extends Controller
         }
 
         $getArtitle = json_decode(json_encode($getArtitle), true);
-        
         return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $getArtitle);
     }
-    public function getArtitleByProvider($artitle, $provider, $user, $line) {
 
+    public function getArtitleByProvider($artitle, $provider, $user, $line) {
         $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
         if ($arrResponseCheckUser['error']) {
             DB::rollBack();
@@ -450,31 +458,31 @@ class AcquisitionManagementController extends Controller
         
         try {
             $objArtitle = (array) DB::table('S002V01TDEAR')
-                ->where("ARTI_NULI", "=", $line)
-                ->where("DEAR_IDDE", "=", $idArtitle)
-                ->where("DEAR_NUPR", "=", $idProvider)
-                ->join("S002V01TARTI", "ARTI_IDAR", "=", "DEAR_IDAR")
-                ->join("S002V01TFAMI", "ARTI_COFA", "=", "FAMI_COFA")
-                ->join("S002V01TSUBF", "ARTI_COSU", "=", "SUBF_COSU")
-                ->join("S002V01TPROV", "DEAR_NUPR", "=", "PROV_NUPR")
-                ->join("S002V01TUNID", "DEAR_IDUN", "=", "UNID_IDUN")
-                ->first([
-                    "DEAR_IDDE AS ID_DESC_ARTI",
-                    "ARTI_IDAR AS ID_ARTICULO",
-                    "ARTI_NOMB AS MODELO",
-                    "FAMI_COFA AS ID_FAMILIA",
-                    "FAMI_NOFA AS FAMILIA",
-                    "SUBF_COSU AS ID_SUBFAMILIA",
-                    "SUBF_NOSU AS SUBFAMILIA",
-                    "DEAR_DESC AS DESCRIPCION",
-                    "DEAR_CARA AS CARACTERISTICAS",
-                    "DEAR_COWE AS COMPRA_WEB",
-                    "UNID_IDUN AS ID_UNIDAD",
-                    "UNID_NOMB AS UNIDAD",
-                    "DEAR_IMAG AS URL_IMAGEN",
-                    "PROV_NUPR AS ID_PROVEEDOR",
-                    "PROV_NOCO AS PROVEEDOR",
-                ]);
+            ->where("ARTI_NULI", "=", $line)
+            ->where("DEAR_IDDE", "=", $idArtitle)
+            ->where("DEAR_NUPR", "=", $idProvider)
+            ->join("S002V01TARTI", "ARTI_IDAR", "=", "DEAR_IDAR")
+            ->join("S002V01TFAMI", "ARTI_COFA", "=", "FAMI_COFA")
+            ->join("S002V01TSUBF", "ARTI_COSU", "=", "SUBF_COSU")
+            ->join("S002V01TPROV", "DEAR_NUPR", "=", "PROV_NUPR")
+            ->join("S002V01TUNID", "DEAR_IDUN", "=", "UNID_IDUN")
+            ->first([
+                "DEAR_IDDE AS ID_DESC_ARTI",
+                "ARTI_IDAR AS ID_ARTICULO",
+                "ARTI_NOMB AS MODELO",
+                "FAMI_COFA AS ID_FAMILIA",
+                "FAMI_NOFA AS FAMILIA",
+                "SUBF_COSU AS ID_SUBFAMILIA",
+                "SUBF_NOSU AS SUBFAMILIA",
+                "DEAR_DESC AS DESCRIPCION",
+                "DEAR_CARA AS CARACTERISTICAS",
+                "DEAR_COWE AS COMPRA_WEB",
+                "UNID_IDUN AS ID_UNIDAD",
+                "UNID_NOMB AS UNIDAD",
+                "DEAR_IMAG AS URL_IMAGEN",
+                "PROV_NUPR AS ID_PROVEEDOR",
+                "PROV_NOCO AS PROVEEDOR",
+            ]);
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(
                 true, 
@@ -483,6 +491,7 @@ class AcquisitionManagementController extends Controller
                 500
             );
         }
+
         if ( empty($objArtitle) ) {
             return $this->responseController->makeResponse(true, "ERR_ARTITLE_GETBYPROVIDER004: No se encontró el resultado deseado.", [], 500);
         }
@@ -490,13 +499,16 @@ class AcquisitionManagementController extends Controller
         try {
             $objArtitle['URL_IMAGEN'] = json_decode($objArtitle['URL_IMAGEN']);
             $arrUrlImage = array();
+
             foreach ($objArtitle['URL_IMAGEN'] as $key => $encImage) {
                 $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($encImage, $user, $line);
                 if ($responseDocument['error']) {
                     return $this->responseController->makeResponse(true, "ERR_ARTITLE_GETBYPROVIDER005: Ocurrió un error al obtener la URL de la imágen.", [], 500);
                 }
+
                 $arrUrlImage[] = $responseDocument['response']['public_uri'];
             }
+
             $objArtitle['URL_IMAGEN'] = $arrUrlImage;
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(
@@ -509,20 +521,20 @@ class AcquisitionManagementController extends Controller
 
         try {
             $arrInformation = DB::table('S002V01TINAR')
-                ->where('INAR_ESTA', '=', 'Activo')
-                ->where('INAR_NULI', '=', $line)
-                ->where('INAR_IDDE', '=', $objArtitle['ID_DESC_ARTI'])
-                ->join('S002V01TCAMO', 'CAMO_COMO', '=', 'INAR_COMO')
-                ->get([
-                    'INAR_IDIN AS NUMERO_INFORMACION',
-                    'INAR_CODI AS CODIGO',
-                    'INAR_MODE AS MODELO',
-                    'CAMO_COMO AS MONEDA',
-                    'CAMO_DESC AS MONEDA_DESCRIPCION',
-                    'INAR_PREC AS PRECIO',
-                    'INAR_MOMI AS MONTO_MINIMO',
-                    'INAR_CARA AS CARACTERISTICAS',
-                ]);
+            ->where('INAR_ESTA', '=', 'Activo')
+            ->where('INAR_NULI', '=', $line)
+            ->where('INAR_IDDE', '=', $objArtitle['ID_DESC_ARTI'])
+            ->join('S002V01TCAMO', 'CAMO_COMO', '=', 'INAR_COMO')
+            ->get([
+                'INAR_IDIN AS NUMERO_INFORMACION',
+                'INAR_CODI AS CODIGO',
+                'INAR_MODE AS MODELO',
+                'CAMO_COMO AS MONEDA',
+                'CAMO_DESC AS MONEDA_DESCRIPCION',
+                'INAR_PREC AS PRECIO',
+                'INAR_MOMI AS MONTO_MINIMO',
+                'INAR_CARA AS CARACTERISTICAS',
+            ]);
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(
                 true, 
@@ -535,6 +547,7 @@ class AcquisitionManagementController extends Controller
         $objArtitle['INFO_PRODUCTO'] = json_encode($arrInformation);
         return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $objArtitle);
     }
+
     public function getArticleById($idArticle, $user, $line) {
 
         $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
@@ -1905,7 +1918,7 @@ class AcquisitionManagementController extends Controller
                     'LINE_OTPR' => $idOrderPreventive,
                     'LINE_OTCO' => $idOrderCorrective,
                     'LINE_NULI' => $requestData['LINE'],
-                    'LINE_ESTA' => 'Workflow',
+                    'LINE_ESTA' => 'En espera',
                     'LINE_USRE' => $user,
                     'LINE_FERE' => $currentDate,
                     'LINE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
@@ -1954,11 +1967,11 @@ class AcquisitionManagementController extends Controller
         $strInfoRegistro = json_encode($arrInfoRegistro);
         $encInfoRegistro = $this->encController->encrypt($strInfoRegistro);
 
-        $arrResponseRequestWorkflow = $this->processManagementController->registerRequestWorkflow(1, $encToWorkflow, $encInfoRegistro, $user, $requestData['LINE']);
+        /*$arrResponseRequestWorkflow = $this->processManagementController->registerRequestWorkflow(1, $encToWorkflow, $encInfoRegistro, $user, $requestData['LINE']);
         if ($arrResponseRequestWorkflow['error']) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, $arrResponseRequestWorkflow['msg'], $arrResponseRequestWorkflow['response'], 500);
-        }
+        }*/
     
         DB::commit();
         return $this->responseController->makeResponse(false, "ÉXITO: Registro correcto");
@@ -2054,8 +2067,9 @@ class AcquisitionManagementController extends Controller
             $index = 0;
             $arrArtitles = array();
             foreach ($getSelected as $keyArtitle => $artitles) {
+                $artitles = (array) $artitles;
                 if ($keyArtitle === 0) {
-                    $arrArtitles[$index] = $artitles;
+                    $arrArtitles[$index] = (array) $artitles;
                     $arrArtitles[$index]['CANTIDAD'] = 1;
                 } else {
                     if (
@@ -2997,59 +3011,58 @@ class AcquisitionManagementController extends Controller
         }
 
         try {
-            $arrOrders = (array) DB::table('S002V01TORCO')
-                ->where('ORCO_NUOR', '=', $order)
-                ->where('ORCO_NULI', '=', $line)
-                ->where('DESP_NULI', '=', $line)
-                ->where('LINE_NULI', '=', $line)
-                ->where('PROV_NULI', '=', $line)
-                ->where('LINE_ESTA', '!=', 'Cancelado')
-                ->where('DESP_ESTA', '=', 'Activo')
-                ->where('PROV_ESTA', '=', 'Activo')
-                ->join('S002V01TLINE', 'ORCO_IDLI', '=', 'LINE_IDLI')
-                ->join('S002V01TDESP', 'ORCO_IDDE', '=', 'DESP_IDDE')
-                ->join('S002V01TPROV', 'LINE_NUPR', '=', 'PROV_NUPR')
-                ->first([
-                    'ORCO_NUOR AS NUMERO_ORDEN',
-                    'ORCO_ESTA AS ESTADO_ORDEN',
-                    'ORCO_USRE AS USUARIO_REGISTRA',
-                    'ORCO_FERE AS FECHA_REGISTRA',
-                    'ORCO_USMO AS USUARIO_MODIFICA',
-                    'ORCO_FEMO AS FECHA_MODIFICA',
-                    'LINE_IDLI AS NUMERO_SOLICITUD_COMPRA',
-                    'LINE_OTPR AS ORDEN_TRABAJO_PREVENTIVO',
-                    'LINE_OTCO AS ORDEN_TRABAJO_CORRECTIVO',
-                    'DESP_IDDE AS ID_DESPACHO',
-                    'DESP_NODE AS NOMBRE_DESPACHO',
-                    'DESP_NOMB AS NOMBRE_RESPONSABLE',
-                    'DESP_APPA AS APELLIDO_PATERNO_RESPONSABLE',
-                    'DESP_APMA AS APELLIDO_MATERNO_RESPONSABLE',
-                    'DESP_LADA AS LADA',
-                    'DESP_TELE AS TELEFONO',
-                    'DESP_CORR AS CORREO_ELECTRONICO',
-                    'DESP_CALL AS CALLE',
-                    'DESP_NUEX AS NUMERO_EXTERIOR',
-                    'DESP_NUIN AS NUMERO_INTERIOR',
-                    'DESP_COPO AS CODIGO_POSTAL',
-                    'DESP_LOCA AS LOCALIDAD',
-                    'DESP_COLO AS COLONIA',
-                    'DESP_MUNI AS MUNICIPIO',
-                    'DESP_ENTI AS ENTIDAD_FEDERATIVA',
-                    'DESP_PAIS AS PAIS',
-                    'DESP_COME AS COMENTARIOS',
-                    'PROV_NUPR AS NUMERO_PROVEEDOR',
-                    'PROV_NOCO AS NOMBRE_COMERCIAL',
-                    'PROV_NOMB AS NOMBRE_PROVEEDOR',
-                    'PROV_APPA AS APELLIDO_PATERNO_PROVEEDOR',
-                    'PROV_APMA AS APELLIDO_MATERNO_PROVEEDOR',
-                    'PROV_CORR AS CORREO_ELECTRONICO_PROVEEDOR',
-                    'PROV_LAD1 AS LADA1_PROVEEDOR',
-                    'PROV_TEL1 AS TELEFONO1_PROVEEDOR',
-                    'PROV_LAD2 AS LADA2_PROVEEDOR',
-                    'PROV_TEL2 AS TELEFONO2_PROVEEDOR',
-                    'PROV_XRFC AS RFC',
-                    'PROV_XTAX AS TAXID',
-                ]);
+            $arrOrders = (array) DB::table('S002V01TORCO')->select([
+                'ORCO_NUOR AS NUMERO_ORDEN',
+                'ORCO_ESTA AS ESTADO_ORDEN',
+                'ORCO_USRE AS USUARIO_REGISTRA',
+                'ORCO_FERE AS FECHA_REGISTRA',
+                'ORCO_USMO AS USUARIO_MODIFICA',
+                'ORCO_FEMO AS FECHA_MODIFICA',
+                'LINE_IDLI AS NUMERO_SOLICITUD_COMPRA',
+                'LINE_OTPR AS ORDEN_TRABAJO_PREVENTIVO',
+                'LINE_OTCO AS ORDEN_TRABAJO_CORRECTIVO',
+                'DESP_IDDE AS ID_DESPACHO',
+                'DESP_NODE AS NOMBRE_DESPACHO',
+                'DESP_NOMB AS NOMBRE_RESPONSABLE',
+                'DESP_APPA AS APELLIDO_PATERNO_RESPONSABLE',
+                'DESP_APMA AS APELLIDO_MATERNO_RESPONSABLE',
+                'DESP_LADA AS LADA',
+                'DESP_TELE AS TELEFONO',
+                'DESP_CORR AS CORREO_ELECTRONICO',
+                'DESP_CALL AS CALLE',
+                'DESP_NUEX AS NUMERO_EXTERIOR',
+                'DESP_NUIN AS NUMERO_INTERIOR',
+                'DESP_COPO AS CODIGO_POSTAL',
+                'DESP_LOCA AS LOCALIDAD',
+                'DESP_COLO AS COLONIA',
+                'DESP_MUNI AS MUNICIPIO',
+                'DESP_ENTI AS ENTIDAD_FEDERATIVA',
+                'DESP_PAIS AS PAIS',
+                'DESP_COME AS COMENTARIOS',
+                'PROV_NUPR AS NUMERO_PROVEEDOR',
+                'PROV_NOCO AS NOMBRE_COMERCIAL',
+                'PROV_NOMB AS NOMBRE_PROVEEDOR',
+                'PROV_APPA AS APELLIDO_PATERNO_PROVEEDOR',
+                'PROV_APMA AS APELLIDO_MATERNO_PROVEEDOR',
+                'PROV_CORR AS CORREO_ELECTRONICO_PROVEEDOR',
+                'PROV_LAD1 AS LADA1_PROVEEDOR',
+                'PROV_TEL1 AS TELEFONO1_PROVEEDOR',
+                'PROV_LAD2 AS LADA2_PROVEEDOR',
+                'PROV_TEL2 AS TELEFONO2_PROVEEDOR',
+                'PROV_XRFC AS RFC',
+                'PROV_XTAX AS TAXID',
+            ])->where([
+                ['ORCO_NUOR', '=', $order],
+                ['ORCO_NULI', '=', $line],
+                ['DESP_NULI', '=', $line],
+                ['LINE_NULI', '=', $line],
+                ['PROV_NULI', '=', $line],
+                ['LINE_ESTA', '!=', 'Cancelado'],
+                ['DESP_ESTA', '=', 'Activo'],
+                ['PROV_ESTA', '=', 'Activo'],
+            ])->join('S002V01TLINE', 'ORCO_IDLI', '=', 'LINE_IDLI')
+            ->join('S002V01TDESP', 'ORCO_IDDE', '=', 'DESP_IDDE')
+            ->join('S002V01TPROV', 'LINE_NUPR', '=', 'PROV_NUPR')->first();
         } catch ( \Throwable $th ) {
             return $this->responseController->makeResponse( 
                 true, 
@@ -3064,53 +3077,52 @@ class AcquisitionManagementController extends Controller
         }
         
         try {
-            $getArtitles = DB::table('S002V01TARSE')
-                ->where('ARSE_IDLI', '=', $arrOrders['NUMERO_SOLICITUD_COMPRA'])
-                ->where('ARSE_ESTA', '!=', 'Eliminado')
-                ->where('ARSE_NULI', '=', $line)
-                ->where('ARTI_ESTA', '=', 'Activo')
-                ->where('ARTI_NULI', '=', $line)
-                ->where('FAMI_ESTA', '=', 'Activo')
-                ->where('FAMI_NULI', '=', $line)
-                ->where('SUBF_ESTA', '=', 'Activo')
-                ->where('SUBF_NULI', '=', $line)
-                ->where('DEAR_ESTA', '=', 'Activo')
-                ->where('DEAR_NULI', '=', $line)
-                ->where('INAR_ESTA', '=', 'Activo')
-                ->where('INAR_NULI', '=', $line)
-                ->where('UNID_ESTA', '=', 'Activo')
-                ->where('UNID_NULI', '=', $line)
-                ->join('S002V01TARTI', 'ARSE_IDAR', '=', 'ARTI_IDAR')
-                ->join('S002V01TINAR', 'ARSE_IDIN', '=', 'INAR_IDIN')
-                ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
-                ->join('S002V01TFAMI', 'ARTI_COFA', '=', 'FAMI_COFA')
-                ->join('S002V01TSUBF', 'ARTI_COSU', '=', 'SUBF_COSU')
-                ->join('S002V01TUNID', 'DEAR_IDUN', '=', 'UNID_IDUN')
-                ->get([
-                    'ARSE_IDAS AS ID_ARTICULO_SELECCION',
-                    'FAMI_COFA AS CODIGO_FAMILIA',
-                    'FAMI_NOFA AS NOMBRE_FAMILIA',
-                    'SUBF_COSU AS CODIGO_SUBFAMILIA',
-                    'SUBF_NOSU AS NOMBRE_SUBFAMILIA',
-                    'ARTI_IDAR AS ID_ARTICULO',
-                    'ARTI_CODI AS CODIGO',
-                    'ARTI_NOMB AS NOMRE_ARTICULO',
-                    'DEAR_IDDE AS ID_DESCRIPCION',
-                    'DEAR_IMAG AS IMAGEN',
-                    'DEAR_DESC AS DESCRIPCION',
-                    'DEAR_CARA AS CARACTERISTICAS',
-                    'DEAR_COWE AS COMPRA_WEB',
-                    'INAR_IDIN AS ID_INFORMACION',
-                    'INAR_CODI AS CODIGO_ARTICULO',
-                    'INAR_MODE AS MODELO_ARTICULO',
-                    'INAR_COMO AS CODIGO_MONEDA',
-                    'INAR_PREC AS PRECIO',
-                    'INAR_MOMI AS MONTO_MINIMO',
-                    'INAR_CARA AS CARACTERISTIAS_INFORMACION',
-                    'UNID_IDUN AS ID_UNIDAD',
-                    'UNID_NOMB AS NOMBRE_UNIDAD',
-                    'UNID_ACRO AS ACRONIMO_UNIDAD',
-                ]);
+            $getArtitles = DB::table('S002V01TARSE')->select([
+                'ARSE_IDAS AS ID_ARTICULO_SELECCION',
+                'FAMI_COFA AS CODIGO_FAMILIA',
+                'FAMI_NOFA AS NOMBRE_FAMILIA',
+                'SUBF_COSU AS CODIGO_SUBFAMILIA',
+                'SUBF_NOSU AS NOMBRE_SUBFAMILIA',
+                'ARTI_IDAR AS ID_ARTICULO',
+                'ARTI_CODI AS CODIGO',
+                'ARTI_NOMB AS NOMRE_ARTICULO',
+                'DEAR_IDDE AS ID_DESCRIPCION',
+                'DEAR_IMAG AS IMAGEN',
+                'DEAR_DESC AS DESCRIPCION',
+                'DEAR_CARA AS CARACTERISTICAS',
+                'DEAR_COWE AS COMPRA_WEB',
+                'INAR_IDIN AS ID_INFORMACION',
+                'INAR_CODI AS CODIGO_ARTICULO',
+                'INAR_MODE AS MODELO_ARTICULO',
+                'INAR_COMO AS CODIGO_MONEDA',
+                'INAR_PREC AS PRECIO',
+                'INAR_MOMI AS MONTO_MINIMO',
+                'INAR_CARA AS CARACTERISTIAS_INFORMACION',
+                'UNID_IDUN AS ID_UNIDAD',
+                'UNID_NOMB AS NOMBRE_UNIDAD',
+                'UNID_ACRO AS ACRONIMO_UNIDAD',
+            ])->where([
+                ['ARSE_IDLI', '=', $arrOrders['NUMERO_SOLICITUD_COMPRA']],
+                ['ARSE_ESTA', '!=', 'Eliminado'],
+                ['ARSE_NULI', '=', $line],
+                ['ARTI_ESTA', '=', 'Activo'],
+                ['ARTI_NULI', '=', $line],
+                ['FAMI_ESTA', '=', 'Activo'],
+                ['FAMI_NULI', '=', $line],
+                ['SUBF_ESTA', '=', 'Activo'],
+                ['SUBF_NULI', '=', $line],
+                ['DEAR_ESTA', '=', 'Activo'],
+                ['DEAR_NULI', '=', $line],
+                ['INAR_ESTA', '=', 'Activo'],
+                ['INAR_NULI', '=', $line],
+                ['UNID_ESTA', '=', 'Activo'],
+                ['UNID_NULI', '=', $line],
+            ])->join('S002V01TARTI', 'ARSE_IDAR', '=', 'ARTI_IDAR')
+            ->join('S002V01TINAR', 'ARSE_IDIN', '=', 'INAR_IDIN')
+            ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
+            ->join('S002V01TFAMI', 'ARTI_COFA', '=', 'FAMI_COFA')
+            ->join('S002V01TSUBF', 'ARTI_COSU', '=', 'SUBF_COSU')
+            ->join('S002V01TUNID', 'DEAR_IDUN', '=', 'UNID_IDUN')->get()->all();
             $arrArtitles = json_decode(json_encode($getArtitles), true);
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse( 
@@ -3120,11 +3132,11 @@ class AcquisitionManagementController extends Controller
                 500
             );
         }
+
         if (empty($arrArtitles) || is_null($arrArtitles)) {
             return $this->responseController->makeResponse( true, "ERR_ORDER_GET005: No se pudo obtener los artículos de las órdenes de compra.", [], 500);
         }
 
-
         $index = 0;
         $arrArtitlesTemp = array();
         foreach ($arrArtitles as $keyArtitle => $artitles) {
@@ -3142,8 +3154,8 @@ class AcquisitionManagementController extends Controller
                 }
             }
         }
-        $arrArtitles = $arrArtitlesTemp;
 
+        $arrArtitles = $arrArtitlesTemp;
         foreach ($arrArtitles as $keyArtitles => $artitles) {
             $arrImageArtitle = json_decode($artitles['IMAGEN']);
             $arrUrlImage = array();
@@ -3152,26 +3164,28 @@ class AcquisitionManagementController extends Controller
                 if ($responseDocument['error']) {
                     return $this->responseController->makeResponse(true, "ERR_ARTITLE_GET003: Ocurrió un error al obtener la URL de la imágen.", [], 500);
                 }
+
                 $arrUrlImage[] = $responseDocument['response']['public_uri'];
             }
+
             $arrArtitles[$keyArtitles]['IMAGEN'] = $arrUrlImage;
         }
 
         try {
-            $getHistoryOrder = DB::table('S002V01THIOR')
-                ->where('HIOR_NUOR', '=', $order)
-                ->where('HIOR_NULI', '=', $line)
-                ->get([
-                    'HIOR_IDHO AS ID_HISTORIA_ORDEN',
-                    'HIOR_ESOR AS ESTADO_ORDEN',
-                    'HIOR_DESC AS DESCRIPCION',
-                    'HIOR_EVID AS EVIDENCIA',
-                    'HIOR_POEN AS PORCENTAJE_ENTREGA',
-                    'HIOR_USRE AS USUARIO_REGISTRA',
-                    'HIOR_FERE AS FECHA_REGISTRA',
-                    'HIOR_USMO AS USUARIO_MODIFICA',
-                    'HIOR_FEMO AS FECHA_MODIFICA',
-                ]);
+            $getHistoryOrder = DB::table('S002V01THIOR')->select([
+                'HIOR_IDHO AS ID_HISTORIA_ORDEN',
+                'HIOR_ESOR AS ESTADO_ORDEN',
+                'HIOR_DESC AS DESCRIPCION',
+                'HIOR_EVID AS EVIDENCIA',
+                'HIOR_POEN AS PORCENTAJE_ENTREGA',
+                'HIOR_USRE AS USUARIO_REGISTRA',
+                'HIOR_FERE AS FECHA_REGISTRA',
+                'HIOR_USMO AS USUARIO_MODIFICA',
+                'HIOR_FEMO AS FECHA_MODIFICA',
+            ])->where([
+                ['HIOR_NUOR', '=', $order],
+                ['HIOR_NULI', '=', $line]
+            ])->get()->all();
             $arrHistoryOrder = json_decode(json_encode($getHistoryOrder), true);
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse( 
@@ -3181,6 +3195,7 @@ class AcquisitionManagementController extends Controller
                 500
             );
         }
+
         if (empty($arrHistoryOrder) || is_null($arrHistoryOrder)) {
             return $this->responseController->makeResponse( true, "ERR_ORDER_GET007: No se pudo obtener el historial de la orden de compra.", [], 500);
         }
@@ -3189,9 +3204,8 @@ class AcquisitionManagementController extends Controller
         if ($responseCheckLatestUpdate['error']) {
             return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
         }
-        $arrHistoryOrder = $responseCheckLatestUpdate['response'];
-
 
+        $arrHistoryOrder = $responseCheckLatestUpdate['response'];
         foreach ($arrHistoryOrder as $keyHistoryOrder => $historyOrder) {
             if ( !is_null($historyOrder['EVIDENCIA']) ) {
                 $arrEvidence = json_decode($historyOrder['EVIDENCIA']);
@@ -3201,10 +3215,13 @@ class AcquisitionManagementController extends Controller
                     if ($responseDocument['error']) {
                         return $this->responseController->makeResponse(true, "ERR_ARTITLE_GET003: Ocurrió un error al obtener la URL de la imágen.", [], 500);
                     }
+
                     $arrUrlImage[] = $responseDocument['response']['public_uri'];
                 }
+
                 $historyOrder['EVIDENCIA'] = $arrUrlImage;
             }
+
             $arrHistoryOrder[$keyHistoryOrder] = $historyOrder;
         }
 
@@ -3214,7 +3231,6 @@ class AcquisitionManagementController extends Controller
         return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrOrders);
     }
     public function getLastSateOrder($order, $user, $line) {
-
         $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
         if ($arrResponseCheckUser['error']) {
             DB::rollBack();
@@ -3233,7 +3249,7 @@ class AcquisitionManagementController extends Controller
                     'HIOR_DESC AS DESCRIPCION',
                     'HIOR_EVID AS EVIDENCIA',
                     'HIOR_POEN AS PORCENTAJE_ENTREGA',
-                    'HIOR_ESTA AS ESTADO_ORDEN',
+                    'HIOR_ESTA AS ESTADO_ORDEN_REGISTRO',
                     'HIOR_USRE AS USUARIO_REGISTRA',
                     'HIOR_FERE AS FECHA_REGISTRA',
                     'HIOR_USMO AS USUARIO_MODIFICA',
@@ -3256,6 +3272,7 @@ class AcquisitionManagementController extends Controller
 
         return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrOrderState);
     }
+
     public function updateStateHistory(Request $request) {
         $validator = Validator::make($request->all(), [
             'ESTADO' => 'required|string',
@@ -4002,8 +4019,11 @@ class AcquisitionManagementController extends Controller
         $ubic = Storage::putFile('files', new File($tempFile));
         $ubic = str_replace("/", "\\", $ubic);
 
-        
-        $ubic = $this->functionsController->getBasePath() . "\storage\app\\" . $ubic;
+        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
+            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
+        } else {
+            $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
+        }
         $tama = filesize($ubic);
         $usac = json_encode([$user]);
 
@@ -10563,7 +10583,7 @@ class AcquisitionManagementController extends Controller
             $getDelayAnalysis = DB::table('S002V01TANRE')
                 ->where('ANRE_NULI', '=', $line)
                 ->join('S002V01TORCO', 'ORCO_NUOR', '=', 'ANRE_NUOR')
-                ->join('S002V01TLINE', 'LINE_NUPR', '=', 'ORCO_IDLI')
+                ->join('S002V01TLINE', 'LINE_IDLI', '=', 'ORCO_IDLI')
                 ->join('S002V01TPROV', 'PROV_NUPR', '=', 'LINE_NUPR')
                 ->join('S002V01TREFI', 'REFI_CRFI', '=', 'PROV_CRFI')
                 ->get([
@@ -13064,9 +13084,12 @@ class AcquisitionManagementController extends Controller
         $noar = 'ficha_de_adquisición_' . $arrOrder['ORCO_NUOR'];
         $exte = 'xlsx';
 
-        
-        $filePath = $this->functionsController->getBasePath() . '/public/public_files/';    // API JEAN
-        
+        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
+            $filePath = 'C:/ITTEC/SAM/Dev/SistemaMantenimiento/sistema-mantenimiento-back/public/public_files/';    // API JEAN
+        } else {
+            $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\';     // API QA
+        }
+
         $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;
 
         $tempFile = $filePath.$fileName;
@@ -13100,7 +13123,11 @@ class AcquisitionManagementController extends Controller
 
         $ubic = Storage::putFile('files', new File($tempFile));
         $ubic = str_replace("/", "\\", $ubic);
-        $ubic = $this->functionsController->getBasePath() . "\storage\app\\" . $ubic;
+        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
+            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
+        } else {
+            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
+        }
         $tama = filesize($ubic);
         $usac = json_encode([$user]);
 
@@ -13639,8 +13666,12 @@ class AcquisitionManagementController extends Controller
         $exte = 'pdf';        
         
         
-        $filePath = $this->functionsController->getBasePath() . '/public/public_files/';    // API JEAN
-        
+        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
+            $filePath = 'C:/ITTEC/SAM/Dev/SistemaMantenimiento/sistema-mantenimiento-back/public/public_files/';    // API JEAN
+        } else {
+            $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\';     // API QA
+        }
+
         $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;
         
         $tempFile = $filePath . $fileName;
@@ -13656,8 +13687,11 @@ class AcquisitionManagementController extends Controller
         $ubic = Storage::putFile('files', new File($tempFile));
 
         $ubic = str_replace("/", "\\", $ubic);
-        $ubic = $this->functionsController->getBasePath() . "\storage\app\\" . $ubic;
-        
+        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
+            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
+        } else {
+            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
+        }
         $tama = filesize($ubic);
         $usac = json_encode([$user]);
 
@@ -13717,6 +13751,7 @@ class AcquisitionManagementController extends Controller
             'LINE_NUMBER' => 'required|integer',
             'REQUEST_LINE' => 'required|string',
         ]);
+
         if ($validator->fails()) {
             return $this->responseController->makeResponse(
                 true,
@@ -13735,12 +13770,14 @@ class AcquisitionManagementController extends Controller
             DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE001: Ocurrió un error al recuperar el archivo PDF.", $th->getMessage(), 500);
         }
+
         try {
             $idArchivoXML = $this->encController->decrypt($responseData['IDARCHIVOXML']);
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE002: Ocurrió un error al recuperar el archivo XML.", $th->getMessage(), 500);
         }
+
         try {
             $user = $this->encController->decrypt($responseData['USER']);
         } catch (\Throwable $th) {
@@ -13749,24 +13786,24 @@ class AcquisitionManagementController extends Controller
         }
 
         try {
-            $fileTempDataXML = DB::table('S002V01TARTE')
-                ->where('ARTE_NULI', '=', $responseData['LINE_NUMBER'])
-                ->where('ARTE_IDAR', '=', $idArchivoXML)
-                ->where('ARTE_ESTA', '=', 'Activo')
-                ->first([
-                    'ARTE_IDAR',
-                    'ARTE_NULI',
-                    'ARTE_NOAR',
-                    'ARTE_EXTE',
-                    'ARTE_TAMA',
-                    'ARTE_UBTE',
-                    'ARTE_ESTA',
-                    'ARTE_USRE',
-                    'ARTE_FERE',
-                    'ARTE_USMO',
-                    'ARTE_FEMO',
-                    'ARTE_FEAR',
-                ]);
+            $fileTempDataXML = DB::table('S002V01TARTE')->select([
+                'ARTE_IDAR',
+                'ARTE_NULI',
+                'ARTE_NOAR',
+                'ARTE_EXTE',
+                'ARTE_TAMA',
+                'ARTE_UBTE',
+                'ARTE_ESTA',
+                'ARTE_USRE',
+                'ARTE_FERE',
+                'ARTE_USMO',
+                'ARTE_FEMO',
+                'ARTE_FEAR',
+            ])->where([
+                ['ARTE_NULI', '=', $responseData['LINE_NUMBER']],
+                ['ARTE_IDAR', '=', $idArchivoXML],
+                ['ARTE_ESTA', '=', 'Activo']
+            ])->first();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true,"ERR_INVOICE_COMPARE004: Ocurrió un error al obtener la información de la base de datos del documento.",$th->getMessage(),500);
@@ -13776,6 +13813,7 @@ class AcquisitionManagementController extends Controller
             DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE005: No se pudo obtener la información del documento.", [], 401);
         }
+
         if($fileTempDataXML->ARTE_ESTA == 'Eliminado'){
             return $this->responseController->makeResponse(true, 'ERR_INVOICE_COMPARE006: El archivo consultado está eliminado', [], 404);
         }
@@ -13786,84 +13824,83 @@ class AcquisitionManagementController extends Controller
         }
 
         try {
-            $arrLineRequestData = DB::table('S002V01TLINE')
-                ->where('LINE_NULI', '=', $responseData['LINE_NUMBER'])
-                ->where('LINE_IDLI', '=', $responseData['REQUEST_LINE'])
-                // ->where('LINE_ESTA', '=', 'En espera')
-                ->where('ARSE_ESTA', '=', 'Activo')
-                ->where('ARSE_NULI', '=', $responseData['LINE_NUMBER'])
-                ->join('S002V01TARSE', 'ARSE_IDLI','=', 'LINE_IDLI')
-                ->join('S002V01TINAR', 'INAR_IDIN','=', 'ARSE_IDIN')
-                ->join('S002V01TCAMO', 'CAMO_COMO','=', 'INAR_COMO')
-                ->join('S002V01TDEAR', 'DEAR_IDDE','=', 'INAR_IDDE')
-                ->join('S002V01TARTI', 'ARTI_IDAR','=', 'DEAR_IDAR')
-                ->join('S002V01TUNID', 'UNID_IDUN','=', 'DEAR_IDUN')
-                ->join('S002V01TPROV', 'PROV_NUPR','=', 'ARSE_NUPR')
-                ->get([
-                    'LINE_IDLI',
-                    // 'LINE_NUOR',
-                    'LINE_OTPR',
-                    'LINE_OTCO',
-                    'ARSE_IDAS',
-                    // 'ARSE_CANT',
-                    // 'ARSE_PRTO',
-                    'INAR_IDIN',
-                    'INAR_CODI',
-                    'INAR_MODE',
-                    'INAR_COMO',
-                    'INAR_PREC',
-                    'INAR_MOMI',
-                    'INAR_CARA',
-                    'CAMO_COMO',
-                    'CAMO_DESC',
-                    // 'CAMO_DECI',
-                    // 'CAMO_POVA',
-                    // 'CAMO_FEIN',
-                    // 'CAMO_FEFI',
-                    'DEAR_IDDE',
-                    'DEAR_IMAG',
-                    'DEAR_DESC',
-                    'DEAR_CARA',
-                    'DEAR_COWE',
-                    'ARTI_IDAR',
-                    'ARTI_COFA',
-                    'ARTI_COSU',
-                    'ARTI_CODI',
-                    'ARTI_NOMB',
-                    'UNID_IDUN',
-                    'UNID_NOMB',
-                    'UNID_ACRO',
-                    'PROV_NUPR',
-                    'PROV_NOCO',
-                    'PROV_NOMB',
-                    'PROV_APPA',
-                    'PROV_APMA',
-                    'PROV_CORR',
-                    'PROV_LAD1',
-                    'PROV_TEL1',
-                    'PROV_LAD2',
-                    'PROV_TEL2',
-                    'PROV_XRFC',
-                    'PROV_XTAX',
-                    'PROV_CRFI',
-                    'PROV_TIPO',
-                    'PROV_TICO',
-                    'PROV_SIWE',
-                    'PROV_MEPA',
-                    'PROV_CALL',
-                    'PROV_NUEX',
-                    'PROV_NUIN',
-                    'PROV_COPO',
-                    'PROV_COLO',
-                    'PROV_MUNI',
-                    'PROV_LOCA',
-                    'PROV_ENTI',
-                    'PROV_PAIS',
-                ]);
+            $arrLineRequestData = DB::table('S002V01TLINE')->select([
+                'LINE_IDLI',
+                // 'LINE_NUOR',
+                'LINE_OTPR',
+                'LINE_OTCO',
+                'ARSE_IDAS',
+                // 'ARSE_CANT',
+                // 'ARSE_PRTO',
+                'INAR_IDIN',
+                'INAR_CODI',
+                'INAR_MODE',
+                'INAR_COMO',
+                'INAR_PREC',
+                'INAR_MOMI',
+                'INAR_CARA',
+                'CAMO_COMO',
+                'CAMO_DESC',
+                // 'CAMO_DECI',
+                // 'CAMO_POVA',
+                // 'CAMO_FEIN',
+                // 'CAMO_FEFI',
+                'DEAR_IDDE',
+                'DEAR_IMAG',
+                'DEAR_DESC',
+                'DEAR_CARA',
+                'DEAR_COWE',
+                'ARTI_IDAR',
+                'ARTI_COFA',
+                'ARTI_COSU',
+                'ARTI_CODI',
+                'ARTI_NOMB',
+                'UNID_IDUN',
+                'UNID_NOMB',
+                'UNID_ACRO',
+                'PROV_NUPR',
+                'PROV_NOCO',
+                'PROV_NOMB',
+                'PROV_APPA',
+                'PROV_APMA',
+                'PROV_CORR',
+                'PROV_LAD1',
+                'PROV_TEL1',
+                'PROV_LAD2',
+                'PROV_TEL2',
+                'PROV_XRFC',
+                'PROV_XTAX',
+                'PROV_CRFI',
+                'PROV_TIPO',
+                'PROV_TICO',
+                'PROV_SIWE',
+                'PROV_MEPA',
+                'PROV_CALL',
+                'PROV_NUEX',
+                'PROV_NUIN',
+                'PROV_COPO',
+                'PROV_COLO',
+                'PROV_MUNI',
+                'PROV_LOCA',
+                'PROV_ENTI',
+                'PROV_PAIS',
+            ])->where([
+                ['LINE_NULI', '=', $responseData['LINE_NUMBER']],
+                ['LINE_IDLI', '=', $responseData['REQUEST_LINE']],
+                //['LINE_ESTA', '=', 'En espera'],
+                ['ARSE_ESTA', '=', 'Activo'],
+                ['ARSE_NULI', '=', $responseData['LINE_NUMBER']]
+            ])->join('S002V01TARSE', 'ARSE_IDLI','=', 'LINE_IDLI')
+            ->join('S002V01TINAR', 'INAR_IDIN','=', 'ARSE_IDIN')
+            ->join('S002V01TCAMO', 'CAMO_COMO','=', 'INAR_COMO')
+            ->join('S002V01TDEAR', 'DEAR_IDDE','=', 'INAR_IDDE')
+            ->join('S002V01TARTI', 'ARTI_IDAR','=', 'DEAR_IDAR')
+            ->join('S002V01TUNID', 'UNID_IDUN','=', 'DEAR_IDUN')
+            ->join('S002V01TPROV', 'PROV_NUPR','=', 'ARSE_NUPR')->get()->all();
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(true,"ERR_INVOICE_COMPARE008: Ocurrió un error al obtener la información de la base de datos del documento.",$th->getMessage(),500);
         }
-        $arrLineRequestData = json_decode(json_encode($arrLineRequestData),true);
+        
         if (empty($arrLineRequestData)) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE009: No se pudo obtener la información de la línea de solicitud de compra.", [], 401);
@@ -13872,13 +13909,12 @@ class AcquisitionManagementController extends Controller
         $index = 0;
         $arrArtitles = array();
         foreach ($arrLineRequestData as $keyArtitle => $artitles) {
+            $artitles = (array) $artitles;
             if ($keyArtitle === 0) {
                 $arrArtitles[$index] = $artitles;
                 $arrArtitles[$index]['CANTIDAD'] = 1;
             } else {
-                if (
-                    in_array($artitles['INAR_IDIN'], array_column($arrArtitles, 'INAR_IDIN'))
-                ) {
+                if (in_array($artitles['INAR_IDIN'], array_column($arrArtitles, 'INAR_IDIN'))) {
                     $indexArtitle = array_search($artitles['INAR_IDIN'], array_column($arrArtitles, 'INAR_IDIN'));
                     $arrArtitles[$indexArtitle]['CANTIDAD'] = $arrArtitles[$indexArtitle]['CANTIDAD'] + 1;
                 } else {
@@ -14267,39 +14303,47 @@ class AcquisitionManagementController extends Controller
                 $arrConceptos[$keyConceptos] = $conceptos;
             }
 
-
             foreach ($arrLineRequestData as $keyLineRequestData => $lineRequestData) {
                 $countErrors = 0;
-                if($conceptos['Cantidad'] != $lineRequestData['CANTIDAD']){
+                if(!array_key_exists('Cantidad', $conceptos) || !array_key_exists('Unidad', $conceptos) || !array_key_exists('Descripcion', $conceptos)
+                || !array_key_exists('ValorUnitario', $conceptos)) {
                     $arrResponseFunction['error'] = true;
                     $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
                     $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Cantidad del concepto.';
                     $countErrors++;
+                }else{
+                    if($conceptos['Cantidad'] != $lineRequestData['CANTIDAD']){
+                        $arrResponseFunction['error'] = true;
+                        $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
+                        $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Cantidad del concepto.';
+                        $countErrors++;
+                    }
+                    if($conceptos['Unidad'] != $lineRequestData['UNID_NOMB']){
+                        $arrResponseFunction['error'] = true;
+                        $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
+                        $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Unidad del concepto.';
+                        $countErrors++;
+                    }
+                    if($conceptos['Descripcion'] != $lineRequestData['INAR_CODI']){
+                        $arrResponseFunction['error'] = true;
+                        $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
+                        $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Descripción del concepto.';
+                        $countErrors++;
+                    }
+                    if($conceptos['ValorUnitario'] != $lineRequestData['INAR_PREC']){
+                        $arrResponseFunction['error'] = true;
+                        $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
+                        $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Valor Unitario del concepto.';
+                        $countErrors++;
+                    }
+                    /* if($conceptos['Importe'] != $lineRequestData['ARSE_PRTO']){
+                        $arrResponseFunction['error'] = true;
+                        $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
+                        $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Importe del concepto.';
+                        $countErrors++;
+                    } */
                 }
-                if($conceptos['Unidad'] != $lineRequestData['UNID_NOMB']){
-                    $arrResponseFunction['error'] = true;
-                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
-                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Unidad del concepto.';
-                    $countErrors++;
-                }
-                if($conceptos['Descripcion'] != $lineRequestData['INAR_CODI']){
-                    $arrResponseFunction['error'] = true;
-                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
-                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Descripción del concepto.';
-                    $countErrors++;
-                }
-                if($conceptos['ValorUnitario'] != $lineRequestData['INAR_PREC']){
-                    $arrResponseFunction['error'] = true;
-                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
-                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Valor Unitario del concepto.';
-                    $countErrors++;
-                }
-                /* if($conceptos['Importe'] != $lineRequestData['ARSE_PRTO']){
-                    $arrResponseFunction['error'] = true;
-                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
-                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Importe del concepto.';
-                    $countErrors++;
-                } */
+
                 if ($countErrors == 0) {
                     $arrResponseFunction['error'] = false;
                     $arrResponseFunction['msg'] = '';

+ 444 - 115
sistema-mantenimiento-back/app/Http/Controllers/CorrectiveMaintenanceController.php

@@ -327,6 +327,20 @@ class CorrectiveMaintenanceController extends Controller{
             'OTCO_USRE' => $idUser,
             'OTCO_FERE' => $nowStr
         ]);
+            
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+        $orderPriorities = $paramsArr['order_priorities'];
+        $orderPriority = $priority;
+        $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+            return $v['value'] == $orderPriority;
+        }, ARRAY_FILTER_USE_BOTH);
+
+        $notificationColor = "rgb(35, 95, 172)";
+        if(count($priorityFilt) > 0){
+            $priority = end($priorityFilt);
+            $notificationColor = $priority['color'];
+        }
 
         $this->notificationsController->emitNotification(
             'S002V01M09GMCO',
@@ -350,7 +364,8 @@ class CorrectiveMaintenanceController extends Controller{
             $form['linea'],
             $this->getSocketClient(),
             $orderID,
-            'Correctivo'
+            'Correctivo',
+            $notificationColor
         );
 
         $idOrderEnc = $this->encryptionController->encrypt($orderID);
@@ -1162,6 +1177,20 @@ class CorrectiveMaintenanceController extends Controller{
                 $audience[] = $employee->PERS_IDUS;
             }
         }
+            
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+        $orderPriorities = $paramsArr['order_priorities'];
+        $orderPriority = $order->OTCO_PRIO;
+        $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+            return $v['value'] == $orderPriority;
+        }, ARRAY_FILTER_USE_BOTH);
+
+        $notificationColor = "rgb(35, 95, 172)";
+        if(count($priorityFilt) > 0){
+            $priority = end($priorityFilt);
+            $notificationColor = $priority['color'];
+        }
 
         $this->notificationsController->emitNotification(
             'S002V01M09GMCO',
@@ -1185,7 +1214,8 @@ class CorrectiveMaintenanceController extends Controller{
             $form['linea'],
             $this->getSocketClient(),
             $idOrder,
-            'Correctivo'
+            'Correctivo',
+            $notificationColor
         );
 
         $now = $this->functionsController->now();
@@ -1333,6 +1363,20 @@ class CorrectiveMaintenanceController extends Controller{
         $statusApproved['PERSONAL'] = $staff;
         $statusHistoryArr[$approvedKey] = $statusApproved;
         $statusHistoryStr = json_encode($statusHistoryArr);
+            
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+        $orderPriorities = $paramsArr['order_priorities'];
+        $orderPriority = $order->OTCO_PRIO;
+        $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+            return $v['value'] == $orderPriority;
+        }, ARRAY_FILTER_USE_BOTH);
+
+        $notificationColor = "rgb(35, 95, 172)";
+        if(count($priorityFilt) > 0){
+            $priority = end($priorityFilt);
+            $notificationColor = $priority['color'];
+        }
 
         $this->notificationsController->emitNotification(
             'S002V01M09GMCO',
@@ -1356,7 +1400,8 @@ class CorrectiveMaintenanceController extends Controller{
             $form['linea'],
             $this->getSocketClient(),
             $idOrder,
-            'Correctivo'
+            'Correctivo',
+            $notificationColor
         );
 
         $now = $this->functionsController->now();
@@ -1465,6 +1510,20 @@ class CorrectiveMaintenanceController extends Controller{
         foreach($validatedStatus['ATENCION'] as $item){
             if($item['RESPUESTA'] == 'A') $audience[] = $item['ID'];
         }
+            
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+        $orderPriorities = $paramsArr['order_priorities'];
+        $orderPriority = $order->OTCO_PRIO;
+        $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+            return $v['value'] == $orderPriority;
+        }, ARRAY_FILTER_USE_BOTH);
+
+        $notificationColor = "rgb(35, 95, 172)";
+        if(count($priorityFilt) > 0){
+            $priority = end($priorityFilt);
+            $notificationColor = $priority['color'];
+        }
 
         $this->notificationsController->emitNotification(
             'S002V01M09GMCO',
@@ -1484,7 +1543,8 @@ class CorrectiveMaintenanceController extends Controller{
             $form['linea'],
             $this->getSocketClient(),
             $idOrder,
-            'Correctivo'
+            'Correctivo',
+            $notificationColor
         );
 
         $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'EP', 'FECHA' => $nowStr];
@@ -1602,21 +1662,13 @@ class CorrectiveMaintenanceController extends Controller{
         if($order->OTCO_ESOR == 'EP' && $status == 'CE'){
             $status = 'CP';
         }
-        
-        /*$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)){
+
         if($status == 'CP' && is_null($order->OTCO_FTIN)){
             $ftin = $nowStr;
             $startDate = new Carbon($order->OTCO_FIFA);
@@ -1630,45 +1682,158 @@ class CorrectiveMaintenanceController extends Controller{
         }
 
         $statusHistoryArr = json_decode($order->OTCO_HIES, true);
-        $validatedStatusFilt = array_filter($statusHistoryArr, function($v, $k) {
-            return $v['ESTADO'] == 'VA';
-        }, ARRAY_FILTER_USE_BOTH);
+        if($status == 'CE'){
+            $validatedStatusFilt = array_filter($statusHistoryArr, function($v, $k) {
+                return $v['ESTADO'] == 'VA';
+            }, ARRAY_FILTER_USE_BOTH);
 
-        $validatedStatus = end($validatedStatusFilt);
-        $attendance = $validatedStatus['ATENCION'];
-        $enabledUsersToClose = [];
+            $validatedStatus = end($validatedStatusFilt);
+            $attendance = $validatedStatus['ATENCION'];
+            $enabledUsersToClose = [];
 
-        foreach($attendance as $item){
-            if($item['RESPUESTA'] == 'A') $enabledUsersToClose[] = $item['ID'];
-        }
+            foreach($attendance as $item){
+                if($item['RESPUESTA'] == 'A') $enabledUsersToClose[] = $item['ID'];
+            }
 
-        if(!in_array($idUser, $enabledUsersToClose)){
-            return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
-        }
+            if(!in_array($idUser, $enabledUsersToClose)){
+                return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
+            }
 
-        $closeUserName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-        $audience = [$order->OTCO_IDUR];
+            $closeUserName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+            $audience = [$order->OTCO_IDUR];
+                
+            $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+            $paramsArr = json_decode($paramsStr, true);
+            $orderPriorities = $paramsArr['order_priorities'];
+            $orderPriority = $order->OTCO_PRIO;
+            $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+                return $v['value'] == $orderPriority;
+            }, ARRAY_FILTER_USE_BOTH);
 
-        $this->notificationsController->emitNotification(
-            'S002V01M09GMCO',
-            "Orden de mantenimiento correctivo #$idOrder",
-            "El usuario $closeUserName ($idUser) cerró la orden de mantenimiento #$idOrder con los siguientes comentarios: $form[comments].",
-            [[
-                'BOTON' => 'Ver detalles',
-                'FUNCION' => 'openCorrectiveWorkOrderDetails',
-                '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->getSocketClient(),
-            $idOrder,
-            'Correctivo'
-        );
+            $notificationColor = "rgb(35, 95, 172)";
+            if(count($priorityFilt) > 0){
+                $priority = end($priorityFilt);
+                $notificationColor = $priority['color'];
+            }
+
+            $this->notificationsController->emitNotification(
+                'S002V01M09GMCO',
+                "Orden de mantenimiento correctivo #$idOrder",
+                "El usuario $closeUserName ($idUser) cerró la orden de mantenimiento #$idOrder con los siguientes comentarios: $form[comments].",
+                [[
+                    'BOTON' => 'Ver detalles',
+                    'FUNCION' => 'openCorrectiveWorkOrderDetails',
+                    '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->getSocketClient(),
+                $idOrder,
+                'Correctivo',
+                $notificationColor
+            );
+        }else if($status == 'CA'){
+            $pendingStatusFilt = array_filter($statusHistoryArr, function($v, $k) {
+                return $v['ESTADO'] == 'PE';
+            }, ARRAY_FILTER_USE_BOTH);
+
+            $pendingStatus = end($pendingStatusFilt);
+            if($pendingStatus['USUARIO'] != $idUser){
+                return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
+            }
+
+            $cancelUserName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+            $audience = [$order->OTCO_IDUR];
+                
+            $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+            $paramsArr = json_decode($paramsStr, true);
+            $orderPriorities = $paramsArr['order_priorities'];
+            $orderPriority = $order->OTCO_PRIO;
+            $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+                return $v['value'] == $orderPriority;
+            }, ARRAY_FILTER_USE_BOTH);
+
+            $notificationColor = "rgb(35, 95, 172)";
+            if(count($priorityFilt) > 0){
+                $priority = end($priorityFilt);
+                $notificationColor = $priority['color'];
+            }
+
+            $this->notificationsController->emitNotification(
+                'S002V01M09GMCO',
+                "Orden de mantenimiento correctivo #$idOrder",
+                "El usuario $cancelUserName ($idUser) canceló la ejecución de la orden de mantenimiento #$idOrder con los siguientes comentarios: $form[comments].",
+                [[
+                    'BOTON' => 'Ver detalles',
+                    'FUNCION' => 'openCorrectiveWorkOrderDetails',
+                    '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->getSocketClient(),
+                $idOrder,
+                'Correctivo',
+                $notificationColor
+            );
+        }else if($status == 'RE'){
+            if($order->OTCO_IDUR != $idUser){
+                return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
+            }
+
+            $pendingStatusFilt = array_filter($statusHistoryArr, function($v, $k) {
+                return $v['ESTADO'] == 'PE';
+            }, ARRAY_FILTER_USE_BOTH);
+
+            $pendingStatus = end($pendingStatusFilt);
+            $declineUserName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+            $audience = [$pendingStatus['USUARIO']];
+                
+            $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+            $paramsArr = json_decode($paramsStr, true);
+            $orderPriorities = $paramsArr['order_priorities'];
+            $orderPriority = $order->OTCO_PRIO;
+            $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+                return $v['value'] == $orderPriority;
+            }, ARRAY_FILTER_USE_BOTH);
+
+            $notificationColor = "rgb(35, 95, 172)";
+            if(count($priorityFilt) > 0){
+                $priority = end($priorityFilt);
+                $notificationColor = $priority['color'];
+            }
+
+            $this->notificationsController->emitNotification(
+                'S002V01M09GMCO',
+                "Orden de mantenimiento correctivo #$idOrder",
+                "El usuario $declineUserName ($idUser) rechazó la orden de mantenimiento #$idOrder con los siguientes comentarios: $form[comments].",
+                [[
+                    'BOTON' => 'Ver detalles',
+                    'FUNCION' => 'openCorrectiveWorkOrderDetails',
+                    '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->getSocketClient(),
+                $idOrder,
+                'Correctivo',
+                $notificationColor
+            );
+        }
 
         $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => $status, 'FECHA' => $nowStr];
         $statusHistoryStr = json_encode($statusHistoryArr);
@@ -1769,6 +1934,20 @@ class CorrectiveMaintenanceController extends Controller{
 
         $closeUserName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
         $audience = [$order->OTCO_USRE];
+            
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+        $orderPriorities = $paramsArr['order_priorities'];
+        $orderPriority = $order->OTCO_PRIO;
+        $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+            return $v['value'] == $orderPriority;
+        }, ARRAY_FILTER_USE_BOTH);
+
+        $notificationColor = "rgb(35, 95, 172)";
+        if(count($priorityFilt) > 0){
+            $priority = end($priorityFilt);
+            $notificationColor = $priority['color'];
+        }
 
         $this->notificationsController->emitNotification(
             'S002V01M09GMCO',
@@ -1788,7 +1967,8 @@ class CorrectiveMaintenanceController extends Controller{
             $form['linea'],
             $this->getSocketClient(),
             $idOrder,
-            'Correctivo'
+            'Correctivo',
+            $notificationColor
         );
 
         $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => $status, 'FECHA' => $nowStr];
@@ -2080,6 +2260,20 @@ class CorrectiveMaintenanceController extends Controller{
             'OTCO_USMO' => $idUser,
             'OTCO_FEMO' => $nowStr
         ]);
+            
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+        $orderPriorities = $paramsArr['order_priorities'];
+        $orderPriority = $order->OTCO_PRIO;
+        $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+            return $v['value'] == $orderPriority;
+        }, ARRAY_FILTER_USE_BOTH);
+
+        $notificationColor = "rgb(35, 95, 172)";
+        if(count($priorityFilt) > 0){
+            $priority = end($priorityFilt);
+            $notificationColor = $priority['color'];
+        }
 
         $this->notificationsController->emitNotification(
             'S002V01M09GMCO',
@@ -2103,7 +2297,8 @@ class CorrectiveMaintenanceController extends Controller{
             $form['linea'],
             $this->getSocketClient(),
             $idOrder,
-            'Correctivo'
+            'Correctivo',
+            $notificationColor
         );
 
         $actions = DB::getQueryLog();
@@ -3690,12 +3885,15 @@ class CorrectiveMaintenanceController extends Controller{
             'priority' => 'required|string',
             'total_duration' => 'required|numeric',
             'classification' => 'required|string|max:100',
-            'specialties' => 'required|json',
-            'specialties_conf' => 'required|json',
+            'staff' => 'required|json',
             'resources' => 'required|json',
             'attached' => 'required|json',
             'symptom' => 'required|string',
             'scada' => 'required|string',
+            'security_management' => 'required|string',
+            'id_counter' => 'required|string',
+            'id_responsible' => 'required|string',
+            'type_responsible' => 'required|string|in:U,S',
         ]);
  
         if($validator->fails()){
@@ -3781,7 +3979,62 @@ class CorrectiveMaintenanceController extends Controller{
             return $this->responseController->makeResponse(true, 'La prioridad seleccionada es inválida.', [], 400);
         }
 
-        //PENDINTE REVISAR RECURSOS CON STOCK
+        $staffArr = json_decode($form['staff'], true);
+        if(count($staffArr) == 0){
+            return $this->responseController->makeResponse(true, 'El arreglo del personal está vacío.', [], 400);
+        }
+
+        $staff = [];
+        foreach($staffArr as $key=>$specialty){
+            $specialtyDec = $this->encryptionController->decrypt($specialty['SPECIALTY']);
+            if(!$specialtyDec){
+                return $this->responseController->makeResponse(true, "El código en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
+            }
+
+            $specialtyObj = DB::table('S002V01TGEES')->where([
+                ['GEES_NULI', '=', $form['linea']],
+                ['GEES_COES', '=', $specialtyDec]
+            ])->first();
+
+            if(is_null($specialtyObj)){
+                return $this->responseController->makeResponse(true, "El item en la posición $key del arreglo de especialidades no existe.", [], 404);
+            }
+
+            $staff[] = [
+                'ID' => $specialtyDec,
+                'CANT' => $specialty['CANT']
+            ];
+        }
+
+        $staffStrFn = json_encode($staff);
+        $resources = json_decode($form['resources'], true);
+        if(empty($resources)){
+            return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
+        }
+
+        foreach($resources as $key=>$item){
+            if(!array_key_exists('ID', $item)){
+                return $this->responseController->makeResponse(true, "No se pudo encontrar el ID del elemento en la posición $key del arreglo de recursos.", [], 400);
+            }
+
+            if($item['ID'] != 'SH'){
+                $idItemDec = $this->encryptionController->decrypt($item['ID']);
+                $resource = DB::table('S002V01TINST')->where([
+                    ['INST_NULI', '=', $form['linea']],
+                    ['INST_IDIS', '=', $idItemDec],
+                ])->first();
+
+                if(is_null($resource)){
+                    return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de recursos no existe.", [], 404);
+                }
+
+                $item['ID'] = $idItemDec;
+            }
+
+            $resources[$key] = $item;
+        }
+
+        $recu = json_encode($resources);
         $attachedArr = json_decode($form['attached'], true);
         $attachedArrFn = [];
         foreach($attachedArr as $key=>$attached){
@@ -3840,22 +4093,51 @@ class CorrectiveMaintenanceController extends Controller{
             return $this->responseController->makeResponse(true, 'El SCADA relacionado no existe.', [], 404);
         }
 
+        $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);
+        }
+        
+        $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);
+        }
+        
+        $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);
+        }
+
         //Una vez que se aprueban los datos se registra el contador relacionado
         $now = $this->functionsController->now();
         $nowStr = $now->toDateTimeString();
-        $idCounter = DB::table('S002V01TCONA')->insertGetId([
-            'CONA_NULI' => $form['linea'],
-            'CONA_INLE' => 5,
-            'CONA_UTIL' => 'min',
-            'CONA_TOIN' => 1,
-            'CONA_UTTI' => 'min',
-            'CONA_IDSC' => $idSCADA,
-            'CONA_COEQ' => is_null($lrui) ? $equipmentCode : $lrui,
-            'CONA_COVI' => '[]',
-            'CONA_USRE' => $idUser,
-            'CONA_FERE' => $nowStr
-        ]);
-
         $repeatStartDate = new Carbon($now->toDateString());
         $repeatStart = str_replace(' ', 'T', $repeatStartDate->toDateTimeString());
 
@@ -3892,6 +4174,7 @@ class CorrectiveMaintenanceController extends Controller{
 
         //Se procede a crear un activador relacionado al contador nuevo
         $symptomRepeatStr = json_encode($symptomRepeat);
+
         $idActivator = DB::table('S002V01TACTI')->insertGetId([
             'ACTI_NULI' => $form['linea'],
             'ACTI_PRIO' => $priorityDec,
@@ -3901,14 +4184,6 @@ class CorrectiveMaintenanceController extends Controller{
             'ACTI_USRE' => $idUser,
             'ACTI_FERE' => $nowStr,
         ]);
-        
-        $specialtiesArr = json_decode($form['specialties'], true);
-        $specialtiesDec = [];
-        foreach($specialtiesArr as $specialty){
-            $specialtiesDec[] = $this->encryptionController->decrypt($specialty);
-        }
-
-        $specialtiesStr = json_encode($specialtiesDec);
 
         //Una vez obtenido el ID del nuevo contador relacionado se ingresa el plan de mantenimiento
         $come = isset($form['comments']) ? $form['comments'] : null;
@@ -3917,6 +4192,8 @@ class CorrectiveMaintenanceController extends Controller{
         
         $idPlan = DB::table('S002V01TPMCO')->insertGetId([
             'PMCO_NULI' => $form['linea'],
+            'PMCO_IDUR' => $idUserResponsible,
+            'PMCO_TURE' => $form['type_responsible'],
             'PMCO_EQIN' => $equipmentCode,
             'PMCO_LRUI' => $lrui,
             'PMCO_EFEQ' => $form['equipment_status'],
@@ -3925,13 +4202,13 @@ class CorrectiveMaintenanceController extends Controller{
             'PMCO_TIES' => $form['inm_time'],
             'PMCO_DTIN' => $form['total_duration'],
             'PMCO_CLAS' => $form['classification'],
-            'PMCO_ESRE' => $specialtiesStr,
-            'PMCO_COES' => $form['specialties_conf'],
+            'PMCO_ESRE' => $staffStrFn,
             'PMCO_COME' => $come,
-            'PMCO_RECU' => $form['resources'],
+            'PMCO_RECU' => $recu,
             'PMCO_DEAD' => $dead,
             'PMCO_DORE' => $dore,
             'PMCO_CORE' => $idCounter,
+            'PMCO_GESE' => $idManagement,
             'PMCO_USRE' => $idUser,
             'PMCO_FERE' => $nowStr,
         ]);
@@ -4084,8 +4361,19 @@ class CorrectiveMaintenanceController extends Controller{
 
         $plan = DB::table('S002V01TPMCO')->select([
             'PMCO_IDPM AS ID_PLAN',
-            'PMCO_EQIN AS EQUIPAMIENTO',
-            'PMCO_LRUI AS LRU',
+            'PMCO_IDUR AS ID_USUARIO_RESPONSABLE',
+            'USRES.USUA_NOMB AS NOMBRE_USUARIO_RESPONSABLE',
+            'USRES.USUA_APPA AS APE_PAT_USUARIO_RESPONSABLE',
+            'USRES.USUA_APMA AS APE_MAT_USUARIO_RESPONSABLE',
+            'PMCO_TURE AS TIPO_USUARIO_RESPONSABLE',
+            'PMCO_EQIN AS CODIGO_EQUIPAMIENTO',
+            'EQUI.EQUI_TIPO AS TIPO_EQUIPAMIENTO',
+            'EQUI.EQUI_MODE AS MODELO_EQUIPAMIENTO',
+            'EQUI.EQUI_IDEQ AS ID_EQUIPAMIENTO',
+            'PMCO_LRUI AS CODIGO_LRU',
+            'LRUI.EQUI_TIPO AS TIPO_LRU',
+            'LRUI.EQUI_MODE AS MODELO_LRU',
+            'LRUI.EQUI_IDEQ AS ID_LRU',
             'PMCO_EFEQ AS ESTADO_FUNCIONAMIENTO_EQUIPAMIENTO',
             'PMCO_EFLR AS ESTADO_FUNCIONAMIENTO_LRU',
             'PMCO_DESC AS DESCRIPCION',
@@ -4093,48 +4381,70 @@ class CorrectiveMaintenanceController extends Controller{
             'PMCO_DTIN AS DURACION_TOTAL',
             'PMCO_CLAS AS CLASIFICACION',
             'PMCO_ESRE AS ESPECIALIDADES_REQUERIDAS',
-            'PMCO_COES AS CONFIGURACION_OPERARIOS',
             'PMCO_COME AS COMENTARIOS',
             'PMCO_RECU AS RECURSOS',
             'PMCO_DEAD AS DETALLES_ADICIONALES',
             'PMCO_DORE AS DOCUMENTOS_RELACIONADOS',
             'PMCO_CORE AS CONTADOR',
+            'PMCO_GESE AS GERENCIA_SEGURIDAD',
             'CONA_IDSC AS SCADA',
             'ACTI_IDAC AS ACTIVADOR',
             'ACTI_PRIO AS PRIORIDAD',
             'ACTI_COAC AS SINTOMA',
             'PMCO_ESTA AS ESTADO',
-            'PMCO_USRE AS USRREG',
+            DB::raw("
+                CONCAT(
+                    USREG.USUA_NOMB, 
+                    ' ',
+                    USREG.USUA_APPA,
+                    IF(ISNULL(USREG.USUA_APMA), '', ' '),
+                    IF(ISNULL(USREG.USUA_APMA), '', USREG.USUA_APMA),
+                    ' (',
+                    PMCO_USRE,
+                    ')'
+                ) AS USRREG
+            "),
             'PMCO_FERE AS FECREG',
-            'PMCO_USMO AS USRMOD',
+            DB::raw("
+                IF(
+                    ISNULL(USMOD.USUA_NOMB),
+                    '',
+                    CONCAT(
+                        USMOD.USUA_NOMB, 
+                        ' ',
+                        USMOD.USUA_APPA,
+                        IF(ISNULL(USMOD.USUA_APMA), '', ' '),
+                        IF(ISNULL(USMOD.USUA_APMA), '', USMOD.USUA_APMA),
+                        ' (',
+                        PMCO_USRE,
+                        ')'
+                    )
+                ) AS USRMOD
+            "),
             'PMCO_FEMO AS FECMOD',
         ])->where([
             ['PMCO_NULI', '=', $line],
             ['PMCO_IDPM', '=', $idPlan]
         ])->join('S002V01TACTI', 'ACTI_CORE', '=', 'PMCO_CORE')
-        ->join('S002V01TCONA', 'CONA_IDCO', '=', 'PMCO_CORE')->first();
+        ->join('S002V01TCONA', 'CONA_IDCO', '=', 'PMCO_CORE')
+        ->join('S002V01TUSUA AS USRES', 'USRES.USUA_IDUS', '=', 'PMCO_IDUR')
+        ->join('S002V01TEQUI AS EQUI', 'EQUI.EQUI_COEQ', '=', 'PMCO_EQIN')
+        ->leftJoin('S002V01TEQUI AS LRUI', 'LRUI.EQUI_COEQ', '=', 'PMCO_LRUI')
+        ->join('S002V01TUSUA AS USREG', 'USREG.USUA_IDUS', '=', 'PMCO_USRE')
+        ->leftJoin('S002V01TUSUA AS USMOD', 'USMOD.USUA_IDUS', '=', 'PMCO_USMO')->first();
 
         if(is_null($plan)){
             return $this->responseController->makeResponse(true, 'El plan solicitado no existe.', [], 404);
         }
 
         $plan->ID_PLAN = $this->encryptionController->encrypt($plan->ID_PLAN);
-        $equipment = DB::table('S002V01TEQUI')->where([
-            ['EQUI_NULI', '=', $line],
-            ['EQUI_COEQ', '=', $plan->EQUIPAMIENTO]
-        ])->first();
-
-        $equipmentLabel = $plan->EQUIPAMIENTO . " - " . $equipment->EQUI_TIPO . " - " . $equipment->EQUI_MODE . " (" . $equipment->EQUI_IDEQ . ")";
-        $plan->EQUIPAMIENTO = $this->encryptionController->encrypt($equipmentLabel);
-
-        if(!is_null($plan->LRU)){
-            $lru = DB::table('S002V01TEQUI')->where([
-                ['EQUI_NULI', '=', $line],
-                ['EQUI_COEQ', '=', $plan->LRU]
-            ])->first();
+        $plan->ID_USUARIO_RESPONSABLE = $this->encryptionController->encrypt($plan->ID_USUARIO_RESPONSABLE);
+        $plan->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($plan->CODIGO_EQUIPAMIENTO);
+        $plan->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($plan->ID_EQUIPAMIENTO);
 
-            $lruLabel = $plan->LRU . " - " . $lru->EQUI_TIPO . " - " . $lru->EQUI_MODE . " (" . $lru->EQUI_IDEQ . ")";
-            $plan->LRU = $this->encryptionController->encrypt($lruLabel);
+        if(!is_null($plan->CODIGO_LRU)){
+            $plan->CODIGO_LRU = $this->encryptionController->encrypt($plan->CODIGO_LRU);
+            $plan->ID_LRU = $this->encryptionController->encrypt($plan->ID_LRU);
         }
 
         $documentsArr = json_decode($plan->DOCUMENTOS_RELACIONADOS, true);
@@ -4165,28 +4475,32 @@ class CorrectiveMaintenanceController extends Controller{
         $plan->SCADA = $this->encryptionController->encrypt($plan->SCADA);
         $plan->ACTIVADOR = $this->encryptionController->encrypt($plan->ACTIVADOR);
         $plan->PRIORIDAD = $this->encryptionController->encrypt($plan->PRIORIDAD);
+        $plan->GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($plan->GERENCIA_SEGURIDAD);
 
-        $activationConfig = json_decode($plan->SINTOMA, true);
-        $plan->SINTOMA = $this->encryptionController->encrypt($activationConfig['sign']);
+        $resources = json_decode($plan->RECURSOS, true);
+        foreach($resources as $key=>$resource){
+            if($resource['ID'] != 'SH'){
+                $resourceObj = DB::table('S002V01TINST')->where([
+                    ['INST_NULI', '=', $line],
+                    ['INST_IDIS', '=', $resource['ID']],
+                ])->join('S002V01TSTAR', 'STAR_IDIS', '=', 'INST_IDIS')
+                ->join('S002V01TUNID', 'UNID_IDUN', '=', 'STAR_IDUN')->first();
 
-        $usrReg = DB::table('S002V01TUSUA')->where([
-            ['USUA_NULI', '=', $line],
-            ['USUA_IDUS', '=', $plan->USRREG]
-        ])->first();
+                if(!is_null($resourceObj)){
+                    $resource['NAME'] = $resourceObj->INST_MODE;
+                    $resource['UNIT'] = $resourceObj->UNID_NOMB;
+                }
 
-        $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
-        $plan->USRREG = $usrRegName . " (" . $plan->USRREG . ")";
+                $resource['ID'] = $this->encryptionController->encrypt($resource['ID']);
+            }
 
-        if(!is_null($plan->USRMOD)){
-            $usrMod = DB::table('S002V01TUSUA')->where([
-                ['USUA_NULI', '=', $line],
-                ['USUA_IDUS', '=', $plan->USRMOD]
-            ])->first();
-    
-            $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
-            $plan->USRMOD = $usrModName . " (" . $plan->USRMOD . ")";
+            $resources[$key] = $resource;
         }
 
+        $plan->RECURSOS = json_encode($resources);
+        $activationConfig = json_decode($plan->SINTOMA, true);
+        $plan->SINTOMA = $this->encryptionController->encrypt($activationConfig['sign']);
+
         $now = $this->functionsController->now();
         $nowStr = $now->toDateTimeString();
         $actions = DB::getQueryLog();
@@ -6326,7 +6640,7 @@ class CorrectiveMaintenanceController extends Controller{
 
             $now = $this->functionsController->now();
             $year = $now->year;
-            $month = $now->month < 10 ? "0{$now->month}" : "0{$now->month}";
+            $month = $now->month < 10 ? "0{$now->month}" : "{$now->month}";
             $day = $now->day < 10 ? "0{$now->day}" : "{$now->day}";
             $fecr = substr("$year", -2) . $month . $day;
             $sec = DB::table('S002V01TAFAL')->where([
@@ -6422,6 +6736,20 @@ class CorrectiveMaintenanceController extends Controller{
                 "OTCO_FEMO" => $nowStr,
             ]);
         }
+            
+        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
+        $paramsArr = json_decode($paramsStr, true);
+        $orderPriorities = $paramsArr['order_priorities'];
+        $orderPriority = $order->OTCO_PRIO;
+        $priorityFilt = array_filter($orderPriorities, function ($v, $k) use ($orderPriority) {
+            return $v['value'] == $orderPriority;
+        }, ARRAY_FILTER_USE_BOTH);
+
+        $notificationColor = "rgb(35, 95, 172)";
+        if(count($priorityFilt) > 0){
+            $priority = end($priorityFilt);
+            $notificationColor = $priority['color'];
+        }
 
         $userName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
         $action = $form['attendance'] == 'A' ? 'aceptó' : 'rechazó';
@@ -6462,7 +6790,8 @@ class CorrectiveMaintenanceController extends Controller{
             $form['linea'],
             $this->getSocketClient(),
             $idOrder,
-            'Correctivo'
+            'Correctivo',
+            $notificationColor
         );
 
         return $this->responseController->makeResponse(false, 'EXITO');

+ 32 - 4
sistema-mantenimiento-back/app/Http/Controllers/CountersActivatorsController.php

@@ -92,15 +92,17 @@ class CountersActivatorsController extends Controller{
             'ACTI_IDAC AS IDACTIVADOR',
             'ACTI_PRIO AS PRIORIDAD',
             'ACTI_TIAC AS TIPOACTIVACION',
-            'ACTI_COAC AS CONDICIONES'
+            'ACTI_COAC AS CONDICIONES',
+            'CONA_COEQ AS CODIGO_EQUIPAMIENTO',
         ])->where([
             ['ACTI_NULI', '=', $line],
             ['ACTI_TIAC', '=', $type]
-        ])->get()->all();
+        ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->get()->all();
 
         foreach($activators as $key=>$activator){
             $activator->IDACTIVADOR = $this->encryptionController->encrypt($activator->IDACTIVADOR);
             $activator->PRIORIDAD = $this->encryptionController->encrypt($activator->PRIORIDAD);
+            $activator->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($activator->CODIGO_EQUIPAMIENTO);
 
             if($activator->TIPOACTIVACION == 'Medida' || $activator->TIPOACTIVACION == 'Valor'){
                 $activationConfigArr = json_decode($activator->CONDICIONES, true);
@@ -1193,9 +1195,32 @@ class CountersActivatorsController extends Controller{
             }
         }
 
-        $conditionStr = json_encode($conditionArr);
+        $activationConfig = $form['condition'];
+        $activationConfigArr = json_decode($activationConfig, true);
+        $startDateObj = new Carbon($activationConfigArr['startDate']);
+        $startDateStr = $startDateObj->toDateString();
+        $startDateTimeObj = new Carbon("$startDateStr $activationConfigArr[startHour]");
+        $startDateTimeStr = $startDateTimeObj->toDateTimeString();
         $now = $this->functionsController->now();
         $nowStr = $now->toDateTimeString();
+
+        $preventiveOrdersRelated = DB::table('S002V01TOTPR')->where([
+            ['OTPR_NULI', '=', $form['linea']],
+            ['OTPR_ACAS', '=', $idActivator]
+        ])->get()->all();
+
+        foreach($preventiveOrdersRelated as $preventiveOrder){
+            DB::table('S002V01TOTPR')->where([
+                ['OTPR_NULI', '=', $form['linea']],
+                ['OTPR_IDOT', '=', $preventiveOrder->OTPR_IDOT],
+            ])->update([
+                "OTPR_FIAP" => $startDateTimeStr,
+                "OTPR_USMO" => $idUser,
+                "OTPR_FEMO" => $nowStr
+            ]);
+        }
+
+        $conditionStr = json_encode($conditionArr);
         DB::table('S002V01TACTI')->where([
             ['ACTI_IDAC', '=', $idActivator],
             ['ACTI_NULI', '=', $form['linea']]
@@ -1340,6 +1365,8 @@ class CountersActivatorsController extends Controller{
             'CONA_IDCO AS ID_CONTADOR',
             'ACTI_IDAC AS ID_ACTIVADOR',
             'ACTI_PRIO AS PRIORIDAD',
+            'CONA_IDSC AS ID_SCADA',
+            'LISC_NOSC AS NOMBRE_SCADA',
             'CONA_ESTA AS ESTADO',
             'CONA_FERE AS FECREG',
             'CONA_USRE AS USRREG',
@@ -1348,7 +1375,7 @@ class CountersActivatorsController extends Controller{
         ])->join('S002V01TACTI', 'ACTI_CORE', '=', 'CONA_IDCO')->where([
             ['CONA_NULI', '=', $line],
             ['CONA_COEQ', '=', $equipmentCode]
-        ])->orderBy('CONA_IDCO', 'asc')->get()->all();
+        ])->join('S002V01TLISC', 'LISC_IDSC', '=', 'CONA_IDSC')->orderBy('CONA_IDCO', 'asc')->get()->all();
 
         foreach($counters as $key=>$counter){
             $counter->ID_CONTADOR = $this->encryptionController->encrypt($counter->ID_CONTADOR);
@@ -1356,6 +1383,7 @@ class CountersActivatorsController extends Controller{
                 $counter->ID_ACTIVADOR = $this->encryptionController->encrypt($counter->ID_ACTIVADOR);
             }
 
+            $counter->ID_SCADA = $this->encryptionController->encrypt($counter->ID_SCADA);
             $usrReg = DB::table('S002V01TUSUA')->where([
                 ['USUA_NULI', '=', $line],
                 ['USUA_IDUS', '=', $counter->USRREG]

+ 1 - 2
sistema-mantenimiento-back/app/Http/Controllers/DocumentManagementController.php

@@ -428,8 +428,7 @@ class DocumentManagementController extends Controller{
         }
 
         $form = $request->all();
-        //$idUser = $this->encryptionController->decrypt($form['id_user']);
-        $idUser = "0000000001";
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
         if(!$idUser){
             return $this->responseController->makeResponse(true, "El id del usuario que realizó la petición no fue encriptado correctamente", [], 400);
         }

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

@@ -4730,7 +4730,10 @@ class EquipmentManagementController extends Controller{
             'EQUI_ELOR AS ELEMENTO_ORIGEN',
             'EQUI_TICO AS TIPO_CODIGO',
             'EQUI_EQPA AS EQUIPO_PADRE',
-        ])->where('EQUI_NULI', '=', $line)->get()->all();
+        ])->where([
+            ['EQUI_NULI', '=', $line],
+            ['EQUI_ESEQ', '=', 'I']
+        ])->get()->all();
 
         $idUserEnc = $this->encryptionController->encrypt($idUser);
         foreach($equipments as $key=>$equipment){
@@ -6945,9 +6948,6 @@ class EquipmentManagementController extends Controller{
         ])->where([
             ['EQUI_NULI', '=', $line],
             ['EQUI_IPCC', '=', $intersection],
-        ])->orWhere([
-            ['EQUI_ELOR', 'LIKE', "%$element%"],
-            ['EQUI_ELDE', 'LIKE', "%$element%"],
         ])->get()->all();
 
         foreach($equipments as $key=>$equipment){

+ 61 - 62
sistema-mantenimiento-back/app/Http/Controllers/FailureAnalysisController.php

@@ -571,43 +571,42 @@ class FailureAnalysisController extends Controller
     public function getFailureLog($user, $line) {
 
         try {
-            $getFailureLog = DB::table('S002V01TBIFA')
-                ->where('BIFA_NULI', '=', $line)
-                ->where('LIFA_NULI', '=', $line)
-                ->where('LISI_NULI', '=', $line)
-                ->where('LIME_NULI', '=', $line)
-                ->where('LIFA_ESTA', '=', 'Activo')
-                ->where('LISI_ESTA', '=', 'Activo')
-                ->where('LIME_ESTA', '=', 'Activo')
-                ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
-                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
-                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
-                ->get([
-                    'BIFA_NUFA AS NUMERO_FALLA',
-                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
-                    'BIFA_ESFA AS ESTADO_FALLA',
-                    'LIFA_IDFA AS ID_FALLA',
-                    'LIFA_NOFA AS NOMBRE_FALLA',
-                    'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
-                    'LIFA_CAUS AS CAUSA_FALLA',
-                    'LISI_IDSI AS ID_SINTOMA',
-                    'LISI_NOSI AS NOMBRE_SINTOMA',
-                    'LISI_CLAS AS CLASIFICACION_SINTOMA',
-                    'LISI_CAUS AS CAUSA_SINTOMA',
-                    'BIFA_FEFA AS FECHA_FALLA',
-                    'BIFA_REPA AS REPARABLE',
-                    'BIFA_DESO AS SOLUCION',
-                    'BIFA_COME AS COMENTARIOS',
-                    'BIFA_VAOB AS VALOR_OBTENIDO',
-                    'LIME_IDME AS ID_MEDIDA',
-                    'LIME_NOME AS NOMBRE_MEDIDA',
-                    'LIME_ACME AS ACRONIMO_MEDIDA',
-                    'BIFA_ESTA AS ESTADO',
-                    'BIFA_USRE AS USUARIO_REGISTRA',
-                    'BIFA_FERE AS FECHA_REGISTRA',
-                    'BIFA_USMO AS USUARIO_MODIFICA',
-                    'BIFA_FEMO AS FECHA_MODIFICA',
-                ]);
+            $getFailureLog = DB::table('S002V01TBIFA')->select([
+                'BIFA_NUFA AS NUMERO_FALLA',
+                'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
+                'BIFA_ESFA AS ESTADO_FALLA',
+                'LIFA_IDFA AS ID_FALLA',
+                'LIFA_NOFA AS NOMBRE_FALLA',
+                'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
+                'LIFA_CAUS AS CAUSA_FALLA',
+                'LISI_IDSI AS ID_SINTOMA',
+                'LISI_NOSI AS NOMBRE_SINTOMA',
+                'LISI_CLAS AS CLASIFICACION_SINTOMA',
+                'LISI_CAUS AS CAUSA_SINTOMA',
+                'BIFA_FEFA AS FECHA_FALLA',
+                'BIFA_REPA AS REPARABLE',
+                'BIFA_DESO AS SOLUCION',
+                'BIFA_COME AS COMENTARIOS',
+                'BIFA_VAOB AS VALOR_OBTENIDO',
+                'LIME_IDME AS ID_MEDIDA',
+                'LIME_NOME AS NOMBRE_MEDIDA',
+                'LIME_ACME AS ACRONIMO_MEDIDA',
+                'BIFA_ESTA AS ESTADO',
+                'BIFA_USRE AS USUARIO_REGISTRA',
+                'BIFA_FERE AS FECHA_REGISTRA',
+                'BIFA_USMO AS USUARIO_MODIFICA',
+                'BIFA_FEMO AS FECHA_MODIFICA',
+            ])->where([
+                ['BIFA_NULI', '=', $line],
+                ['LIFA_NULI', '=', $line],
+                ['LISI_NULI', '=', $line],
+                ['LIME_NULI', '=', $line],
+                ['LIFA_ESTA', '=', 'Activo'],
+                ['LISI_ESTA', '=', 'Activo'],
+                ['LIME_ESTA', '=', 'Activo'],
+            ])->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
+            ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
+            ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')->get()->all();
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GET000: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
         }
@@ -1869,31 +1868,30 @@ class FailureAnalysisController extends Controller
         }
 
         try {
-            $getSymptom = DB::table('S002V01TLSEQ')
-                ->where('LSEQ_NULI', '=', $line)
-                ->where('LSEQ_ESTA', '=', 'Activo')
-                ->where('LSEQ_COEQ', '=', $equipment)
-                ->where('LISI_NULI', '=', $line)
-                ->where('LISI_ESTA', '=', 'Activo')
-                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'LSEQ_IDSI')
-                ->join('S002V01TLIME', 'LIME_IDME', '=', 'LISI_IDME')
-                ->get([
-                    'LISI_IDSI AS ID_SINTOMA',
-                    'LISI_NOSI AS NOMBRE_SINTOMA',
-                    'LISI_CLAS AS CLASIFICACION',
-                    'LISI_CAUS AS CAUSA',
-                    'LISI_DESC AS DESCRIPCION',
-                    'LISI_SOLU AS SOLUCION',
-                    'LISI_LIVA AS LIMITE_VALOR',
-                    'LIME_IDME AS ID_MEDIDA',
-                    'LIME_NOME AS NOMBRE_MEDIDA',
-                    'LIME_ACME AS ACRONIMO_MEDIDA',
-                    'LISI_ESTA AS ESTADO',
-                    'LISI_USRE AS USUARIO_REGISTRA',
-                    'LISI_FERE AS FECHA_REGISTRA',
-                    'LISI_USMO AS USUARIO_MODIFICA',
-                    'LISI_FEMO AS FECHA_MODIFICA',
-                ]);
+            $getSymptom = DB::table('S002V01TLSEQ')->select([
+                'LISI_IDSI AS ID_SINTOMA',
+                'LISI_NOSI AS NOMBRE_SINTOMA',
+                'LISI_CLAS AS CLASIFICACION',
+                'LISI_CAUS AS CAUSA',
+                'LISI_DESC AS DESCRIPCION',
+                'LISI_SOLU AS SOLUCION',
+                'LISI_LIVA AS LIMITE_VALOR',
+                'LIME_IDME AS ID_MEDIDA',
+                'LIME_NOME AS NOMBRE_MEDIDA',
+                'LIME_ACME AS ACRONIMO_MEDIDA',
+                'LISI_ESTA AS ESTADO',
+                'LISI_USRE AS USUARIO_REGISTRA',
+                'LISI_FERE AS FECHA_REGISTRA',
+                'LISI_USMO AS USUARIO_MODIFICA',
+                'LISI_FEMO AS FECHA_MODIFICA',
+            ])->where([
+                ['LSEQ_NULI', '=', $line],
+                ['LSEQ_ESTA', '=', 'Activo'],
+                ['LSEQ_COEQ', '=', $equipment],
+                ['LISI_NULI', '=', $line],
+                ['LISI_ESTA', '=', 'Activo'],
+            ])->join('S002V01TLISI', 'LISI_IDSI', '=', 'LSEQ_IDSI')
+            ->join('S002V01TLIME', 'LIME_IDME', '=', 'LISI_IDME')->get()->all();
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(
                 true, 
@@ -2030,6 +2028,7 @@ class FailureAnalysisController extends Controller
             'NUMERO_LINEA' => 'required|integer', 
 
         ]);
+        
         if ($validator->fails()) {
             return $this->responseController->makeResponse(
                 true,

File diff suppressed because it is too large
+ 206 - 759
sistema-mantenimiento-back/app/Http/Controllers/FunctionsController.php


+ 265 - 0
sistema-mantenimiento-back/app/Http/Controllers/LogErrorsController.php

@@ -0,0 +1,265 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Carbon\Carbon;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Http\File;
+
+class LogErrorsController extends Controller{
+    private $responseController;
+    private $encryptionController;
+    private $documentManagementController;
+    private $functionsController;
+    private $resourcesController;
+
+    public function __construct(){
+        $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->documentManagementController = new DocumentManagementController();
+        $this->functionsController = new FunctionsController();
+        $this->resourcesController = new ResourcesController();
+    }
+
+    public function getLogYears($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);
+        }
+
+        $logStoragePath = "C:\\inetpub\\wwwroot\\errors_storage";
+        if(!file_exists($logStoragePath)){
+            return $this->responseController->makeResponse(true, 'No se encontró el directorio de almacenamiento de los errores.', [], 404);
+        }
+
+        $availableYears = scandir($logStoragePath, SCANDIR_SORT_DESCENDING);
+        $availableYearsFn = [];
+
+        foreach($availableYears as $year){
+            if($year == '.' || $year == '..') continue;
+            $availableYearsFn[] = $this->encryptionController->encrypt($year);
+        }
+
+        return $this->responseController->makeResponse(false, 'EXITO.', $availableYearsFn);
+    }
+
+    public function getLogMonths($year, $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);
+        }
+
+        $year = $this->encryptionController->decrypt($year);
+        if(!$year){
+            return $this->responseController->makeResponse(true, 'El año enviado está encriptado correctamente.', [], 400);
+        }else if(intval($year) <= 0){
+            return $this->responseController->makeResponse(true, 'El año enviado es inválido.', [], 400);
+        }
+
+        $pathYear = "C:\\inetpub\\wwwroot\\errors_storage\\$year";
+        if(!file_exists($pathYear)){
+            return $this->responseController->makeResponse(true, 'El año enviado no está registrado en el log de errores.', [], 400);
+        }
+
+        $availableMonths = scandir($pathYear);
+        $availableMonthsFn = [];
+
+        foreach($availableMonths as $month){
+            if($month == '.' || $month == '..') continue;
+            $availableMonthsFn[] = $this->encryptionController->encrypt($month);
+        }
+
+        return $this->responseController->makeResponse(false, 'EXITO.', $availableMonthsFn);
+    }
+
+    public function getLogDays($month, $year, $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);
+        }
+
+        $year = $this->encryptionController->decrypt($year);
+        if(!$year){
+            return $this->responseController->makeResponse(true, 'El año enviado está encriptado correctamente.', [], 400);
+        }else if(intval($year) <= 0){
+            return $this->responseController->makeResponse(true, 'El año enviado es inválido.', [], 400);
+        }
+
+        $pathYear = "C:\\inetpub\\wwwroot\\errors_storage\\$year";
+        if(!file_exists($pathYear)){
+            return $this->responseController->makeResponse(true, 'El año enviado no está registrado en el log de errores.', [], 400);
+        }
+
+        $month = $this->encryptionController->decrypt($month);
+        if(!$month){
+            return $this->responseController->makeResponse(true, 'El mes enviado está encriptado correctamente.', [], 400);
+        }else if(intval($month) <= 0){
+            return $this->responseController->makeResponse(true, 'El mes enviado es inválido.', [], 400);
+        }
+
+        $pathMonth = "$pathYear\\$month";
+        if(!file_exists($pathMonth)){
+            return $this->responseController->makeResponse(true, 'El mes enviado no está registrado en el log de errores.', [], 400);
+        }
+
+        $availableDays = scandir($pathMonth);
+        $availableDaysFn = [];
+
+        foreach($availableDays as $day){
+            if($day == '.' || $day == '..') continue;
+            $availableDaysFn[] = $this->encryptionController->encrypt($day);
+        }
+
+        return $this->responseController->makeResponse(false, 'EXITO.', $availableDaysFn);
+    }
+
+    public function getDayErrors($day, $month, $year, $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);
+        }
+
+        $year = $this->encryptionController->decrypt($year);
+        if(!$year){
+            return $this->responseController->makeResponse(true, 'El año enviado está encriptado correctamente.', [], 400);
+        }else if(intval($year) <= 0){
+            return $this->responseController->makeResponse(true, 'El año enviado es inválido.', [], 400);
+        }
+
+        $pathYear = "C:\\inetpub\\wwwroot\\errors_storage\\$year";
+        if(!file_exists($pathYear)){
+            return $this->responseController->makeResponse(true, 'El año enviado no está registrado en el log de errores.', [], 400);
+        }
+
+        $month = $this->encryptionController->decrypt($month);
+        if(!$month){
+            return $this->responseController->makeResponse(true, 'El mes enviado está encriptado correctamente.', [], 400);
+        }else if(intval($month) <= 0){
+            return $this->responseController->makeResponse(true, 'El mes enviado es inválido.', [], 400);
+        }
+
+        $pathMonth = "$pathYear\\$month";
+        if(!file_exists($pathMonth)){
+            return $this->responseController->makeResponse(true, 'El mes enviado no está registrado en el log de errores.', [], 400);
+        }
+
+        $day = $this->encryptionController->decrypt($day);
+        if(!$day){
+            return $this->responseController->makeResponse(true, 'El día enviado no está encriptado correctamente.', [], 400);
+        }else if(intval($day) <= 0){
+            return $this->responseController->makeResponse(true, 'El día enviado es inválido.', [], 400);
+        }
+
+        $pathDay = "$pathMonth\\$day";
+        if(!file_exists($pathDay)){
+            return $this->responseController->makeResponse(true, 'El día enviado no está registrado en el log de errores.', [], 400);
+        }
+
+        $pathErrors = "$pathDay\\errors_log.json";
+        if(!file_exists($pathErrors)){
+            return $this->responseController->makeResponse(true, 'No se encontró el log de errores del día solicitado.', [], 400);
+        }
+
+        $errorsStr = file_get_contents($pathErrors);
+        $errorsArr = json_decode($errorsStr, true);
+        $errorsArrFn = [];
+
+        foreach($errorsArr as $k=>$v){
+            $errorDateTime = Carbon::createFromTimestamp($k, 'America/Mexico_city');
+            $errorDateTimeStr = $errorDateTime->toDateTimeString();
+            $errorsByDate = [];
+
+            if(array_key_exists($errorDateTimeStr, $errorsArrFn)){
+                $errorsByDate = $errorsArrFn[$errorDateTimeStr];
+            }
+
+            foreach($v as $k1=>$v1){
+                $idError = $k1 + 1;
+                $idErrorEnc = $this->encryptionController->encrypt($idError);
+                $module = DB::table('S002V01TMODU')->where([
+                    ['MODU_IDMO', '=', $v1['MODULO']],
+                    ['MODU_NULI', '=', $line]
+                ])->first();
+
+                if(!is_null($module)){
+                    $v1['MODULO'] = "{$module->MODU_NOMO} ($v1[MODULO])";
+                }
+
+                $user = DB::table('S002V01TUSUA')->where([
+                    ['USUA_IDUS', '=', $v1['ID_USUARIO']],
+                    ['USUA_NULI', '=', $line]
+                ])->first();
+
+                if(!is_null($user)){
+                    $v1['ID_USUARIO'] = $this->functionsController->joinName($user->USUA_NOMB, $user->USUA_APPA, $user->USUA_APMA) . " ($v1[ID_USUARIO])";
+                }
+
+                $v1['NUM_ERROR'] = $idErrorEnc;
+                $v1['MODULO'] = $this->encryptionController->encrypt($v1['MODULO']);
+                $v1['ID_USUARIO'] = $this->encryptionController->encrypt($v1['ID_USUARIO']);
+
+                $errorsByDate[] = $v1;
+            }
+
+            $errorsArrFn[$errorDateTimeStr] = $errorsByDate;
+        }
+
+        $errorsFn = [];
+        foreach($errorsArrFn as $k=>$v){
+            $errorsFn[] = [
+                'FECHA' => $k,
+                'ERRORES' => $v,
+            ];
+        }
+
+        return $this->responseController->makeResponse(false, 'EXITO.', $errorsFn);
+    }
+}

+ 28 - 22
sistema-mantenimiento-back/app/Http/Controllers/LoginController.php

@@ -21,7 +21,6 @@ class LoginController extends Controller{
     private $responseController;
     private $encryptionController;
     private $functionsController;
-    private $socketClient;
     private $secretKey = "ydl27x22cNsNY0z6o3Fr6XZoUvsX0QMZx6MaiwN+KCnM6APS4Xbb7GDfudOYD5uD/r8TzQElh4d4HIal5Os0XA==";
     private $publicKey = "zOgD0uF22+xg37nTmA+bg/6/E80BJYeHeByGpeTrNFw=";
 
@@ -29,11 +28,15 @@ class LoginController extends Controller{
         $this->responseController = new ResponseController();
         $this->encryptionController = new EncryptionController();
         $this->functionsController = new FunctionsController;
+    }
 
+    private function getSocketClient(){
         $url = 'http://localhost:3200';
-        $this->socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
-        $this->socketClient->initialize();
-        $this->socketClient->of('/');
+        $socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
+        $socketClient->initialize();
+        $socketClient->of('/');
+
+        return $socketClient;
     }
 
     public function login(Request $request){
@@ -195,22 +198,25 @@ class LoginController extends Controller{
             return $this->responseController->makeResponse(true, 'La configuración de sesiones máximas no existe.', [], 404);
         }
 
-        $this->socketClient->emit('get_sessions', []);
-        if($packet = $this->socketClient->wait('new_session_saved')){
-            $maxSessions = $politicsArr['active_sessions_number'];
-            $dataStr = $packet->data;
-            $dataArr = json_decode($dataStr, true);
-            $sessionsCount = 0;
-
-            foreach($dataArr as $session){
-                $sessionUser = $this->encryptionController->decrypt($session['user']);
-                if($sessionUser == $usr->USUA_IDUS){
-                    $sessionsCount++;
+        $idUserInt = intval($usr->USUA_IDUS);
+        if($idUserInt > 0){
+            $this->getSocketClient()->emit('get_sessions', []);
+            if($packet = $this->getSocketClient()->wait('new_session_saved')){
+                $maxSessions = $politicsArr['active_sessions_number'];
+                $dataStr = $packet->data;
+                $dataArr = json_decode($dataStr, true);
+                $sessionsCount = 0;
+
+                foreach($dataArr as $session){
+                    $sessionUser = $this->encryptionController->decrypt($session['user']);
+                    if($sessionUser == $usr->USUA_IDUS){
+                        $sessionsCount++;
+                    }
                 }
-            }
 
-            if($sessionsCount >= $maxSessions){
-                return $this->responseController->makeResponse(true, 'Número máximo de sesiones alcanzado.', [], 401);
+                if($sessionsCount >= $maxSessions){
+                    return $this->responseController->makeResponse(true, 'Número máximo de sesiones alcanzado.', [], 401);
+                }
             }
         }
 
@@ -352,8 +358,8 @@ class LoginController extends Controller{
     }
 
     public function privateValidateSocketSessions() {
-        $this->socketClient->emit('get_sessions', []);
-        if($packet = $this->socketClient->wait('new_session_saved')){
+        $this->getSocketClient()->emit('get_sessions', []);
+        if($packet = $this->getSocketClient()->wait('new_session_saved')){
             $dataStr = $packet->data;
             $dataArr = json_decode($dataStr, true);
 
@@ -361,13 +367,13 @@ class LoginController extends Controller{
                 try{
                     $decoded = JWT::decode($session['token'], new Key($this->publicKey, 'EdDSA'));
                 }catch(Exception $e){
-                    $this->socketClient->emit('etl_delete_session', $session);
+                    $this->getSocketClient()->emit('etl_delete_session', $session);
                 }
 
                 $now = $this->functionsController->now();
                 $nowTimestamp = $now->timestamp;
                 if($nowTimestamp > $decoded->cad){
-                    $this->socketClient->emit('etl_delete_session', $session);
+                    $this->getSocketClient()->emit('etl_delete_session', $session);
                 }
             }
         }

+ 5 - 1
sistema-mantenimiento-back/app/Http/Controllers/NotificationsController.php

@@ -31,7 +31,8 @@ class NotificationsController extends Controller{
         int $line,
         object $socket,
         int $idOrder = null,
-        string $orderType = null
+        string $orderType = null,
+        string $color = "rgb(35, 95, 172)"
     ) : bool {
         $moduleObj = DB::table('S002V01TMODU')->where([
             ['MODU_NULI', '=', $line],
@@ -59,6 +60,7 @@ class NotificationsController extends Controller{
             'NOTI_CONT' => $content,
             'NOTI_IDOT' => $idOrder,
             'NOTI_TIOR' => $orderType,
+            'NOTI_COLO' => $color,
             'NOTI_ACCI' => json_encode($actions),
             'NOTI_AUDI' => $audienceStr,
             'NOTI_ALCA' => json_encode($scope),
@@ -105,6 +107,7 @@ class NotificationsController extends Controller{
             'NOTI_CONT AS CUERPO_NOTIFICACION',
             'NOTI_IDOT AS ID_ORDEN',
             'NOTI_TIOR AS TIPO_ORDEN',
+            'NOTI_COLO AS COLOR',
             'NOTI_ACCI AS ACCIONES',
             'NOTI_AUDI AS AUDIENCIA',
             'NOTI_ALCA AS ALCANCE',
@@ -215,6 +218,7 @@ class NotificationsController extends Controller{
             'NOTI_CONT AS CUERPO_NOTIFICACION',
             'NOTI_IDOT AS ID_ORDEN',
             'NOTI_TIOR AS TIPO_ORDEN',
+            'NOTI_COLO AS COLOR',
             'NOTI_AUDI AS AUDIENCIA',
             'NOTI_ALCA AS ALCANCE',
             'NOTI_USRE AS USRREG',

+ 12 - 9
sistema-mantenimiento-back/app/Http/Controllers/PRTGController.php

@@ -12,7 +12,6 @@ class PRTGController extends Controller{
     private $functionsController;
     private $encryptionController;
     private $notificationsController;
-    private $socketClient;
     private $monitoredItems;
 
     public function __construct(){
@@ -21,14 +20,18 @@ class PRTGController extends Controller{
         $this->encryptionController = new EncryptionController();
         $this->notificationsController = new NotificationsController();
 
-        $url = 'http://localhost:3200';
-        $this->socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
-        $this->socketClient->initialize();
-        $this->socketClient->of('/');
-        
         $this->monitoredItems = ['R650', 'R450'];
     }
 
+    private function getSocketClient(){
+        $url = 'http://localhost:3200';
+        $socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
+        $socketClient->initialize();
+        $socketClient->of('/');
+
+        return $socketClient;
+    }
+
     public function registerData(Request $request) {
         $validator = Validator::make($request->all(), [
             'data' => 'required|string'
@@ -80,7 +83,7 @@ class PRTGController extends Controller{
                                 ['0000000000'],
                                 '0000000000', 
                                 $form['linea'],
-                                $this->socketClient,
+                                $this->getSocketClient(),
                                 '',
                                 ''
                             );
@@ -110,7 +113,7 @@ class PRTGController extends Controller{
                                     ['0000000000'],
                                     '0000000000', 
                                     $form['linea'],
-                                    $this->socketClient,
+                                    $this->getSocketClient(),
                                     '',
                                     ''
                                 );
@@ -128,7 +131,7 @@ class PRTGController extends Controller{
         ]);
 
         $idReportEnc = $this->encryptionController->encrypt($idReport);
-        $this->socketClient->emit('new_prtg_report', ['report' => $idReportEnc]);
+        $this->getSocketClient()->emit('new_prtg_report', ['report' => $idReportEnc]);
 
         return $this->responseController->makeResponse(false, 'EXITO');
     }

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

@@ -120,7 +120,7 @@ class PersonnelManagementController extends Controller
         $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
         return $this->responseController->makeResponse(false, 'EXITO', $employees);
     }
-    
+
     public function getEmployeeById($idEmployee, $idUser, $line) {
         DB::enableQueryLog();
 

File diff suppressed because it is too large
+ 172 - 184
sistema-mantenimiento-back/app/Http/Controllers/PreventiveMaintenanceController.php


+ 15 - 13
sistema-mantenimiento-back/app/Http/Controllers/ProcessManagementController.php

@@ -19,10 +19,8 @@ class ProcessManagementController extends Controller
     private $functionsController;
 
     private $notificationsController;
-    private $socketClient;
 
-    public function __construct()
-    {
+    public function __construct(){
         $this->responseController = new ResponseController();
         $this->encController = new EncryptionController();
         $this->resourcesController = new ResourcesController();
@@ -30,11 +28,15 @@ class ProcessManagementController extends Controller
         $this->functionsController = new FunctionsController();
 
         $this->notificationsController = new NotificationsController();
+    }
 
+    private function getSocketClient(){
         $url = 'http://localhost:3200';
-        $this->socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
-        $this->socketClient->initialize();
-        $this->socketClient->of('/');
+        $socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
+        $socketClient->initialize();
+        $socketClient->of('/');
+
+        return $socketClient;
     }
 
     //Submódulo de gestión de workflows 
@@ -1599,7 +1601,7 @@ class ProcessManagementController extends Controller
                     [$arrNextNotificate['USUARIO_NOTIFICACION']],
                     $user,
                     $requestData['NUMERO_LINEA'],
-                    $this->socketClient,
+                    $this->getSocketClient(),
                 );
 
 
@@ -1991,8 +1993,8 @@ class ProcessManagementController extends Controller
             $validateUser =  $notiValidate[0]['ID_USUARIO'];
 
             $arrInfoConnection = array();
-            $this->socketClient->emit('get_connections', []);
-            if ($packet = $this->socketClient->wait('current_connections')) {
+            $this->getSocketClient()->emit('get_connections', []);
+            if ($packet = $this->getSocketClient()->wait('current_connections')) {
                 $data = json_decode($packet->data, true);
                 $arrInfoConnection = $data;
             }
@@ -2091,7 +2093,7 @@ class ProcessManagementController extends Controller
                 [$validateUser],
                 $user,
                 $line,
-                $this->socketClient,
+                $this->getSocketClient(),
             );
 
             // Se obtiene los usuarios que solo son para notificar
@@ -2149,7 +2151,7 @@ class ProcessManagementController extends Controller
                 $arrUserNoti,
                 $user,
                 $line,
-                $this->socketClient,
+                $this->getSocketClient(),
             );
 
             foreach ($arrNotification as $key => $notification) {
@@ -2433,7 +2435,7 @@ class ProcessManagementController extends Controller
                         $arrUserNotificate,
                         $user,
                         $requestData['NUMERO_LINEA'],
-                        $this->socketClient,
+                        $this->getSocketClient(),
                     );
                 }
 
@@ -2455,7 +2457,7 @@ class ProcessManagementController extends Controller
                         [$userValidate],
                         $user,
                         $requestData['NUMERO_LINEA'],
-                        $this->socketClient,
+                        $this->getSocketClient(),
                     );
                 }
             }

+ 391 - 194
sistema-mantenimiento-back/app/Http/Controllers/StockController.php

@@ -22,8 +22,7 @@ use Illuminate\Support\Carbon;
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
 use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 use Dompdf\Dompdf;
-
-
+use Illuminate\Database\Query\JoinClause;
 
 class StockController extends Controller
 {
@@ -2387,8 +2386,8 @@ class StockController extends Controller
             'FECHA_VENCIMIENTO' => 'nullable|string',
             'IMAGES' => 'required|json',
             'PRE_GENERATED_CODE' => 'required|string',
-            'REPARABLE' => 'required|boolean',
-            'CONSUMIBLE' => 'required|boolean',
+            'CARACTER' => 'required|string|in:R,C',
+            'TIPO_DE_ARTICULO' => 'required|string|in:H,R',
             'USUARIO' => 'required|string',
             'NUMERO_LINEA' => 'required|integer',
         ]);
@@ -2422,16 +2421,13 @@ class StockController extends Controller
         }
 
         try {
-            $infoAdquisition = (array) DB::table('S002V01TINAR')
-                ->where([
-                    ['INAR_IDIN', '=', $requestData['ID_INFORMATION']],
-                    ['INAR_NULI', '=', $requestData['NUMERO_LINEA']],
-                ])
-                ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
-                ->join('S002V01TUNID', 'UNID_IDUN', '=', 'DEAR_IDUN')
-                ->first([
-                    'DEAR_CAAR AS CANTIDAD_ARTICULOS',
-                ]);
+            $infoAdquisition = (array) DB::table('S002V01TINAR')->select([
+                'DEAR_CAAR AS CANTIDAD_ARTICULOS',
+            ])->where([
+                ['INAR_IDIN', '=', $requestData['ID_INFORMATION']],
+                ['INAR_NULI', '=', $requestData['NUMERO_LINEA']],
+            ])->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
+            ->join('S002V01TUNID', 'UNID_IDUN', '=', 'DEAR_IDUN')->first();
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de la adquisición.', $th->getMessage(), 404);
         }
@@ -2527,10 +2523,10 @@ class StockController extends Controller
 
         // Se verifica que la información exista
         try {
-            $validateWarehouse = DB::table('S002V01TALMA')
-                ->where('ALMA_COAL', '=', $idWarehouse)
-                ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->exists();
+            $validateWarehouse = DB::table('S002V01TALMA')->where([
+                ['ALMA_COAL', '=', $idWarehouse],
+                ['ALMA_NULI', '=', $requestData['NUMERO_LINEA']]
+            ])->exists();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el almacen existe.', $th->getMessage(), 500);
@@ -2542,11 +2538,11 @@ class StockController extends Controller
         }
 
         try {
-            $validateArea = DB::table('S002V01TAREA')
-                ->where('AREA_COAL', '=', $idWarehouse)
-                ->where('AREA_COAR', '=', $idArea)
-                ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->exists();
+            $validateArea = DB::table('S002V01TAREA')->where([
+                ['AREA_COAL', '=', $idWarehouse],
+                ['AREA_COAR', '=', $idArea],
+                ['AREA_NULI', '=', $requestData['NUMERO_LINEA']]
+            ])->exists();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el área existe.', $th->getMessage(), 500);
@@ -2558,12 +2554,12 @@ class StockController extends Controller
         }
 
         try {
-            $validateLevel = DB::table('S002V01TNIVE')
-                ->where('NIVE_COAL', '=', $idWarehouse)
-                ->where('NIVE_COAR', '=', $idArea)
-                ->where('NIVE_CONI', '=', $idLevel)
-                ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->exists();
+            $validateLevel = DB::table('S002V01TNIVE')->where([
+                ['NIVE_COAL', '=', $idWarehouse],
+                ['NIVE_COAR', '=', $idArea],
+                ['NIVE_CONI', '=', $idLevel],
+                ['NIVE_NULI', '=', $requestData['NUMERO_LINEA']]
+            ])->exists();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el nivel existe.', $th->getMessage(), 500);
@@ -2575,13 +2571,13 @@ class StockController extends Controller
         }
         
         try {
-            $validateZone = DB::table('S002V01TZONA')
-                ->where('ZONA_COAL', '=', $idWarehouse)
-                ->where('ZONA_COAR', '=', $idArea)
-                ->where('ZONA_CONI', '=', $idLevel)
-                ->where('ZONA_COZO', '=', $idZone)
-                ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->exists();
+            $validateZone = DB::table('S002V01TZONA')->where([
+                ['ZONA_COAL', '=', $idWarehouse],
+                ['ZONA_COAR', '=', $idArea],
+                ['ZONA_CONI', '=', $idLevel],
+                ['ZONA_COZO', '=', $idZone],
+                ['ZONA_NULI', '=', $requestData['NUMERO_LINEA']]
+            ])->exists();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si la zona existe.', $th->getMessage(), 500);
@@ -2592,10 +2588,10 @@ class StockController extends Controller
         }
 
         try {
-            $validateFamily = DB::table('S002V01TFAMI')
-                ->where('FAMI_COFA', '=', $idFamily)
-                ->where('FAMI_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->exists();
+            $validateFamily = DB::table('S002V01TFAMI')->where([
+                ['FAMI_COFA', '=', $idFamily],
+                ['FAMI_NULI', '=', $requestData['NUMERO_LINEA']]
+            ])->exists();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si la familia existe.', $th->getMessage(), 500);
@@ -2607,11 +2603,11 @@ class StockController extends Controller
         }
 
         try {
-            $validateSubfamily = DB::table('S002V01TSUBF')
-                ->where('SUBF_COFA', '=', $idFamily)
-                ->where('SUBF_COSU', '=', $idSubfamily)
-                ->where('SUBF_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->exists();
+            $validateSubfamily = DB::table('S002V01TSUBF')->where([
+                ['SUBF_COFA', '=', $idFamily],
+                ['SUBF_COSU', '=', $idSubfamily],
+                ['SUBF_NULI', '=', $requestData['NUMERO_LINEA']]
+            ])->exists();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si la subfamilia existe.', $th->getMessage(), 500);
@@ -2623,22 +2619,23 @@ class StockController extends Controller
         }
 
         try {
-            $orden = (array) DB::table('S002V01TORCO')
-                ->where('ORCO_NUOR', '=', $requestData['ORDER'])
-                ->where('ORCO_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->where('ORCO_ESTA', '=', 'Recibido')
-                ->first([
-                    'ORCO_IDLI AS ID_LINEA_SOLICITUD',
-                    'ORCO_IDDE AS ID_DESCRIPCION',
-                ]);
+            $orderNumber = intval($requestData['ORDER']);
+            $orden = (array) DB::table('S002V01TORCO')->select([
+                'ORCO_IDLI AS ID_LINEA_SOLICITUD',
+                'ORCO_IDDE AS ID_DESCRIPCION',
+            ])->where([
+                ['ORCO_NUOR', '=', $requestData['ORDER']],
+                ['ORCO_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['ORCO_ESTA', '=', 'Recibido']
+            ])->first();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de la orden de compra.', $th->getMessage(), 500);
         }
 
-        if (is_null($orden)) {
+        if (empty($orden) && $orderNumber > 0) {
             DB::rollBack();
-            return $this->responseController->makeResponse(true, 'La orden de compra no existe.', [], 500);
+            return $this->responseController->makeResponse(true, 'La orden de compra no existe.', [], 404);
         }
 
         $now = $this->functionsController->now();
@@ -2649,56 +2646,56 @@ class StockController extends Controller
         }
 
         try {
-            $info = DB::table('S002V01TARSE')
-                ->where('ARSE_IDIN', '=', $requestData['ID_INFORMATION'])
-                ->where('ARSE_ESTA', '=', 'Activo')
-                ->where('ARSE_IDLI', '=', $orden['ID_LINEA_SOLICITUD'])
-                ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->where('ARTI_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->where('DEAR_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->where('UNID_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->where('INAR_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->where('ARSE_ESTA', '=', 'Activo')
-                ->where('ARTI_ESTA', '=', 'Activo')
-                ->where('DEAR_ESTA', '=', 'Activo')
-                ->where('UNID_ESTA', '=', 'Activo')
-                ->where('INAR_ESTA', '=', 'Activo')
-                ->where('INAR_CODI', '=', $requestData['CODIGO_MODELO'])
-                ->where('INAR_MODE', '=', $requestData['MODELO'])
-                ->join('S002V01TARTI', 'ARTI_IDAR', '=', 'ARSE_IDAR')
-                ->join('S002V01TINAR', 'INAR_IDIN', '=', 'ARSE_IDIN')
-                ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
-                ->join('S002V01TUNID', 'UNID_IDUN', '=', 'DEAR_IDUN')
-                ->limit($requestData['NUMBER_ITEMS'])
-                ->get([
-                    'ARSE_IDAS AS NUMERO_SELECCIONADO',
-
-                    'ARTI_IDAR AS ID_ARTICULO',
-                    'ARTI_COFA AS CODIGO_FAMILIA',
-                    'ARTI_COSU AS CODIGO_SUBFAMILIA',
-                    'ARTI_CODI AS CODIGO_ARTICULO',
-                    'ARTI_NOMB AS NOMBRE_ARTICULO',
-
-                    'DEAR_IDDE AS ID_DESCRIPCION', 
-                    'DEAR_IMAG AS IMAGENES', 
-                    'DEAR_DESC AS DESCRIPCION', 
-                    'DEAR_CARA AS CARACTERISTICAS', 
-                    'DEAR_COWE AS COMPRA_WEB', 
-                    'DEAR_NUPR AS NUMERO_PROVEEDOR', 
-                    
-                    'UNID_IDUN AS ID_UNIDAD',
-                    'UNID_NOMB AS NOMBRE_UNIDAD',
-                    'UNID_ACRO AS ACRONIMO_UNIDAD',
-
-                    'INAR_IDIN AS ID_INFORMACION',
-                    'INAR_CODI AS CODIGO_INFORMACION',
-                    'INAR_MODE AS MODELO_INFORMACION',
-                    'INAR_COMO AS CODIGO_MONEDA',
-                    'INAR_PREC AS PRECIO',
-                    'INAR_MOMI AS MONTO_MINIMO',
-                    'INAR_CARA AS CARACTERISTICAS',
-                ]);
-            $info = json_decode(json_encode($info), true);
+            $info = DB::table('S002V01TARSE')->select([
+                'ARSE_IDAS AS NUMERO_SELECCIONADO',
+
+                'ARTI_IDAR AS ID_ARTICULO',
+                'ARTI_COFA AS CODIGO_FAMILIA',
+                'ARTI_COSU AS CODIGO_SUBFAMILIA',
+                'ARTI_CODI AS CODIGO_ARTICULO',
+                'ARTI_NOMB AS NOMBRE_ARTICULO',
+
+                'DEAR_IDDE AS ID_DESCRIPCION', 
+                'DEAR_IMAG AS IMAGENES', 
+                'DEAR_DESC AS DESCRIPCION', 
+                'DEAR_CARA AS CARACTERISTICAS', 
+                'DEAR_COWE AS COMPRA_WEB', 
+                'DEAR_NUPR AS NUMERO_PROVEEDOR', 
+                
+                'UNID_IDUN AS ID_UNIDAD',
+                'UNID_NOMB AS NOMBRE_UNIDAD',
+                'UNID_ACRO AS ACRONIMO_UNIDAD',
+
+                'INAR_IDIN AS ID_INFORMACION',
+                'INAR_CODI AS CODIGO_INFORMACION',
+                'INAR_MODE AS MODELO_INFORMACION',
+                'INAR_COMO AS CODIGO_MONEDA',
+                'INAR_PREC AS PRECIO',
+                'INAR_MOMI AS MONTO_MINIMO',
+                'INAR_CARA AS CARACTERISTICAS',
+            ])->where([
+                ['ARSE_IDIN', '=', $requestData['ID_INFORMATION']],
+                ['ARSE_ESTA', '=', 'Activo'],
+                ['ARSE_IDLI', '=', $orden['ID_LINEA_SOLICITUD']],
+                ['ARSE_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['ARTI_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['DEAR_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['UNID_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['INAR_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['ARSE_ESTA', '=', 'Activo'],
+                ['ARTI_ESTA', '=', 'Activo'],
+                ['DEAR_ESTA', '=', 'Activo'],
+                ['UNID_ESTA', '=', 'Activo'],
+                ['INAR_ESTA', '=', 'Activo'],
+                ['INAR_CODI', '=', $requestData['CODIGO_MODELO']],
+                ['INAR_MODE', '=', $requestData['MODELO']],
+            ])->join('S002V01TARTI', 'ARTI_IDAR', '=', 'ARSE_IDAR')
+            ->join('S002V01TINAR', 'INAR_IDIN', '=', 'ARSE_IDIN')
+            ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
+            ->join('S002V01TUNID', 'UNID_IDUN', '=', 'DEAR_IDUN')
+            ->limit($requestData['NUMBER_ITEMS'])->get()->all();
+
+            //$info = json_decode(json_encode($info), true);
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de los productos.', $th->getMessage(), 500);
@@ -2742,10 +2739,10 @@ class StockController extends Controller
         // Se verifican que los códigos de barras no se repitan
         foreach ($arrBarcode as $key => $barcode) {
             try {
-                $validateBarcode = DB::table('S002V01TSTAR')
-                    ->where('STAR_COBA', '=', $barcode)
-                    ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
-                    ->exists();
+                $validateBarcode = DB::table('S002V01TSTAR')->where([
+                    ['STAR_COBA', '=', $barcode],
+                    ['STAR_NULI', '=', $requestData['NUMERO_LINEA']]
+                ])->exists();
             } catch (\Throwable $th) {
                 return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar los códigos de barras.', $th->getMessage(), 500);
             }
@@ -2778,28 +2775,29 @@ class StockController extends Controller
         $currentDate = $now->toDateTimeString();
 
         $idInfoStock = null;
-        if(!isset($info)){
-            goto noStockInfo;
+        $arti = 0;
+        
+        if(isset($info)){
+            $info[0]['ID_ARTICULO'];
         }
 
         try {
-            $infoStock = (array) DB::table('S002V01TINST')
-                ->where('INST_COFA', '=', $idFamily)
-                ->where('INST_COSU', '=', $idSubfamily)
-                ->where('INST_ARTI', '=', $info[0]['ID_ARTICULO'])
-                ->where('INST_MODE', '=', $requestData['MODELO'])
-                ->where('INST_COMO', '=', $requestData['CODIGO_MODELO'])
-                ->where('INST_NULI', '=', $requestData['NUMERO_LINEA'])
-                ->where('INST_ESTA', '=', 'Activo')
-                ->first([
-                    'INST_IDIS AS ID_INFO_STOCK'
-                ]);
+            $infoStock = (array) DB::table('S002V01TINST')->select([
+                'INST_IDIS AS ID_INFO_STOCK'
+            ])->where([
+                ['INST_COFA', '=', $idFamily],
+                ['INST_COSU', '=', $idSubfamily],
+                ['INST_ARTI', '=', $arti],
+                [DB::raw('LOWER(INST_MODE)'), '=', strtolower($requestData['MODELO'])],
+                [DB::raw('LOWER(INST_COMO)'), '=', strtolower($requestData['CODIGO_MODELO'])],
+                ['INST_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['INST_ESTA', '=', 'Activo'],
+            ])->first();
         } catch (\Throwable $th) {
             DB::rollBack();
             return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar la información del stock.', $th->getMessage(), 500);
         }
 
-        noStockInfo:
         if (empty($infoStock) || is_null($infoStock)) {
             // Se obtiene el arreglo de las imagenes
             $imagesArr = json_decode($requestData['IMAGES'], true);
@@ -2908,6 +2906,8 @@ class StockController extends Controller
                 $nupr = isset($info) ? $info[$i]['NUMERO_PROVEEDOR'] : 0;
                 $prad = isset($info) ? $info[$i]['PRECIO'] : 0;
                 $como = isset($info) ? $info[$i]['CODIGO_MONEDA'] : 0;
+                $cons = $requestData['CARACTER'] == 'C' ? 'Si' : 'No';
+                $repa = $requestData['CARACTER'] == 'R' ? 'Si' : 'No';
 
                 $idInsertStAr = DB::table('S002V01TSTAR')->insertGetId([
                     'STAR_NULI' => $requestData['NUMERO_LINEA'],
@@ -2918,8 +2918,8 @@ class StockController extends Controller
                     'STAR_NUPR' => $nupr,
                     'STAR_TIAD' => $tiad,
                     'STAR_IDPC' => $preCodificate,
-                    'STAR_CONS' => $requestData['CONSUMIBLE'] ? 'Si' : 'No',
-                    'STAR_REPA' => $requestData['REPARABLE'] ? 'Si' : 'No',
+                    'STAR_CONS' => $cons,
+                    'STAR_REPA' => $repa,
                     'STAR_PRAD' => $prad,
                     'STAR_COMO' => $como,
                     'STAR_ESTA' => 'Pendiente',
@@ -2979,20 +2979,20 @@ class StockController extends Controller
                 $nupr = isset($info) ? $info[$i]['NUMERO_PROVEEDOR'] : 0;
                 $idli = array_key_exists('ID_LINEA_SOLICITUD', $orden) ? $orden['ID_LINEA_SOLICITUD'] : 0;
 
-                $validateUpdateArSe = DB::table('S002V01TARSE')
-                    ->where('ARSE_IDAS', '=', $idas)
-                    ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
-                    ->where('ARSE_IDLI', '=', $idli)
-                    ->where('ARSE_IDAR', '=', $idar)
-                    ->where('ARSE_NUPR', '=', $nupr)
-                    ->where('ARSE_IDIN', '=', $requestData['ID_INFORMATION'])
-                    ->where('ARSE_ESTA', '=', 'Activo')
-                    ->update([
-                        'ARSE_ESTA' => 'Guardado',
-                        'ARSE_USMO' => $user,
-                        'ARSE_FEMO' => $currentDate,
-                        'ARSE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
-                    ]);
+                $validateUpdateArSe = DB::table('S002V01TARSE')->where([
+                    ['ARSE_IDAS', '=', $idas],
+                    ['ARSE_NULI', '=', $requestData['NUMERO_LINEA']],
+                    ['ARSE_IDLI', '=', $idli],
+                    ['ARSE_IDAR', '=', $idar],
+                    ['ARSE_NUPR', '=', $nupr],
+                    ['ARSE_IDIN', '=', $requestData['ID_INFORMATION']],
+                    ['ARSE_ESTA', '=', 'Activo'],
+                ])->update([
+                    'ARSE_ESTA' => 'Guardado',
+                    'ARSE_USMO' => $user,
+                    'ARSE_FEMO' => $currentDate,
+                    'ARSE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
+                ]);
             } catch (\Throwable $th) {
                 DB::rollBack();
                 return $this->responseController->makeResponse(true, 'Ocurrió un error al modificar el artículo seleccionado.', $th->getMessage(), 500);
@@ -3071,29 +3071,121 @@ class StockController extends Controller
     }
 
     // FUNCIÓN PARA JOSÉ LUIS
-    public function getInfoStock($user, $line) {
+    public function getInfoStock($limit, $offset, $user, $line) {
         $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
         if ($arrResponseCheckUser['error']) {
             return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
         }
 
         try {
-            $arrStockArtitle = DB::table('S002V01TSTAR')
-                ->where('STAR_NULI', '=', $line)
-                ->where('STAR_ESTA', '=', 'Activo')
-                ->where('INST_NULI', '=', $line)
-                ->where('INST_ESTA', '=', 'Activo')
-                ->where('UBAR_ESTA', '=', 'Activo')
-                ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
-                ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
-                ->get([
-                    'STAR_IDST AS ID_STOCK',
-                    'INST_MODE AS MODELO',
-                    'INST_COMO AS CODIGO_MODELO',
-                    'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
-                    'STAR_CONS AS CONSUMIBLE',
-                    'STAR_REPA AS REPARABLE',
-                ]);
+            $arrStockArtitle = DB::table('S002V01TSTAR')->select([
+                DB::raw("
+                    CONCAT(
+                        INST_IDIS,'|',
+    	                SUBSTRING(UBAR_COUB, 1, LENGTH(UBAR_COUB) - 7),
+                        '|',INST_MODE,'|',INST_COMO,'|',IF(
+        	                ISNULL(INST_STMI),'0',INST_STMI
+                        ),'|',IF(
+        	                ISNULL(INST_STMA),'0',INST_STMA
+                        ),'|',EQUI_GAIM,'|',EQUI_PREQ,'|',PROV_NOCO,'|',
+                        UBAR_COAL,'|',ALMA_NOAL,'|',UBAR_COAR,'|',AREA_NOAR,
+                        '|',UBAR_CONI,'|',NIVE_NONI,'|',UBAR_COZO,'|',ZONA_NOZO,'|',IF(
+        	                ISNULL(INST_CARE),'0',INST_CARE
+                        )
+                    ) AS INFO_EQUIPAMIENTO
+                "),
+                DB::raw("COUNT(*) AS CANTIDAD_DISPONIBLE")
+            ])->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
+            ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
+            ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'UBAR_COUB')
+            ->join('S002V01TPROV', 'PROV_NUPR', '=', 'EQUI_PREQ')
+            ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
+            ->join('S002V01TAREA', function(JoinClause $join) {
+                $join->on('AREA_COAL', '=', 'UBAR_COAL')
+                ->on('AREA_COAR', '=', 'UBAR_COAR');
+            })->join('S002V01TNIVE', function(JoinClause $join) {
+                $join->on('NIVE_COAL', '=', 'UBAR_COAL')
+                ->on('NIVE_COAR', '=', 'UBAR_COAR')
+                ->on('NIVE_CONI', '=', 'UBAR_CONI');
+            })->join('S002V01TZONA', function(JoinClause $join) {
+                $join->on('ZONA_COAL', '=', 'UBAR_COAL')
+                ->on('ZONA_COAR', '=', 'UBAR_COAR')
+                ->on('ZONA_CONI', '=', 'UBAR_CONI')
+                ->on('ZONA_COZO', '=', 'UBAR_COZO');
+            })->where([
+                ['INST_NULI', '=', $line],
+                ['INST_ESTA', '=', 'Activo'],
+            ])->groupBy('INFO_EQUIPAMIENTO')->limit($limit)->offset($offset)->get()->all();
+
+            $arrStockArtitleFn = [];
+            foreach($arrStockArtitle as $item){
+                $equipmentInfoArr = explode('|', $item->INFO_EQUIPAMIENTO);
+                $imagesGallery = json_decode($equipmentInfoArr[6], true);
+
+                foreach($imagesGallery as $k0=>$v0){
+                    $v0 = $this->encController->encrypt($v0);
+                    $imagesGallery[$k0] = $v0;
+                }
+
+                $equipmentInfoArrFn = [
+                    'ID_STOCK' => $this->encController->encrypt($equipmentInfoArr[0]),
+                    'CODIGO_EQUIPAMIENTO' => $this->encController->encrypt($equipmentInfoArr[1]),
+                    'MODELO' => $equipmentInfoArr[2],
+                    'CODIGO_MODELO' => $this->encController->encrypt($equipmentInfoArr[3]),
+                    'STOCK_MINIMO' => intval($equipmentInfoArr[4]),
+                    'STOCK_MAXIMO' => intval($equipmentInfoArr[5]),
+                    'GALERIA_IMAGENES' => $imagesGallery,
+                    'ID_PROVEEDOR' => $this->encController->encrypt($equipmentInfoArr[7]),
+                    'NOMBRE_PROVEEDOR' => $equipmentInfoArr[8],
+                    'CODIGO_ALMACEN' => $this->encController->encrypt($equipmentInfoArr[9]),
+                    'ALMACEN' => $equipmentInfoArr[10],
+                    'CODIGO_AREA' => $this->encController->encrypt($equipmentInfoArr[11]),
+                    'AREA' => $equipmentInfoArr[12],
+                    'CODIGO_NIVEL' => $this->encController->encrypt($equipmentInfoArr[13]),
+                    'NIVEL' => $equipmentInfoArr[14],
+                    'CODIGO_ZONA' => $this->encController->encrypt($equipmentInfoArr[15]),
+                    'ZONA' => $equipmentInfoArr[16],
+                    'CANTIDAD_DISPONIBLE' => $item->CANTIDAD_DISPONIBLE,
+                    'CANTIDAD_REABASTECIMIENTO' => intval($equipmentInfoArr[17])
+                ];
+
+                $arrStockArtitleFn[] = $equipmentInfoArrFn;
+            }
+        } catch (\Throwable $th) {
+            return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
+        }
+
+        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStockArtitleFn);
+    }
+    public function getInfoStockTotalItems($user, $line) {
+        $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
+        if ($arrResponseCheckUser['error']) {
+            return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
+        }
+
+        try {
+            $arrStockArtitle = DB::table('S002V01TINST')->select([
+                DB::raw('COUNT(*) AS TOTAL_ITEMS')
+            ])->join('S002V01TUBAR', 'UBAR_IDST', '=', 'INST_IDIS')
+            ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'UBAR_COUB')
+            ->join('S002V01TPROV', 'PROV_NUPR', '=', 'EQUI_PREQ')
+            ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
+            ->join('S002V01TAREA', function(JoinClause $join) {
+                $join->on('AREA_COAL', '=', 'UBAR_COAL')
+                ->on('AREA_COAR', '=', 'UBAR_COAR');
+            })->join('S002V01TNIVE', function(JoinClause $join) {
+                $join->on('NIVE_COAL', '=', 'UBAR_COAL')
+                ->on('NIVE_COAR', '=', 'UBAR_COAR')
+                ->on('NIVE_CONI', '=', 'UBAR_CONI');
+            })->join('S002V01TZONA', function(JoinClause $join) {
+                $join->on('ZONA_COAL', '=', 'UBAR_COAL')
+                ->on('ZONA_COAR', '=', 'UBAR_COAR')
+                ->on('ZONA_CONI', '=', 'UBAR_CONI')
+                ->on('ZONA_COZO', '=', 'UBAR_COZO');
+            })->where([
+                ['INST_NULI', '=', $line],
+                ['INST_ESTA', '=', 'Activo'],
+            ])->first();
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
         }
@@ -3849,44 +3941,57 @@ class StockController extends Controller
         }
 
         try {
-            $arrInfo = (array) DB::table('S002V01TSTAR')
-                ->where('STAR_IDST', '=', $idStock)
-                ->where('STAR_NULI', '=', $line)
-                ->where('INST_NULI', '=', $line)
-                ->where('UBAR_NULI', '=', $line)
-                ->where('INST_ESTA', '=', 'Activo')
-                ->where('UBAR_ESTA', '=', 'Activo')
-                ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
-                ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
-                ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
-                ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
-                ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
-                ->join('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
-                ->join('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
-                ->join('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
-                ->join('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
-                ->first([
-                    DB::raw('CONCAT(FAMI_NOFA, " (", FAMI_COFA, ")") AS FAMILIA'),
-                    DB::raw('CONCAT(SUBF_NOSU, " (", SUBF_COSU, ")") AS SUBFAMILIA'),
-                    'INST_MODE AS MODELO',
-                    'INST_COMO AS CODIGO_MODELO',
-                    'INST_STMI AS STOCK_MINIMO',
-                    'INST_STMA AS STOCK_MAXIMO',
-                    'STAR_IDST AS ID_STOCK',
-                    'STAR_COBA AS CODIGO_BARRAS',
-                    'STAR_FEVE AS FECHA_VENCIMIENTO',
-                    DB::raw('CONCAT(PROV_NOCO, " (", PROV_NUPR, ")") AS NUMERO_PROVEEDOR'),
-                    'STAR_TIAD AS TIPO_ADQUISICION',
-                    'STAR_CONS AS CONSUMIBLE',
-                    'STAR_REPA AS REPARABLE',
-                    'STAR_ESTA AS ESTADO',
-                    'UBAR_IDUB AS ID_UBICACION',
-                    DB::raw('CONCAT(ALMA_NOAL, " (", ALMA_COAL, ")") AS ALMACEN'),
-                    DB::raw('CONCAT(AREA_NOAR, " (", AREA_COAR, ")") AS AREA'),
-                    DB::raw('CONCAT(NIVE_NONI, " (", NIVE_CONI, ")") AS NIVEL'),
-                    DB::raw('CONCAT(ZONA_NOZO, " (", ZONA_COZO, ")") AS ZONA'),
-                    'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
-                ]);
+            $arrInfo = DB::table('S002V01TSTAR')->select([
+                DB::raw("CONCAT(FAMI_NOFA, ' (', FAMI_COFA, ')') AS FAMILIA"),
+                DB::raw("CONCAT(SUBF_NOSU, ' (', SUBF_COSU, ')') AS SUBFAMILIA"),
+                'INST_MODE AS MODELO',
+                'INST_COMO AS CODIGO_MODELO',
+                'INST_STMI AS STOCK_MINIMO',
+                'INST_STMA AS STOCK_MAXIMO',
+                'STAR_IDST AS ID_STOCK',
+                'STAR_COBA AS CODIGO_BARRAS',
+                'STAR_FEVE AS FECHA_VENCIMIENTO',
+                DB::raw('CONCAT(PROV_NOCO, " (", PROV_NUPR, ")") AS NUMERO_PROVEEDOR'),
+                'STAR_TIAD AS TIPO_ADQUISICION',
+                'STAR_CONS AS CONSUMIBLE',
+                'STAR_REPA AS REPARABLE',
+                'STAR_ESTA AS ESTADO',
+                'UBAR_IDUB AS ID_UBICACION',
+                DB::raw('CONCAT(ALMA_NOAL, " (", ALMA_COAL, ")") AS ALMACEN'),
+                DB::raw('CONCAT(AREA_NOAR, " (", AREA_COAR, ")") AS AREA'),
+                DB::raw('CONCAT(NIVE_NONI, " (", NIVE_CONI, ")") AS NIVEL'),
+                DB::raw('CONCAT(ZONA_NOZO, " (", ZONA_COZO, ")") AS ZONA'),
+                'EQUI_COEQ AS CODIGO_EQUIPAMIENTO',
+            ])->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
+            ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
+            ->join('S002V01TSUBF', function (JoinClause $join) {
+                $join->on('SUBF_COFA', '=', 'INST_COFA')
+                ->on('SUBF_COSU', '=', 'INST_COSU');
+            })->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
+            ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'UBAR_COUB')
+            ->join('S002V01TPROV', 'PROV_NUPR', '=', 'EQUI_PREQ')
+            ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
+            ->join('S002V01TAREA', function (JoinClause $join) {
+                $join->on('AREA_COAL', '=', 'UBAR_COAL')
+                ->on('AREA_COAR', '=', 'UBAR_COAR');
+            })->join('S002V01TNIVE', function (JoinClause $join) {
+                $join->on('NIVE_COAL', '=', 'UBAR_COAL')
+                ->on('NIVE_COAR', '=', 'UBAR_COAR')
+                ->on('NIVE_CONI', '=', 'UBAR_CONI');
+            })->join('S002V01TZONA', function (JoinClause $join) {
+                $join->on('ZONA_COAL', '=', 'UBAR_COAL')
+                ->on('ZONA_COAR', '=', 'UBAR_COAR')
+                ->on('ZONA_CONI', '=', 'UBAR_CONI')
+                ->on('ZONA_COZO', '=', 'UBAR_COZO');
+            })->where([
+                ['STAR_IDST', '=', $idStock],
+                ['STAR_NULI', '=', $line],
+                ['INST_NULI', '=', $line],
+                ['UBAR_NULI', '=', $line],
+                ['INST_ESTA', '=', 'Activo'],
+                ['UBAR_ESTA', '=', 'Activo'],
+            ])->first();
+
             $arrInfo = json_decode(json_encode($arrInfo), true);
         } catch (\Throwable $th) {
             return $this->responseController->makeResponse(true, "Ocurrió un error al recuperar la información.", $th->getMessage(), 500);
@@ -4079,6 +4184,98 @@ class StockController extends Controller
         return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
     }
 
+    public function updateReplenishment(Request $request) {
+        $validator = Validator::make($request->all(), [
+            'id_stock' => 'required|string',
+            'replenishment' => 'required|integer',
+            'USUARIO' => 'required|string',
+            'NUMERO_LINEA' => 'required|integer',
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                true,
+                "Se encontraron uno o más errores.",
+                $this->responseController->makeErrors(
+                    $validator->errors()->messages()
+                ),
+                401
+            );
+        }
+
+        DB::beginTransaction();
+        $requestData = $request->all();
+
+        $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
+        if ($arrResponseCheckUser['error']) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
+        }
+
+        $user = $arrResponseCheckUser['response'];
+
+        $idInfo = $this->encController->decrypt($requestData['id_stock']);
+        if (is_null($idInfo)) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
+        }
+
+        try {
+            $validateExist = DB::table('S002V01TINST')->where([
+                ['INST_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['INST_IDIS', '=', $idInfo],
+                ['INST_ESTA', '=', 'Activo'],
+            ])->exists();
+        } catch (\Throwable $th) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si existe el artículo.', $th->getMessage(), 500);
+        }
+
+        if (!$validateExist) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, 'El artículo no existe.', [], 401);
+        }
+
+        try {
+            $replenishment = intval($requestData['replenishment']);
+        } catch (\Throwable $th) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, 'Ocurrió un error con el formato de la cantidad de reabastecimiento.', $th->getMessage(), 500);
+        }
+
+        if ($replenishment < 0) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, 'La cantidad de reabastecimiento no debe ser menor a 0.', [], 401);
+        }
+
+        $now = $this->functionsController->now();
+        $currentDate = $now->toDateTimeString();
+
+        try {
+            $validateUpdate = DB::table('S002V01TINST')->where([
+                ['INST_NULI', '=', $requestData['NUMERO_LINEA']],
+                ['INST_IDIS', '=', $idInfo],
+                ['INST_ESTA', '=', 'Activo'],
+            ])->update([
+                'INST_CARE' => $replenishment,
+                'INST_USMO' => $user,
+                'INST_FEMO' => $currentDate,
+                'INST_FEAR' => DB::raw('CURRENT_TIMESTAMP')
+            ]);
+        } catch (\Throwable $th) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, 'Ocurrió un error al modificar la cantidad de reabastecimiento.', $th->getMessage(), 500);
+        }
+        
+        if (!$validateUpdate) {
+            DB::rollBack();
+            return $this->responseController->makeResponse(true, 'No se pudo modificar la cantidad de reabastecimiento.', [], 401);
+        }
+
+        DB::commit();
+        return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
+    }
+
     public function getStockBarcode($user, $line) {
         $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
         if ($arrResponseCheckUser['error']) {

+ 101 - 9
sistema-mantenimiento-back/app/Http/Controllers/UsersProfilesController.php

@@ -2,6 +2,7 @@
 
 namespace App\Http\Controllers;
 
+use Illuminate\Database\Query\Builder;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Validator;
@@ -95,6 +96,94 @@ class UsersProfilesController extends Controller{
         $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
         return $this->responseController->makeresponse(false, "EXITO", $users);
     }
+    
+    public function getUsersFilt($value, $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_IDUS', '=', $idUser],
+            ['USUA_NULI', '=', $line],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 400);
+        }
+        
+        $value = strtoupper($value);
+        $valueLike = "%$value%";
+        $users = DB::table('S002V01TUSUA')->select([
+            'USUA_IDUS as IDUSUARIO',
+            'USUA_NOMB as NOMBRE',
+            'USUA_APPA as APEPAT',
+            'USUA_APMA as APEMAT',
+            'USUA_COEL as EMAIL',
+            DB::raw("CONCAT(PERF_NOPE, ' (', PERF_IDPE, ')') AS PERFIL"),
+            DB::raw("IF(ISNULL(PACO_IDPC), FALSE, TRUE) AS TIENE_PANEL"),
+            DB::raw("IF(ISNULL(PACO_IDPC), '-', CONCAT(PACO_NPCO, ' (', PACO_IDPC, ')')) AS PANEL_CONTROL"),
+            'PERS_TICO AS TIPO_EMPLEADO',
+            'USUA_ESTA as ESTATUS',
+            'BIAC_FECO as ULCON',
+            'USUA_ORGA as ORGANIGRAMA',
+        ])->join('S002V01TPERF', 'USUA_PERF', '=', 'PERF_IDPE')
+        ->leftJoin('S002V01TBIAC', 'USUA_ULCO', '=', 'BIAC_IDCO')
+        ->leftJoin('S002V01TPACO', 'USUA_PCRE', '=', 'PACO_IDPC')
+        ->leftJoin('S002V01TPERS', 'PERS_IDUS', '=', 'USUA_IDUS')
+        ->where('USUA_NULI', '=', $line)->where(function (Builder $query) use ($valueLike) {
+            $query->orWhere('USUA_IDUS', 'LIKE', $valueLike)
+            ->orWhere('USUA_NOMB', 'LIKE', $valueLike)
+            ->orWhere('USUA_APPA', 'LIKE', $valueLike)
+            ->orWhere('USUA_APMA', 'LIKE', $valueLike);
+        })->get()->all();
+
+        $usersFn = [];
+        foreach($users as $key=>$user){
+            $user->IDUSUARIO = $this->encryptionController->encrypt($user->IDUSUARIO);
+            $user->TIENE_PANEL = $user->TIENE_PANEL == 1;
+
+            if(is_null($user->ORGANIGRAMA)){
+                $user->ORGANIGRAMA = '[]';
+            }else{
+                $organization = json_decode($user->ORGANIGRAMA, true);
+                foreach($organization as $index=>$item){
+                    $idChiefEnc = $this->encryptionController->encrypt($item['id_chief']);
+                    $item['id_chief'] = $idChiefEnc;
+
+                    $organization[$index] = $item;
+                }
+
+                $user->ORGANIGRAMA = json_encode($organization);
+            }
+
+            if(!is_null($user->TIPO_EMPLEADO)){
+                $usersFn[] = $user;
+            }
+        }
+
+        $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,
+            $this->moduleCode,
+            'S002V01F01ADUS',
+            'S002V01P01COUS',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los usuarios registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GEUS'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeresponse(false, "EXITO", $usersFn);
+    }
 
     public function configureUserOrganization(Request $request){
         DB::enableQueryLog();
@@ -513,17 +602,19 @@ class UsersProfilesController extends Controller{
             foreach($permissionsPerSubmodule as $perm){ $permissionsArr[] = $perm; }
             foreach($permissionsPerFunction as $perm){ $permissionsArr[] = $perm; }
 
-            $moduleAccess = $profilePermissions['permissions'][$moduleIndex]['access'];
+            if(array_key_exists($moduleIndex, $profilePermissions['permissions'])){
+                $moduleAccess = $profilePermissions['permissions'][$moduleIndex]['access'];
 
-            $permissions[] = [
-                'id' => $this->encryptionController->encrypt($module->MODU_IDMO),
-                'name' => $module->MODU_NOMO,
-                'access' => $moduleAccess,
-                'children' => $permissionsArr,
-                'enabled' => $module->MODU_ESTA == 'E'
-            ];
+                $permissions[] = [
+                    'id' => $this->encryptionController->encrypt($module->MODU_IDMO),
+                    'name' => $module->MODU_NOMO,
+                    'access' => $moduleAccess,
+                    'children' => $permissionsArr,
+                    'enabled' => $module->MODU_ESTA == 'E'
+                ];
 
-            $moduleIndex++;
+                $moduleIndex++;
+            }
         }
 
         $now = $this->functionsController->now();
@@ -1327,6 +1418,7 @@ class UsersProfilesController extends Controller{
                 'name' => $module->MODU_NOMO,
                 'access' => 0,
                 'children' => $permissionsArr,
+                'enabled' => $module->MODU_ESTA == 'E',
             ];
         }
 

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