responseController = new ResponseController(); $this->encryptionController = new EncryptionController(); $this->functionsController = new FunctionsController(); $this->templatesUbic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\public\pdf_templates\\01_03_GMPR\\"; $this->documentManagementController = new DocumentManagementController(); } public function registerWorkOrder(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'description' => 'required|string', 'instructions' => 'required|json', 'start_date' => 'required|date', 'start_hour' => 'required|string', 'end_date' => 'date', 'end_hour' => 'string', 'equipment' => 'required|string', 'inm_time' => 'required|numeric', 'total_time' => 'required|numeric', 'resources' => 'required|json', 'activator' => 'required|string', 'attached' => 'json', 'exists' => 'required|string|in:S,N', 'id_order' => 'required_if:exists,=,S|string', 'clasification' => 'required|string|max:100', 'staff' => '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); } $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; } $rhre = json_encode($resources); $idActivator = $this->encryptionController->decrypt($form['activator']); if(!$idActivator){ return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400); } $activator = DB::table('S002V01TACTI')->where([ ['ACTI_NULI', '=', $form['linea']], ['ACTI_IDAC', '=', $idActivator] ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first(); if(is_null($activator)){ return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404); } $startDateTime = "$form[start_date] $form[start_hour]"; $validStartDateTime = $this->functionsController->validateDate($startDateTime); if(!$validStartDateTime){ return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400); } $dateTimeStart = new Carbon($startDateTime); if($activator->ACTI_TIAC == 'Calendario' || $activator->ACTI_TIAC == 'Sintoma'){ $activatorConfig = json_decode($activator->ACTI_COAC, true); $activatorStartDate = explode('T', $activatorConfig['startDate'])[0]; $activatorStartDateTime = "$activatorStartDate $activatorConfig[startHour]"; $activatorStartDateTimeObj = new Carbon($activatorStartDateTime); if($dateTimeStart->lt($activatorStartDateTimeObj)){ return $this->responseController->makeResponse(true, 'La fecha de inicio de la orden no puede ser menor a la fecha de inicio configurada en el activador.', [], 400); } } $ftap = '0001-01-01 00:00:00'; if(isset($form['end_hour'])){ $endDateTime = "$form[end_date] $form[end_hour]"; $validEndDateTime = $this->functionsController->validateDate($endDateTime); if(!$validEndDateTime){ return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400); } $dateTimeEnd = new Carbon("$endDateTime"); if($dateTimeStart->gt($dateTimeEnd)){ return $this->responseController->makeResponse(true, 'La hora de término es menor a la hora de inicio.', [], 400); } $ftap = $dateTimeEnd->toDateTimeString(); } $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 equipaiento seleccionado no existe.', [], 404); }else if($activator->CONA_COEQ != $equipmentCode){ return $this->responseController->makeResponse(true, 'El activador seleccionado no puede ser asignado al equipamiento relacionado, ya que el contador pertenece a otro equipo.', [], 401); }else if(floatval($form['inm_time']) > floatval($form['total_time'])){ return $this->responseController->makeResponse(true, 'El tiempo de inmovilización aproximado no puede ser mayor al tiempo de duración aproximada.', [], 400); } $staffArr = json_decode($form['staff'], true); if(empty($staffArr)){ return $this->responseController->makeResponse(true, 'El JSON de 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'] ]; } $instructionsArr = json_decode($form['instructions'], true); foreach($instructionsArr as $key=>$instruction){ $instructionInd = $key + 1; $instructionStartArr = explode(' ', $instruction['INICIO']); if(count($instructionStartArr) != 3){ return $this->responseController->makeResponse(true, "La fecha de inicio de la instrucción $instructionInd tiene un formato inválido.", [], 400); } $startHourArr = explode(':', $instructionStartArr[1]); $startHourInt = intval($startHourArr[0]); if($instructionStartArr[2] == 'PM' && $startHourInt < 12){ $startHourInt = $startHourInt + 12; } $startOrigin = $instruction['INICIO']; $startHourStr = $startHourInt < 10 ? "0$startHourInt" : "$startHourInt"; $instructionStartStr = "$startHourStr:$startHourArr[1]:00"; $instruction['INICIO'] = "$instructionStartArr[0] $instructionStartStr"; $instructionStartDateTime = new Carbon($instruction['INICIO']); if($instructionStartDateTime->lt($dateTimeStart)){ return $this->responseController->makeResponse(true, "La fecha de inicio de la instrucción $instructionInd no puede ser menor a la fecha de inicio del activador.", [], 400); } $instructionEndArr = explode(' ', $instruction['FIN']); if(count($instructionEndArr) != 3){ return $this->responseController->makeResponse(true, "La fecha de término de la instrucción $instructionInd tiene un formato inválido.", [], 400); } $endHourArr = explode(':', $instructionEndArr[1]); $endHourInt = intval($endHourArr[0]); if($instructionEndArr[2] == 'PM' && $endHourInt < 12){ $endHourInt = $endHourInt + 12; } $endOrigin = $instruction['FIN']; $endHourStr = $endHourInt < 10 ? "0$endHourInt" : "$endHourInt"; $instructionEndStr = "$endHourStr:$endHourArr[1]:00"; $instruction['FIN'] = "$instructionEndArr[0] $instructionEndStr"; if(isset($form['end_hour'])){ $dateTimeEnd = new Carbon($ftap); $instructionEndDateTime = new Carbon($instruction['FIN']); if($instructionEndDateTime->gt($dateTimeEnd)){ return $this->responseController->makeResponse(true, "La fecha de término de la instrucción $instructionInd no puede ser mayor a la fecha de término del activador.", [], 400); } } $instruction['ID'] = $this->encryptionController->decrypt($instruction['ID']); $instruction['INICIO'] = $startOrigin; $instruction['FIN'] = $endOrigin; $instructionsArr[$key] = $instruction; } $inin = json_encode($instructionsArr); $oppr = json_encode($staff); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $fiap = $dateTimeStart->toDateTimeString(); $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'], 'GMPR', 'OR', $tempFile, $idUser); if(!$finalFile){ return $this->responseController->makeResponse(true, $finalFile[1], [], 400); }else{ $attachedArrFn[] = $finalFile[1]; } } } } $done = json_encode($attachedArrFn); if($form['exists'] == 'S'){ $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('S002V01TOTPR')->where([ ['OTPR_IDOT', '=', $idOrder], ['OTPR_NULI', '=', $form['linea']] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404); } DB::table('S002V01TOTPR')->where([ ['OTPR_IDOT', '=', $idOrder], ['OTPR_NULI', '=', $form['linea']] ])->update([ 'OTPR_DEIN' => $form['description'], 'OTPR_ININ' => $inin, 'OTPR_EQIN' => $equipmentCode, 'OTPR_FIAP' => $fiap, 'OTPR_FTAP' => $ftap, 'OTPR_TIIN' => $form['inm_time'], 'OTPR_OPPR' => $oppr, 'OTPR_DTIN' => $form['total_time'], 'OTPR_RHRE' => $rhre, 'OTPR_DONE' => $done, 'OTPR_ACAS' => $idActivator, 'OTPR_CLAS' => $form['clasification'], 'OTPR_ESTA' => 'R', 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr, ]); }else{ $idOrder = DB::table('S002V01TOTPR')->insertGetId([ 'OTPR_NULI' => $form['linea'], 'OTPR_DEIN' => $form['description'], 'OTPR_ININ' => $inin, 'OTPR_EQIN' => $equipmentCode, 'OTPR_FIAP' => $fiap, 'OTPR_FTAP' => $ftap, 'OTPR_TIIN' => $form['inm_time'], 'OTPR_OPPR' => $oppr, 'OTPR_DTIN' => $form['total_time'], 'OTPR_RHRE' => $rhre, 'OTPR_DONE' => $done, 'OTPR_ACAS' => $idActivator, 'OTPR_CLAS' => $form['clasification'], 'OTPR_ESTA' => 'R', 'OTPR_USRE' => $idUser, 'OTPR_FERE' => $nowStr, ]); } $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P01ROTR', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró la orden de trabajo #$idOrder.", $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); } $workOrders = DB::table('S002V01TOTPR')->select([ 'OTPR_IDOT AS IDORDEN', 'OTPR_EQIN AS EQUIPO', 'OTPR_FIAP AS FECHAINICIO', 'OTPR_FTAP AS FECHAFINAL', 'OTPR_ACAS AS ACTIVADOR', 'ACTI_TIAC AS TIPOACTIVADOR', 'ACTI_PRIO AS PRIORIDAD', 'OTPR_ESTA AS ESTATUS' ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS') ->where('OTPR_NULI', '=', $line) ->orderBy('OTPR_IDOT', 'desc')->get()->all(); foreach($workOrders as $key=>$order){ $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN); $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO); $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR); if(!is_null($order->PRIORIDAD)){ $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD); } if($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null; if($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null; $workOrders[$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, 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P01HOTP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo registradas.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $workOrders); } 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 no está encriptado correctamente.', [], 400); } $workOrder = DB::table('S002V01TOTPR')->select([ 'OTPR_IDOT AS IDORDEN', 'OTPR_DEIN AS DESCRIPCION', 'OTPR_ININ AS INSTRUCCIONES', 'OTPR_EQIN AS EQUIPAMIENTO', 'EQUI_TIPO AS TIPO_EQUIPAMIENTO', 'EQUI_MODE AS MODELO_EQUIPAMIENTO', 'EQUI_IDEQ AS ID_EQUIPAMIENTO', 'OTPR_FIAP AS FECHAINICIO', 'OTPR_FTAP AS FECHAFINAL', 'OTPR_SEAN AS ANALISIS', 'OTPR_TIIN AS TIEMPOINMOESTI', 'OTPR_CLAS AS CLASIFICACION', 'OTPR_OPPR AS OPERARIOS', 'OTPR_DTIN AS DURACIONTOTAL', 'OTPR_RHRE AS RECURSOS', 'OTPR_DONE AS DOCUMENTOS', 'OTPR_RECO AS CONTRATOS', 'OTPR_ACAS AS ACTIVADOR', 'ACTI_TIAC AS TIPOACTIVADOR', 'ACTI_PRIO AS PRIORIDAD', 'OTPR_ESTA AS ESTADO', 'OTPR_USRE AS USUARIOREGISTRA', 'OTPR_FERE AS FECHAREGISTRO', 'OTPR_USMO AS USUARIOMODIFICA', 'OTPR_FEMO AS FECHAMODIFICACION', ])->leftJoin('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN') ->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([ ['OTPR_IDOT', '=', $idOrder], ['OTPR_NULI', '=', $line], ])->first(); if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden de trabajo consultada no existe.', [], 404); } $workOrder->IDORDEN = $this->encryptionController->encrypt($workOrder->IDORDEN); $workOrder->EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->EQUIPAMIENTO); $workOrder->ACTIVADOR = $this->encryptionController->encrypt($workOrder->ACTIVADOR); if(!is_null($workOrder->ID_EQUIPAMIENTO)){ $workOrder->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->ID_EQUIPAMIENTO); } if(!is_null($workOrder->PRIORIDAD)){ $workOrder->PRIORIDAD = $this->encryptionController->encrypt($workOrder->PRIORIDAD); } $workOrder->FECHAFINAL = $workOrder->FECHAFINAL == '0001-01-01 00:00:00' ? null : $workOrder->FECHAFINAL; $workOrder->FECHAINICIO = $workOrder->FECHAINICIO == '0001-01-01 00:00:00' ? null : $workOrder->FECHAINICIO; $instructionsArr = json_decode($workOrder->INSTRUCCIONES, true); foreach($instructionsArr as $key=>$instruction){ $instruction['ID'] = $this->encryptionController->encrypt($instruction['ID']); $instructionsArr[$key] = $instruction; } $workOrder->INSTRUCCIONES = json_encode($instructionsArr); $staffArr = json_decode($workOrder->OPERARIOS, 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; } $workOrder->OPERARIOS = json_encode($staffArr); $resources = json_decode($workOrder->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; } $workOrder->RECURSOS = json_encode($resources); $documentsArr = json_decode($workOrder->DOCUMENTOS, 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' ]; } $workOrder->DOCUMENTOS = json_encode($documentsFn); if(!is_null($workOrder->ANALISIS)){ $analysisArr = json_decode($workOrder->ANALISIS, true); $teamsConf = $analysisArr['teamsConf']; foreach($teamsConf as $key=>$val){ $idEnc = $this->encryptionController->encrypt($val['ID']); $val['ID'] = $idEnc; $teamsConf[$key] = $val; } $analysisArr['teamsConf'] = $teamsConf; $workOrder->ANALISIS = json_encode($analysisArr); } $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $workOrder->USUARIOREGISTRA], ])->first(); $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $workOrder->USUARIOREGISTRA = $nameReg . " (" . $workOrder->USUARIOREGISTRA . ")"; if(!is_null($workOrder->USUARIOMODIFICA)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $workOrder->USUARIOMODIFICA], ])->first(); $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA); $workOrder->USUARIOMODIFICA = $nameMod . " (" . $workOrder->USUARIOMODIFICA . ")"; } $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, 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P04COIN', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó la orden de trabajo #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $workOrder); } public function executePreventiveWorkOrder(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'configuration' => 'required|string', 'execution_date' => 'required|date' ]); 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 seleccionada no fue encriptado correctamente.', [], 400); } $workOrder = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); }else if($workOrder->OTPR_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404); } $configurationStr = $this->encryptionController->decrypt($form['configuration']); if(!$configurationStr){ return $this->responseController->makeResponse(true, 'La cadena de configuración no fue encriptada correctamente.', [], 400); } $configurationArr = json_decode($configurationStr, true); $staffArr = []; foreach($configurationArr as $key=>$value){ $specialty = DB::table('S002V01TGEES')->where([ ['GEES_NULI', '=', $form['linea']], ['GEES_COES', '=', $key] ])->first(); if(!is_null($specialty)){ $specialtyEmployees = []; foreach($value as $key0=>$value0){ $idEmployeeDec = $this->encryptionController->decrypt($value0); if(!$idEmployeeDec){ return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key no fue encriptado correctamente.", [], 400); } $employee = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $form['linea']], ['PERS_IDPE', '=', $idEmployeeDec] ])->first(); if(is_null($employee)){ return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key no existe.", [], 404); }else if($employee->PERS_ESTA == 'Eliminado'){ return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key está eliminado.", [], 404); } $specialtyEmployees[] = $idEmployeeDec; } $staffArr[$key] = $specialtyEmployees; } } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $staffStr = json_encode($staffArr); $validExecutionDate = $this->functionsController->validateDate($form['execution_date']); if(!$validExecutionDate){ return $this->responseController->makeResponse(true, 'La fecha de ejecución tiene un formato inválido.', [], 400); } $execDate = new Carbon($form['execution_date']); $fecIni = new Carbon($workOrder->OTPR_FIAP); if($fecIni->gt($execDate)){ $tmp = $fecIni->toDateTimeString() . '|' . $execDate->toDateTimeString(); return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.' . $tmp, [], 400); } $execDateStr = $execDate->toDateString(); $execution = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $form['linea']], ['BEOT_IDOT', '=', $form['id_order']], ['BEOT_FEPR', '=', $execDateStr] ])->first(); if(!is_null($execution)){ $estatus = $execution->BEOT_TIAC; if($estatus == 'Ejecucion'){ return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya fue realizada.", [], 401); }else if($estatus == 'Cancelacion'){ return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr fue cancelada.", [], 401); }else if($estatus == 'Finalizado'){ return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha finalizado.", [], 401); } } DB::table('S002V01TBEOT')->insert([ 'BEOT_NULI' => $form['linea'], 'BEOT_IDOT' => $idOrder, 'BEOT_FEPR' => $execDateStr, 'BEOT_TIAC' => 'Ejecucion', 'BEOT_OPER' => $staffStr, 'BEOT_FEEJ' => $nowStr, 'BEOT_USEJ' => $idUser, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F02EMOT', '-', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") ejecutó la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function cancelWorkOrder(Request $request){ //PENDIENTE REVISAR DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|integer', 'execution_date' => 'required|date', 'observations' => '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); } $workOrder = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $form['id_order']] ])->first(); if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404); } $execDate = new Carbon($form['execution_date']); $fecIni = new Carbon($workOrder->OTPR_FIAP); if($fecIni->gt($execDate)){ return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.', [], 400); } $execDateStr = $execDate->toDateString(); $execution = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $form['linea']], ['BEOT_IDOT', '=', $form['id_order']], ['BEOT_FEPR', '=', $execDateStr] ])->first(); if(!is_null($execution)){ $estatus = $execution->BEOT_TIAC; if($estatus == 'Ejecucion'){ return $this->responseController->makeResponse(true, "La programación de la orden para la fecha $execDateStr no se puede cancelar porque ya se ha iniciado su ejecución.", [], 401); }else if($estatus == 'Finalizado'){ return $this->responseController->makeResponse(true, "La programación de la orden para la fecha $execDateStr no se puede cancelar porque ya se ha finalizado.", [], 401); }else if($estatus == 'Cancelacion'){ return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha sido cancelada.", [], 401); } } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TBEOT')->insert([ 'BEOT_NULI' => $form['linea'], 'BEOT_IDOT' => $form['id_order'], 'BEOT_FEPR' => $execDateStr, 'BEOT_TIAC' => 'Cancelacion', 'BEOT_OBSE' => $form['observations'], 'BEOT_FEEJ' => $nowStr, 'BEOT_USEJ' => $idUser, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F02EMOT', '-', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") canceló la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.", $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 solicitada no fue encriptado correctamente.', [], 400); } $workOrder = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404); }else if($workOrder->OTPR_ESTA == 'E'){ return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada', [], 401); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TOTPR')->where([ ['OTPR_IDOT', '=', $idOrder], ['OTPR_NULI', '=', $form['linea']] ])->update([ 'OTPR_ESTA' => 'E', 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F04EOTP', '-', 'Eliminación', "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la orden de trabajo #$form[id_order].", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function updateWorkOrder(Request $request){ //PENDIENTE ELIMINAR DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|integer', 'title' => 'required|string', 'repeat' => 'required|json', 'start_date' => 'required|date', 'start_hour' => 'required|string', 'inm_time' => 'required|numeric', 'description' => 'required|string|max:100', 'clasification' => 'required|string|max:50', 'priority' => 'required|string|in:1,2,3', 'equipment' => 'required|string', 'analisis' => 'required|string', 'specialties' => '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); } $workOrder = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $form['id_order']] ])->first(); if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404); } $repeArr = json_decode($form['repeat'], true); if(empty($repeArr)){ return $this->responseController->makeResponse(true, 'El JSON de repetición tiene un formato inválido.', [], 400); }else if(!array_key_exists('type', $repeArr)){ return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de repetición.', [], 400); }else if(!array_key_exists('config', $repeArr)){ return $this->responseController->makeResponse(true, 'El campo config no fue enviado en el JSON de repetición.', [], 400); } $hourArr = explode(' ', $form['start_hour']); $timeArr = ''; if(count($hourArr) < 2){ return $this->responseController->makeResponse(true, 'La hora de inicio tiene un formato inválido.', [], 400); }else if($hourArr[1] == 'PM'){ $hour = explode(':', $hourArr[0]); $h = intval($hour[0]); if($h != 12){ $h = $h + 12; } $hourStr = "$h:$hour[1]:00"; $timeArr .= " $hourStr"; }else if($hourArr[1] == 'AM'){ $hour = explode(':', $hourArr[0]); $h = intval($hour[0]); $hStr = $h < 10 ? "0$h" : "$h"; $hStr .= ":$hour[1]:00"; $timeArr .= " $hStr"; }else{ return $this->responseController->makeResponse(true, 'No se pudo determinar el periodo del horario.', [], 400); } $specialtiesArr = json_decode($form['specialties'], true); if(empty($specialtiesArr)){ return $this->responseController->makeResponse(true, 'El JSON de especialidades tiene un formato inválido.', [], 400); } foreach($specialtiesArr as $specialty){ if(!array_key_exists('specialty', $specialty)){ return $this->responseController->makeResponse(true, 'El campo specialty no fue enviado en el JSON de especialidad.', [], 400); }else if(!array_key_exists('type', $specialty)){ return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de especialidad.', [], 400); }else if(!array_key_exists('staff', $specialty)){ return $this->responseController->makeResponse(true, 'El campo staff no fue enviado en el JSON de especialidad.', [], 400); } } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $documents = isset($form['attached']) ? $form['attached'] : null; DB::table('S002V01TOTPR')->where([ ['OTPR_IDOT', '=', $form['id_order']], ['OTPR_NULI', '=', $form['linea']], ])->update([ 'OTPR_TIOR' => $form['title'], 'OTPR_REPE' => $form['repeat'], 'OTPR_FIIN' => $form['start_date'], 'OTPR_HIIN' => $timeArr, 'OTPR_TIES' => $form['inm_time'], 'OTPR_DEIN' => $form['description'], 'OTPR_ANIN' => $form['analisis'], 'OTPR_CEIN' => $form['equipment'], 'OTPR_PERE' => $form['specialties'], 'OTPR_CLAS' => $form['clasification'], 'OTPR_PRIO' => $form['priority'], 'OTPR_DONE' => $documents, 'OTPR_USRE' => $idUser, 'OTPR_FERE' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P01ROTR', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo $form[title] ($form[id_order]).", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function geStartedtWorkOrders($idUser, $line){ //PENDIENTE REVISAR 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); } $startedWorkOrders = DB::table('S002V01TBEOT')->select([ 'BEOT_IDRE AS IDREGISTRO', 'BEOT_IDOT AS IDORDEN', 'BEOT_FEPR AS FECHAPROGRAMA', 'BEOT_FEEJ AS FECHAEJECUCION', 'BEOT_USEJ AS USUARIOEJECUCION', 'BEOT_TIAC AS ESTADO', 'OTPR_TIOR AS TITULOORDEN', 'OTPR_HIIN AS HORAPROGRAMA', 'OTPR_TIES AS TIEMPOESTIMADO', 'OTPR_PRIO AS PRIORIDAD', ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')->where([ ['BEOT_NULI', '=', $line], ])->get()->all(); foreach($startedWorkOrders as $workOrder){ $usrEje = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $workOrder->USUARIOEJECUCION] ])->first(); $nameEje = $this->functionsController->joinName($usrEje->USUA_NOMB, $usrEje->USUA_APPA, $usrEje->USUA_APMA); $workOrder->USUARIOEJECUCION = $nameEje . " (" . $workOrder->USUARIOEJECUCION . ")"; } $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, 'S002V01M10GMPR', 'S002V01F05BEOT', 'S002V01P01HOEJ', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo en ejecución.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $startedWorkOrders); } public function endOrderExecution(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|integer', 'id_reg' => 'required|integer', 'observations' => '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); } $workOrder = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $form['id_order']] ])->first(); if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404); } $register = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $form['linea']], ['BEOT_IDRE', '=', $form['id_reg']], ['BEOT_IDOT', '=', $form['id_order']] ])->first(); if(is_null($register)){ return $this->responseController->makeResponse(true, 'El registro solicitado no existe', [], 404); }else if($register->BEOT_TIAC == 'Cancelacion'){ return $this->responseController->makeResponse(true, 'El registro solicitado fue cancelado', [], 401); }else if($register->BEOT_TIAC == 'Finalizado'){ return $this->responseController->makeResponse(true, 'El registro solicitado ya fue finalizado', [], 401); } $now = $this->functionsController->now(); $executionDate = new Carbon($register->BEOT_FEEJ); $diff = $now->diffInMilliseconds($executionDate); //Milisegundos $diff = $diff / 1000; //Segundos $diff = $diff / 60; //Minutos $diff = $diff / 60; //Horas $nowStr = $now->toDateTimeString(); DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $form['linea']], ['BEOT_IDRE', '=', $form['id_reg']], ['BEOT_IDOT', '=', $form['id_order']] ])->update([ "BEOT_TIAC" => 'Finalizado', "BEOT_DTEJ" => $diff, "BEOT_OBSE" => $form['observations'], "BEOT_FEFI" => $nowStr, "BEOT_USFI" => $idUser, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F05SEOR', '-', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") finalizó la ejecución del día ". $register->BEOT_FEPR ." de la orden #$form[id_order].", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getExecRegister($date, $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 orden relacionada no fue encriptado correctamente.', [], 400); } $dateArr = explode('|', $date); $workOrder = null; if(count($dateArr) == 2){ if($dateArr[1] == 'O'){ $workOrder = DB::table('S002V01TOTPR')->select( 'OTPR_IDOT AS IDORDEN', 'OTPR_DEIN AS DESCRIPCION', DB::raw("CONCAT( OTPR_EQIN, ' - ', EQUI_TIPO, ' - ', EQUI_MODE, ' (', EQUI_IDEQ, ')' ) AS EQUIPAMIENTO"), 'OTPR_FIAP AS FECHAINICIO', DB::raw("'Programada' AS ESTADODEEJECUCION"), DB::raw("'-' AS IDREG"), DB::raw("NULL AS OBSERVACIONES"), DB::raw("NULL AS OPERARIOS"), )->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idRegister], ])->first(); }else{ $validDate = $this->functionsController->validDate($dateArr[0]); if(!$validDate){ return $this->responseController->makeResponse(true, 'La fecha de ejecución enviada tiene un formato inválido.', [], 400); } $workOrder = DB::table('S002V01TBEOT')->select([ 'BEOT_IDOT AS IDORDEN', 'OTPR_DEIN AS DESCRIPCION', DB::raw("CONCAT( OTPR_EQIN, ' - ', EQUI_TIPO, ' - ', EQUI_MODE, ' (', EQUI_IDEQ, ')' ) AS EQUIPAMIENTO"), 'OTPR_FIAP AS FECHAINICIO', 'BEOT_TIAC AS ESTADODEEJECUCION', 'BEOT_IDRE AS IDREG', 'BEOT_OBSE AS OBSERVACIONES', 'BEOT_OPER AS OPERARIOS' ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT') ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $idRegister], ['BEOT_FEPR', '=', $dateArr[0]], ])->first(); } }else{ $workOrder = DB::table('S002V01TBEOT')->select([ 'BEOT_IDOT AS IDORDEN', 'OTPR_DEIN AS DESCRIPCION', DB::raw("CONCAT( OTPR_EQIN, ' - ', EQUI_TIPO, ' - ', EQUI_MODE, ' (', EQUI_IDEQ, ')' ) AS EQUIPAMIENTO"), 'OTPR_FIAP AS FECHAINICIO', 'BEOT_TIAC AS ESTADODEEJECUCION', 'BEOT_IDRE AS IDREG', 'BEOT_OBSE AS OBSERVACIONES', 'BEOT_OPER AS OPERARIOS' ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT') ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDRE', '=', $idRegister], ])->first(); } if(is_null($workOrder)){ return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404); } $idOrder = $workOrder->IDORDEN; $workOrder->IDORDEN = $this->encryptionController->encrypt($workOrder->IDORDEN); $workOrder->EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->EQUIPAMIENTO); $workOrder->IDREG = $this->encryptionController->encrypt($workOrder->IDREG); if(!is_null($workOrder->OPERARIOS)){ $staffArr = json_decode($workOrder->OPERARIOS); $staffArrFn = []; foreach($staffArr as $key=>$val){ $specialtyObj = DB::table('S002V01TGEES')->where([ ['GEES_NULI', '=', $line], ['GEES_COES', '=', $key] ])->first(); $specialtyConf = []; if(!is_null($specialtyObj)){ $specialtyConf['CODIGO_ESPECIALIDAD'] = $this->encryptionController->encrypt($specialtyObj->GEES_COES); $specialtyConf['NOMBRE_ESPECIALIDAD'] = $specialtyObj->GEES_NOES; $staff = []; foreach($val as $val0){ $employee = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([ ['PERS_NULI', '=', $line], ['PERS_IDPE', '=', $val0] ])->first(); $employeeObj = [ 'ID_EMPLEADO' => $this->encryptionController->encrypt($employee->PERS_IDPE), 'ID_USUARIO' => $this->encryptionController->encrypt($employee->USUA_IDUS), 'NOMBRE_EMPLEADO' => $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA), 'TIPO_EMPLEADO' => $employee->PERS_TICO ]; $staff[] = $employeeObj; } $specialtyConf['OPERARIOS'] = $staff; } $staffArrFn[] = $specialtyConf; } $workOrder->OPERARIOS = $staffArrFn; } $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, 'S002V01M10GMPR', 'S002V01F08VCPR', '-', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó el estado de la ejecución de la orden #" . $idOrder . " para la fecha $date.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $workOrder); } public function copyWorkOrder(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'equipment' => '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 que desea copiar no fue encriptado correctamente.', [], 400); } $workOrder = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($workOrder)){ 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 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 seleccionado no existe.', [], 404); }else if($equipmentCode == $workOrder->OTPR_EQIN){ return $this->responseController->makeResponse(true, 'El equipo seleccionado es igual al de la orden copiada.', [], 400); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $idOrderNew = DB::table('S002V01TOTPR')->insertGetId([ "OTPR_NULI" => $form['linea'], "OTPR_DEIN" => $workOrder->OTPR_DEIN, "OTPR_ININ" => $workOrder->OTPR_ININ, "OTPR_EQIN" => $equipmentCode, "OTPR_FIAP" => $workOrder->OTPR_FIAP, "OTPR_FTAP" => $workOrder->OTPR_FTAP, "OTPR_SEAN" => $workOrder->OTPR_SEAN, "OTPR_TIIN" => $workOrder->OTPR_TIIN, "OTPR_OPPR" => $workOrder->OTPR_OPPR, "OTPR_DTIN" => $workOrder->OTPR_DTIN, "OTPR_RHRE" => $workOrder->OTPR_RHRE, "OTPR_DONE" => '[]', "OTPR_RECO" => $workOrder->OTPR_RECO, "OTPR_ACAS" => $workOrder->OTPR_ACAS, "OTPR_CLAS" => $workOrder->OTPR_CLAS, "OTPR_ESTA" => 'R', "OTPR_USRE" => $idUser, "OTPR_FERE" => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F06COVE', '-', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") copió la orden #$idOrder para el equipamiento $equipmentCode dentro de la orden #$idOrderNew.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function savePresetWorkOrder(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'exists' => 'required|string|in:S,N', 'id_order' => 'required_if:exists,=,S|string', 'description' => 'required|string', 'instructions' => 'required|string', 'start_date' => 'required|string', 'start_hour' => 'required|string', 'end_date' => 'required|string', 'end_hour' => 'required|string', 'equipment' => 'required|string', 'inm_time' => 'required|string', 'total_time' => 'required|string', 'staff' => 'required|string', 'attached' => 'required|string', 'activator_type' => 'required|string', 'activator' => 'required|string', 'clasification' => 'required|string|max:100', 'resources' => '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); } $acas = '0'; if($form['activator'] != '-'){ $idActivator = $this->encryptionController->decrypt($form['activator']); if(!$idActivator){ return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400); } $activator = DB::table('S002V01TACTI')->where([ ['ACTI_NULI', '=', $form['linea']], ['ACTI_IDAC', '=', $idActivator] ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first(); if(is_null($activator)){ return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404); } $acas = $idActivator; } $rhre = '[]'; if($form['resources'] != '[]'){ $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; } $rhre = json_encode($resources); } $startDateTime = '0001-01-01 00:00:00'; if($form['start_date'] != '-' && $form['start_hour'] != '-'){ $startDateTime = "$form[start_date] $form[start_hour]"; $validStartDateTime = $this->functionsController->validateDate($startDateTime); if(!$validStartDateTime){ return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400); } } $endDateTime = '0001-01-01 00:00:00'; if($form['end_date'] != '-' && $form['end_hour'] != '-'){ $endDateTime = "$form[end_date] $form[end_hour]"; $validEndDateTime = $this->functionsController->validateDate($endDateTime); if(!$validEndDateTime){ return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400); } } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $dein = $form['description']; $eqin = '-'; if($form['equipment'] != '-'){ $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 equipaiento seleccionado no existe.', [], 404); } $eqin = $equipmentCode; } $tiin = $form['inm_time'] == '-' ? 0 : floatval($form['inm_time']); $dtin = $form['total_time'] == '-' ? 0 : floatval($form['total_time']); $staffArr = json_decode($form['staff'], true); $staff = []; if($form['staff'] != '-' && !empty($staffArr)){ $staffArr = json_decode($form['staff'], true); 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'] ]; } } $oppr = json_encode($staff); $clas = $form['clasification']; $inin = '[]'; if($form['instructions'] != '-'){ $instructions = json_decode($form['instructions'], true); foreach($instructions as $key=>$instruction){ $instruction['ID'] = $this->encryptionController->decrypt($instruction['ID']); $instructions[$key] = $instruction; } $inin = json_encode($instructions); } $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'], 'GMPR', 'OR', $tempFile, $idUser); if(!$finalFile){ return $this->responseController->makeResponse(true, $finalFile[1], [], 400); }else{ $attachedArrFn[] = $finalFile[1]; } } } } $done = json_encode($attachedArrFn); if($form['exists'] == 'N'){ $idOrder = DB::table('S002V01TOTPR')->insertGetId([ 'OTPR_NULI' => $form['linea'], 'OTPR_DEIN' => $dein, 'OTPR_ININ' => $inin, 'OTPR_EQIN' => $eqin, 'OTPR_FIAP' => $startDateTime, 'OTPR_FTAP' => $endDateTime, 'OTPR_TIIN' => $tiin, 'OTPR_OPPR' => $oppr, 'OTPR_DTIN' => $dtin, 'OTPR_RHRE' => $rhre, 'OTPR_DONE' => $done, 'OTPR_ACAS' => $acas, 'OTPR_CLAS' => $clas, 'OTPR_ESTA' => 'B', 'OTPR_USRE' => $idUser, 'OTPR_FERE' => $nowStr, ]); }else{ $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('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder], ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404); } DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder] ])->update([ 'OTPR_DEIN' => $dein, 'OTPR_ININ' => $inin, 'OTPR_EQIN' => $eqin, 'OTPR_FIAP' => $startDateTime, 'OTPR_FTAP' => $endDateTime, 'OTPR_TIIN' => $tiin, 'OTPR_OPPR' => $oppr, 'OTPR_DTIN' => $dtin, 'OTPR_RHRE' => $rhre, 'OTPR_DONE' => $done, 'OTPR_ACAS' => $acas, 'OTPR_CLAS' => $clas, 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr, ]); } $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P02ROTP', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró un borrador para la orden de trabajo #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeresponse(false, "EXITO"); } public function getActiveOrders($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); } $activeWorkOrders = DB::table('S002V01TOTPR')->select([ 'OTPR_IDOT AS IDORDEN', 'OTPR_EQIN AS EQUIPAMIENTO', 'OTPR_FIAP AS FECHAINICIO', 'OTPR_FTAP AS FECHATERMINO', 'OTPR_TIIN AS TIEMPOESTIMADO', 'OTPR_DTIN AS TIEMPOTOTAL', 'OTPR_CLAS AS CLASIFICACION', 'OTPR_ACAS AS ACTIVADOR', 'ACTI_PRIO AS PRIORIDAD', 'ACTI_TIAC AS TIPOACTIVADOR' ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([ ['OTPR_NULI', '=', $line], ['OTPR_ESTA', '=', 'A'] ])->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, 'S002V01M10GMPR', 'S002V01F01ACMA', 'S002V01P01OTAC', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de mantenimiento preventivo activas.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $activeWorkOrders); } public function getPreventiveCalendar($fecIni, $fecFin, $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); } if(!$this->functionsController->validDate($fecIni)){ return $this->responseController->makeResponse(true, 'La fecha de inicio es inválida.', [], 400); } if(!$this->functionsController->validDate($fecFin)){ return $this->responseController->makeResponse(true, 'La fecha final es inválida.', [], 400); } $fecIniObj = new Carbon($fecIni . ' 00:00:00'); $fecFinObj = new Carbon($fecFin . ' 23:59:59'); $workOrders = DB::table('S002V01TOTPR')->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([ ['OTPR_NULI', '=', $line], ['OTPR_ESTA', '=', 'A'], ])->get()->all(); $programmedWorkOrders = []; foreach($workOrders as $order){ $orderStart = new Carbon($order->OTPR_FIAP); if($order->ACTI_TIAC == 'Calendario' || $order->ACTI_TIAC == 'Sintoma'){ $repeatConfig = json_decode($order->ACTI_COAC, true); switch($repeatConfig['repeat']){ case 'AN': while ($orderStart->lte($fecFinObj)){ if($orderStart->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStart->addYear(); } break; case 'ME': while ($orderStart->lte($fecFinObj)){ if($orderStart->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStart->addMonth(); } break; case 'SE': while ($orderStart->lte($fecFinObj)){ if($orderStart->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStart->addWeek(); } break; case 'TD': while ($orderStart->lte($fecFinObj)){ if($orderStart->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStart->addDay(); } break; case 'NR': if($orderStart->gte($fecIniObj) && $orderStart->lte($fecFinObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } break; case 'PE': $customRepeat = json_decode($repeatConfig['customRepeat'], true); $repeatEvery = explode('|', $customRepeat['repeatEvery']); switch($repeatEvery[1]){ case '0': //Repeticiones por día $days = intval($repeatEvery[0]); while ($orderStart->lte($fecFinObj)){ if($orderStart->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStart->addDays($days); } break; case '1': //Repeticiones por semana $weeks = intval($repeatEvery[0]); $orderStartAux = new Carbon($orderStart->toDateTimeString()); $repeatOn = $customRepeat['repeatOn']; while ($orderStart->lte($fecFinObj)){ $dayInd = $orderStartAux->dayOfWeek; for($i = $dayInd; $i < 7; $i++){ $dayName = strtolower($orderStartAux->dayName); $dayKey = substr($dayName, 0, 3); $shouldRepeat = $repeatOn[$dayKey]; if($shouldRepeat && $orderStartAux->lte($fecFinObj) && $orderStartAux->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStartAux->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStartAux->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStartAux->addDay(); } $orderStart->addWeeks($weeks); } break; case '2': //Repeticiones por mes $months = intval($repeatEvery[0]); while ($orderStart->lte($fecFinObj)){ if($orderStart->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStart->addMonths($months); } break; case '3': //Repeticiones por año $years = intval($repeatEvery[0]); while ($orderStart->lte($fecFinObj)){ if($orderStart->gte($fecIniObj)){ $reg = DB::table('S002V01TBEOT')->where([ ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $order->OTPR_IDOT], ['BEOT_FEPR', '=', $orderStart->toDateString()] ])->first(); $programmedWorkOrders[] = [ "IDORDEN" => $order->OTPR_IDOT, "EVENTCOLOR" => $repeatConfig['color'], "DATE" => $orderStart->toDateString(), "TYPE" => $order->ACTI_TIAC, "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC, ]; } $orderStart->addYears($years); } break; } break; } } } $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, 'S002V01M10GMPR', 'S002V01F08VCPR', '-', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los eventos programados entre las fechas $fecIni y $fecFin.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $programmedWorkOrders); } public function newUnprogrammedOrder(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'equipment' => 'required|string', 'resources' => 'required|json', 'comments' => 'required|string|min:35', 'staff' => '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); } $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 seleccionado no existe.', [], 404); } $staffArr = json_decode($form['staff'], true); if(empty($staffArr)){ return $this->responseController->makeResponse(true, 'El JSON de personal está vacío.', [], 400); } $staff = []; foreach($staffArr as $val){ if(!array_key_exists('TYPE', $val) && !array_key_exists('ID', $val)){ return $this->responseController->makeResponse(true, "El arreglo del personal no tiene un formato válido.", [], 400); } $typeStr = ''; if($val['TYPE'] == 'EQ'){ $typeStr = 'equipo de trabajo'; }else if($val['TYPE'] == 'SU'){ $typeStr = 'subcontratista'; }else if($val['TYPE'] == 'EM'){ $typeStr = 'empleado'; } $key = $this->encryptionController->decrypt($val['ID']); if(!$key){ return $this->responseController->makeResponse(true, "El ID del $typeStr no fue encriptado correctamente.", [], 400); } $res = null; if($val['TYPE'] == 'EQ'){ $res = DB::table('S002V01TEQMA')->where([ ['EQMA_NULI', '=', $form['linea']], ['EQMA_IDEQ', '=', $key], ])->first(); }else if($val['TYPE'] == 'SU'){ $res = DB::table('S002V01TPESU')->where([ ['PESU_NULI', '=', $form['linea']], ['PESU_IDPS', '=', $key], ])->first(); }else if($val['TYPE'] == 'EM'){ $res = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $form['linea']], ['PERS_IDPE', '=', $key], ])->first(); } if(is_null($res)){ return $this->responseController->makeResponse(true, "El $typeStr no está registrado.", [], 400); } $staff[] = [ 'ID' => $key, 'TYPE' => $val['TYPE'] ]; } $resources = json_decode($form['resources'], true); if(empty($resources)){ return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400); } $commentsArr = [ 'CI' => $form['comments'] ]; $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $commentsStr = json_encode($commentsArr); $staffStr = json_encode($staff); $idVisit = DB::table('S002V01TRVTN')->insertGetId([ 'RVTN_NULI' => $form['linea'], 'RVTN_EQRE' => $equipmentCode, 'RVTN_PEIN' => $staffStr, 'RVTN_MAUT' => $form['resources'], 'RVTN_COME' => $commentsStr, 'RVTN_USRE' => $idUser, 'RVTN_FERE' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F11RVTP', 'S002V01P01REVI', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró la visita no programada #$idVisit.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getUnprogrammedVisits($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); } $visits = DB::table('S002V01TRVTN')->select([ 'RVTN_IDVI AS IDVISITA', 'RVTN_EQRE AS EQUIPAMIENTO', 'EQUI_TIPO AS TIPO_EQUIPAMIENTO', 'EQUI_MODE AS MODELO_EQUIPAMIENTO', 'EQUI_IDEQ AS ID_EQUIPAMIENTO', 'RVTN_ESTA AS ESTATUS', 'RVTN_USRE AS USRREG', 'RVTN_FERE AS FECREG', 'RVTN_UARE AS USAURE', 'RVTN_FARE AS FEAURE', 'RVTN_USCA AS USRCAN', 'RVTN_FECA AS FECCAN', 'RVTN_USFI AS USRFIN', 'RVTN_FEFI AS FECFIN', 'RVTN_USMO AS USRMOD', 'RVTN_FEMO AS FECMOD', ])->where('RVTN_NULI', '=', $line) ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE') ->orderBy('RVTN_IDVI', 'desc')->get()->all(); foreach($visits as $visit){ $visit->IDVISITA = $this->encryptionController->encrypt($visit->IDVISITA); $visit->EQUIPAMIENTO = $this->encryptionController->encrypt($visit->EQUIPAMIENTO); $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO); switch($visit->ESTATUS){ case 'P': $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $visit->USRREG] ])->first(); $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA); $nameReg .= " (" . $visit->USRREG . ")"; $visit->USRREG = $nameReg; break; } } $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, 'S002V01M10GMPR', 'S002V01F11RVTP', 'S002V01P02COVI', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó la lista de visitas no programadas.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $visits); } public function getUnprogrammedVisit($idVisit, $idUser, $line){ DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $idUser], ['USUA_NULI', '=', $line] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idVisit = $this->encryptionController->decrypt($idVisit); if(!$idVisit){ return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400); } $visit = DB::table('S002V01TRVTN')->select([ 'RVTN_IDVI AS IDVISITA', 'RVTN_EQRE AS EQUIPAMIENTO', 'EQUI_TIPO AS TIPO_EQUIPAMIENTO', 'EQUI_MODE AS MODELO_EQUIPAMIENTO', 'EQUI_IDEQ AS ID_EQUIPAMIENTO', 'RVTN_PEIN AS PERSONAL', 'RVTN_MAUT AS MATERIAL', 'RVTN_COME AS COMENTARIOS', 'RVTN_ESTA AS ESTADO', 'RVTN_USRE AS USRREG', 'RVTN_FERE AS FECREG', 'RVTN_UARE AS USAURE', 'RVTN_FARE AS FEAURE', 'RVTN_USCA AS USRCAN', 'RVTN_FECA AS FECCAN', 'RVTN_USFI AS USUFIN', 'RVTN_FEFI AS FECFIN', 'RVTN_USMO AS USRMOD', 'RVTN_FEMO AS FECMOD', ])->where([ ['RVTN_IDVI', '=', $idVisit], ['RVTN_NULI', '=', $line] ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')->first(); if(is_null($visit)){ return $this->responseController->makeResponse(true, 'La visita consultada no existe.', [], 404); } $visit->IDVISITA = $this->encryptionController->encrypt($visit->IDVISITA); $visit->EQUIPAMIENTO = $this->encryptionController->encrypt($visit->EQUIPAMIENTO); $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO); $staffFn = []; $staffArr = json_decode($visit->PERSONAL, true); foreach($staffArr as $item){ $name = ''; if($item['TYPE'] == 'EQ'){ $workTeam = DB::table('S002V01TEQMA')->where([ ['EQMA_NULI', '=', $line], ['EQMA_IDEQ', '=', $item['ID']] ])->first(); $name = $workTeam->EQMA_NOMB; }else if($item['TYPE'] == 'SU'){ $subcontratist = DB::table('S002V01TPESU')->where([ ['PESU_NULI', '=', $line], ['PESU_IDPS', '=', $item['ID']] ])->first(); $name = $subcontratist->PESU_RASO; }else if($item['TYPE'] == 'EM'){ $employee = DB::table('S002V01TPERS') ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([ ['PERS_NULI', '=', $line], ['PERS_IDPE', '=', $item['ID']] ])->first(); $name = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA); } $staffFn[] = [ 'ID' => $this->encryptionController->encrypt($item['ID']), 'TYPE' => $item['TYPE'], 'NAME' => $name, ]; } $visit->PERSONAL = json_encode($staffFn); $usrReg = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $visit->USRREG], ])->first(); $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA) . " (" . $visit->USRREG . ")"; $visit->USRREG = $nameReg; if(!is_null($visit->USAURE)){ $usaure = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $visit->USAURE], ])->first(); $nameUre = $this->functionsController->joinName($usaure->USUA_NOMB, $usaure->USUA_APPA, $usaure->USUA_APMA) . " (" . $visit->USAURE . ")"; $visit->USAURE = $nameUre; } if(!is_null($visit->USRCAN)){ $usrCan = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $visit->USRCAN], ])->first(); $nameCan = $this->functionsController->joinName($usrCan->USUA_NOMB, $usrCan->USUA_APPA, $usrCan->USUA_APMA) . " (" . $visit->USRCAN . ")"; $visit->USRCAN = $nameCan; } if(!is_null($visit->USUFIN)){ $usrFin = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $visit->USUFIN], ])->first(); $nameFin = $this->functionsController->joinName($usrFin->USUA_NOMB, $usrFin->USUA_APPA, $usrFin->USUA_APMA) . " (" . $visit->USUFIN . ")"; $visit->USUFIN = $nameFin; } if(!is_null($visit->USRMOD)){ $usrMod = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $visit->USRMOD], ])->first(); $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA) . " (" . $visit->USRMOD . ")"; $visit->USRMOD = $nameMod; } $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, 'S002V01M10GMPR', 'S002V01F11RVTP', 'S002V01P02COVI', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó la visita no programada #$idVisit.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $visit); } public function updateVisitStatus(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_visit' => 'required|string', 'comments' => 'required|string|min:35', 'status' => 'required|string|in:C,R,A,F' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idVisit = $this->encryptionController->decrypt($form['id_visit']); if(!$idVisit){ return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400); } $visit = DB::table('S002V01TRVTN')->where([ ['RVTN_NULI', '=', $form['linea']], ['RVTN_IDVI', '=', $idVisit], ])->first(); $commentsArr = json_decode($visit->RVTN_COME, true); $commentsArr["C$form[status]"] = $form['comments']; $commentsStr = json_encode($commentsArr); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $updateArr = [ 'RVTN_ESTA' => $form['status'], 'RVTN_COME' => $commentsStr, 'RVTN_USMO' => $idUser, 'RVTN_FEMO' => $nowStr, ]; if($form['status'] == 'A' || $form['status'] == 'R'){ $updateArr['RVTN_UARE'] = $idUser; $updateArr['RVTN_FARE'] = $nowStr; } if($form['status'] == 'F'){ $updateArr['RVTN_USFI'] = $idUser; $updateArr['RVTN_FEFI'] = $nowStr; } if($form['status'] == 'C'){ $updateArr['RVTN_USCA'] = $idUser; $updateArr['RVTN_FECA'] = $nowStr; } DB::table('S002V01TRVTN')->where([ ['RVTN_NULI', '=', $form['linea']], ['RVTN_IDVI', '=', $idVisit], ])->update($updateArr); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F11RVTP', 'S002V01P01REVI', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la visita no programada #$idVisit.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function updateOrderStatus(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'status' => 'required|string|in:B,R,A,E' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder], ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); } if($form['status'] == 'A' && $order->OTPR_SEAN == null){ return $this->responseController->makeResponse(true, 'La orden no puede ser aprobada sin la asignación del análisis presupuestario.', [], 401); } $statusStr = ''; switch($form['status']){ case 'B': $statusStr = 'Borrador'; break; case 'R': $statusStr = 'Revisión'; break; case 'A': $statusStr = 'Aprobado'; break; case 'E': $statusStr = 'Eliminado'; break; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder], ])->update([ 'OTPR_ESTA' => $form['status'], 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P01HOTP', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden #$idOrder a $statusStr.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function setBudgetAnalysis(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'analysis' => 'required|json' ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden no está encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404); } $analysisArr = json_decode($form['analysis'], true); if(empty($analysisArr)){ return $this->responseController->makeResponse(true, 'El JSON de análisis no contiene información.', [], 400); }else if(!array_key_exists('teamsConf', $analysisArr)){ return $this->responseController->makeResponse(true, 'La información de la configuración de los equipos no se envió en el JSON.', [], 400); }else if(!is_array($analysisArr['teamsConf'])){ return $this->responseController->makeResponse(true, 'La configuración de los equipos tiene un formato inválido.', [], 400); } $teamsConf = $analysisArr['teamsConf']; foreach($teamsConf as $key=>$conf){ $idDec = $this->encryptionController->decrypt($conf['ID']); if(!$idDec){ return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400); } $conf['ID'] = $idDec; $teamsConf[$key] = $conf; } $analysisArr['teamsConf'] = $teamsConf; $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $sean = json_encode($analysisArr); DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder], ])->update([ 'OTPR_SEAN' => $sean, 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P01HOTP', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") asignó el análisis presupuestario de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function getMaintenanceSimulation($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('S002V01TOTPR')->select([ 'OTPR_IDOT AS IDORDER', 'OTPR_DEIN AS DESCRIPCION', 'OTPR_ININ AS INSTRUCCIONES', 'OTPR_EQIN AS EQUIPAMIENTO', 'OTPR_FIAP AS FECHAINICIO', 'OTPR_FTAP AS FECHAFINAL', 'OTPR_SEAN AS ANALISIS', 'OTPR_TIIN AS TIEINMEST', 'OTPR_OPPR AS OPERARIOS', 'OTPR_DTIN AS TIETOTEST', 'OTPR_RHRE AS RECURSOS', 'OTPR_ACAS AS ACTIVADOR', 'OTPR_ESTA AS ESTADO', 'ACTI_PRIO AS PRIORIDAD', 'ACTI_TIAC AS TIPOACTIVADOR', 'ACTI_COAC AS CONFIGACTI' ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404); }else if($order->ESTADO == 'B'){ return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en borradores.', [], 401); }else if($order->ESTADO == 'R'){ return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en revisión.', [], 401); }else if($order->ESTADO == 'E'){ return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque ha sido eliminado.', [], 401); } $analisisArr = json_decode($order->ANALISIS, true); $teamsConf = $analisisArr['teamsConf']; foreach($teamsConf as $key=>$val){ $val['ID'] = $this->encryptionController->encrypt($val['ID']); $teamsConf[$key] = $val; } $analisisArr['teamsConf'] = $teamsConf; $order->ANALISIS = json_encode($analisisArr); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $idac = $this->functionsController->registerActivity( $line, 'S002V01M10GMPR', 'S002V01F06SPMA', 'S002V01P02VSPM', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó la simulación de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $order); } public function getOrderWithActivator($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('S002V01TOTPR')->select([ 'OTPR_IDOT AS IDORDEN', 'OTPR_DEIN AS DESCRIPCION', 'OTPR_ININ AS INSTRUCCIONES', 'OTPR_EQIN AS EQUIPAMIENTO', 'OTPR_FIAP AS FECHAINICIO', 'OTPR_FTAP AS FECHAFINAL', 'OTPR_TIIN AS TIEINMEST', 'OTPR_DTIN AS TIETOTEST', 'OTPR_ACAS AS ACTIVADOR', 'OTPR_CLAS AS CLASIFICACION', 'OTPR_ESTA AS ESTADO', 'ACTI_PRIO AS PRIORIDAD', 'ACTI_TIAC AS TIPOACTIVADOR', 'ACTI_COAC AS CONFIGACTIVADOR', ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder], ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404); } $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, 'S002V01M10GMPR', 'S002V01F02AFDT', 'S002V01P01OTAT', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó la información de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $order); } public function updateOrderWithActivator(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'id_activator' => 'required|string', 'start_date' => 'required|date', 'end_date' => 'required|date', 'activator_type' => 'required|string|in:Calendario,Sintoma,Medida,Valor', 'priority' => 'required|string|in:1,2,3,4', 'config_activator' => 'required|json', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $idUser], ['USUA_NULI', '=', $form['linea']], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder], ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404); } $idActivator = $this->encryptionController->decrypt($form['id_activator']); if(!$idActivator){ return $this->responseController->makeResponse(true, 'El ID del activador solicitado no está encriptado correctamente.', [], 400); } $activator = DB::table('S002V01TACTI')->where([ ['ACTI_IDAC', '=', $idActivator], ['ACTI_NULI', '=', $form['linea']] ])->first(); if(is_null($activator)){ return $this->responseController->makeResponse(true, 'El activador solicitado no existe.', [], 404); } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder], ])->update([ 'OTPR_ACAS' => $idActivator, 'OTPR_FIAP' => $form['start_date'], 'OTPR_FTAP' => $form['end_date'], 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr, ]); DB::table('S002V01TACTI')->where([ ['ACTI_IDAC', '=', $idActivator], ['ACTI_NULI', '=', $form['linea']] ])->update([ 'ACTI_PRIO' => $form['priority'], 'ACTI_TIAC' => $form['activator_type'], 'ACTI_COAC' => $form['config_activator'], 'ACTI_USMO' => $idUser, 'ACTI_FEMO' => $nowStr, ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F02AFDT', 'S002V01P02ACAC', 'Actualización', "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden #$idOrder y el activador #$idActivator.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function printOrderSimulation($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('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404); } $simulation = DB::table('S002V01TRESI')->where([ ['RESI_NULI', '=', $line], ['RESI_IDOT', '=', $idOrder] ])->first(); if(is_null($simulation)){ return $this->responseController->makeResponse(true, "La orden #$idOrder aún no ha sido simulada.", [], 401); } $content = json_decode($simulation->RESI_CUSI, true); $html = " "; foreach($content as $item){ $imgContent = file_get_contents("C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\files\\$item[icon].png"); $imgB64 = "data:image/png;base64, " . base64_encode($imgContent); $html .= " "; if(!$item['isMain']){ $html .= ''; } $html .= " "; } $html .= "
$item[label]
"; $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\'; $noar = "simulacion_orden_$idOrder"; $exte = "pdf"; $line = intval($line); $line = $line < 10 ? "0$line" : "$line"; $como = "GMPR"; $cldo = "OR"; $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"; } $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 = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\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, ]); $filesArr = json_decode($order->OTPR_DONE, true); $filesArr[] = $fileName; $filesStr = json_encode($filesArr); DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->update([ 'OTPR_DONE' => $filesStr, 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M10GMPR', 'S002V01F06SPMA', 'S002V01P02VSPM', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]); } public function saveOrderSimulation(Request $request){ DB::enableQueryLog(); $validator = Validator::make($request->all(), [ 'id_user' => 'required|string', 'linea' => 'required|integer', 'id_order' => 'required|string', 'content' => 'required|json', ]); if($validator->fails()){ return $this->responseController->makeResponse( true, "Se encontraron uno o más errores.", $this->responseController->makeErrors( $validator->errors()->messages() ), 401 ); } $form = $request->all(); $idUser = $this->encryptionController->decrypt($form['id_user']); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $form['linea']], ['USUA_IDUS', '=', $idUser], ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idOrder = $this->encryptionController->decrypt($form['id_order']); if(!$idOrder){ return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400); } $order = DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $form['linea']], ['OTPR_IDOT', '=', $idOrder], ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404); } $simulation = DB::table('S002V01TRESI')->where([ ['RESI_NULI', '=', $form['linea']], ['RESI_IDOT', '=', $idOrder], ])->first(); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); if(is_null($simulation)){ DB::table('S002V01TRESI')->insert([ 'RESI_NULI' => $form['linea'], 'RESI_IDOT' => $idOrder, 'RESI_CUSI' => $form['content'], 'RESI_FUSI' => $nowStr, 'RESI_UUSI' => $idUser, ]); }else{ $timestamp = $now->timestamp; $history = $simulation->RESI_HISI == null ? [] : json_decode($simulation->RESI_HISI, true); $history[$timestamp] = [ 'USUARIO' => $simulation->RESI_UUSI, 'FECHA' => $simulation->RESI_FUSI, 'CONTENIDO' => $simulation->RESI_CUSI, ]; $historyStr = json_encode($history); DB::table('S002V01TRESI')->where([ ['RESI_NULI', '=', $form['linea']], ['RESI_IDOT', '=', $idOrder], ])->update([ 'RESI_CUSI' => $form['content'], 'RESI_FUSI' => $nowStr, 'RESI_UUSI' => $idUser, 'RESI_HISI' => $historyStr, ]); } $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $form['linea'], 'S002V01M10GMPR', 'S002V01F06SPMA', 'S002V01P02VSPM', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") registró una simulación para la orden #$idOrder.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']); return $this->responseController->makeResponse(false, 'EXITO.'); } public function printOrderDetails($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('S002V01TOTPR')->join( 'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC', )->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404); } $html = " "; }else{ $html .= " $analisis "; } $html .= "
Descripción
" . $order->OTPR_DEIN . "
Instrucciones
"; $instructions = json_decode($order->OTPR_ININ, true); $cont = 1; foreach($instructions as $instruction){ $html .= $cont . ".- " . $instruction['INSTRUCCION'] . "
"; $cont++; } $startDate = $this->functionsController->formatDateTime($order->OTPR_FIAP); $endDate = $this->functionsController->formatDateTime($order->OTPR_FTAP); $html .= "
Equipamiento relacionado
" . $order->OTPR_EQIN . "
Fecha y hora de inicio Fecha y hora final
$startDate $endDate
Análisis presupuestario
"; $analisis = $order->OTPR_SEAN == null ? 'Sin configuración' : json_decode($order->OTPR_SEAN, true); if(gettype($analisis) == 'array'){ //PENDIENTE $teamsConf = $analisis['teamsConf']; foreach($teamsConf as $key=>$team){ /*var_dump($key); echo "
";*/ } $html .= " PENDIENTE
Clasificación Duración total estimada Tiempo de inmovilización estimado
" . $order->OTPR_CLAS . " " . $order->OTPR_DTIN . " hora(s) " . $order->OTPR_TIIN . " hora(s)
Personal involucrado
PENDIENTE
Recursos requerido
PENDIENTE
Documentos requeridos
PENDIENTE
Contratos requeridos
PENDIENTE
Información del activador
PENDIENTE
Usuario que registró Fecha de registro
PENDIENTE PENDIENTE
Usuario de la última modificación Fecha de la última modificación
PENDIENTE PENDIENTE
"; $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\'; $noar = "detalles_orden_$idOrder"; $exte = "pdf"; $line = intval($line); $line = $line < 10 ? "0$line" : "$line"; $como = "GMPR"; $cldo = "OR"; $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"; } $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 = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\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, ]); $filesArr = json_decode($order->OTPR_DONE, true); $filesArr[] = $fileName; $filesStr = json_encode($filesArr); DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->update([ 'OTPR_DONE' => $filesStr, 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M10GMPR', 'S002V01F06SPMA', 'S002V01P02VSPM', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]); } public function extractMaintenancePlan($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('S002V01TOTPR')->join( 'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC', )->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404); } $html = file_get_contents($this->templatesUbic . "01-GMPR-PL-010101-000003=01=PDF_PLAN_MANTENIMIENTO.html"); $logo = file_get_contents("C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\public\global_resources\sam-short-logo.png"); $logoStr = "data:image/svg+xml;base64," . base64_encode($logo); $html = str_replace("%stcImage%", $logoStr, $html); $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $currentDate = $this->functionsController->buildHumanCurrentDate($nowStr); $html = str_replace("%currentDate%", $currentDate, $html); $html = str_replace("%idOrder%", $order->OTPR_IDOT, $html); $startDateTimeArr = explode(" ", $order->OTPR_FIAP); $startTimeArr = explode(":", $startDateTimeArr[1]); $startHour = intval($startTimeArr[0]); $startPeriod = $startHour < 12 ? 'AM' : 'PM'; $startHour = $startHour > 12 ? $startHour - 12 : $startHour; $startTimeStr = "$startHour:$startTimeArr[1] $startPeriod"; $html = str_replace("%startTime%", $startTimeStr, $html); $startDateTimeObj = new Carbon($order->OTPR_FIAP); $totalDuration = floatval($order->OTPR_DTIN); $totalDurationHours = intval($totalDuration); $startDateTimeObj->addHours($totalDuration); $totalDurationFloatMinutes = $this->functionsController->floatSub($totalDuration, $totalDurationHours); $totalDurationFloatMinutes = $this->functionsController->floatMul($totalDurationFloatMinutes, 60); $totalDurationMinutes = ceil($totalDurationFloatMinutes); $startDateTimeObj->addMinutes($totalDurationMinutes); $endDateTimeArr = explode(" ", $startDateTimeObj->toDateTimeString()); $endTimeArr = explode(":", $endDateTimeArr[1]); $endHour = intval($endTimeArr[0]); $endPeriod = $startHour < 12 ? 'AM' : 'PM'; $endHour = $endHour > 12 ? $endHour - 12 : $endHour; $endTimeStr = "$endHour:$endTimeArr[1] $endPeriod"; $html = str_replace("%endTime%", $endTimeStr, $html); $html = str_replace("%inmTime%", $order->OTPR_TIIN . " h", $html); $html = str_replace("%totalTime%", $order->OTPR_DTIN . " h", $html); $html = str_replace("%equipment%", $order->OTPR_EQIN, $html); $html = str_replace("%description%", $order->OTPR_DEIN, $html); $instructions = json_decode($order->OTPR_ININ, true); $activitiesTableBody = ""; foreach($instructions as $k=>$v){ $key = $k + 1; $activitiesTableBody .= ""; $activitiesTableBody .= "$key"; $activitiesTableBody .= "$v[INSTRUCCION]"; $activitiesTableBody .= ""; /*foreach($v['ESPECIALIDADES'] as $v0){ /*$team = array_filter($teams, function($v1) use ($v0) { return ($v1['ID'] == $v0); }); $activitiesTableBody .= /*end($team)['ESP'] '--' . "
"; }*/ $activitiesTableBody .= ""; $activitiesTableBody .= ""; } $html = str_replace("%activitiesTableBody%", $activitiesTableBody, $html); $personalArr = json_decode($order->OTPR_OPPR, true); $constConf = json_decode($order->OTPR_SEAN, true); $cont = 1; $specialtiesTableBody = ""; foreach($personalArr as $k=>$v){ /*$team = array_filter($teams, function($v1) use ($k) { return ($v1['ID'] == $k); });*/ $specialtiesTableBody .= ""; $specialtiesTableBody .= "$cont"; $specialtiesTableBody .= "" . /*end($team)['ESP']*/ '--' . ""; $specialtiesTableBody .= ""; foreach($constConf['teamsConf'][$k] as $v0){ $usrID = '-';//$v0['USER']; $usrInv = DB::table('S002V01TUSUA')->where([ ['USUA_NULI', '=', $line], ['USUA_IDUS', '=', $usrID], ])->first(); $invName = /*$this->functionsController->joinName($usrInv->USUA_NOMB, $usrInv->USUA_APPA, $usrInv->USUA_APMA) . " ($usrID)"*/ '-'; $specialtiesTableBody .= $invName . "
"; } $specialtiesTableBody .= ""; $specialtiesTableBody .= ""; $cont++; } $html = str_replace("%specialtiesTableBody%", $specialtiesTableBody, $html); $como = 'GMPR'; $cldo = 'OR'; $noar = "plan_de_mantenimiento_preventivo_orden_$idOrder"; $exte = "pdf"; $line = $line < 10 ? "0$line" : "$line"; $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 = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\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 = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\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, ]); $filesArr = json_decode($order->OTPR_DONE, true); $filesArr[] = $fileName; $filesStr = json_encode($filesArr); DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->update([ 'OTPR_DONE' => $filesStr, 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M10GMPR', 'S002V01F07EPMA', 'S002V01P02DPMA', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]); } public function getMaintenancePlanAnalysis($idFile, $idUser, $line) { DB::enableQueryLog(); $idUser = $this->encryptionController->decrypt($idUser); if(!$idUser){ return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400); } $usr = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $idUser], ['USUA_NULI', '=', $line] ])->first(); if(is_null($usr)){ return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404); } $idFile = $this->encryptionController->decrypt($idFile); if(!$idFile){ return $this->responseController->makeResponse(true, 'El ID del archivo solicitado no está encriptado correctamente.', [], 400); } $tempFile = DB::table('S002V01TARTE')->where([ ['ARTE_NULI', '=', $line], ['ARTE_IDAR', '=', $idFile] ])->first(); if(is_null($tempFile)){ return $this->responseController->makeResponse(true, 'El archivo solicitado no está registrado.', [], 404); } $fileColumnsEsp = ['Id', 'Activo', 'Modo de tarea', 'Nombre', 'Duración', 'Comienzo', 'Fin', 'Trabajo_Programado', 'Costo', 'Duración de línea base estimada', 'Comienzo previsto', 'Fin de línea base', 'Trabajo previsto', 'Costo de línea base', 'Variación de duración', 'Variación de trabajo', 'Variación de costo']; $fileColumnsIng = ['ID', 'Active', 'Task Mode', 'Name', 'Duration', 'Start', 'Finish', 'Predecessors', 'Outline Level', 'Notes']; $MONTHS_ESP = ['enero' => '01', 'febrero' => '02', 'marzo' => '03', 'abril' => '04', 'mayo' => '05', 'junio' => '06', 'julio' => '07', 'agosto' => '08', 'septiembre' => '09', 'octubre' => '10', 'noviembre' => '11', 'diciembre' => '12']; $MONTHS_ING = ['1' => '01', '2' => '02', '3' => '03', '4' => '04', '5' => '05', '6' => '06', '7' => '07', '8' => '08', '9' => '09', '10' => '10', '11' => '11', '12' => '12']; $spreadsheet = IOFactory::load($tempFile->ARTE_UBTE); $workSheet = $spreadsheet->getActiveSheet(); $maxColStr = $workSheet->getHighestColumn(); $maxCol = Coordinate::columnIndexFromString($maxColStr); for($i = 1; $i <= $maxCol; $i++){ $colStr = Coordinate::stringFromColumnIndex($i); $cell = $workSheet->getCell($colStr . "1"); $val = $cell->getValue(); if(!in_array($val, $fileColumnsEsp) && !in_array($val, $fileColumnsIng)){ return $this->responseController->makeResponse(true, 'El archivo tiene un formato inválido.', [], 400); } } $instructions = []; $maxRow = $workSheet->getHighestRow(); for($row = 2; $row <= $maxRow; $row++){ $activo = $workSheet->getCell("B$row")->getValue(); $language = $activo == 'Yes' ? 'I' : 'E'; if($activo == 'Sí' || $activo == 'Si' || $activo == 'Yes'){ $durationStr = $workSheet->getCell("E$row")->getValue(); $durationArr = explode(" ", $durationStr); $duration = 0; if($durationArr[1] == 'días' || $durationArr[1] == 'dias' || $durationArr[1] == 'día' || $durationArr[1] == 'dia' || $durationArr[1] == 'days' || $durationArr[1] == 'day'){ $daysFloat = floatval($durationArr[0]); $daysInt = intval($daysFloat); $duration += $daysInt * 24; $hoursDec = $this->functionsController->floatSub($daysFloat, $daysInt); $hoursFloat = $this->functionsController->floatMul($hoursDec, 24); $duration = $this->functionsController->floatAdd($duration, $hoursFloat); } if($durationArr[1] == 'mins' || $durationArr[1] == 'min'){ $minsFloat = floatval($durationArr[0]); $hoursFloat = $this->functionsController->floatDiv($minsFloat, 60); $duration = $this->functionsController->floatAdd($duration, $hoursFloat); } $duration = round($duration, 5); $startDateStr = $workSheet->getCell("F$row")->getValue(); $startDateArr = explode(" ", $startDateStr); if($language == 'I'){ $americanDateArr = explode('/', $startDateArr[1]); $startMonth = $MONTHS_ING[$americanDateArr[0]]; }else{ $startMonth = $MONTHS_ESP[$startDateArr[1]]; $startPeriod = $startDateArr[4] . $startDateArr[5]; $startPeriod = str_replace('.', '', $startPeriod); $startHourArr = explode(":", $startDateArr[3]); $startHour = intval($startHourArr[0]); $startHour = $startPeriod == 'pm' && $startHour < 12 ? $startHour + 12 : $startHour; $startHourStr = $startHour < 10 ? "0$startHour" : "$startHour"; $startDateTime = "$startDateArr[2]-$startMonth-$startDateArr[0] $startHourStr:$startHourArr[1]:00"; $startDateTimeObj = new Carbon($startDateTime); $startTimestamp = $startDateTimeObj->timestamp; $endDateStr = $workSheet->getCell("G$row")->getValue(); $endDateArr = explode(" ", $endDateStr); $endMonth = $MONTHS_ESP[$endDateArr[1]]; $endPeriod = $endDateArr[4] . $endDateArr[5]; $endPeriod = str_replace('.', '', $endPeriod); $endHourArr = explode(":", $endDateArr[3]); $endHour = intval($endHourArr[0]); $endHour = $endPeriod == 'pm' && $endHour < 12 ? $endHour + 12 : $endHour; $endHourStr = $endHour < 10 ? "0$endHour" : "$endHour"; $endDateTime = "$endDateArr[2]-$endMonth-$endDateArr[0] $endHourStr:$endHourArr[1]:00"; $endDateTimeObj = new Carbon($endDateTime); $endTimestamp = $endDateTimeObj->timestamp; } $difference = $endTimestamp - $startTimestamp; $minutes = $this->functionsController->floatDiv($difference, 60); $hours = $this->functionsController->floatDiv($minutes, 60); $duration = round($hours, 5); $instructions[] = [ "INSTRUCTION" => $workSheet->getCell("D$row")->getValue(), "DURATION" => $duration, "START" => $startDateTime, "END" => $endDateTime, "COST" => $workSheet->getCell("I$row")->getValue(), ]; } } $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, 'S002V01M10GMPR', 'S002V01F10DIBI', '-', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó el plan de mantenimiento para una nueva orden desde MS Project.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $instructions); } public function getFileToMSProject($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('S002V01TOTPR')->where([ ['OTPR_IDOT', '=', $idOrder], ['OTPR_NULI', '=', $line] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404); } $cols = ['Id', 'Activo', 'Modo de tarea', 'Nombre', 'Duración', 'Comienzo', 'Fin', 'Trabajo_Programado', 'Costo', 'Duración de línea base estimada', 'Comienzo previsto', 'Fin de línea base', 'Trabajo previsto', 'Costo de línea base', 'Variación de duración', 'Variación de trabajo', 'Variación de costo']; $analysis = json_decode($order->OTPR_SEAN, true); $instructionsConf = /*$analysis['instructionsConf']*/ '{}'; $instructions = json_decode($order->OTPR_ININ, true); $arrCols = []; $cont = 1; foreach($instructions as $instruction){ $projectDuration = ""; if($instruction['DURACION'] < 24){ $duration = $instruction['DURACION'] * 60; $projectDuration = "$duration min"; if($duration > 1){ $projectDuration .= "s"; } }else{ $duration = $this->functionsController->floatDiv($instruction['DURACION'], 24); $duration = round($duration, 2); $projectDuration = "$duration día"; if($duration > 1){ $projectDuration .= "s"; } } $instructionStartDateTimeArr = explode(' ', $instruction['INICIO']); $instructionStartTimeArr = explode(':', $instructionStartDateTimeArr[1]); $instructionStartHour = intval($instructionStartTimeArr[0]); if($instructionStartDateTimeArr[2] == 'PM' && $instructionStartHour < 12){ $instructionStartHour = $instructionStartHour + 12; } $instructionStartHourStr = $instructionStartHour < 10 ? "0$instructionStartHour" : "$instructionStartHour"; $instructionStartTimeStr = "$instructionStartHourStr:$instructionStartTimeArr[1]:00"; $instructionStartDateTimeStr = "$instructionStartDateTimeArr[0] $instructionStartTimeStr"; $instructionEndDateTimeArr = explode(' ', $instruction['FIN']); $instructionEndTimeArr = explode(':', $instructionEndDateTimeArr[1]); $instructionEndHour = intval($instructionEndTimeArr[0]); if($instructionEndDateTimeArr[2] == 'PM' && $instructionEndHour < 12){ $instructionEndHour = $instructionEndHour + 12; } $instructionEndHourStr = $instructionEndHour < 10 ? "0$instructionEndHour" : "$instructionEndHour"; $instructionEndTimeStr = "$instructionEndHourStr:$instructionEndTimeArr[1]:00"; $instructionEndDateTimeStr = "$instructionEndDateTimeArr[0] $instructionEndTimeStr"; $projectStartDate = $this->functionsController->buildProjectDate($instructionStartDateTimeStr); $projectEndDate = $this->functionsController->buildProjectDate($instructionEndDateTimeStr); $cost = /*$instruction['ISFROMFILE'] ? $instruction['COSTO'] : $instructionsConf[$instruction['ID']]*/ '0'; $arrCol = [ "A" => $cont, "B" => 'Sí', "C" => 'Programada manualmente', "D" => $instruction['INSTRUCCION'], "E" => $projectDuration, "F" => $projectStartDate, "G" => $projectEndDate, "H" => "0h", "I" => $cost, "J" => "0d", "K" => "NOD", "L" => "NOD", "M" => "0h", "N" => "0", "O" => $projectDuration, "P" => "0h", "Q" => "0", ]; $arrCols[] = $arrCol; $cont++; } $now = $this->functionsController->now(); $nowStr = $now->toDateTimeString(); $dateTimeArr = explode(" ", $nowStr); $dateArr = explode("-", $dateTimeArr[0]); $year = substr($dateArr[0], 2); $como = 'GMPR'; $cldo = 'OR'; $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 = ""; 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; } $noar = "plan_de_mantenimiento_preventivo_ms_project_orden_$idOrder"; $exte = "xlsx"; $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 = ""; if(is_null($ver)){ $nuve = "01"; }else{ $vers = intval($ver->AFAL_NUVE) + 1; $nuve = $vers < 10 ? "0$vers" : "$vers"; } $line = $line < 10 ? "0$line" : "$line"; $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\'; $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte"; $tempFile = $filePath . $fileName; if(file_exists($tempFile)){ unlink($tempFile); } $spreadsheet = new Spreadsheet(); $workSheet = $spreadsheet->getActiveSheet(); $colInd = 1; foreach($cols as $colName){ $colStr = Coordinate::stringFromColumnIndex($colInd); $workSheet->setCellValue($colStr . "1", $colName); $workSheet->getColumnDimension($colStr)->setAutoSize(true); $colInd++; } $row = 2; foreach($arrCols as $col){ foreach($col as $k=>$v){ $workSheet->setCellValue($k . $row, $v); } $row++; } $writer = new Xlsx($spreadsheet); $writer->save($tempFile); $ubic = Storage::putFile('files', new File($tempFile)); $ubic = str_replace("/", "\\", $ubic); $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\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, ]); $filesArr = json_decode($order->OTPR_DONE, true); $filesArr[] = $fileName; $filesStr = json_encode($filesArr); DB::table('S002V01TOTPR')->where([ ['OTPR_NULI', '=', $line], ['OTPR_IDOT', '=', $idOrder] ])->update([ 'OTPR_DONE' => $filesStr, 'OTPR_USMO' => $idUser, 'OTPR_FEMO' => $nowStr ]); $actions = DB::getQueryLog(); $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA); $idac = $this->functionsController->registerActivity( $line, 'S002V01M10GMPR', 'S002V01F10DIBI', '-', 'Registro', "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento para MS Project de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S02AOTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]); } public function getOrderStaff($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('S002V01TOTPR')->where([ ['OTPR_IDOT', '=', $idOrder], ['OTPR_NULI', '=', $line] ])->first(); if(is_null($order)){ return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404); } $staffArr = json_decode($order->OTPR_OPPR, true); $staffTmp = []; foreach($staffArr as $val){ if($val['TYPE'] == 'EQ'){ $employees = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $line], ['PERS_EQTR', '=', $val['ID']], ])->get()->all(); foreach($employees as $employee){ if(!in_array($employee->PERS_IDPE, $staffTmp)){ $staffTmp[] = $employee->PERS_IDPE; } } }else if($val['TYPE'] == 'SU'){ $employees = DB::table('S002V01TPERS')->where([ ['PERS_NULI', '=', $line], ['PERS_IDPS', '=', $val['ID']], ])->get()->all(); foreach($employees as $employee){ if(!in_array($employee->PERS_IDPE, $staffTmp)){ $staffTmp[] = $employee->PERS_IDPE; } } }else{ $id = intval($val['ID']); if(!in_array($id, $staffTmp)){ $staffTmp[] = $id; } } } $staffFn = []; foreach($staffTmp as $empID){ $employee = DB::table('S002V01TPERS')->select([ 'PERS_IDPE AS IDEMPLEADO', 'PERS_IDUS AS IDUSUARIO', DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NOMBREUSUARIO'), 'PERS_TICO AS TIPOCONTRATO', 'PERS_IDPS AS IDSUBCONTRATISTA', 'PESU_RASO AS RAZONSOCIAL', 'PESU_REFI AS REGIMENFISCAL', 'PERS_EQTR AS IDEQUIPO', 'EQMA_NOMB AS NOMBREEQUIPO' ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS') ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS') ->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')->where([ ['PERS_NULI', '=', $line], ['PERS_IDPE', '=', $empID], ])->first(); if(!is_null($employee)){ $staffFn[] = $employee; } } $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, 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P03COTP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los empleados de la orden #$idOrder.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $staffFn); } public function getOrderExecutionDetails($idExecution, $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); } $idExecution = $this->encryptionController->decrypt($idExecution); if(!$idExecution){ return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada no está encriptado correctamente.', [], 400); } $idExecArr = explode('|', $idExecution); if(count($idExecArr) < 4){ return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada tiene un formato inválido.', [], 400); } $execution = DB::table('S002V01TBEOT')->select([ 'BEOT_IDRE AS IDREGISTRO', 'BEOT_IDOT AS IDORDEN', 'BEOT_FEPR AS FECHAPROGRAMACION', 'BEOT_TIAC AS TIPOACCION', 'BEOT_TIOR AS TIPOORDEN', 'BEOT_DTEJ AS TIEMPOEJECUCION', 'BEOT_OBSE AS OBSERVACIONES', 'BEOT_FEEJ AS FECHAEJECUCION', 'BEOT_USEJ AS USUARIOEJECUCION', 'BEOT_FEFI AS FECHAFINALIZACION', 'BEOT_USFI AS USUARIOFINALIZO' ])->where([ ['BEOT_IDRE', '=', $idExecArr[0]], ['BEOT_NULI', '=', $line], ['BEOT_IDOT', '=', $idExecArr[2]], ['BEOT_FEPR', '=', $idExecArr[3]], ])->first(); if(is_null($execution)){ return $this->responseController->makeResponse(true, 'El registro de la ejecución solicitada no existe.', [], 404); } $execution->IDREGISTRO = $this->encryptionController->encrypt($execution->IDREGISTRO); $execution->IDORDEN = $this->encryptionController->encrypt($execution->IDORDEN); $execUsr = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $execution->USUARIOEJECUCION], ['USUA_NULI', '=', $line] ])->first(); $execName = $this->functionsController->joinName($execUsr->USUA_NOMB, $execUsr->USUA_APPA, $execUsr->USUA_APMA); $execution->USUARIOEJECUCION = $execName . " (" . $execution->USUARIOEJECUCION . ")"; if(!is_null($execution->USUARIOFINALIZO)){ $finUsr = DB::table('S002V01TUSUA')->where([ ['USUA_IDUS', '=', $execution->USUARIOFINALIZO], ['USUA_NULI', '=', $line] ])->first(); $finName = $this->functionsController->joinName($finUsr->USUA_NOMB, $finUsr->USUA_APPA, $finUsr->USUA_APMA); $execution->USUARIOFINALIZO = $finName . " (" . $execution->USUARIOFINALIZO . ")"; } $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, 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P03COTP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles de la ejecución del a orden de trabajo preventivo #$idExecArr[2] para la fecha $idExecArr[3].", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $execution); } public function getWorkOrdersByEquipment($equipmentCode, $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); } $equipmentCode = $this->encryptionController->decrypt($equipmentCode); if(!$equipmentCode){ return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no está encriptado correctamente.', [], 400); } $equipment = DB::table('S002V01TEQUI')->where([ ['EQUI_NULI', '=', $line], ['EQUI_COEQ', '=', $equipmentCode] ])->first(); if(is_null($equipment)){ return $this->responseController->makeResponse(true, 'El equipamiento relacionado no está registrado.', [], 404); } $workOrders = DB::table('S002V01TOTPR')->select([ 'OTPR_IDOT AS IDORDEN', 'OTPR_EQIN AS EQUIPO', 'OTPR_FIAP AS FECHAINICIO', 'OTPR_FTAP AS FECHAFINAL', 'OTPR_ACAS AS ACTIVADOR', 'ACTI_TIAC AS TIPOACTIVADOR', 'ACTI_PRIO AS PRIORIDAD', 'OTPR_ESTA AS ESTATUS' ])->where([ ['OTPR_NULI', '=', $line], ['OTPR_EQIN', '=', $equipmentCode], ['OTPR_ESTA', '!=', 'E'], ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS') ->orderBy('OTPR_IDOT', 'desc')->get()->all(); foreach($workOrders as $key=>$order){ $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN); $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO); $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR); if(!is_null($order->PRIORIDAD)){ $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD); } if($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null; if($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null; $workOrders[$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, 'S002V01M10GMPR', 'S002V01F01COTP', 'S002V01P01HOTP', 'Consulta', "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo relacionadas al equipamient $equipmentCode.", $idUser, $nowStr, 'S002V01S01ORTR' ); $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line); return $this->responseController->makeResponse(false, 'EXITO.', $workOrders); } }