responseController = new ResponseController(); $this->encryptionController = new EncryptionController(); $this->functionsController = new FunctionsController(); $this->documentManagementController = new DocumentManagementController(); $this->notificationsController = new NotificationsController(); $this->templatesUbic = $this->functionsController->getBasePath() . "\storage\app\public\pdf_templates\\01_04_GMCO\\"; } private function getSocketClient(){ $url = 'http://localhost:3200'; $socketClient = new Client(Client::engine(Client::CLIENT_4X, $url)); $socketClient->initialize(); $socketClient->of('/'); return $socketClient; } public function registerWorkOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_responsible' => 'required|string', 'type_responsible' => 'required|string|in:U,S', 'description' => 'required|string|min:15', 'equipment' => 'required|string', 'start_date_time' => 'required|date', 'solution_time' => 'required|numeric', 'priority' => 'required|string', 'id_counter' => 'required|string', 'id_last_measure' => 'required|string', 'clasification' => 'required|string|max:50', 'staff' => 'required|json', 'security_management' => 'required|string', 'activation_type' => 'required|string|in:Manual,Automática', 'resources' => 'required|json', 'attached' => 'json', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idUserResponsible = $this->encryptionController->decrypt($form['id_responsible']); if(!$idUserResponsible){ return $this->responseController->makeResponse(true, 'El ID del usuario responsable no fue encriptado correctamente.', [], 400); } $usrResponsible = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUserResponsible] ])->first(); if(is_null($usrResponsible)){ return $this->responseController->makeResponse(true, 'El usuario responsable de atender la solicitud no existe.', [], 404); } $equipmentCode = $this->encryptionController->decrypt($form['equipment']); if(!$equipmentCode){ return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400); } $equipment = DB::table('S002V01TEQUI')->where([ ['EQUI_NULI', '=', $form['linea']], ['EQUI_COEQ', '=', $equipmentCode], ])->first(); if(is_null($equipment)){ return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404); } if(floatval($form['solution_time']) <= 0){ return $this->responseController->makeResponse(true, 'El tiempo de solución estimado debe ser mayor a cero.', [], 400); } $priority = $this->encryptionController->decrypt($form['priority']); if(!$priority){ return $this->responseController->makeResponse(true, 'La prioridad relacionada no fue encriptada correctamente.', [], 400); } $validPriorities = ['1', '2', '3', '4']; if(!in_array($priority, $validPriorities)){ return $this->responseController->makeResponse(true, 'La prioridad relacionada es inválida.', [], 400); } $idCounter = $this->encryptionController->decrypt($form['id_counter']); if(!$idCounter){ return $this->responseController->makeResponse(true, 'El ID del contador relacionado no fue encriptado correctamente.', [], 400); } $counter = DB::table('S002V01TCONA')->where([ ['CONA_IDCO', '=', $idCounter], ['CONA_NULI', '=', $form['linea']] ])->first(); if(is_null($counter)){ return $this->responseController->makeResponse(true, 'El contador relacionado no existe.', [], 404); } $idLastMeasure = $this->encryptionController->decrypt($form['id_last_measure']); if(!$idLastMeasure){ return $this->responseController->makeResponse(true, 'El ID de la última medida del contador relacionado no fue encriptado correctamente.', [], 400); } $lastMeasure = DB::table('S002V01TMEDI')->select([ 'MEDI_IDME AS ID_MEDIDA', 'MEDI_CORE AS CONTADOR', 'MEDI_VALO AS VALOR', 'MEDI_WSRE AS ID_SERVICIO_WEB', 'LSWE_URLX AS URL_SERVICIO_WEB', 'MEDI_HORE AS HORA_REGISTRO', ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([ ['MEDI_IDME', '=', $idLastMeasure], ['MEDI_NULI', '=', $form['linea']], ['MEDI_CORE', '=', $idCounter] ])->orderBy('MEDI_HORE', 'desc')->first(); if(is_null($lastMeasure)){ return $this->responseController->makeResponse(true, 'La última medida del contador relacionado no existe.', [], 404); } $staffArr = json_decode($form['staff'], true); if(count($staffArr) == 0){ return $this->responseController->makeResponse(true, 'El arreglo del personal está vacío.', [], 400); } $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); $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); } $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; } $rhut = json_encode($resources); $attachedArrFn = []; if(isset($form['attached'])){ $attachedArr = json_decode($form['attached'], true); foreach($attachedArr as $key=>$attached){ $idDec = $this->encryptionController->decrypt($attached['id']); if(!$idDec){ return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400); } if($attached['type'] == 'Existente'){ $codeArr = explode('=', $idDec); $codeArr0 = explode('-', $codeArr[0]); $file = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $form['linea']], ['AFAL_COMO', '=', $codeArr0[1]], ['AFAL_CLDO', '=', $codeArr0[2]], ['AFAL_FECR', '=', $codeArr0[3]], ['AFAL_NUSE', '=', $codeArr0[4]], ['AFAL_NUVE', '=', $codeArr[1]], ])->first(); if(is_null($file)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($file->AFAL_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $attachedArrFn[] = $idDec; }else if($attached['type'] == 'Nuevo'){ $tempFile = DB::table('S002V01TARTE')->where([ ['ARTE_IDAR', '=', $idDec], ['ARTE_NULI', '=', $form['linea']] ])->first(); if(is_null($tempFile)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($tempFile->ARTE_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser); if(!$finalFile[0]){ return $this->responseController->makeResponse(true, $finalFile[1], [], 400); }else{ $attachedArrFn[] = $finalFile[1]; } } } } $activationType = $form['activation_type'][0]; $attachedStrFn = json_encode($attachedArrFn); $lastMeasureStr = json_encode($lastMeasure); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $statusHistoryStr = json_encode([ ['USUARIO' => $idUser, 'ESTADO' => 'PE', 'FECHA' => $nowStr] ]); $orderID = DB::table('S002V01TOTCO')->insertGetId([ 'OTCO_NULI' => $form['linea'], 'OTCO_IDUR' => $idUserResponsible, 'OTCO_TURE' => $form['type_responsible'], 'OTCO_DEIN' => $form['description'], 'OTCO_EQIN' => $equipmentCode, 'OTCO_FIFA' => $form['start_date_time'], 'OTCO_TESO' => $form['solution_time'], 'OTCO_CORE' => $idCounter, 'OTCO_DRCO' => $lastMeasureStr, 'OTCO_PRIO' => $priority, 'OTCO_RHUT' => $rhut, 'OTCO_PEIN' => $staffStrFn, 'OTCO_TIAC' => $activationType, 'OTCO_DORE' => $attachedStrFn, 'OTCO_CLAS' => $form['clasification'], 'OTCO_GESE' => $idManagement, 'OTCO_HIES' => $statusHistoryStr, 'OTCO_ESOR' => 'PE', 'OTCO_USRE' => $idUser, 'OTCO_FERE' => $nowStr ]); $this->notificationsController->emitNotification( 'S002V01M09GMCO', "Orden de mantenimiento correctivo #$orderID", "Su usuario ha sido asignado como responsable de atender la orden de mantenimiento #$orderID.", [[ 'BOTON' => 'Ver detalles', 'FUNCION' => 'openCorrectiveWorkOrderDetails', 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($orderID)]) ], [ 'BOTON' => 'Validar orden', 'FUNCION' => 'validateCorrectiveWorkOrder', 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($orderID)]) ], [ 'BOTON' => 'Ir al módulo', 'FUNCION' => 'openModule', 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')]) ]], [$idUserResponsible], $idUser, $form['linea'], $this->getSocketClient(), $orderID, 'Correctivo' ); $idOrderEnc = $this->encryptionController->encrypt($orderID); $socketData = ['idOrder' => $idOrderEnc]; $this->getSocketClient()->emit('new_corrective_work_order', $socketData); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F04GEOT', 'S002V01P01GEOT', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró la orden de trabajo correctivo #$orderID.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getWorkOrders($idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404); } $orders = DB::table('S002V01TOTCO')->select([ 'OTCO_IDOT AS ID_ORDEN', 'OTCO_EQIN AS CODIGO_EQUIPAMIENTO', 'EQUI_TIPO AS TIPO_EQUIPAMIENTO', 'EQUI_MODE AS MODELO_EQUIPAMIENTO', 'EQUI_IDEQ AS ID_EQUIPAMIENTO', 'OTCO_FIFA AS FECHA_INICIO', 'OTCO_CORE AS CONTADOR', 'OTCO_FTIN AS FECHA_FIN', 'OTCO_TIAC AS TIPO_ACTIVACION', 'OTCO_IDUR AS ID_RESPONSABLE', 'OTCO_TURE AS TIPO_RESPONSABLE', 'OTCO_PRIO AS PRIORIDAD', 'OTCO_ESOR AS ESTADO' ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTCO_EQIN') ->where('OTCO_NULI', '=', $line) ->orderBy('OTCO_IDOT', 'desc')->get()->all(); $subcontratistTypes = ['S' => 'Subcontratista', 'U' => 'Usuario']; $activationTypes = ['M' => 'Manual', 'A' => 'Automática']; $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; foreach($orders as $key=>$order){ if($order->TIPO_RESPONSABLE == 'U'){ $userResponsible = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $order->ID_RESPONSABLE], ['USUA_NULI', '=', $line] ])->first(); $userResponsibleName = $this->functionsController->joinName($userResponsible->USUA_NOMB, $userResponsible->USUA_APPA, $userResponsible->USUA_APMA); $order->ID_RESPONSABLE = $userResponsibleName . " (" . $order->ID_RESPONSABLE . ")"; }else{ $subcontratistResponsible = DB::table('S002V01TPESU')->where([ ['PESU_NULI', '=', $line], ['PESU_IDPS', '=', $order->ID_RESPONSABLE] ])->first(); if(!is_null($subcontratistResponsible)){ $order->ID_RESPONSABLE = $subcontratistResponsible->PESU_RASO . " (" . $subcontratistResponsible->PESU_REFI . ") (" . $order->ID_RESPONSABLE . ")"; }else{ $order->ID_RESPONSABLE = "N/D"; } } $order->TIPO_RESPONSABLE = $subcontratistTypes[$order->TIPO_RESPONSABLE]; $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN); $order->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($order->CODIGO_EQUIPAMIENTO); $order->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($order->ID_EQUIPAMIENTO); $order->CONTADOR = $this->encryptionController->encrypt($order->CONTADOR); $order->TIPO_ACTIVACION = $activationTypes[$order->TIPO_ACTIVACION]; $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD); $order->ESTADO = $orderStates[$order->ESTADO]; $orders[$key] = $order; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F01GEOP', 'S002V01P01COOP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de mantenimiento correctivo registradas.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $orders); } public function getWorkOrder($idOrder, $idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idOrder = $this->encryptionController->decrypt($idOrder); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente', [], 400); } $order = DB::table('S002V01TOTCO')->select([ 'OTCO_IDOT AS ID_ORDEN', 'OTCO_DEIN AS DESCRIPCION', 'OTCO_EQIN AS CODIGO_EQUIPAMIENTO', 'EQUI_TIPO AS TIPO_EQUIPAMIENTO', 'EQUI_MODE AS MODELO_EQUIPAMIENTO', 'EQUI_IDEQ AS ID_EQUIPAMIENTO', 'OTCO_FIFA AS FECHA_INICIO', 'OTCO_TESO AS TIEMPO_ESTIMADO', 'OTCO_CORE AS CONTADOR', 'OTCO_DRCO AS MEDIDAS', 'OTCO_PRIO AS PRIORIDAD', 'OTCO_FTIN AS FECHA_FINAL', 'OTCO_DTIN AS DURACION_TOTAL', 'OTCO_RHUT AS RECURSOS', 'OTCO_PEIN AS PERSONAL', 'OTCO_TIAC AS TIPO_ACTIVACION', 'OTCO_IDUR AS ID_RESPONSABLE', 'OTCO_TURE AS TIPO_RESPONSABLE', 'OTCO_ANCO AS ANALISIS_COSTOS', 'OTCO_DORE AS DOCUMENTOS_RELACIONADOS', 'OTCO_CLAS AS CLASIFICACION', 'OTCO_COME AS COMENTARIOS', 'OTCO_GESE AS GERENCIA_SEGURIDAD', 'OTCO_CAEX AS CAMPOS_EXTRA', 'OTCO_ESOR AS ESTADO', 'OTCO_USRE AS USUREG', 'OTCO_FERE AS FECREG', 'OTCO_USMO AS USUMOD', 'OTCO_FEMO AS FECMOD' ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTCO_EQIN') ->where([ ['OTCO_IDOT', '=', $idOrder], ['OTCO_NULI', '=', $line] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404); } $subcontratistTypes = ['S' => 'Subcontratista', 'U' => 'Usuario']; if($order->TIPO_RESPONSABLE == 'U'){ $userResponsible = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $order->ID_RESPONSABLE], ['USUA_NULI', '=', $line] ])->first(); $userResponsibleName = $this->functionsController->joinName($userResponsible->USUA_NOMB, $userResponsible->USUA_APPA, $userResponsible->USUA_APMA); $order->ID_RESPONSABLE = $userResponsibleName . " (" . $order->ID_RESPONSABLE . ")"; }else{ $subcontratistResponsible = DB::table('S002V01TPESU')->where([ ['PESU_NULI', '=', $line], ['PESU_IDPS', '=', $order->ID_RESPONSABLE] ])->first(); if(!is_null($subcontratistResponsible)){ $order->ID_RESPONSABLE = $subcontratistResponsible->PESU_RASO . " (" . $subcontratistResponsible->PESU_REFI . ") (" . $order->ID_RESPONSABLE . ")"; } } $order->TIPO_RESPONSABLE = $subcontratistTypes[$order->TIPO_RESPONSABLE]; $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN); $order->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($order->CODIGO_EQUIPAMIENTO); $order->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($order->ID_EQUIPAMIENTO); $order->CONTADOR = $this->encryptionController->encrypt($order->CONTADOR); $measureArr = json_decode($order->MEDIDAS, true); if(!empty($measureArr)){ $measureArr['CONTADOR'] = $this->encryptionController->encrypt($measureArr['CONTADOR']); $measureArr['ID_MEDIDA'] = $this->encryptionController->encrypt($measureArr['ID_MEDIDA']); $measureArr['ID_SERVICIO_WEB'] = $this->encryptionController->encrypt($measureArr['ID_SERVICIO_WEB']); } $order->MEDIDAS = json_encode($measureArr); $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD); $order->GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($order->GERENCIA_SEGURIDAD); $staffArr = json_decode($order->PERSONAL, true); foreach($staffArr as $key=>$val){ $specialty = DB::table('S002V01TGEES')->where([ ['GEES_NULI', '=', $line], ['GEES_COES', '=', $val['ID']] ])->first(); $val['ID'] = $this->encryptionController->encrypt($val['ID']); $val['NAME'] = $specialty->GEES_NOES; $staffArr[$key] = $val; } $activationTypes = ['M' => 'Manual', 'A' => 'Automática']; $order->PERSONAL = json_encode($staffArr); $order->TIPO_ACTIVACION = $activationTypes[$order->TIPO_ACTIVACION]; $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; $resources = json_decode($order->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(); if(!is_null($resourceObj)){ $resource['NAME'] = $resourceObj->INST_MODE; $resource['UNIT'] = $resourceObj->UNID_NOMB; } $resource['ID'] = $this->encryptionController->encrypt($resource['ID']); } $resources[$key] = $resource; } $order->RECURSOS = json_encode($resources); $order->ESTADO = $orderStates[$order->ESTADO]; $documentsArr = json_decode($order->DOCUMENTOS_RELACIONADOS, true); $documentsFn = []; foreach($documentsArr as $document){ $documentArr = explode('=', $document); $codeArr = explode('-', $documentArr[0]); $file = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $line], ['AFAL_COMO', '=', $codeArr[1]], ['AFAL_CLDO', '=', $codeArr[2]], ['AFAL_FECR', '=', $codeArr[3]], ['AFAL_NUSE', '=', $codeArr[4]], ['AFAL_NUVE', '=', $documentArr[1]] ])->first(); $documentsFn[] = [ 'id' => $this->encryptionController->encrypt($document), 'name' => $file->AFAL_NOAR . '.' . $file->AFAL_EXTE, 'size' => $file->AFAL_TAMA, 'type' => 'Existente' ]; } $order->DOCUMENTOS_RELACIONADOS = json_encode($documentsFn); $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $order->USUREG], ['USUA_NULI', '=', $line] ])->first(); if(is_null($usrReg)){ $order->USUREG = "AUTOMÁTICO (0)"; }else{ $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $order->USUREG = $nameReg . " (" . $order->USUREG . ")"; } if(!is_null($order->USUMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $order->USUMOD], ['USUA_NULI', '=', $line] ])->first(); $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $order->USUMOD = $nameMod . " (" . $order->USUMOD . ")"; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F01GEOP', 'S002V01P01COOP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles de la orden #$idOrder de mantenimiento correctivo registradas.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $order); } public function updateWorkOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'description' => 'required|string|min:15', 'equipment' => 'required|string', 'start_date_time' => 'required|date', 'solution_time' => 'required|numeric', 'priority' => 'required|string', 'id_counter' => 'required|string', 'id_last_measure' => 'required|string', 'clasification' => 'required|string|max:50', 'staff' => 'required|json', 'security_management' => 'required|string', 'activation_type' => 'required|string|in:Manual,Automática', 'resources' => 'required|json', 'attached' => 'json', 'id_order' => 'required|string' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_IDOT', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); } $equipmentCode = $this->encryptionController->decrypt($form['equipment']); if(!$equipmentCode){ return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400); } $equipment = DB::table('S002V01TEQUI')->where([ ['EQUI_NULI', '=', $form['linea']], ['EQUI_COEQ', '=', $equipmentCode], ])->first(); if(is_null($equipment)){ return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404); } if(floatval($form['solution_time']) <= 0){ return $this->responseController->makeResponse(true, 'El tiempo de solución estimado debe ser mayor a cero.', [], 400); } $priority = $this->encryptionController->decrypt($form['priority']); if(!$priority){ return $this->responseController->makeResponse(true, 'La prioridad relacionada no fue encriptada correctamente.', [], 400); } $validPriorities = ['1', '2', '3', '4']; if(!in_array($priority, $validPriorities)){ return $this->responseController->makeResponse(true, 'La prioridad relacionada es inválida.', [], 400); } $idCounter = $this->encryptionController->decrypt($form['id_counter']); if(!$idCounter){ return $this->responseController->makeResponse(true, 'El ID del contador relacionado no fue encriptado correctamente.', [], 400); } $counter = DB::table('S002V01TCONA')->where([ ['CONA_IDCO', '=', $idCounter], ['CONA_NULI', '=', $form['linea']] ])->first(); if(is_null($counter)){ return $this->responseController->makeResponse(true, 'El contador relacionado no existe.', [], 404); } $idLastMeasure = $this->encryptionController->decrypt($form['id_last_measure']); if(!$idLastMeasure){ return $this->responseController->makeResponse(true, 'El ID de la última medida del contador relacionado no fue encriptado correctamente.', [], 400); } $lastMeasure = DB::table('S002V01TMEDI')->select([ 'MEDI_IDME AS ID_MEDIDA', 'MEDI_CORE AS CONTADOR', 'MEDI_VALO AS VALOR', 'MEDI_WSRE AS ID_SERVICIO_WEB', 'LSWE_URLX AS URL_SERVICIO_WEB', 'MEDI_HORE AS HORA_REGISTRO', ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([ ['MEDI_IDME', '=', $idLastMeasure], ['MEDI_NULI', '=', $form['linea']], ['MEDI_CORE', '=', $idCounter] ])->orderBy('MEDI_HORE', 'desc')->first(); if(is_null($lastMeasure)){ return $this->responseController->makeResponse(true, 'La última medida del contador relacionado no existe.', [], 404); } $staffArr = json_decode($form['staff'], true); if(count($staffArr) == 0){ return $this->responseController->makeResponse(true, 'El arreglo del personal está vacío.', [], 400); } $staffArrFn = []; foreach($staffArr as $key=>$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); } $staffArrFn[] = [ 'ID' => $specialtyDec, 'CANT' => $specialty['CANT'] ]; } $staffStrFn = json_encode($staffArrFn); $idManagement = $this->encryptionController->decrypt($form['security_management']); if(!$idManagement){ return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400); } $management = DB::table('S002V01TGESE')->where([ ['GESE_NULI', '=', $form['linea']], ['GESE_IDGS', '=', $idManagement] ])->first(); if(is_null($management)){ return $this->responseController->makeResponse(true, 'La gerencia de seguridad seleccionada no está registrada.', [], 404); } $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; } $rhut = json_encode($resources); $attachedArrFn = []; if(isset($form['attached'])){ $attachedArr = json_decode($form['attached'], true); foreach($attachedArr as $key=>$attached){ $idDec = $this->encryptionController->decrypt($attached['id']); if(!$idDec){ return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400); } if($attached['type'] == 'Existente'){ $codeArr = explode('=', $idDec); $codeArr0 = explode('-', $codeArr[0]); $file = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $form['linea']], ['AFAL_COMO', '=', $codeArr0[1]], ['AFAL_CLDO', '=', $codeArr0[2]], ['AFAL_FECR', '=', $codeArr0[3]], ['AFAL_NUSE', '=', $codeArr0[4]], ['AFAL_NUVE', '=', $codeArr[1]], ])->first(); if(is_null($file)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($file->AFAL_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $attachedArrFn[] = $idDec; }else if($attached['type'] == 'Nuevo'){ $tempFile = DB::table('S002V01TARTE')->where([ ['ARTE_IDAR', '=', $idDec], ['ARTE_NULI', '=', $form['linea']] ])->first(); if(is_null($tempFile)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($tempFile->ARTE_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser); if(!$finalFile){ return $this->responseController->makeResponse(true, $finalFile[1], [], 400); }else{ $attachedArrFn[] = $finalFile[1]; } } } } $activationType = $form['activation_type'][0]; $attachedStrFn = json_encode($attachedArrFn); $lastMeasureStr = json_encode($lastMeasure); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TOTCO')->where([ ['OTCO_IDOT', '=', $idOrder], ['OTCO_NULI', '=', $form['linea']] ])->update([ 'OTCO_DEIN' => $form['description'], 'OTCO_EQIN' => $equipmentCode, 'OTCO_FIFA' => $form['start_date_time'], 'OTCO_TESO' => $form['solution_time'], 'OTCO_CORE' => $idCounter, 'OTCO_DRCO' => $lastMeasureStr , 'OTCO_PRIO' => $priority, 'OTCO_FTIN' => $order->OTCO_FTIN, 'OTCO_DTIN' => $order->OTCO_DTIN, 'OTCO_RHUT' => $rhut, 'OTCO_PEIN' => $staffStrFn, 'OTCO_TIAC' => $activationType, 'OTCO_ANCO' => $order->OTCO_ANCO, 'OTCO_DORE' => $attachedStrFn, 'OTCO_CLAS' => $form['clasification'], 'OTCO_COME' => $order->OTCO_COME, 'OTCO_GESE' => $idManagement, 'OTCO_CAEX' => $order->OTCO_CAEX, 'OTCO_ESOR' => $order->OTCO_ESOR, 'OTCO_USMO' => $idUser, 'OTCO_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F04GEOT', 'S002V01P01GEOT', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo correctivo #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function deleteWorkOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_IDOT', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $statusHistoryArr = json_decode($order->OTCO_HIES, true); $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'EL', 'FECHA' => $nowStr]; $statusHistoryStr = json_encode($statusHistoryArr); DB::table('S002V01TOTCO')->where([ ['OTCO_IDOT', '=', $idOrder], ['OTCO_NULI', '=', $form['linea']] ])->update([ 'OTCO_ESOR' => 'EL', 'OTCO_HIES' => $statusHistoryStr, 'OTCO_USMO' => $idUser, 'OTCO_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F04GEOT', 'S002V01P01GEOT', 'Eliminación', "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la orden de trabajo correctivo #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function approveWorkOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'config' => 'required|json', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_IDOT', '=', $idOrder] ])->first(); $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); }else if($order->OTCO_ESOR == 'EL'){ return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404); }else if($order->OTCO_ESOR != 'PE'){ $status = $orderStates[$order->OTCO_ESOR]; return $this->responseController->makeResponse(true, "La orden está $status.", [], 401); } $staffConfigArr = json_decode($form['config'], true); $audience = []; foreach($staffConfigArr as $key=>$val){ if(!array_key_exists('SPECIALTY', $val) || !array_key_exists('STAFF', $val)){ return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400); } $specialtyDec = $this->encryptionController->decrypt($val['SPECIALTY']); if(!$specialtyDec){ return $this->responseController->makeResponse(true, "El identificador de la especialidad en el item $key del arreglo de configuración de operarios no fue encriptado correctamente.", [], 400); } if(gettype($val['STAFF']) != 'array'){ return $this->responseController->makeResponse(true, "El contenedor de oerarios en el item $key del arreglo de configuración de operarios es inválido-.", [], 400); } foreach($val['STAFF'] as $key0=>$val0){ if(!array_key_exists('ID', $val0) || !array_key_exists('TYPE', $val0)){ return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400); } $idDec = $this->encryptionController->decrypt($val0['ID']); $employee = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $form['linea']], ['PERS_IDPE', '=', $idDec] ])->first(); if(is_null($employee)){ return $this->responseController->makeResponse(true, "El perario $key0 de la especialidad $specialtyDec del arreglo de configuración de operarios tiene un formato inválido.", [], 404); } $audience[] = $employee->PERS_IDUS; } } $this->notificationsController->emitNotification( 'S002V01M09GMCO', "Orden de mantenimiento correctivo #$idOrder", "Se ha generado la orden de mantenimiento correctivo #$idOrder y requiere su atención.", [[ 'BOTON' => 'Ver detalles', 'FUNCION' => 'openCorrectiveWorkOrderDetails', 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)]) ], [ 'BOTON' => 'Atender orden', 'FUNCION' => 'attendCorrectiveWorkOrder', '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' ); var_dump($audience); exit; $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $statusHistoryArr = json_decode($order->OTCO_HIES, true); $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'VA', 'FECHA' => $nowStr]; $statusHistoryStr = json_encode($statusHistoryArr); DB::table('S002V01TOTCO')->where([ ['OTCO_IDOT', '=', $idOrder], ['OTCO_NULI', '=', $form['linea']] ])->update([ 'OTCO_ESOR' => 'VA', 'OTCO_HIES' => $statusHistoryStr, 'OTCO_USMO' => $idUser, 'OTCO_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F04GEOT', 'S002V01P01GEOT', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") validó la orden de trabajo correctivo #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function startWorkOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_IDOT', '=', $idOrder] ])->first(); $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); }else if($order->OTCO_ESOR == 'EL'){ return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404); }else if($order->OTCO_ESOR != 'VA'){ $status = $orderStates[$order->OTCO_ESOR]; return $this->responseController->makeResponse(true, "La orden está $status.", [], 401); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $statusHistoryArr = json_decode($order->OTCO_HIES, true); $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'EP', 'FECHA' => $nowStr]; $statusHistoryStr = json_encode($statusHistoryArr); DB::table('S002V01TOTCO')->where([ ['OTCO_IDOT', '=', $idOrder], ['OTCO_NULI', '=', $form['linea']] ])->update([ 'OTCO_ESOR' => 'EP', 'OTCO_HIES' => $statusHistoryStr, 'OTCO_USMO' => $idUser, 'OTCO_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F04GEOT', 'S002V01P01GEOT', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") inició la orden de trabajo correctivo #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function updateWorkOrderStatus(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'status' => 'required|string|in:RE,CE,CA', 'comments' => 'required|string|min:15' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_IDOT', '=', $idOrder] ])->first(); $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); }else if($order->OTCO_ESOR == 'EL'){ return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404); } $status = $form['status']; switch($status){ case 'RE': if($order->OTCO_ESOR != 'PE'){ $status = $orderStates[$order->OTCO_ESOR]; return $this->responseController->makeResponse(true, "La orden está $status.", [], 401); } break; case 'CE': if($order->OTCO_ESOR != 'EP' && $order->OTCO_ESOR != 'CP'){ $status = $orderStates[$order->OTCO_ESOR]; return $this->responseController->makeResponse(true, "La orden está $status.", [], 401); } break; case 'CA': if($order->OTCO_ESOR != 'VA'){ $status = $orderStates[$order->OTCO_ESOR]; return $this->responseController->makeResponse(true, "La orden está $status.", [], 401); } break; } $message = ''; if($status == 'CE' && is_null($order->OTCO_ANCO)){ $status = 'CP'; $message = 'La orden no puede cerrarse complentamente hasta asignar el análisis de costos.'; }else{ $message = 'Actualización correcta.'; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $ftin = null; $dtin = null; if(($status == 'CE' || $status == 'CP') && is_null($order->OTCO_FTIN)){ $ftin = $nowStr; $startDate = new Carbon($order->OTCO_FIFA); $diffInSecs = $now->diffInSeconds($startDate); $diffInMins = $this->functionsController->floatDiv($diffInSecs, 60); $dtin = $this->functionsController->floatDiv($diffInMins, 60); }else{ $ftin = $order->OTCO_FTIN; $dtin = $order->OTCO_DTIN; } $statusHistoryArr = json_decode($order->OTCO_HIES, true); $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => $status, 'FECHA' => $nowStr]; $statusHistoryStr = json_encode($statusHistoryArr); DB::table('S002V01TOTCO')->where([ ['OTCO_IDOT', '=', $idOrder], ['OTCO_NULI', '=', $form['linea']] ])->update([ 'OTCO_ESOR' => $status, 'OTCO_COME' => $form['comments'], 'OTCO_HIES' => $statusHistoryStr, 'OTCO_FTIN' => $ftin, 'OTCO_DTIN' => $dtin, 'OTCO_USMO' => $idUser, 'OTCO_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F04GEOT', 'S002V01P01GEOT', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden de trabajo correctivo #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, "EXITO: $message"); } public function getWorkOrderClasifications($idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404); } $clasifications = DB::table('S002V01TOTCO')->select([ DB::raw('DISTINCT(OTCO_CLAS) AS CLASIFICACION') ])->get()->all(); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F01GEOP', 'S002V01P01COOP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó las clasificaciones registradas.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $clasifications); } public function getResponsibleUsers($idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404); } $profiles = DB::table('S002V01TPERF')->where('PERF_NULI', '=', $line)->get()->all(); $profilesWithAccess = []; foreach($profiles as $profile){ $permissions = json_decode($profile->PERF_PERM, true); $permissionsArr = $permissions['permissions']; $correctiveMaintenanceFilt = array_filter($permissionsArr, function($v, $k) { return $v['id'] == 'S002V01M09GMCO'; }, ARRAY_FILTER_USE_BOTH); $correctiveMaintenance = end($correctiveMaintenanceFilt); if(intval($correctiveMaintenance['access']) > 0){ $submodules = $correctiveMaintenance['children']; $workOrdersFilt = array_filter($submodules, function($v, $k) { return $v['id'] == 'S002V01S01ORTR'; }, ARRAY_FILTER_USE_BOTH); $workOrders = end($workOrdersFilt); if(intval($workOrders['access']) > 0){ $functions = $workOrders['children']; $operationsManagementFilt = array_filter($functions, function($v, $k) { return $v['id'] == 'S002V01F01GEOP'; }, ARRAY_FILTER_USE_BOTH); $operationsManagement = end($operationsManagementFilt); if(intval($operationsManagement['access']) > 0){ $profilesWithAccess[] = $profile->PERF_IDPE; } } } } $usersWithAccess = []; foreach($profilesWithAccess as $idProfile){ $users = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_PERF', '=', $idProfile], ['USUA_ESTA', '=', 'Activo'] ])->get()->all(); foreach($users as $user){ $userName = $this->functionsController->joinName($user->USUA_NOMB, $user->USUA_APPA, $user->USUA_APMA); $usersWithAccess[] = [ 'ID' => $this->encryptionController->encrypt($user->USUA_IDUS), 'NOMBRE' => $userName, ]; } } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F01GEOP', 'S002V01P01COOP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los usuarios con acceso a la gestión de las operaciones.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $usersWithAccess); } public function transferWorkOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'id_new_user' => 'required|string', 'type' => 'required|string|in:U,S' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_IDOT', '=', $idOrder] ])->first(); $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); }else if($order->OTCO_ESOR == 'EL'){ return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404); }else if($order->OTCO_ESOR != 'PE'){ $status = $orderStates[$order->OTCO_ESOR]; return $this->responseController->makeResponse(true, "La orden está $status.", [], 401); } if($order->OTCO_TURE == 'U' && $order->OTCO_IDUR != $idUser){ return $this->responseController->makeResponse(true, "El usuario que realizó la solicitud no es el responsable de atenderla.", [], 401); }else if($order->OTCO_TURE == 'S'){ $users = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $form['linea']], ['PERS_TICO', '=', 'Subcontratista'], ['PERS_IDPS', '=', $order->OTCO_IDUR], ])->get()->all(); $enabledUsers = []; foreach($users as $user){ $enabledUsers[] = $user->PERS_IDUS; } if(!in_array($idUser, $enabledUsers)){ return $this->responseController->makeResponse(true, "El usuario que realizó la solicitud no es el responsable de atenderla.", [], 401); } } $audience = []; $idNewUser = $this->encryptionController->decrypt($form['id_new_user']); if(!$idNewUser){ return $this->responseController->makeResponse(true, 'El ID del nuevo encargado no fue encriptado correctamente.', [], 400); } if($form['type'] == 'U'){ $newUser = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idNewUser] ])->first(); if(is_null($newUser)){ return $this->responseController->makeResponse(true, 'El usuario seleccionado no existe.', [], 404); } $audience[] = $idNewUser; }else if($form['type'] == 'S'){ $subcontratist = DB::table('S002V01TPESU')->where([ ['PESU_IDPS', '=', $idNewUser], ['PESU_NULI', '=', $form['linea']] ])->first(); if(is_null($subcontratist)){ return $this->responseController->makeResponse(true, 'El subcontratista seleccionado no existe.', [], 404); } $users = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $form['linea']], ['PERS_TICO', '=', 'Subcontratista'], ['PERS_IDPS', '=', $idNewUser], ])->get()->all(); foreach($users as $user){ $audience[] = $user->PERS_IDUS; } } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_IDOT', '=', $idOrder] ])->update([ 'OTCO_IDUR' => $idNewUser, 'OTCO_TURE' => $form['type'], 'OTCO_USMO' => $idUser, 'OTCO_FEMO' => $nowStr ]); $this->notificationsController->emitNotification( 'S002V01M09GMCO', "Orden de mantenimiento correctivo #$idOrder", "Su usuario ha sido asignado como responsable de atender la orden de mantenimiento #$idOrder.", [[ 'BOTON' => 'Ver detalles', 'FUNCION' => 'openCorrectiveWorkOrderDetails', 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)]) ], [ 'BOTON' => 'Validar orden', 'FUNCION' => 'validateCorrectiveWorkOrder', 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)]) ], [ 'BOTON' => 'Ir al módulo', 'FUNCION' => 'openModule', 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')]) ]], $audience, $idUser, $form['linea'], $this->getSocketClient(), $idOrder, 'Correctivo' ); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F06TROT', '-', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") traspasó la orden de trabajo correctivo al usuario o subcontratista #$idNewUser.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function registerSecurityManagement(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'lada1' => 'required|string|max:8', 'phone1' => 'required|string|min:10|max:11', 'ext1' => 'string|max:5', 'lada2' =>'string|max:8', 'phone2' => 'string|min:10|max:11', 'ext2' => 'string|max:5', 'email' => 'required|string|max:150', 'id_manager' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idManager = $this->encryptionController->decrypt($form['id_manager']); if(!$idManager){ return $this->responseController->makeResponse(true, 'El ID del gerente no fue encriptado correctamente.', [], 400); } $manager = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idManager] ])->first(); if(is_null($manager)){ return $this->responseController->makeResponse(true, 'El usuario seleccionado como gerente no existe.', [], 404); } $email = $form['email']; if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ return $this->responseController->makeResponse(true, 'El formato del correo electrónico enviado es inválido.', [], 400); } $emailVerified = DB::table('S002V01TGESE')->where([ ['GESE_NULI', '=', $form['linea']], ['GESE_COEL', '=', $email] ])->get()->all(); if(count($emailVerified) > 0){ return $this->responseController->makeResponse(true, 'El correo electrónico enviado ya ha sido registrado.', [], 400); } $lada1 = DB::table('S002V01TPAIS')->where([ ['PAIS_NULI', '=', $form['linea']], ['PAIS_LADA', '=', $form['lada1']] ])->first(); if(is_null($lada1)){ return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono principal es inválida.', [], 400); }else if(!$this->functionsController->validPhoneNumber($form['phone1'])){ return $this->responseController->makeResponse(true, 'El número de teléfono principal es inválido.', [], 400); }else if(isset($form['ext1']) && !is_numeric($form['ext1'])){ return $this->responseController->makeResponse(true, 'La extensión de teléfono principal es inválida.', [], 400); } $ext1 = isset($form['ext1']) ? $form['ext1']: null; $lad2 = null; $tel2 = null; $ext2 = null; if(isset($form['lada2']) || isset($form['phone2'])){ if(!isset($form['lada2']) || !isset($form['phone2'])){ if(!isset($form['lada2'])){ return $this->responseController->makeResponse(true, 'La lada del teléfono secundario es obligatoria cuando se envía el teléfono o la extensión secundarios', [], 400); } if(!isset($form['phone2'])){ return $this->responseController->makeResponse(true, 'El teléfono secundario es obligatorio cuando se envía la lada o la extensión secundarias', [], 400); } } $lada2 = DB::table('S002V01TPAIS')->where([ ['PAIS_NULI', '=', $form['linea']], ['PAIS_LADA', '=', $form['lada2']] ])->first(); if(is_null($lada2)){ return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono secundario es inválida.', [], 400); }else if(!$this->functionsController->validPhoneNumber($form['phone2'])){ return $this->responseController->makeResponse(true, 'El número de teléfono secundario es inválido.', [], 400); }else if(isset($form['ext2']) && !is_numeric($form['ext2'])){ return $this->responseController->makeResponse(true, 'La extensión de teléfono secundario es inválida.', [], 400); } $lad2 = $form['lada2']; $tel2 = $form['phone2']; $ext2 = isset($form['ext2']) ? $form['ext2'] : null; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $idManagement = DB::table('S002V01TGESE')->insertGetId([ 'GESE_NULI' => $form['linea'], 'GESE_LAD1' => $form['lada1'], 'GESE_TEL1' => $form['phone1'], 'GESE_EXT1' => $ext1, 'GESE_LAD2' => $lad2, 'GESE_TEL2' => $tel2, 'GESE_EXT2' => $ext2, 'GESE_COEL' => $email, 'GESE_GERE' => $idManager, 'GESE_USRE' => $idUser, 'GESE_FERE' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P02GSAU', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró la gerencia de seguridad #$idManagement.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getSegurityManagements($idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404); } $securityManagements = DB::table('S002V01TGESE')->select([ 'GESE_IDGS AS ID_GERENCIA_SEGURIDAD', 'GESE_LAD1 AS LADA_TELEFONO_PRINCIPAL', 'GESE_TEL1 AS TELEFONO_PRINCIPAL', 'GESE_EXT1 AS EXTENSION_TELEFONO_PRINCIPAL', 'GESE_LAD2 AS LADA_TELEFONO_SECUNDARIO', 'GESE_TEL2 AS TELEFONO_SECUNDARIO', 'GESE_EXT2 AS EXTENSION_TELEFONO_SECUNDARIO', 'GESE_COEL AS CORREO_GERENCIA', 'GESE_GERE AS GERENTE', 'GESE_ESTA AS ESTADO', 'GESE_USRE AS USUREG', 'GESE_FERE AS FECREG', 'GESE_USMO AS USUMOD', 'GESE_FEMO AS FECMOD' ])->where('GESE_NULI', '=', $line)->get()->all(); foreach($securityManagements as $key=>$item){ $workOrders = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $line], ['OTCO_GESE', '=', $item->ID_GERENCIA_SEGURIDAD] ])->get()->all(); $item->NUMERO_ORDENES = count($workOrders); $item->ID_GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($item->ID_GERENCIA_SEGURIDAD); $manager = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $item->GERENTE] ])->first(); $managerName = $this->functionsController->joinName($manager->USUA_NOMB, $manager->USUA_APPA, $manager->USUA_APMA); $item->GERENTE = $managerName . " (" . $item->GERENTE . ")"; $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $item->USUREG] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $item->USUREG = $usrRegName . " (" . $item->USUREG . ")"; if(!is_null($item->USUMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $item->USUMOD] ])->first(); $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $item->USUMOD = $usrModName . " (" . $item->USUMOD . ")"; } $securityManagements[$key] = $item; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P02GSAU', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó las gerencias de seguridad registradas.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $securityManagements); } public function getSecurityManagement($idManagement, $idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404); } $idManagement = $this->encryptionController->decrypt($idManagement); if(!$idManagement){ return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400); } $management = DB::table('S002V01TGESE')->select([ 'GESE_IDGS AS ID_GERENCIA_SEGURIDAD', 'GESE_LAD1 AS LADA_TELEFONO_PRINCIPAL', 'GESE_TEL1 AS TELEFONO_PRINCIPAL', 'GESE_EXT1 AS EXTENSION_TELEFONO_PRINCIPAL', 'GESE_LAD2 AS LADA_TELEFONO_SECUNDARIO', 'GESE_TEL2 AS TELEFONO_SECUNDARIO', 'GESE_EXT2 AS EXTENSION_TELEFONO_SECUNDARIO', 'GESE_COEL AS CORREO_GERENCIA', 'GESE_GERE AS GERENTE', 'GESE_ESTA AS ESTADO', 'GESE_USRE AS USUREG', 'GESE_FERE AS FECREG', 'GESE_USMO AS USUMOD', 'GESE_FEMO AS FECMOD' ])->where([ ['GESE_NULI', '=', $line], ['GESE_IDGS', '=', $idManagement] ])->first(); if(is_null($management)){ return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404); } $workOrders = DB::table('S002V01TOTCO')->select([ 'OTCO_IDOT AS ID_ORDEN' ])->where([ ['OTCO_NULI', '=', $line], ['OTCO_GESE', '=', $idManagement] ])->get()->all(); foreach($workOrders as $key=>$order){ $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN); $workOrders[$key] = $order; } $management->ORDENES_TRABAJO = $workOrders; $management->ID_GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($management->ID_GERENCIA_SEGURIDAD); $manager = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $management->GERENTE] ])->first(); $managerName = $this->functionsController->joinName($manager->USUA_NOMB, $manager->USUA_APPA, $manager->USUA_APMA); $management->GERENTE = $managerName . " (" . $management->GERENTE . ")"; $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $management->USUREG] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $management->USUREG = $usrRegName . " (" . $management->USUREG . ")"; if(!is_null($management->USUMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $management->USUMOD] ])->first(); $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $management->USUMOD = $usrModName . " (" . $management->USUMOD . ")"; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P02GSAU', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó la gerencias de seguridad #$idManagement.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $management); } public function updateSecurityManagement(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'lada1' => 'required|string|max:8', 'phone1' => 'required|string|min:10|max:11', 'ext1' => 'string|max:5', 'lada2' =>'string|max:8', 'phone2' => 'string|min:10|max:11', 'ext2' => 'string|max:5', 'email' => 'required|string|max:150', 'id_manager' => 'required|string', 'id_management' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idManagement = $this->encryptionController->decrypt($form['id_management']); if(!$idManagement){ return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400); } $management = DB::table('S002V01TGESE')->where([ ['GESE_NULI', '=', $form['linea']], ['GESE_IDGS', '=', $idManagement] ])->first(); if(is_null($management)){ return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404); } $idManager = $this->encryptionController->decrypt($form['id_manager']); if(!$idManager){ return $this->responseController->makeResponse(true, 'El ID del gerente no fue encriptado correctamente.', [], 400); } $manager = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idManager] ])->first(); if(is_null($manager)){ return $this->responseController->makeResponse(true, 'El usuario seleccionado como gerente no existe.', [], 404); } $email = $form['email']; if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ return $this->responseController->makeResponse(true, 'El formato del correo electrónico enviado es inválido.', [], 400); } $emailVerified = DB::table('S002V01TGESE')->where([ ['GESE_NULI', '=', $form['linea']], ['GESE_COEL', '=', $email], ['GESE_IDGS', '!=', $idManagement] ])->get()->all(); if(count($emailVerified) > 0){ return $this->responseController->makeResponse(true, 'El correo electrónico enviado ya ha sido registrado.', [], 400); } $lada1 = DB::table('S002V01TPAIS')->where([ ['PAIS_NULI', '=', $form['linea']], ['PAIS_LADA', '=', $form['lada1']] ])->first(); if(is_null($lada1)){ return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono principal es inválida.', [], 400); }else if(!$this->functionsController->validPhoneNumber($form['phone1'])){ return $this->responseController->makeResponse(true, 'El número de teléfono principal es inválido.', [], 400); }else if(isset($form['ext1']) && !is_numeric($form['ext1'])){ return $this->responseController->makeResponse(true, 'La extensión de teléfono principal es inválida.', [], 400); } $ext1 = isset($form['ext1']) ? $form['ext1']: null; $lad2 = null; $tel2 = null; $ext2 = null; if(isset($form['lada2']) || isset($form['phone2'])){ if(!isset($form['lada2']) || !isset($form['phone2'])){ if(!isset($form['lada2'])){ return $this->responseController->makeResponse(true, 'La lada del teléfono secundario es obligatoria cuando se envía el teléfono o la extensión secundarios', [], 400); } if(!isset($form['phone2'])){ return $this->responseController->makeResponse(true, 'El teléfono secundario es obligatorio cuando se envía la lada o la extensión secundarias', [], 400); } } $lada2 = DB::table('S002V01TPAIS')->where([ ['PAIS_NULI', '=', $form['linea']], ['PAIS_LADA', '=', $form['lada2']] ])->first(); if(is_null($lada2)){ return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono secundario es inválida.', [], 400); }else if(!$this->functionsController->validPhoneNumber($form['phone2'])){ return $this->responseController->makeResponse(true, 'El número de teléfono secundario es inválido.', [], 400); }else if(isset($form['ext2']) && !is_numeric($form['ext2'])){ return $this->responseController->makeResponse(true, 'La extensión de teléfono secundario es inválida.', [], 400); } $lad2 = $form['lada2']; $tel2 = $form['phone2']; $ext2 = isset($form['ext2']) ? $form['ext2'] : null; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TGESE')->where([ ['GESE_NULI', '=', $form['linea']], ['GESE_IDGS', '=', $idManagement] ])->update([ 'GESE_LAD1' => $form['lada1'], 'GESE_TEL1' => $form['phone1'], 'GESE_EXT1' => $ext1, 'GESE_LAD2' => $lad2, 'GESE_TEL2' => $tel2, 'GESE_EXT2' => $ext2, 'GESE_COEL' => $email, 'GESE_GERE' => $idManager, 'GESE_USMO' => $idUser, 'GESE_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P02GSAU', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la gerencia de seguridad #$idManagement.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function deleteSecurityManagement(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_management' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idManagement = $this->encryptionController->decrypt($form['id_management']); if(!$idManagement){ return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400); } $management = DB::table('S002V01TGESE')->where([ ['GESE_NULI', '=', $form['linea']], ['GESE_IDGS', '=', $idManagement] ])->first(); if(is_null($management)){ return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404); } $workOrders = DB::table('S002V01TOTCO')->select([ 'OTCO_IDOT AS ID_ORDEN' ])->where([ ['OTCO_NULI', '=', $form['linea']], ['OTCO_GESE', '=', $idManagement], ['OTCO_ESOR', '!=', 'EL'], ])->get()->all(); if(count($workOrders) > 0){ return $this->responseController->makeResponse(true, 'La gerencia no se puede eliminar porque tiene órdenes de trabajo relacionadas.', [], 401); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TGESE')->where([ ['GESE_NULI', '=', $form['linea']], ['GESE_IDGS', '=', $idManagement] ])->update([ 'GESE_ESTA' => 'Eliminado', 'GESE_USMO' => $idUser, 'GESE_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P02GSAU', 'Eliminación', "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la gerencia de seguridad #$idManagement.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function registerBlock(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'blocked' => 'required|string', 'type' => 'required|string|in:USR,SUB' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idBlocked = $this->encryptionController->decrypt($form['blocked']); if(!$idBlocked){ return $this->responseController->makeResponse(true, 'El ID que desea bloquear no fue encriptado correctamente.', [], 400); } $blockedTypes = ['USR' => 'Empleado', 'SUB' => 'Subcontratista']; $blockedType = $blockedTypes[$form['type']]; if($blockedType == 'Empleado'){ $employee = DB::table('S002V01TPERS')->where([ ['PERS_IDPE', '=', $idBlocked], ['PERS_NULI', '=', $form['linea']] ])->first(); if(is_null($employee)){ return $this->responseController->makeResponse(true, 'El empleado que desea bloquear no está registrado.', [], 404); } }else{ $subcontratist = DB::table('S002V01TPESU')->where([ ['PESU_NULI', '=', $form['linea']], ['PESU_IDPS', '=', $idBlocked] ])->first(); if(is_null($subcontratist)){ return $this->responseController->makeResponse(true, 'El subcontratista que desea bloquear no está registrado.', [], 404); } } $checkStatus = DB::table('S002V01TBIBL')->where([ ['BIBL_NULI', '=', $form['linea']], ['BIBL_BLOQ', '=', $idBlocked], ['BIBL_TIBL', '=', $blockedType], ['BIBL_ESTA', '=', 'Activo'] ])->get()->all(); if(count($checkStatus)){ return $this->responseController->makeResponse(true, "El $blockedType que desea bloquear ya se encuentra bloqueado.", [], 401); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TBIBL')->insert([ 'BIBL_NULI' => $form['linea'], 'BIBL_BLOQ' => $idBlocked, 'BIBL_TIBL' => $blockedType, 'BIBL_USRE' => $idUser, 'BIBL_FERE' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P04REBL', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") bloqueó al $blockedType #$idBlocked.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getBlockRegisters($idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404); } $blockRegisters = DB::table('S002V01TBIBL')->select([ 'BIBL_IDBL AS ID_BLOQUEO', 'BIBL_BLOQ AS BLOQUEADO', 'BIBL_TIBL AS TIPO_BLOQUEADO', 'BIBL_ESTA AS ESTADO', 'BIBL_USRE AS USUREG', 'BIBL_FERE AS FECREG', 'BIBL_USMO AS USUMOD', 'BIBL_FEMO AS FECMOD' ])->where('BIBL_NULI', '=', $line)->get()->all(); foreach($blockRegisters as $key=>$register){ $register->ID_BLOQUEO = $this->encryptionController->encrypt($register->ID_BLOQUEO); if($register->TIPO_BLOQUEADO == 'Subcontratista'){ $subcontratist = DB::table('S002V01TPESU')->where([ ['PESU_NULI', '=', $line], ['PESU_IDPS', '=', $register->BLOQUEADO] ])->first(); $register->BLOQUEADO = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $register->BLOQUEADO . ")"; }else{ $employee = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $line], ['PERS_IDPE', '=', $register->BLOQUEADO] ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->first(); $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA); $register->BLOQUEADO = $employeeName . " (" . $register->BLOQUEADO . ")"; } $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $register->USUREG] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $register->USUREG = $usrRegName . " (" . $register->USUREG . ")"; if(!is_null($register->USUMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $register->USUMOD] ])->first(); $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $register->USUMOD = $usrModName . " (" . $register->USUMOD . ")"; } $blockRegisters[$key] = $register; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P03BLOQ', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los bloqueos registrados.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $blockRegisters); } public function unblockRegister(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_register' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idBlocked = $this->encryptionController->decrypt($form['id_register']); if(!$idBlocked){ return $this->responseController->makeResponse(true, 'El ID del bloqueo no fue encriptado correctamente.', [], 400); } $register = DB::table('S002V01TBIBL')->where([ ['BIBL_NULI', '=', $form['linea']], ['BIBL_IDBL', '=', $idBlocked] ])->first(); if(is_null($register)){ return $this->responseController->makeResponse(true, 'El bloqueo que desea revocar no está registrado.', [], 404); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TBIBL')->where([ ['BIBL_NULI', '=', $form['linea']], ['BIBL_IDBL', '=', $idBlocked] ])->update([ 'BIBL_ESTA' => 'Anulado', 'BIBL_USMO' => $idUser, 'BIBL_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F03GESE', 'S002V01P04REBL', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") anuló el bloqueo #$idBlocked.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getWorkOrderStatusHistory($idOrder, $idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idOrder = $this->encryptionController->decrypt($idOrder); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente', [], 400); } $order = DB::table('S002V01TOTCO')->select([ 'OTCO_HIES AS HISTORIAL', ])->where([ ['OTCO_IDOT', '=', $idOrder], ['OTCO_NULI', '=', $line] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404); } $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; $statusHistoryArr = json_decode($order->HISTORIAL, true); foreach($statusHistoryArr as $key=>$item){ $item['ESTADO'] = $orderStates[$item['ESTADO']]; $usrSta = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $item['USUARIO']] ])->first(); $usrStaName = $this->functionsController->joinName($usrSta->USUA_NOMB, $usrSta->USUA_APPA, $usrSta->USUA_APMA); $item['USUARIO'] = $usrStaName . " (" . $item['USUARIO'] . ")"; $statusHistoryArr[$key] = $item; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F01GEOT', '-', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó el historial de estados de la orden #$idOrder de mantenimiento correctivo.", $idUser, $nowStr, 'S002V01S03PRIN' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $statusHistoryArr); } public function generateReport(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'report_type' => 'required|string|in:TODAS,MANUA,AUTOM,ESTAD', 'start_date' => 'date', 'end_date' => 'date', 'order_state' => 'required_if:report_type,=,ESTAD|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $systemParamsExists = file_exists($this->functionsController->getBasePath() .'\storage\app\files\system-params.json'); if(!$systemParamsExists){ return $this->responseController->makeResponse(true, 'El archivo de parámetros del sistema no fue encontrado.', [], 500); } $paramsStr = file_get_contents($this->functionsController->getBasePath() .'\storage\app\files\system-params.json'); $paramsArr = json_decode($paramsStr, true); $ordersBuilder = DB::table('S002V01TOTCO')->select([ 'OTCO_IDOT AS ID_ORDEN', 'OTCO_IDUR AS USUARIO_RESPONSABLE', 'OTCO_TURE AS TIPO_USUARIO_RESPONSABLE', 'OTCO_DEIN AS DESCRIPCION', 'OTCO_EQIN AS EQUIPAMIENTO', 'OTCO_FIFA AS FECHA_REGISTRO_FALLA', 'OTCO_TESO AS TIEMPO_ESTIMADO', 'OTCO_CORE AS CONTADOR', 'OTCO_DRCO AS MEDIDA_REGISTRADA', 'OTCO_PRIO AS PRIORIDAD', 'OTCO_FTIN AS FECHA_FINALIZACION', 'OTCO_DTIN AS DURACION_TOTAL', 'OTCO_RHUT AS RECURSOS', 'OTCO_PEIN AS PERSONAL', 'OTCO_TIAC AS TIPO_ACTIVACION', 'OTCO_ANCO AS ANALISIS_COSTOS', 'OTCO_DORE AS DOCUMENTOS', 'OTCO_CLAS AS CLASIFICACION', 'OTCO_COME AS COMENTARIOS', 'OTCO_GESE AS GERENCIA_SGURIDAD', 'OTCO_HIES AS HISTORIAL_ESTADOS', 'OTCO_ESOR AS ESTADO', 'OTCO_USRE AS USUREG', 'OTCO_FERE AS FECREG', 'OTCO_USMO AS USUMOD', 'OTCO_FEMO AS FECMOD' ])->where('OTCO_NULI', '=', $form['linea']); if(isset($form['start_date'])){ $ordersBuilder->where('OTCO_FERE', '>=', $form['start_date']); } if(isset($form['end_date'])){ $ordersBuilder->where('OTCO_FERE', '<=', $form['end_date']); } $orderStates = [ 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado', 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente', 'CA' => 'Cancelado', 'EL' => 'Eliminado' ]; if(isset($form['order_state']) && !array_key_exists($form['order_state'], $orderStates)){ return $this->responseController->makeResponse(true, 'El estado solicitado para las órdenes de mantenimiento correctivo es inválido.', [], 400); }else if(isset($form['order_state']) && array_key_exists($form['order_state'], $orderStates)){ $ordersBuilder->where('OTCO_ESOR', '=', $form['order_state']); } if($form['report_type'] == 'MANUA'){ $ordersBuilder->where('OTCO_TIAC', '=', 'M'); } if($form['report_type'] == 'AUTOM'){ $ordersBuilder->where('OTCO_TIAC', '=', 'A'); } $workOrders = $ordersBuilder->get()->all(); foreach($workOrders as $order){ $order->ID_ORDEN = "#" . $order->ID_ORDEN; if($order->TIPO_USUARIO_RESPONSABLE == 'S'){ $subcontratist = DB::table('S002V01TPESU')->where([ ['PESU_NULI', '=', $form['linea']], ['PESU_IDPS', '=', $order->USUARIO_RESPONSABLE] ])->first(); $order->USUARIO_RESPONSABLE = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $subcontratist->PESU_IDPS . ")"; $order->TIPO_USUARIO_RESPONSABLE = 'Subcontratista'; }else if($order->TIPO_USUARIO_RESPONSABLE == 'U'){ $usrResp = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $order->USUARIO_RESPONSABLE] ])->first(); $nameUsrResp = $this->functionsController->joinName($usrResp->USUA_NOMB, $usrResp->USUA_APPA, $usrResp->USUA_APMA); $order->USUARIO_RESPONSABLE = $nameUsrResp . " (" . $order->USUARIO_RESPONSABLE . ")"; $order->TIPO_USUARIO_RESPONSABLE = 'Empleado'; } $equipment = DB::table('S002V01TEQUI')->where([ ['EQUI_NULI', '=', $form['linea']], ['EQUI_COEQ', '=', $order->EQUIPAMIENTO] ])->first(); $order->EQUIPAMIENTO = $order->EQUIPAMIENTO . ' - ' . $equipment->EQUI_TIPO . ' - ' . $equipment->EQUI_MODE . ' (' . $equipment->EQUI_IDEQ . ')'; $order->FECHA_REGISTRO_FALLA = $this->functionsController->formatDateTime($order->FECHA_REGISTRO_FALLA); $order->TIEMPO_ESTIMADO = $order->TIEMPO_ESTIMADO . "h"; $counterActivator = DB::table('S002V01TACTI')->where([ ['ACTI_NULI', '=', $form['linea']], ['ACTI_CORE', '=', $order->CONTADOR] ])->first(); $measureArr = json_decode($order->MEDIDA_REGISTRADA, true); $activationConfig = json_decode($counterActivator->ACTI_COAC, true); if($counterActivator->ACTI_TIAC == 'Medida' || $counterActivator->ACTI_TIAC == 'Valor'){ $unit = DB::table('S002V01TLIME')->where([ ['LIME_IDME', '=', $activationConfig['unit']], ['LIME_MAGN', '=', $activationConfig['magnitude']], ])->first(); $order->MEDIDA_REGISTRADA = "Medida #" . $measureArr['ID_MEDIDA'] . ". Valor registrado: " . $measureArr['VALOR'] . ' ' . $unit->LIME_ACME . ". Fecha de registro: " . $this->functionsController->formatDateTime($measureArr['HORA_REGISTRO']) . ". Servicio web de recepción: " . $measureArr['URL_SERVICIO_WEB'] . " (" . $measureArr['ID_SERVICIO_WEB'] . ")"; }else if($counterActivator->ACTI_TIAC == 'Sintoma'){ $symptom = DB::table('S002V01TLISI')->where([ ['LISI_IDSI', '=', $activationConfig['sign']], ['LISI_NULI', '=', $form['linea']] ])->first(); $unit = DB::table('S002V01TLIME')->where([ ['LIME_IDME', '=', $symptom->LISI_IDME], ['LIME_MAGN', '=', $activationConfig['magnitude']], ])->first(); $order->MEDIDA_REGISTRADA = "Medida #" . $measureArr['ID_MEDIDA'] . ". Valor registrado: " . $measureArr['VALOR'] . ' ' . $unit->LIME_ACME . ". Fecha de registro: " . $this->functionsController->formatDateTime($measureArr['HORA_REGISTRO']) . ". Servicio web de recepción: " . $measureArr['URL_SERVICIO_WEB'] . " (" . $measureArr['ID_SERVICIO_WEB'] . ")"; }else{ $order->MEDIDA_REGISTRADA = 'No aplica'; } $order->CONTADOR = "#" . $order->CONTADOR; $orderPriorities = $paramsArr['order_priorities']; $priorityFilt = array_filter($orderPriorities, function($v, $k) use($order) { return $v['value'] == $order->PRIORIDAD; }, ARRAY_FILTER_USE_BOTH); if(count($priorityFilt) < 1){ $order->PRIORIDAD = 'Desconocido'; }else{ $priority = end($priorityFilt); $order->PRIORIDAD = $priority['label'] . " (" . $order->PRIORIDAD . ")"; } if(is_null($order->FECHA_FINALIZACION)) { $order->FECHA_FINALIZACION = '-'; }else{ $order->FECHA_FINALIZACION = $this->functionsController->formatDateTime($order->FECHA_FINALIZACION); } if(is_null($order->DURACION_TOTAL)) { $order->DURACION_TOTAL = '-'; }else{ $order->DURACION_TOTAL = $order->DURACION_TOTAL . "h"; } $resourcesArr = json_decode($order->RECURSOS, true); if(count($resourcesArr) < 1){ $order->RECURSOS = 'Ninguno'; }else{ //Pendiente procesar los recursos } $staffArr = json_decode($order->PERSONAL, true); $staffStr = ""; foreach($staffArr as $item){ if($item['TYPE'] == 'EQ'){ $workTeam = DB::table('S002V01TEQMA')->where([ ['EQMA_IDEQ', '=', $item['ID']], ['EQMA_NULI', '=', $form['linea']] ])->first(); $staffStr .= "equipo de trabajo " . $workTeam->EQMA_NOMB . " (" . $item['ID'] . "), "; }else if($item['TYPE'] == 'SU'){ $subcontratist = DB::table('S002V01TPESU')->where([ ['PESU_IDPS', '=', $item['ID']], ['PESU_NULI', '=', $form['linea']] ])->first(); $staffStr .= "subcontratista " . $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $item['ID'] . "), "; }else if($item['TYPE'] == 'EM'){ $employee = DB::table('S002V01TPERS')->where([ ['PERS_IDPE', '=', $item['ID']], ['PERS_NULI', '=', $form['linea']] ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->first(); $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA); $staffStr .= "empleado " . $employeeName . " (" . $item['ID'] . "), "; } } $staffStr = substr($staffStr, 0, -2); $staffStr = ucfirst($staffStr); $order->PERSONAL = $staffStr; $order->TIPO_ACTIVACION = $order->TIPO_ACTIVACION == 'M' ? 'Manual' : 'Automática'; if(is_null($order->ANALISIS_COSTOS)){ $order->ANALISIS_COSTOS = 'Sin asignar'; }else{ //Pendiente revisar el análisis de costos } $documentsArr = json_decode($order->DOCUMENTOS, true); $documentsStr = ""; if(count($documentsArr) < 1){ $documentsStr = 'Ninguno'; }else{ foreach($documentsArr as $document){ $documentsStr .= $document . ", "; } $documentsStr = substr($documentsStr, 0, -2); } $order->DOCUMENTOS = $documentsStr; if(is_null($order->COMENTARIOS)){ $order->COMENTARIOS = 'Sin comentarios'; } $order->GERENCIA_SGURIDAD = "Gerencia #" . $order->GERENCIA_SGURIDAD; $statusHistoryArr = json_decode($order->HISTORIAL_ESTADOS, true); $statusHistoryStr = ""; foreach($statusHistoryArr as $item){ $statusHistoryStr .= $orderStates[$item['ESTADO']] . ' - ' . $this->functionsController->formatDateTime($item['FECHA']); $usrState = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $item['USUARIO']], ['USUA_NULI', '=', $form['linea']] ])->first(); $usrStateName = $this->functionsController->joinName($usrState->USUA_NOMB, $usrState->USUA_APPA, $usrState->USUA_APMA); $statusHistoryStr .= ' - ' . $usrStateName . ' (' . $item['USUARIO'] . '), '; } $statusHistoryStr = substr($statusHistoryStr, 0, -2); $order->HISTORIAL_ESTADOS = $statusHistoryStr; $order->ESTADO = $orderStates[$order->ESTADO]; $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $order->USUREG], ['USUA_NULI', '=', $form['linea']] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $order->USUREG = $usrRegName . " (" . $order->USUREG . ")"; $order->FECREG = $this->functionsController->formatDateTime($order->FECREG); if(!is_null($order->USUMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $order->USUMOD], ['USUA_NULI', '=', $form['linea']] ])->first(); $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $order->USUMOD = $usrModName . " (" . $order->USUMOD . ")"; $order->FECMOD = $this->functionsController->formatDateTime($order->FECMOD); }else{ $order->USUMOD = "-"; $order->FECMOD = "-"; } } $document = $this->reportWorkOrders($workOrders); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $dateTimeArr = explode(" ", $nowStr); $dateArr = explode("-", $dateTimeArr[0]); $year = substr($dateArr[0], 2); $como = 'GMCO'; $cldo = 'IN'; $fecr = $year . $dateArr[1] . $dateArr[2]; $sec = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $form['linea']], ['AFAL_COMO', '=', $como], ['AFAL_CLDO', '=', $cldo], ])->orderBy('AFAL_NUSE', 'desc')->first(); $nuse = ""; if(is_null($sec)){ $nuse = '000001'; }else{ $secu = "" . intval($sec->AFAL_NUSE) + 1 . ""; $nuse = ""; for($i = strlen($secu); $i < 6; $i++){ $nuse .= "0"; } $nuse = $nuse . $secu; } $timestamp = $now->timestamp; $noar = "informe_ordenes_mantenimiento_correctivo_$timestamp"; $exte = "xlsx"; $ver = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $form['linea']], ['AFAL_COMO', '=', $como], ['AFAL_CLDO', '=', $cldo], ['AFAL_NOAR', '=', $noar], ['AFAL_EXTE', '=', $exte], ])->orderBy('AFAL_NUVE', 'desc')->first(); $nuve = ""; if(is_null($ver)){ $nuve = "01"; }else{ $vers = intval($ver->AFAL_NUVE) + 1; $nuve = $vers < 10 ? "0$vers" : "$vers"; } $line = $form['linea'] < 10 ? "0$form[linea]" : "$form[linea]"; $filePath = $this->functionsController->getBasePath() .'\public_files\\'; $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte"; $tempFile = $filePath . $fileName; if(file_exists($tempFile)){ unlink($tempFile); } $writer = IOFactory::createWriter($document, 'Xlsx'); $writer->save($tempFile); $ubic = Storage::putFile('files', new File($tempFile)); $ubic = str_replace("/", "\\", $ubic); $ubic = $this->functionsController->getBasePath() ."\storage\app\\" . $ubic; $tama = filesize($ubic); $usac = json_encode([$idUser]); unlink($tempFile); DB::table('S002V01TAFAL')->insert([ 'AFAL_NULI' => $line, 'AFAL_COMO' => $como, 'AFAL_CLDO' => $cldo, 'AFAL_FECR' => $fecr, 'AFAL_NUSE' => $nuse, 'AFAL_NUVE' => $nuve, 'AFAL_NOAR' => $noar, 'AFAL_EXTE' => $exte, 'AFAL_TAMA' => $tama, 'AFAL_UBIC' => $ubic, 'AFAL_USAC' => $usac, 'AFAL_USRE' => $idUser, 'AFAL_FERE' => $nowStr, ]); $idReport = DB::table('S002V01TIMCO')->insertGetId([ 'IMCO_NULI' => $form['linea'], 'IMCO_TIIN' => $form['report_type'], 'IMCO_DORE' => $fileName, 'IMCO_USRE' => $idUser, 'IMCO_FERE' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F02PRIN', 'S002V01P01REIN', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró el informe #$idReport.", $idUser, $nowStr, 'S002V01S03PRIN' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.', ['report' => $this->encryptionController->encrypt($fileName)]); } private function reportWorkOrders($workOrders) : Spreadsheet { $spreadsheet = new Spreadsheet; $spreadsheet->getProperties() ->setCreator('STC') ->setTitle('Historial de órdenes de trabajo de mantenimiento correctivo.') ->setSubject('Historial documento') ->setKeywords('Historial Órdenes Mantenimiento Correctivo') ->setCategory('Historial archivo'); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->setTitle('ÓRDENES DE MANT CORRECTIVO'); $columns = ['# ORDEN', 'RESPONSABLE', 'TIPO DE USUARIO RESPONSABLE', 'DESCRIPCIÓN', 'EQUIPAMIENTO', 'FECHA Y HORA DE REGISTRO DE LA FALLA', 'TIEMPO ESTIMADO DE DURACIÓN DE LA INTERVENCIÓN', 'CONTADOR RELACIONADO', 'MEDIDA REGISTRADA AL MOMENTO DE LA FALLA', 'PRIORIDAD', 'FECHA DE FINALIZACIÓN DE LA INTERVENCIÓN', 'DURACIÓN TOTAL DE LA INTERVENCIÓN', 'CONSUMIBLES UTILIZADOS', 'PERSONAL INVOLUCRADO', 'TIPO DE ACTIVACIÓN', 'ANÁLISIS DE COSTOS', 'DOCUMENTOS REQUERIDOS', 'CLASIFICACIÓN', 'COMENTARIOS REALIZADOS DURANTE LA INTERVENCIÓN', 'GERENCIA DE SEGURIDAD RELACIONADA', 'HISTORIAL DE ESTADOS', 'ESTADO DE LA ORDEN', 'USUARIO DE REGISTRO', 'FECHA DE REGISTRO', 'USUARIO DE ACTIALIZACIÓN', 'FECHA DE ACTUALIZACIÓN']; $startRow = 2; $startCol = 2; $maxRow = $startRow + count($workOrders) + 1; $maxCol = $startCol + count($columns) - 1; for($row = $startRow; $row <= $maxRow; $row++){ $startColStr = Coordinate::stringFromColumnIndex($startCol); $maxColStr = Coordinate::stringFromColumnIndex($maxCol); if($row == 2){ $worksheet->mergeCells($startColStr . $row . ':' . $maxColStr . $row); $worksheet->setCellValue($startColStr . $row, 'INFORME DE ÓRDENES DE MANTENIMIENTO CORRECTIVO')->getStyle($startColStr . $row)->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setRGB('B7BCC4'); $worksheet->getStyle($startColStr . $row)->getFont()->setBold(true); $worksheet->getStyle($startColStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); }else if($row == 3){ for($col = $startCol; $col <= $maxCol; $col++){ $colStr = Coordinate::stringFromColumnIndex($col); $colInd = $col - 2; $column = $columns[$colInd]; $worksheet->setCellValue($colStr . $row, $column); $worksheet->getStyle($colStr . $row)->getFont()->setBold(true); $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); } }else if($row > 3){ $rowInd = $row - 4; $order = (array) $workOrders[$rowInd]; $keys = array_keys($order); for($col = $startCol; $col <= $maxCol; $col++){ $colInd = $col - 2; $key = $keys[$colInd]; $value = $order[$key]; $colStr = Coordinate::stringFromColumnIndex($col); if($key == 'ID_ORDEN' || $key == 'TIEMPO_ESTIMADO' || $key == 'CONTADOR' || $key == 'DURACION_TOTAL' || $key == 'GERENCIA_SGURIDAD'){ $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); $worksheet->getColumnDimension($colStr)->setAutoSize(true); }else if($key == 'EQUIPAMIENTO' || $key == 'DESCRIPCION' || $key == 'MEDIDA_REGISTRADA' || $key == 'PERSONAL' || $key == 'DOCUMENTOS' || $key == 'COMENTARIOS' || $key == 'HISTORIAL_ESTADOS'){ $worksheet->getColumnDimension($colStr)->setWidth(48); $worksheet->getStyle($colStr . $row)->getAlignment()->setWrapText(true); }else{ $worksheet->getColumnDimension($colStr)->setAutoSize(true); } $worksheet->getStyle($colStr . $row)->getAlignment()->setVertical(Alignment::HORIZONTAL_CENTER); $worksheet->setCellValue($colStr . $row, $value); } } } return $spreadsheet; } public function getReports($type, $startDate, $endDate, $idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $reportsBuilder = DB::table('S002V01TIMCO')->select([ 'IMCO_IDIN AS ID_INFORME', 'IMCO_TIIN AS TIPO_INFORME', 'IMCO_DORE AS DOCUMENTO', 'IMCO_USRE AS USUREG', 'IMCO_FERE AS FECREG' ])->where('IMCO_NULI', '=', $line); if($type != '-'){ $validReports = ['TODAS','MANUA','AUTOM','ESTAD']; if(!in_array($type, $validReports)){ return $this->responseController->makeResponse(true, "El tipo de reportes solicitado es inválido.", [], 400); } $reportsBuilder->where('IMCO_TIIN', '=', $type); } if($startDate != '-'){ $startDateArr = explode('-', $startDate); if(count($startDateArr) != 3){ return $this->responseController->makeResponse(true, 'La fecha de inicio tiene un formato inválido.', [], 400); } try{ $startDateObj = new Carbon($startDate); }catch(InvalidFormatException $e){ return $this->responseController->makeResponse(true, "La fecha de inicio tiene un formato inválido: " . $e->getMessage(), [], 400); } $startDate = $startDateObj->toDateTimeString(); $reportsBuilder->where('IMCO_FERE', '>=', $startDate); } if($endDate != '-'){ $endDateArr = explode('-', $endDate); if(count($endDateArr) != 3){ return $this->responseController->makeResponse(true, 'La fecha final tiene un formato inválido.', [], 400); } try{ $endDateObj = new Carbon($endDate); $endDateObj->addDay(); $endDateObj->subSecond(); }catch(InvalidFormatException $e){ return $this->responseController->makeResponse(true, "La fecha final tiene un formato inválido: " . $e->getMessage(), [], 400); } $endDate = $endDateObj->toDateTimeString(); $reportsBuilder->where('IMCO_FERE', '<=', $endDate); } $reports = $reportsBuilder->get()->all(); foreach($reports as $key=>$report){ $report->ID_INFORME = $this->encryptionController->encrypt($report->ID_INFORME); $report->DOCUMENTO = $this->encryptionController->encrypt($report->DOCUMENTO); $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $report->USUREG], ['USUA_NULI', '=', $line] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $report->USUREG = $usrRegName . " (" . $report->USUREG . ")"; $reports[$key] = $report; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F02PRIN', '-', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los informes de tipo $type.", $idUser, $nowStr, 'S002V01S03PRIN' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $reports); } public function registerMaintnencePlan(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'equipment' => 'required|string', 'equipment_status' => 'required|string|in:DE,DP,EF', 'lru' => 'string', 'lru_status' => 'string|in:DE,DP,EF', 'description' => 'required|string|min:15', 'inm_time' => 'required|numeric', 'priority' => 'required|string', 'total_duration' => 'required|numeric', 'classification' => 'required|string|max:100', 'specialties' => 'required|json', 'specialties_conf' => 'required|json', 'resources' => 'required|json', 'attached' => 'required|json', 'symptom' => 'required|string', 'scada' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $equipmentCode = $this->encryptionController->decrypt($form['equipment']); if(!$equipmentCode){ return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400); } $equipment = DB::table('S002V01TEQUI')->where([ ['EQUI_COEQ', '=', $equipmentCode], ['EQUI_NULI', '=', $form['linea']] ])->first(); if(is_null($equipment)){ return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404); } $lrui = null; $eflr = null; if(isset($form['lru'])){ $lruCode = $this->encryptionController->decrypt($form['lru']); if(!$lruCode){ return $this->responseController->makeResponse(true, 'El código del LRU no fue encriptado correctamente.', [], 400); } $lru = DB::table('S002V01TEQUI')->where([ ['EQUI_COEQ', '=', $lruCode], ['EQUI_NULI', '=', $form['linea']] ])->first(); if(is_null($lru)){ return $this->responseController->makeResponse(true, 'El LRU relacionado no existe.', [], 404); } if(!isset($form['lru_status'])){ return $this->responseController->makeResponse(true, 'El estado del lru es obligatorio cuando se envía el campo lru.', [], 400); } $lrui = $lruCode; $eflr = $form['lru_status']; } $priorityDec = $this->encryptionController->decrypt($form['priority']); $systemParamsExists = file_exists($this->functionsController->getBasePath() .'\storage\app\files\system-params.json'); if(!$systemParamsExists){ return $this->responseController->makeResponse(true, 'El archivo de parámetros del sistema no fue encontrado.', [], 500); } $paramsStr = file_get_contents($this->functionsController->getBasePath() . '\storage\app\files\system-params.json'); $paramsArr = json_decode($paramsStr, true); $orderPriorities = $paramsArr['order_priorities']; $priorityFilt = array_filter($orderPriorities, function($v, $k) use($priorityDec) { return $v['value'] == $priorityDec; }, ARRAY_FILTER_USE_BOTH); if(count($priorityFilt) < 1){ return $this->responseController->makeResponse(true, 'La prioridad seleccionada es inválida.', [], 400); } //PENDINTE REVISAR RECURSOS CON STOCK $attachedArr = json_decode($form['attached'], true); $attachedArrFn = []; foreach($attachedArr as $key=>$attached){ $idDec = $this->encryptionController->decrypt($attached['id']); if(!$idDec){ return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400); } $tempFile = DB::table('S002V01TARTE')->where([ ['ARTE_IDAR', '=', $idDec], ['ARTE_NULI', '=', $form['linea']] ])->first(); if(is_null($tempFile)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($tempFile->ARTE_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser); if(!$finalFile[0]){ return $this->responseController->makeResponse(true, $finalFile[1], [], 400); }else{ $attachedArrFn[] = [ 'ID' => $finalFile[1], 'TYPE' => $attached['type'] ]; } } $idSymptom = $this->encryptionController->decrypt($form['symptom']); if(!$idSymptom){ return $this->responseController->makeResponse(true, 'El ID del síntoma no fue encriptado correctamente.', [], 400); } $symptom = DB::table('S002V01TLISI')->where([ ['LISI_NULI', '=', $form['linea']], ['LISI_IDSI', '=', $idSymptom], ])->first(); if(is_null($symptom)){ return $this->responseController->makeResponse(true, 'El síntoma relacionado no existe.', [], 404); } $idSCADA = $this->encryptionController->decrypt($form['scada']); if(!$idSCADA){ return $this->responseController->makeResponse(true, 'El ID del SCADA no fue encriptado correctamente.', [], 400); } $scada = DB::table('S002V01TLISC')->where([ ['LISC_NULI', '=', $form['linea']], ['LISC_IDSC', '=', $idSCADA] ])->first(); if(is_null($scada)){ return $this->responseController->makeResponse(true, 'El SCADA relacionado 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()); $repeatHourDate = new Carbon($nowStr); $hour = $repeatHourDate->hour; $hourStr = ""; $minute = $repeatHourDate->minute; $minuteStr = ""; if($minute > 0 && $minute <= 15){ $minuteStr = "15"; $hourStr = $hour < 10 ? "0$hour" : "$hour"; }else if($minute > 15 && $minute <= 30){ $minuteStr = "30"; $hourStr = $hour < 10 ? "0$hour" : "$hour"; }else if($minute > 30 && $minute <= 45){ $minuteStr = "45"; $hourStr = $hour < 10 ? "0$hour" : "$hour"; }else{ $minuteStr = "00"; $hourAux = $hour + 1; $hourStr = $hourAux < 10 ? "0$hourAux" : "$hourAux"; } $repeatHourStr = "$hourStr:$minuteStr:00"; $symptomRepeat = [ 'sign' => $idSymptom, 'color' => 'rgb(79, 195, 255)', 'repeat' => 'TD', 'startDate' => "$repeatStart.000Z", 'startHour' => $repeatHourStr, 'customRepeat' => '', ]; //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, 'ACTI_TIAC' => 'Sintoma', 'ACTI_COAC' => $symptomRepeatStr, 'ACTI_CORE' => $idCounter, '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; $dead = isset($form['extra_details']) ? $form['extra_details'] : null; $dore = json_encode($attachedArrFn); $idPlan = DB::table('S002V01TPMCO')->insertGetId([ 'PMCO_NULI' => $form['linea'], 'PMCO_EQIN' => $equipmentCode, 'PMCO_LRUI' => $lrui, 'PMCO_EFEQ' => $form['equipment_status'], 'PMCO_EFLR' => $eflr, 'PMCO_DESC' => $form['description'], 'PMCO_TIES' => $form['inm_time'], 'PMCO_DTIN' => $form['total_duration'], 'PMCO_CLAS' => $form['classification'], 'PMCO_ESRE' => $specialtiesStr, 'PMCO_COES' => $form['specialties_conf'], 'PMCO_COME' => $come, 'PMCO_RECU' => $form['resources'], 'PMCO_DEAD' => $dead, 'PMCO_DORE' => $dore, 'PMCO_CORE' => $idCounter, 'PMCO_USRE' => $idUser, 'PMCO_FERE' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F02PLAN', 'S002V01P01ASPL', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró el plan de mantenimiento correctivo #$idPlan.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.', [ 'PLAN' => $this->encryptionController->encrypt($idPlan), 'ACTIVADOR' => $this->encryptionController->encrypt($idActivator), 'CONTADOR' => $this->encryptionController->encrypt($idCounter), ]); } public function getMaintenancePlans($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); } $plansList = DB::table('S002V01TPMCO')->select([ 'PMCO_IDPM AS ID_PLAN', 'PMCO_EQIN AS EQUIPAMIENTO', 'PMCO_LRUI AS LRU', 'PMCO_TIES AS TIEMPO_INMOVILIZACION_ESTIMADO', 'PMCO_DTIN AS DURACION_TOTAL', 'PMCO_CLAS AS CLASIFICACION', 'PMCO_CORE AS CONTADOR', 'ACTI_IDAC AS ACTIVADOR', 'ACTI_PRIO AS PRIORIDAD', 'PMCO_ESTA AS ESTADO', 'PMCO_USRE AS USRREG', 'PMCO_FERE AS FECREG', 'PMCO_USMO AS USRMOD', 'PMCO_FEMO AS FECMOD', ])->join('S002V01TACTI', 'ACTI_CORE', '=', 'PMCO_CORE')->get()->all(); foreach($plansList as $key=>$plan){ $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(); $lruLabel = $plan->LRU . " - " . $lru->EQUI_TIPO . " - " . $lru->EQUI_MODE . " (" . $lru->EQUI_IDEQ . ")"; $plan->LRU = $this->encryptionController->encrypt($lruLabel); } $plan->CONTADOR = $this->encryptionController->encrypt($plan->CONTADOR); $plan->ACTIVADOR = $this->encryptionController->encrypt($plan->ACTIVADOR); $plan->PRIORIDAD = $this->encryptionController->encrypt($plan->PRIORIDAD); $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $plan->USRREG], ['USUA_NULI', '=', '1'], ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $plan->USRREG = $usrRegName . " (" . $plan->USRREG . ")"; if(!is_null($plan->USRMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $plan->USRMOD], ['USUA_NULI', '=', '1'], ])->first(); $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $plan->USRMOD = $usrModName . " (" . $plan->USRMOD . ")"; } $plansList[$key] = $plan; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F02PLAN', 'S002V01P01ASPL', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los planes de mantenimiento registrados.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $plansList); } public function getMaintenancePlan($idPlan, $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); } $idPlan = $this->encryptionController->decrypt($idPlan); if(!$idPlan){ return $this->responseController->makeResponse(true, 'El ID del plan de mantenimiento no está encriptado correctamente.', [], 400); } $plan = DB::table('S002V01TPMCO')->select([ 'PMCO_IDPM AS ID_PLAN', 'PMCO_EQIN AS EQUIPAMIENTO', 'PMCO_LRUI AS LRU', 'PMCO_EFEQ AS ESTADO_FUNCIONAMIENTO_EQUIPAMIENTO', 'PMCO_EFLR AS ESTADO_FUNCIONAMIENTO_LRU', 'PMCO_DESC AS DESCRIPCION', 'PMCO_TIES AS TIEMPO_INMOVILIZACION_ESTIMADO', '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', 'CONA_IDSC AS SCADA', 'ACTI_IDAC AS ACTIVADOR', 'ACTI_PRIO AS PRIORIDAD', 'ACTI_COAC AS SINTOMA', 'PMCO_ESTA AS ESTADO', 'PMCO_USRE AS USRREG', 'PMCO_FERE AS FECREG', 'PMCO_USMO 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(); 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(); $lruLabel = $plan->LRU . " - " . $lru->EQUI_TIPO . " - " . $lru->EQUI_MODE . " (" . $lru->EQUI_IDEQ . ")"; $plan->LRU = $this->encryptionController->encrypt($lruLabel); } $documentsArr = json_decode($plan->DOCUMENTOS_RELACIONADOS, true); $documentsFn = []; foreach($documentsArr as $document){ $documentCodeArr0 = explode('=', $document['ID']); $documentCodeArr1 = explode('-', $documentCodeArr0[0]); $documentObj = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $line], ['AFAL_COMO', '=', $documentCodeArr1[1]], ['AFAL_CLDO', '=', $documentCodeArr1[2]], ['AFAL_FECR', '=', $documentCodeArr1[3]], ['AFAL_NUSE', '=', $documentCodeArr1[4]], ['AFAL_NUVE', '=', $documentCodeArr0[1]], ])->first(); $documentsFn[] = [ 'id' => $this->encryptionController->encrypt($document['ID']), 'name' => $document['ID'], 'size' => $documentObj->AFAL_TAMA, 'type' => $document['TYPE'] ]; } $plan->DOCUMENTOS_RELACIONADOS = json_encode($documentsFn); $plan->CONTADOR = $this->encryptionController->encrypt($plan->CONTADOR); $plan->SCADA = $this->encryptionController->encrypt($plan->SCADA); $plan->ACTIVADOR = $this->encryptionController->encrypt($plan->ACTIVADOR); $plan->PRIORIDAD = $this->encryptionController->encrypt($plan->PRIORIDAD); $activationConfig = json_decode($plan->SINTOMA, true); $plan->SINTOMA = $this->encryptionController->encrypt($activationConfig['sign']); $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $plan->USRREG] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $plan->USRREG = $usrRegName . " (" . $plan->USRREG . ")"; 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 . ")"; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F02PLAN', 'S002V01P01ASPL', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó el plan de mantenimiento #$idPlan.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $plan); } public function updateMaintenancePlan(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_plan' => 'required|string', 'equipment' => 'required|string', 'equipment_status' => 'required|string|in:DE,DP,EF', 'lru' => 'string', 'lru_status' => 'string|in:DE,DP,EF', 'description' => 'required|string|min:15', 'inm_time' => 'required|numeric', 'total_duration' => 'required|numeric', 'classification' => 'required|string|max:100', 'specialties' => 'required|json', 'specialties_conf' => 'required|json', 'resources' => 'required|json', 'attached' => 'required|json', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idPlan = $this->encryptionController->decrypt($form['id_plan']); if(!$idPlan){ return $this->responseController->makeResponse(true, 'El ID del plan de mantenimiento no fue encriptado correctamente.', [], 400); } $plan = DB::table('S002V01TPMCO')->where([ ['PMCO_NULI', '=', $form['linea']], ['PMCO_IDPM', '=', $idPlan] ])->first(); if(is_null($plan)){ return $this->responseController->makeResponse(true, 'El plan que desea modificar no existe.', [], 404); }else if($plan->PMCO_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, 'El plan que desea modificar está eliminado.', [], 404); } $equipmentCode = $this->encryptionController->decrypt($form['equipment']); if(!$equipmentCode){ return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400); } $equipment = DB::table('S002V01TEQUI')->where([ ['EQUI_COEQ', '=', $equipmentCode], ['EQUI_NULI', '=', $form['linea']] ])->first(); if(is_null($equipment)){ return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404); } $lrui = null; $eflr = null; if(isset($form['lru'])){ $lruCode = $this->encryptionController->decrypt($form['lru']); if(!$lruCode){ return $this->responseController->makeResponse(true, 'El código del LRU no fue encriptado correctamente.', [], 400); } $lru = DB::table('S002V01TEQUI')->where([ ['EQUI_COEQ', '=', $lruCode], ['EQUI_NULI', '=', $form['linea']] ])->first(); if(is_null($lru)){ return $this->responseController->makeResponse(true, 'El LRU relacionado no existe.', [], 404); } if(!isset($form['lru_status'])){ return $this->responseController->makeResponse(true, 'El estado del lru es obligatorio cuando se envía el campo lru.', [], 400); } $lrui = $lruCode; $eflr = $form['lru_status']; } $planCounter = DB::table('S002V01TCONA')->where([ ['CONA_NULI', '=', $form['linea']], ['CONA_IDCO', '=', $plan->PMCO_CORE] ])->first(); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $counterEquipment = $planCounter->CONA_COEQ; if(is_null($lrui) && $counterEquipment != $equipmentCode){ DB::table('S002V01TCONA')->where([ ['CONA_NULI', '=', $form['linea']], ['CONA_IDCO', '=', $plan->PMCO_CORE] ])->update([ 'CONA_COEQ' => $equipmentCode, 'CONA_USMO' => $idUser, 'CONA_FEMO' => $nowStr ]); }else if($lrui != $counterEquipment){ DB::table('S002V01TCONA')->where([ ['CONA_NULI', '=', $form['linea']], ['CONA_IDCO', '=', $plan->PMCO_CORE] ])->update([ 'CONA_COEQ' => $lrui, 'CONA_USMO' => $idUser, 'CONA_FEMO' => $nowStr ]); } $specialtiesArr = json_decode($form['specialties'], true); if(count($specialtiesArr) == 0){ return $this->responseController->makeResponse(true, 'El arreglo de especialidades está vacío.', [], 400); } $specialtiesDec = []; foreach($specialtiesArr as $specialty){ $specialtiesDec[] = $this->encryptionController->decrypt($specialty); } $specialtiesStr = json_encode($specialtiesDec); $attachedArr = json_decode($form['attached'], true); if(count($attachedArr) == 0){ return $this->responseController->makeResponse(true, 'El arreglo de documentos está vacío.', [], 400); } $attachedArrFn = []; foreach($attachedArr as $key=>$attached){ $idDec = $this->encryptionController->decrypt($attached['id']); if(!$idDec){ return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400); } if($attached['isFinalFile']){ $documentCodeArr0 = explode('=', $idDec); $documentCodeArr1 = explode('-', $documentCodeArr0[0]); $file = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $form['linea']], ['AFAL_COMO', '=', $documentCodeArr1[1]], ['AFAL_CLDO', '=', $documentCodeArr1[2]], ['AFAL_FECR', '=', $documentCodeArr1[3]], ['AFAL_NUSE', '=', $documentCodeArr1[4]], ['AFAL_NUVE', '=', $documentCodeArr0[1]], ])->first(); if(is_null($file)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($file->AFAL_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $attachedArrFn[] = [ 'ID' => $idDec, 'TYPE' => $attached['type'] ]; }else{ $tempFile = DB::table('S002V01TARTE')->where([ ['ARTE_IDAR', '=', $idDec], ['ARTE_NULI', '=', $form['linea']] ])->first(); if(is_null($tempFile)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($tempFile->ARTE_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser); if(!$finalFile[0]){ return $this->responseController->makeResponse(true, $finalFile[1], [], 400); }else{ $attachedArrFn[] = [ 'ID' => $finalFile[1], 'TYPE' => $attached['type'] ]; } } } $come = isset($form['comments']) ? $form['comments'] : null; $dead = isset($form['extra_details']) ? $form['extra_details'] : null; $dore = json_encode($attachedArrFn); DB::table('S002V01TPMCO')->where([ ['PMCO_NULI', '=', $form['linea']], ['PMCO_IDPM', '=', $idPlan] ])->update([ 'PMCO_EQIN' => $equipmentCode, 'PMCO_LRUI' => $lrui, 'PMCO_EFEQ' => $form['equipment_status'], 'PMCO_EFLR' => $eflr, 'PMCO_DESC' => $form['description'], 'PMCO_TIES' => $form['inm_time'], 'PMCO_DTIN' => $form['total_duration'], 'PMCO_CLAS' => $form['classification'], 'PMCO_ESRE' => $specialtiesStr, 'PMCO_COES' => $form['specialties_conf'], 'PMCO_COME' => $come, 'PMCO_RECU' => $form['resources'], 'PMCO_DEAD' => $dead, 'PMCO_DORE' => $dore, 'PMCO_USMO' => $idUser, 'PMCO_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F02PLAN', 'S002V01P01ASPL', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el plan de mantenimiento correctivo #$idPlan.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function deleteMaintenancePlan(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_plan' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idPlan = $this->encryptionController->decrypt($form['id_plan']); if(!$idPlan){ return $this->responseController->makeResponse(true, 'El ID del plan de mantenimiento no fue encriptado correctamente.', [], 400); } $plan = DB::table('S002V01TPMCO')->where([ ['PMCO_NULI', '=', $form['linea']], ['PMCO_IDPM', '=', $idPlan] ])->first(); if(is_null($plan)){ return $this->responseController->makeResponse(true, 'El plan que desea modificar no existe.', [], 404); }else if($plan->PMCO_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, 'El plan que desea modificar está eliminado.', [], 404); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TPMCO')->where([ ['PMCO_NULI', '=', $form['linea']], ['PMCO_IDPM', '=', $idPlan] ])->update([ 'PMCO_ESTA' => 'Eliminado', 'PMCO_USMO' => $idUser, 'PMCO_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F02PLAN', 'S002V01P01ASPL', 'Eliminación', "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el plan de mantenimiento correctivo #$idPlan.", $idUser, $nowStr, 'S002V01S02GEME' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function registerWorkGroup(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'work_group_name' => 'required|string|max:100|min:8', 'related_teams' => 'required|json', 'specialty' => 'required|string|max:100|min:8', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $relatedTeamsArr = json_decode($form['related_teams'], true); if(count($relatedTeamsArr) < 2){ return $this->responseController->makeResponse(true, 'El arreglo de equipos relacionados debe contener al menos 2 elementos.', [], 400); } $relatedTeamsArrDec = []; foreach($relatedTeamsArr as $key=>$team){ $itemDec = $this->encryptionController->decrypt($team); if(!$itemDec){ return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no fue encriptado correctamente.", [], 400); } $workTeam = DB::table('S002V01TEQMA')->where([ ['EQMA_NULI', '=', $form['linea']], ['EQMA_IDEQ', '=', $itemDec] ])->first(); if(is_null($workTeam)){ return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no existe.", [], 404); }else if($workTeam->EQMA_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados está eliminado.", [], 404); } $relatedTeamsArrDec[] = $itemDec; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $relatedTeamsStr = json_encode($relatedTeamsArrDec); $idWorkGroup = DB::table('S002V01TGMCO')->insertGetId([ 'GMCO_NULI' => $form['linea'], 'GMCO_NGMC' => $form['work_group_name'], 'GMCO_EQRE' => $relatedTeamsStr, 'GMCO_ESPE' => $form['specialty'], 'GMCO_USRE' => $idUser, 'GMCO_FERE' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F02AEMA', 'S002V01P01AEOP', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró el grupo de trabajo $form[work_group_name] ($idWorkGroup).", $idUser, $nowStr, 'S002V01S04FUFL' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getWorkGroups($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); } $workGroups = DB::table('S002V01TGMCO')->select([ 'GMCO_IDGM AS ID_GRUPO', 'GMCO_NGMC AS NOMBRE_GRUPO', 'GMCO_ESPE AS ESPECIALIDAD', 'GMCO_ESTA AS ESTADO', 'GMCO_USRE AS USUREG', 'GMCO_FERE AS FECREG', 'GMCO_USMO AS USUMOD', 'GMCO_FEMO AS FECMOD' ])->where('GMCO_NULI', '=', $line)->get()->all(); foreach($workGroups as $key=>$group){ $group->ID_GRUPO = $this->encryptionController->encrypt($group->ID_GRUPO); $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $group->USUREG], ['USUA_NULI', '=', $line] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $group->USUREG = $usrRegName . " (" . $group->USUREG . ')'; if(!is_null($group->USUMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $group->USUMOD], ['USUA_NULI', '=', $line] ])->first(); $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $group->USUMOD = $usrModName . " (" . $group->USUMOD . ')'; } $workGroups[$key] = $group; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F02AEMA', 'S002V01P01AEOP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los grupos de trabajo registrados.", $idUser, $nowStr, 'S002V01S04FUFL' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $workGroups); } public function getWorkGroup($idGroup, $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); } $idGroup = $this->encryptionController->decrypt($idGroup); if(!$idGroup){ return $this->responseController->makeResponse(true, 'El ID del grupo de trabajo no está encriptado correctamente', [], 400); } $workGroup = DB::table('S002V01TGMCO')->select([ 'GMCO_IDGM AS ID_GRUPO', 'GMCO_NGMC AS NOMBRE_GRUPO', 'GMCO_EQRE AS EQUIPOS_RELACIONADOS', 'GMCO_ESPE AS ESPECIALIDAD', 'GMCO_ESTA AS ESTADO', 'GMCO_USRE AS USUREG', 'GMCO_FERE AS FECREG', 'GMCO_USMO AS USUMOD', 'GMCO_FEMO AS FECMOD' ])->where([ ['GMCO_IDGM', '=', $idGroup], ['GMCO_NULI', '=', $line] ])->first(); if(is_null($workGroup)){ return $this->responseController->makeResponse(true, 'El grupo de trabajo consultado no está registrado.', [], 404); } $workGroup->ID_GRUPO = $this->encryptionController->encrypt($workGroup->ID_GRUPO); $relatedTeamsArr = json_decode($workGroup->EQUIPOS_RELACIONADOS, true); $relatedTeams = []; foreach($relatedTeamsArr as $team){ $teamInfo = DB::table('S002V01TEQMA')->where([ ['EQMA_NULI', '=', $line], ['EQMA_IDEQ', '=', $team] ])->first(); if(!is_null($teamInfo)){ $relatedTeams[] = [ 'ID_EQUIPO' => $this->encryptionController->encrypt($teamInfo->EQMA_IDEQ), 'NOMBRE_EQUIPO' => $teamInfo->EQMA_NOMB, 'ESPECIALIDAD' => $teamInfo->EQMA_ESPE ]; } } $workGroup->EQUIPOS_RELACIONADOS = json_encode($relatedTeams); $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $workGroup->USUREG], ['USUA_NULI', '=', $line] ])->first(); $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $workGroup->USUREG = $usrRegName . " (" . $workGroup->USUREG . ')'; if(!is_null($workGroup->USUMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $workGroup->USUMOD], ['USUA_NULI', '=', $line] ])->first(); $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $workGroup->USUMOD = $usrModName . " (" . $workGroup->USUMOD . ')'; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M09GMCO', 'S002V01F02AEMA', 'S002V01P01AEOP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó el grupo de trabajo " . $workGroup->NOMBRE_GRUPO . " ($idGroup).", $idUser, $nowStr, 'S002V01S04FUFL' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $workGroup); } public function updateWorkGroup(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_work_group' => 'required|string', 'work_group_name' => 'required|string|max:100|min:8', 'related_teams' => 'required|json', 'specialty' => 'required|string|max:100|min:8', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idWorkGroup = $this->encryptionController->decrypt($form['id_work_group']); if(!$idWorkGroup){ return $this->responseController->makeResponse(true, 'El ID del grupo de trabajo no fue encriptado correctamente.', [], 400); } $workGroup = DB::table('S002V01TGMCO')->where([ ['GMCO_NULI', '=', $form['linea']], ['GMCO_IDGM', '=', $idWorkGroup] ])->first(); if(is_null($workGroup)){ return $this->responseController->makeResponse(true, 'El grupo de trabajo solicitado no existe.', [], 404); } $relatedTeamsArr = json_decode($form['related_teams'], true); if(count($relatedTeamsArr) < 2){ return $this->responseController->makeResponse(true, 'El arreglo de equipos relacionados debe contener al menos 2 elementos.', [], 400); } $relatedTeamsArrDec = []; foreach($relatedTeamsArr as $key=>$team){ $itemDec = $this->encryptionController->decrypt($team); if(!$itemDec){ return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no fue encriptado correctamente.", [], 400); } $workTeam = DB::table('S002V01TEQMA')->where([ ['EQMA_NULI', '=', $form['linea']], ['EQMA_IDEQ', '=', $itemDec] ])->first(); if(is_null($workTeam)){ return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no existe.", [], 404); }else if($workTeam->EQMA_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados está eliminado.", [], 404); } $relatedTeamsArrDec[] = $itemDec; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $relatedTeamsStr = json_encode($relatedTeamsArrDec); DB::table('S002V01TGMCO')->where([ ['GMCO_NULI', '=', $form['linea']], ['GMCO_IDGM', '=', $idWorkGroup] ])->update([ 'GMCO_NGMC' => $form['work_group_name'], 'GMCO_EQRE' => $relatedTeamsStr, 'GMCO_ESPE' => $form['specialty'], 'GMCO_USMO' => $idUser, 'GMCO_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F02AEMA', 'S002V01P01AEOP', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el grupo de trabajo $form[work_group_name] ($idWorkGroup).", $idUser, $nowStr, 'S002V01S04FUFL' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function deleteWorkGroup(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_work_group' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idWorkGroup = $this->encryptionController->decrypt($form['id_work_group']); if(!$idWorkGroup){ return $this->responseController->makeResponse(true, 'El ID del grupo de trabajo no fue encriptado correctamente.', [], 400); } $workGroup = DB::table('S002V01TGMCO')->where([ ['GMCO_NULI', '=', $form['linea']], ['GMCO_IDGM', '=', $idWorkGroup] ])->first(); if(is_null($workGroup)){ return $this->responseController->makeResponse(true, 'El grupo de trabajo solicitado no existe.', [], 404); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TGMCO')->where([ ['GMCO_NULI', '=', $form['linea']], ['GMCO_IDGM', '=', $idWorkGroup] ])->update([ 'GMCO_ESTA' => 'Eliminado', 'GMCO_USMO' => $idUser, 'GMCO_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M09GMCO', 'S002V01F02AEMA', 'S002V01P01AEOP', 'Eliminación', "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el grupo de trabajo #$idWorkGroup.", $idUser, $nowStr, 'S002V01S04FUFL' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getNoMeasuresFormFields($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); } $noMeasuresFormFields = DB::table('S002V01TCAPE')->select([ 'CAPE_VERS AS VERSION', 'CAPE_FEAC AS FECHA_ACTUALIZACION', 'CAPE_CAMP AS CAMPOS' ])->where([ ['CAPE_NULI', '=', $line], ['CAPE_TIFO', '=', 'RSM'] ])->orderBy('CAPE_VERS', 'desc')->first(); if(is_null($noMeasuresFormFields)){ return $this->responseController->makeResponse(false, 'EXITO', []); } $fieldsArr = json_decode($noMeasuresFormFields->CAMPOS, true); foreach($fieldsArr as $key=>$field){ if(array_key_exists('fieldID', $field)){ $field['fieldID'] = $this->encryptionController->encrypt($field['fieldID']); } $fieldsArr[$key] = $field; } $noMeasuresFormFields->CAMPOS = $fieldsArr; return $this->responseController->makeResponse(false, 'EXITO', $noMeasuresFormFields); } public function saveNoMeasuresFormFields(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'form_fields' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $formFields = $this->encryptionController->decrypt($form['form_fields']); if(!$formFields){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $lastFormVersion = DB::table('S002V01TCAPE')->where([ ['CAPE_NULI', '=', $form['linea']], ['CAPE_TIFO', '=', 'RSM'] ])->orderBy('CAPE_VERS', 'desc')->first(); $lastVersion = 0; if(is_null($lastFormVersion)){ $lastVersion = 1; }else{ $lastVersion = intval($lastFormVersion->CAPE_VERS) + 1; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TCAPE')->insert([ 'CAPE_NULI' => $form['linea'], 'CAPE_TIFO' => 'RSM', 'CAPE_VERS' => $lastVersion, 'CAPE_FEAC' => $nowStr, 'CAPE_USAC' => $idUser, 'CAPE_CAMP' => $formFields ]); return $this->responseController->makeResponse(false, 'EXITO.'); } public function saveNoMeasuresOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'data' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $noMeasuresFormFields = DB::table('S002V01TCAPE')->select([ 'CAPE_VERS AS VERSION', 'CAPE_FEAC AS FECHA_ACTUALIZACION', 'CAPE_CAMP AS CAMPOS' ])->where([ ['CAPE_NULI', '=', $form['linea']], ['CAPE_TIFO', '=', 'RSM'] ])->orderBy('CAPE_VERS', 'desc')->first(); if(is_null($noMeasuresFormFields)){ return $this->responseController->makeResponse(true, 'No se encontró algún formulario registrado.', [], 404); } $noMeasuresFormFieldsArr = json_decode($noMeasuresFormFields->CAMPOS, true); $formData = $this->encryptionController->decrypt($form['data']); if(!$formData){ return $this->responseController->makeResponse(true, 'El formulario enviado no fue encriptado correctamente.', [], 400); } $formDataArr = json_decode($formData, true); if(is_null($formDataArr)){ return $this->responseController->makeResponse(true, 'El formulario enviado no tiene un formato válido.', [], 400); } $errorsArr = []; $formDataFn = []; foreach($formDataArr as $control=>$value){ $isEncrypted = $this->encryptionController->decrypt($value); if($isEncrypted){ $value = $isEncrypted; } $controlFilt = array_filter($noMeasuresFormFieldsArr, function($v, $k) use($control) { return $v['fieldID'] == $control; }, ARRAY_FILTER_USE_BOTH); if(count($controlFilt) > 0){ $controlObj = end($controlFilt); $controlValidators = json_decode($controlObj['validators'], true); if(in_array('CARE', $controlValidators)){ if($value == null || is_null($value)){ $errorsArr[] = "El campo $controlObj[label] es obligatorio."; } } if(in_array('NUME', $controlValidators)){ $validNumber = $this->functionsController->validNumber($value, $controlObj['includeDecimal']); if(!$validNumber){ $errorsArr[] = "El campo $controlObj[label] tiene un valor inválido."; } } if(in_array('LOMI', $controlValidators)){ $minLengthNum = intval($controlObj['minLength']); if(strlen($value) < $minLengthNum){ $errorsArr[] = "El campo $controlObj[label] debe contener al menos $minLengthNum caracteres."; } } if(in_array('LOMA', $controlValidators)){ $maxLengthNum = intval($controlObj['maxLength']); if(strlen($value) > $maxLengthNum){ $errorsArr[] = "El campo $controlObj[label] puede contener hasta $maxLengthNum caracteres."; } } $selectorOptions = []; foreach($controlObj['selectorOptions'] as $option){ if(array_key_exists('value', $option)){ $valueEnc = $this->encryptionController->decrypt($option['value']); if($valueEnc){ $option['value'] = $valueEnc; } $selectorOptions[] = $option; } } if($controlObj['fieldType'] == 'SE-4' && !$controlObj['isMultiple']){ $valueFilt = array_filter($selectorOptions, function($v, $k) use($value) { if(array_key_exists('value', $v) && $v['value'] == $value) return true; }, ARRAY_FILTER_USE_BOTH); if(count($valueFilt) <= 0){ $errorsArr[] = "El calor del campo $controlObj[label] es inválido."; } } $formDataFn[$control] = $value; }else{ return $this->responseController->makeResponse(true, "El control $control no existe en la versión " . $noMeasuresFormFields->CAMPOS . " del formulario de órdenes sin mediciones", [], 400); } } if(count($errorsArr) > 0){ return $this->responseController->makeResponse(true, 'Se encontraron uno o más errores.', $errorsArr, 400); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $formDataStrFn = json_encode($formDataFn); $idRegister = DB::table('S002V01TFCPE')->insertGetId([ 'FCPE_NULI' => $form['linea'], 'FCPE_TIFO' => 'RSM', 'FCPE_VERS' => $noMeasuresFormFields->VERSION, 'FCPE_DATO' => $formDataStrFn, 'FCPE_FERE' => $nowStr, 'FCPE_USRE' => $idUser, ]); $idRegisterEnc = $this->encryptionController->encrypt($idRegister); return $this->responseController->makeResponse(false, 'EXITO', ['order' => $idRegisterEnc]); } public function getNoMeasuresOrders($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); } $noMeasuresOrders = DB::table('S002V01TFCPE')->select([ 'FCPE_IDRE AS ID_REGISTRO', 'FCPE_VERS AS VERSION_FORMULARIO', 'FCPE_ESTA AS ESTATUS', 'FCPE_FERE AS FECHA_REGISTRO', DB::raw("CONCAT(USRE.USUA_NOMB, ' ', USRE.USUA_APPA, IF(ISNULL(USRE.USUA_APMA), '', ' '), IF(ISNULL(USRE.USUA_APMA), '', USRE.USUA_APMA), ' (', FCPE_USRE, ')') AS USUARIO_REGISTRO"), 'FCPE_FEAC AS FECHA_ACTUALIZACION', DB::raw("IF(ISNULL(USMO.USUA_NOMB), '-', CONCAT(USMO.USUA_NOMB, ' ', USMO.USUA_APPA, IF(ISNULL(USMO.USUA_APMA), '', ' '), IF(ISNULL(USMO.USUA_APMA), '', USMO.USUA_APMA), ' (', FCPE_USAC, ')')) AS USUARIO_ACTUALIZACION") ])->join(DB::raw('S002V01TUSUA USRE'), 'USRE.USUA_IDUS', '=', 'FCPE_USRE') ->leftJoin(DB::raw('S002V01TUSUA USMO'), 'USMO.USUA_IDUS', '=', 'FCPE_USAC') ->orderBy('FCPE_IDRE', 'desc')->where([ ['FCPE_NULI', '=', $line], ['FCPE_IOMC', '=', null] ])->get()->all(); foreach($noMeasuresOrders as $key=>$order){ $order->ID_REGISTRO = $this->encryptionController->encrypt($order->ID_REGISTRO); $order->USUARIO_REGISTRO = $this->encryptionController->encrypt($order->USUARIO_REGISTRO); if(!is_null($order->USUARIO_ACTUALIZACION)){ $order->USUARIO_ACTUALIZACION = $this->encryptionController->encrypt($order->USUARIO_ACTUALIZACION); } $noMeasuresOrders[$key] = $order; } return $this->responseController->makeResponse(false, 'EXITO', $noMeasuresOrders); } public function getNoMeasuresOrder($idRegister, $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); } $idRegister = $this->encryptionController->decrypt($idRegister); if(!$idRegister){ return $this->responseController->makeResponse(true, 'El ID de la solicitud no fue encriptado correctamente.', [], 400); } $noMeasuresOrder = DB::table('S002V01TFCPE')->select([ 'FCPE_IDRE AS ID_REGISTRO', 'FCPE_VERS AS VERSION_FORMULARIO', 'FCPE_DATO AS DATOS', 'FCPE_VAPO AS VALIDADO_POR', 'FCPE_EXPE AS EXPEDIENTE', 'FCPE_ESTA AS ESTATUS', 'FCPE_ACRE AS ACTIVIDADES', 'FCPE_EVCI AS EVIDENCIA', 'FCPE_FERE AS FECHA_REGISTRO', DB::raw("CONCAT(USRE.USUA_NOMB, ' ', USRE.USUA_APPA, IF(ISNULL(USRE.USUA_APMA), '', ' '), IF(ISNULL(USRE.USUA_APMA), '', USRE.USUA_APMA), ' (', FCPE_USRE, ')') AS USUARIO_REGISTRO"), 'FCPE_FEAC AS FECHA_ACTUALIZACION', DB::raw("IF(ISNULL(USMO.USUA_NOMB), '-', CONCAT(USMO.USUA_NOMB, ' ', USMO.USUA_APPA, IF(ISNULL(USMO.USUA_APMA), '', ' '), IF(ISNULL(USMO.USUA_APMA), '', USMO.USUA_APMA), ' (', FCPE_USAC, ')')) AS USUARIO_ACTUALIZACION") ])->join(DB::raw('S002V01TUSUA USRE'), 'USRE.USUA_IDUS', '=', 'FCPE_USRE') ->leftJoin(DB::raw('S002V01TUSUA USMO'), 'USMO.USUA_IDUS', '=', 'FCPE_USAC')->where([ ['FCPE_NULI', '=', $line], ['FCPE_TIFO', '=', 'RSM'], ['FCPE_IDRE', '=', $idRegister] ])->first(); if(is_null($noMeasuresOrder)){ return $this->responseController->makeResponse(true, 'La solicitud la consultada no está registrada.', [], 404); } $noMeasuresOrder->ID_REGISTRO = $this->encryptionController->encrypt($noMeasuresOrder->ID_REGISTRO); $orderForm = DB::table('S002V01TCAPE')->select([ 'CAPE_VERS AS VERSION', 'CAPE_FEAC AS FECHA_ACTUALIZACION', 'CAPE_CAMP AS CAMPOS' ])->where([ ['CAPE_NULI', '=', $line], ['CAPE_TIFO', '=', 'RSM'], ['CAPE_VERS', '=', $noMeasuresOrder->VERSION_FORMULARIO], ])->first(); if(is_null($orderForm)){ return $this->responseController->makeResponse(true, 'El formulario en el que se registró la orden solicitada no existe', [], 404); } $fieldsArr = json_decode($orderForm->CAMPOS, true); $dataArr = json_decode($noMeasuresOrder->DATOS, true); $dataArrFn = []; foreach($dataArr as $key=>$value){ $fieldFilt = array_filter($fieldsArr, function($v, $k) use($key){ $idNum = intval($v['fieldID']); return $idNum == $key; }, ARRAY_FILTER_USE_BOTH); if(count($fieldFilt) > 0){ $field = end($fieldFilt); if($field['fieldType'] == 'SE-4'){ $selectorOptions = $field['selectorOptions']; foreach($selectorOptions as $option){ if(array_key_exists('value', $option)){ $valueDec = $this->encryptionController->decrypt($option['value']); if($valueDec == $value){ $value = $option['value']; } } } } } $dataArrFn[$key] = $value; } foreach($fieldsArr as $key=>$value){ if(array_key_exists('fieldID', $value)){ $value['fieldID'] = $this->encryptionController->encrypt($value['fieldID']); } $fieldsArr[$key] = $value; } $dataStr = json_encode($dataArrFn); $noMeasuresOrder->DATOS = $this->encryptionController->encrypt($dataStr); $orderForm->CAMPOS = $fieldsArr; if(!is_null($noMeasuresOrder->ACTIVIDADES)){ $activitiesArr = json_decode($noMeasuresOrder->ACTIVIDADES, true); foreach($activitiesArr as $key=>$activity){ $activity['id'] = $this->encryptionController->encrypt($activity['id']); $activitiesArr[$key] = $activity; } $noMeasuresOrder->ACTIVIDADES = $activitiesArr; } if(!is_null($noMeasuresOrder->EVIDENCIA)){ $evidenceArr = json_decode($noMeasuresOrder->EVIDENCIA, true); foreach($evidenceArr as $key=>$file){ $evidenceArr[$key] = $this->encryptionController->encrypt($file); } $noMeasuresOrder->EVIDENCIA = $evidenceArr; } return $this->responseController->makeResponse(false, 'EXITO', [ 'DATOS' => $noMeasuresOrder, 'FORMULARIO' => $orderForm ]); } public function updateNoMeasuresOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'data' => 'required|string', 'id_order' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404); } $noMeasuresFormFields = DB::table('S002V01TCAPE')->select([ 'CAPE_VERS AS VERSION', 'CAPE_FEAC AS FECHA_ACTUALIZACION', 'CAPE_CAMP AS CAMPOS' ])->where([ ['CAPE_NULI', '=', $form['linea']], ['CAPE_TIFO', '=', 'RSM'], ['CAPE_VERS', '=', $order->FCPE_VERS] ])->orderBy('CAPE_VERS', 'desc')->first(); if(is_null($noMeasuresFormFields)){ return $this->responseController->makeResponse(true, 'El formulario relacionado a la solicitud no existe.', [], 404); } $noMeasuresFormFieldsArr = json_decode($noMeasuresFormFields->CAMPOS, true); $formData = $this->encryptionController->decrypt($form['data']); if(!$formData){ return $this->responseController->makeResponse(true, 'El formulario enviado no fue encriptado correctamente.', [], 400); } $formDataArr = json_decode($formData, true); if(is_null($formDataArr)){ return $this->responseController->makeResponse(true, 'El formulario enviado no tiene un formato válido.', [], 400); } $errorsArr = []; $formDataFn = []; foreach($formDataArr as $control=>$value){ $isEncrypted = $this->encryptionController->decrypt($value); if($isEncrypted){ $value = $isEncrypted; } $controlFilt = array_filter($noMeasuresFormFieldsArr, function($v, $k) use($control) { return $v['fieldID'] == $control; }, ARRAY_FILTER_USE_BOTH); if(count($controlFilt) > 0){ $controlObj = end($controlFilt); $controlValidators = json_decode($controlObj['validators'], true); if(in_array('CARE', $controlValidators)){ if($value == null || is_null($value)){ $errorsArr[] = "El campo $controlObj[label] es obligatorio."; } } if(in_array('NUME', $controlValidators)){ $validNumber = $this->functionsController->validNumber($value, $controlObj['includeDecimal']); if(!$validNumber){ $errorsArr[] = "El campo $controlObj[label] tiene un valor inválido."; } } if(in_array('LOMI', $controlValidators)){ $minLengthNum = intval($controlObj['minLength']); if(strlen($value) < $minLengthNum){ $errorsArr[] = "El campo $controlObj[label] debe contener al menos $minLengthNum caracteres."; } } if(in_array('LOMA', $controlValidators)){ $maxLengthNum = intval($controlObj['maxLength']); if(strlen($value) > $maxLengthNum){ $errorsArr[] = "El campo $controlObj[label] puede contener hasta $maxLengthNum caracteres."; } } $selectorOptions = []; foreach($controlObj['selectorOptions'] as $option){ if(array_key_exists('value', $option)){ $valueEnc = $this->encryptionController->decrypt($option['value']); if($valueEnc){ $option['value'] = $valueEnc; } $selectorOptions[] = $option; } } if($controlObj['fieldType'] == 'SE-4' && !$controlObj['isMultiple']){ $valueFilt = array_filter($selectorOptions, function($v, $k) use($value) { if(array_key_exists('value', $v) && $v['value'] == $value) return true; }, ARRAY_FILTER_USE_BOTH); if(count($valueFilt) <= 0){ $errorsArr[] = "El calor del campo $controlObj[label] es inválido."; } } $formDataFn[$control] = $value; }else{ return $this->responseController->makeResponse(true, "El control $control no existe en la versión " . $noMeasuresFormFields->CAMPOS . " del formulario de órdenes sin mediciones", [], 400); } } if(count($errorsArr) > 0){ return $this->responseController->makeResponse(true, 'Se encontraron uno o más errores.', $errorsArr, 400); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $formDataStrFn = json_encode($formDataFn); DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->update([ 'FCPE_DATO' => $formDataStrFn, 'FCPE_FEAC' => $nowStr, 'FCPE_USAC' => $idUser, ]); return $this->responseController->makeResponse(false, 'EXITO'); } public function deleteNoMeasuresOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404); }else if($order->FCPE_ESTA == 'EL'){ return $this->responseController->makeResponse(true, 'La solicitud seleccionada está eliminada.', [], 401); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->update([ 'FCPE_ESTA' => 'EL', 'FCPE_FEAC' => $nowStr, 'FCPE_USAC' => $idUser, ]); return $this->responseController->makeResponse(false, 'EXITO'); } public function noMeasuresOrderValidation(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'validated_by' => 'required|string', 'record' => 'required|string', 'validation' => 'required|string|in:Si,No' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404); }else if($order->FCPE_ESTA != 'PE'){ return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está pendiente.', [], 401); } $validationStatus = $form['validation'] == 'Si' ? 'VA' : 'NV'; $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->update([ 'FCPE_VAPO' => $form['validated_by'], 'FCPE_EXPE' => $form['record'], 'FCPE_ESTA' => $validationStatus, 'FCPE_FEAC' => $nowStr, 'FCPE_USAC' => $idUser, ]); return $this->responseController->makeResponse(false, 'EXITO'); } public function closeNoMeasuresOrder(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'evidence' => 'required|json', 'activities' => 'required|json', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404); }else if($order->FCPE_ESTA != 'VA'){ return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está validada.', [], 401); } $activitiesArr = json_decode($form['activities'], true); if(count($activitiesArr) <= 0){ return $this->responseController->makeResponse(true, 'El arreglo de actividades está vacío.', [], 400); } foreach($activitiesArr as $key=>$activity){ if(!array_key_exists('id', $activity)){ return $this->responseController->makeResponse(true,"El elemento $key de la lista de actividades tiene un formato inválido.", [], 400); } $activity['id'] = $this->encryptionController->decrypt($activity['id']); $activitiesArr[$key] = $activity; } $activitiesStr = json_encode($activitiesArr); $evidenceArr = json_decode($form['evidence'], true); if(count($evidenceArr) <= 0){ return $this->responseController->makeResponse(true, 'El arreglo de evidencias está vacío.', [], 400); } $evidenceArrFn = []; foreach($evidenceArr as $key=>$attached){ $idDec = $this->encryptionController->decrypt($attached['id']); if(!$idDec){ return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400); } $tempFile = DB::table('S002V01TARTE')->where([ ['ARTE_IDAR', '=', $idDec], ['ARTE_NULI', '=', $form['linea']] ])->first(); if(is_null($tempFile)){ return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404); }else if($tempFile->ARTE_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404); } $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser); if(!$finalFile[0]){ return $this->responseController->makeResponse(true, $finalFile[1], [], 400); }else{ $evidenceArrFn[] = $finalFile[1]; } } $evidenceStr = json_encode($evidenceArrFn); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->update([ 'FCPE_ESTA' => 'CE', 'FCPE_ACRE' => $activitiesStr, 'FCPE_EVCI' => $evidenceStr, 'FCPE_FEAC' => $nowStr, 'FCPE_USAC' => $idUser, ]); return $this->responseController->makeResponse(false, 'EXITO'); } public function closedNoMeasuresOrderValidation(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'validation' => 'required|string|in:Si,No', 'validated_by' => 'required|string', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404); }else if($order->FCPE_ESTA != 'CE'){ return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está cerrada.', [], 401); } $validationStatus = $form['validation'] == 'Si' ? 'CV' : 'VA'; $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->update([ 'FCPE_CVPO' => $form['validated_by'], 'FCPE_ESTA' => $validationStatus, 'FCPE_FEAC' => $nowStr, 'FCPE_USAC' => $idUser, ]); return $this->responseController->makeResponse(false, 'EXITO'); } public function generateNoMeasuresReport(Request $request) { DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'report_type' => 'required|string|in:RITR,RIIF,RAAV', 'report_data' => 'required|string' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400); } $order = DB::table('S002V01TFCPE')->where([ ['FCPE_NULI', '=', $form['linea']], ['FCPE_IDRE', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404); }else if($order->FCPE_ESTA != 'CV'){ return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está cerrada y validada.', [], 401); } $reportDataDec = $this->encryptionController->decrypt($form['report_data']); if(!$reportDataDec){ return $this->responseController->makeResponse(true, 'Los datos del reporte no fueron encriptados correctamente.', [], 400); } $reportDataArr = json_decode($reportDataDec, true); $html = ''; $crrcLogo = file_get_contents($this->functionsController->getBasePath() . "\storage\app\public\global_resources\logo_crrc.webp"); $ingeropLogo = file_get_contents($this->functionsController->getBasePath() ."\storage\app\public\global_resources\logo_ingerop.png"); $stcLogo = file_get_contents($this->functionsController->getBasePath() ."\storage\app\public\global_resources\logo_stc.webp"); $stcShortLogo = file_get_contents($this->functionsController->getBasePath() ."\storage\app\public\global_resources\logo_stc_small.png"); $crrcLogoStr = "data:image/svg+xml;base64," . base64_encode($crrcLogo); $ingeropLogoStr = "data:image/svg+xml;base64," . base64_encode($ingeropLogo); $stcLogoStr = "data:image/svg+xml;base64," . base64_encode($stcLogo); $stcShortLogoStr = "data:image/svg+xml;base64," . base64_encode($stcShortLogo); $noar = ''; if($form['report_type'] == 'RITR'){ $html = file_get_contents($this->templatesUbic . "01-GMCO-PL-010101-000001=01=PDF_REPORTE_KIZEO_01.html"); $html = str_replace("%logo_crrc%", $crrcLogoStr, $html); $html = str_replace("%logo_stc%", $stcLogoStr, $html); $html = str_replace("%logo_ingerop%", $ingeropLogoStr, $html); $noar = "rep_int_trenes_mod_nm16_nm22_ord_$idOrder"; }else if($form['report_type'] == 'RIIF'){ $html = file_get_contents($this->templatesUbic . "01-GMCO-PL-010101-000001=01=PDF_REPORTE_KIZEO_02.html"); $html = str_replace("%logo_stc_small%", $stcShortLogoStr, $html); $html = str_replace("%logo_crrc%", $crrcLogoStr, $html); $noar = "rep_inc_inst_fija_ord_$idOrder"; }else if($form['report_type'] == 'RAAV'){ $html = file_get_contents($this->templatesUbic . "01-GMCO-PL-010101-000001=01=PDF_REPORTE_KIZEO_03.html"); $html = str_replace("%logo_crrc%", $crrcLogoStr, $html); $html = str_replace("%logo_stc%", $stcLogoStr, $html); $html = str_replace("%logo_ingerop%", $ingeropLogoStr, $html); $noar = "reg_aten_aver_ord_$idOrder"; } if(strlen($html) <= 0){ return $this->responseController->makeResponse(true, 'No se encontró ninguna plantilla para el reporte solicitado.', [], 404); } foreach($reportDataArr as $key=>$val){ $keyInd = "##$key##"; $val = is_null($val) ? ' ' : $val; $html = str_replace($keyInd, $val, $html); } $como = 'GMCO'; $cldo = 'IN'; $exte = "pdf"; $line = intval($form['linea']) < 10 ? "0$form[linea]" : "$form[linea]"; $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $nowArr = explode(" ", $nowStr); $dateArr = explode("-", $nowArr[0]); $year = substr($dateArr[0], 2); $fecr = $year . $dateArr[1] .$dateArr[2]; $sec = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $line], ['AFAL_COMO', '=', $como], ['AFAL_CLDO', '=', $cldo], ])->orderBy('AFAL_NUSE', 'desc')->first(); $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . ""; for($i = strlen($nuse); $i < 6; $i++){ $nuse = "0$nuse"; } $ver = DB::table('S002V01TAFAL')->where([ ['AFAL_NULI', '=', $line], ['AFAL_COMO', '=', $como], ['AFAL_CLDO', '=', $cldo], ['AFAL_NOAR', '=', $noar], ['AFAL_EXTE', '=', $exte], ])->orderBy('AFAL_NUVE', 'desc')->first(); $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . ""; for($i = strlen($nuve); $i < 2; $i++){ $nuve = "0$nuve"; } $filePath = $this->functionsController->getBasePath() .'\public_files\\'; $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte"; $dompdf = new Dompdf(); $dompdf->loadHtml($html); $dompdf->setPaper('A4', 'portrait'); $dompdf->render(); $output = $dompdf->output(); $tempFile = $filePath . $fileName; if(!file_exists($tempFile)){ fopen($tempFile, 'w'); } file_put_contents($tempFile, $output); $ubic = Storage::putFile('files', new File($tempFile)); $ubic = str_replace("/", "\\", $ubic); $ubic = $this->functionsController->getBasePath() ."\sam\storage\app\\" . $ubic; $tama = filesize($ubic); $usac = json_encode([$idUser]); unlink($tempFile); DB::table('S002V01TAFAL')->insert([ 'AFAL_NULI' => $line, 'AFAL_COMO' => $como, 'AFAL_CLDO' => $cldo, 'AFAL_FECR' => $fecr, 'AFAL_NUSE' => $nuse, 'AFAL_NUVE' => $nuve, 'AFAL_NOAR' => $noar, 'AFAL_EXTE' => $exte, 'AFAL_TAMA' => $tama, 'AFAL_UBIC' => $ubic, 'AFAL_USAC' => $usac, 'AFAL_USRE' => $idUser, 'AFAL_FERE' => $nowStr, ]); return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]); } public function getWorkOrderStaff($idOrder, $idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idOrder = $this->encryptionController->decrypt($idOrder); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden relacionada no está encriptado correctamente', [], 400); } $workOrder = DB::table('S002V01TOTCO')->where([ ['OTCO_NULI', '=', $line], ['OTCO_IDOT', '=', $idOrder] ])->first(); if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden relacionada no está registrada.', [], 404); } $staffArr = json_decode($workOrder->OTCO_PEIN, true); $staffArrFn = []; foreach($staffArr as $val){ if(array_key_exists('TYPE', $val)){ if($val['TYPE'] == 'EQ'){ $workTeamStaff = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([ ['PERS_NULI', '=', $line], ['PERS_EQTR', '=', $val['ID']] ])->get()->all(); foreach($workTeamStaff as $item){ $itemID = $item->PERS_IDPE; $itemFilt = array_filter($staffArrFn, function($v, $k) use($itemID) { return $v['ID'] == $itemID; }, ARRAY_FILTER_USE_BOTH); if(count($itemFilt) <= 0){ $staffArrFn[] = [ 'ID' => $itemID, 'ID_USER' => $item->USUA_IDUS, 'NAME' => $this->functionsController->joinName($item->USUA_NOMB, $item->USUA_APPA, $item->USUA_APMA), 'TYPE' => $item->PERS_TICO, ]; } } }else if($val['TYPE'] == 'SU'){ $subcontratistStaff = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([ ['PERS_NULI', '=', $line], ['PERS_IDPS', '=', $val['ID']] ])->get()->all(); foreach($subcontratistStaff as $item){ $itemID = $item->PERS_IDPE; $itemFilt = array_filter($staffArrFn, function($v, $k) use($itemID) { return $v['ID'] == $itemID; }, ARRAY_FILTER_USE_BOTH); if(count($itemFilt) <= 0){ $staffArrFn[] = [ 'ID' => $itemID, 'ID_USER' => $item->USUA_IDUS, 'NAME' => $this->functionsController->joinName($item->USUA_NOMB, $item->USUA_APPA, $item->USUA_APMA), 'TYPE' => $item->PERS_TICO, ]; } } }else if($val['TYPE'] == 'EM'){ $employee =DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([ ['PERS_NULI', '=', $line], ['PERS_IDPE', '=', $val['ID']] ])->first(); if(!is_null($employee)){ $itemID = $employee->PERS_IDPE; $itemFilt = array_filter($staffArrFn, function($v, $k) use($itemID) { return $v['ID'] == $itemID; }, ARRAY_FILTER_USE_BOTH); if(count($itemFilt) <= 0){ $staffArrFn[] = [ 'ID' => $itemID, 'ID_USER' => $employee->USUA_IDUS, 'NAME' => $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA), 'TYPE' => $employee->PERS_TICO, ]; } } } } } foreach($staffArrFn as $key=>$item){ $item['ID'] = $this->encryptionController->encrypt($item['ID']); $item['ID_USER'] = $this->encryptionController->encrypt($item['ID_USER']); $staffArrFn[$key] = $item; } return $this->responseController->makeResponse(false, 'EXITO', $staffArrFn); } }