| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- class ResourcesController extends Controller
- {
- private $responseController;
- public $arrAlphabet;
- public $encController;
- public function __construct() {
- $this->responseController = new ResponseController();
- $this->encController = new EncryptionController();
- $this->arrAlphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
- }
- public function formatSecuence($cont, $length){
- $longigud = strlen($cont);
- $aumentar = $length - $longigud;
- $contador = '';
- for ($i = 0; $i < $aumentar; $i++) {
- $contador .= '0';
- }
- $contador .= $cont === 0 ? 1 : $cont;
- return $contador;
- }
- // Establece la duracion entre dos fechas
- public function durationDate($date)
- {
- if ($date->d > 29) {
- if ($date->m > 11) {
- $date->y++;
- } else {
- $date->m++;
- }
- }else{
- $date->d++;
- }
- if ($date->y > 0) {
- if ($date->y > 1) {
- $duration = $date->y . " años, ";
- } else {
- $duration = $date->y . " año, ";
- }
- if ($date->m > 1) {
- $duration .= $date->m . " meses, ";
- } else if ($date->m == 1) {
- $duration .= $date->m . " mes, ";
- }
- if ($date->d > 1) {
- $duration .= $date->d . " dias";
- } else if ($date->d == 1) {
- $duration .= $date->d . " dia";
- }
- } else if ($date->m > 0) {
- if ($date->m > 1) {
- $duration = $date->m . " meses, ";
- } else {
- $duration = $date->m . " mes, ";
- }
- if ($date->d > 1) {
- $duration .= $date->d . " dias";
- } else if ($date->d == 1) {
- $duration .= $date->d . " dia";
- }
- } else if ($date->d > 0) {
- if ($date->d > 1) {
- $duration = $date->d . " dias";
- } else {
- $duration = $date->d . " dia";
- }
- } else {
- $duration = "Menos de 1 dia";
- }
- return $duration;
- }
- public function saveImage($img, $pathSave, $nameImage, $line) {
- $ruta = storage_path().$pathSave;
- $secuenceNumber = 0;
- if ( !is_dir($ruta) ) {
- $arrResponseCreate = $this->createRouteSave($pathSave);
- if ($arrResponseCreate['error']) {
- return $arrResponseCreate;
- }else{
- $this->saveImage($img, $pathSave, $nameImage, $line);
- }
- }else{
- $gestor = opendir($ruta);
- while (($archivo = readdir($gestor)) !== false) {
- if ($archivo != '.' && $archivo != '..') {
- $secuenceNumber++;
- }
- }
- $numeroLinea = $this->formatSecuence($line, 2);
- $numeroSecuencia = $this->formatSecuence($secuenceNumber, 6);
- $image = str_replace('data:image/jpeg;base64,', '', $img);
- $image = str_replace(' ', '+', $image);
- $currentDate = date("ymd");
- $imageName = "$numeroLinea-GEAD-FO-$currentDate-$numeroSecuencia-01=$nameImage";
- try {
- $validate = \File::put( storage_path(). $pathSave . '/' . $imageName, base64_decode($image) );
- } catch (\Throwable $th) {
- return $this->responseController->makeResponse(true, "ERR_PATH_CRE000: Ocurrió un error al crear la carpeta.", $th->getMessage(), 500);
- }
- return [
- "error" => false,
- "msg" => "ÉXITO: Imagen Creada Exitosamente",
- "response" => $imageName
- ];
- }
- }
- public function saveDocument($documentBase, $pathSave, $nameDocument, $typeDocument, $line, $codeDocument = '') {
- try {
- // Se obtiene la ruta en donde se guardará el archivo
- $routeSaveDocument = "/app/public/$pathSave";
- // Se obtiene la ruta completa del archivo a guardar
- $pathRoute = storage_path().$routeSaveDocument;
- // Se pregunta si la ruta del archivo a guardar existe
- if ( !is_dir($pathRoute) ) {
- // Si no existe, entonces se intentará crear la ruta del archivo
- $arrResponseCreate = $this->createRouteSave($routeSaveDocument);
- // Si no se pudo crear la ruta del archivo, entonces regresa una respuesta negativa
- if ($arrResponseCreate['error']) {
- return $arrResponseCreate;
- }else{
- // Si si se pudo crear la ruta, entonces se vuelve a ejecutar el método
- return $this->saveDocument($documentBase, $pathSave, $nameDocument, $typeDocument, $line);
- }
- } else {
- // Se abré la ruta del archivo
- $management = opendir($pathRoute);
- // Se inicializa el número de secuencia
- $secuenceNumber = 0;
- // Se obtienen todos los archivos guardados en la ruta donde se guardará el archivo
- while (($file = readdir($management)) !== false) {
- if ($file != '.' && $file != '..') {
- $arrCodeDocument = explode('=',$file);
- $arrStructureDocument = explode('-', $arrCodeDocument[0]);
- // Se va incrementando el número de secuencia según los archivos obtenidos en la ruta
- if ($arrStructureDocument[2] == $typeDocument) {
- $secuenceNumber++;
- }
- }
- }
- // Si no se encontró ningún archivo, entonces se inicializa en 1
- if ( $secuenceNumber === 0 ) {
- $secuenceNumber = 1;
- } else {
- $secuenceNumber += 1;
- }
- // Se obtiene el número de línea en el formato deseado (XX)
- $lineNumber = $this->formatSecuence($line, 2);
- // Se obtiene el número de secuencia en el formato deseado (XXXXXX)
- $secuenceNumber = $this->formatSecuence($secuenceNumber, 6);
- // Se obtiene la fecha actual en el formato deseado (YYMMDD)
- $currentDate = date("ymd");
- // Se obtiene el nombre del documento en el formato deseado (mayuscula y sin espacios en blanco)
- $nameDocument = strtoupper(str_replace(' ', '_', trim($nameDocument)));
- // Se genera el código del documento
- $codeDocument = "$lineNumber-$pathSave-$typeDocument-$currentDate-$secuenceNumber-01=$nameDocument";
- $arrDocument = explode(',', $documentBase);
- if (count($arrDocument) > 1) {
- $document = $arrDocument[1];
- } else {
- $document = $arrDocument[0];
- }
- // Se obtiene la información del documento en base64
- $document = str_replace(' ', '+', $document);
- try {
- // Se guarda el documento en la ruta deseada con el nombre del código generado
- $validate = \File::put( storage_path(). $routeSaveDocument . '/' . $codeDocument, base64_decode($document) );
- } catch (\Throwable $th) {
- return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_CRE001: Ocurrió un error al crear la carpeta.", "response" => $th->getMessage() ];
- }
- // Se valida que se haya guardado correctamente el documento
- if ( !$validate ) {
- return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_CRE002: No se pudo crear la carpeta.", "response" => [] ];
- }
- // Se envía el código del documento
- return [ "error" => false, "msg" => "ÉXITO: Documento Creado Exitosamente", "response" => $codeDocument ];
- }
- } catch (\Throwable $th) {
- return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_CRE000: Ocurrió un error al guardar el documento.", "response" => $th->getMessage() ];
- }
- }
- public function updateDocument($codeDocument, $documentBase, $pathSave, $nameDocument, $typeDocument, $line) {
- try {
- // Se obtiene la ruta en donde se guardará el archivo
- $routeSaveDocument = "/app/public/$pathSave";
- // Se obtiene la ruta completa del archivo a guardar
- $pathRoute = storage_path().$routeSaveDocument;
- // Se pregunta si la ruta del archivo a guardar existe
- if ( !is_dir($pathRoute) ) {
- // Si no existe, entonces se intentará crear la ruta del archivo
- $arrResponseCreate = $this->createRouteSave($routeSaveDocument);
- // Si no se pudo crear la ruta del archivo, entonces regresa una respuesta negativa
- if ($arrResponseCreate['error']) {
- return $arrResponseCreate;
- }else{
- // Si si se pudo crear la ruta, entonces se vuelve a ejecutar el método
- return $this->updateDocument($codeDocument, $documentBase, $pathSave, $nameDocument, $typeDocument, $line);
- }
- } else {
- // Se obtiene la escrutura del código
- $arrResponseStructure = $this->getStrucutreCode( $codeDocument );
- if ( $arrResponseStructure['error'] ) {
- return [ "error" => true, "msg" => $arrResponseStructure['msg'], "response" => [] ];
- }
- $arrStructureCode = $arrResponseStructure['response'];
- // Se abré la ruta del archivo
- $routeGetDocument = "/app/public/$pathSave";
- $management = opendir( storage_path() . $routeGetDocument );
- // Se inicializa la variable si el archivo es encontrado
- $isFound = false;
- // Se obtienen todos los archivos guardados en la ruta donde se guardará el archivo
- while ( ($file = readdir($management)) !== false) {
- $codeDocumentSave = explode('=', $file)[0];
- if ($codeDocumentSave == $codeDocument) {
- // Se va incrementando el número de secuencia según los archivos obtenidos en la ruta
- $isFound = true;
- }
- }
- // Si el documento es encontrado en la base de datos documental, entonces...
- if ( !$isFound ) {
- return [
- "error" => true,
- "msg" => "ERR_RESOURCE_DOCUMENT_UPD001: No se pudo encontrar el documento en la base de datos documental",
- "response" => []
- ];
- }
- // Se obtiene el número de línea en el formato deseado (XX)
- $lineNumber = $arrStructureCode['LINE'];
- // Se obtiene el número de secuencia en el formato deseado (XXXXXX)
- $secuenceNumber = $arrStructureCode['SECUENCE'];
- // Se obtiene la fecha actual en el formato deseado (YYMMDD)
- $currentDate = $arrStructureCode['DATE'];
- // Se obtiene el nombre del documento en el formato deseado (mayuscula y sin espacios en blanco)
- $nameDocument = strtoupper(str_replace(' ', '_', trim($nameDocument)));
- // Se obtiene la versión del documento y se le incrementa uno más
- $versionNumber = $this->formatSecuence( intval($arrStructureCode['VERSION']) + 1 , 2);
- // Se genera el código del documento
- $codeDocument = "$lineNumber-$pathSave-$typeDocument-$currentDate-$secuenceNumber-$versionNumber=$nameDocument";
- // Se obtiene la información del documento en base64
- $document = explode(',', $documentBase)[1];
- $document = str_replace(' ', '+', $document);
- try {
- // Se guarda el documento en la ruta deseada con el nombre del código generado
- $validate = \File::put( storage_path() . $routeSaveDocument . '/' . $codeDocument, base64_decode($document) );
- } catch (\Throwable $th) {
- return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_UPD002: Ocurrió un error al crear la carpeta.", "response" => $th->getMessage() ];
- }
- // Se valida que se haya guardado correctamente el documento
- if ( !$validate ) {
- return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_UPD003: No se pudo crear la carpeta.", "response" => [] ];
- }
- // Se envía el código del documento
- return [ "error" => false, "msg" => "ÉXITO: Documento Creado Exitosamente", "response" => $codeDocument ];
- }
- } catch (\Throwable $th) {
- return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_UPD000: Ocurrió un error al crear la carpeta.", "response" => $th->getMessage() ];
- }
- }
- public function nameFormatDocument($nameDocument){
- $nameDocument = str_replace(' ', '_', $nameDocument);
- $nameDocument = str_replace('-', '', $nameDocument);
- $nameDocument = str_replace('/', '', $nameDocument);
- $nameDocument = str_replace('\\', '', $nameDocument);
- $nameDocument = str_replace('@', '', $nameDocument);
- $nameDocument = str_replace('&', '', $nameDocument);
- $nameDocument = str_replace('|', '', $nameDocument);
- $nameDocument = str_replace('!', '', $nameDocument);
- $nameDocument = str_replace('"', '', $nameDocument);
- $nameDocument = str_replace("'", '', $nameDocument);
- $nameDocument = str_replace('%', '', $nameDocument);
- $nameDocument = str_replace('(', '', $nameDocument);
- $nameDocument = str_replace(')', '', $nameDocument);
- $nameDocument = str_replace('+', '', $nameDocument);
- $nameDocument = str_replace('+', '', $nameDocument);
- $nameDocument = str_replace('[', '', $nameDocument);
- $nameDocument = str_replace(']', '', $nameDocument);
- $nameDocument = str_replace('?', '', $nameDocument);
- $nameDocument = str_replace('¿', '', $nameDocument);
- $nameDocument = str_replace('!', '', $nameDocument);
- $nameDocument = str_replace('#', '', $nameDocument);
- $nameDocument = str_replace('$', '', $nameDocument);
- $nameDocument = str_replace(':', '', $nameDocument);
- $nameDocument = str_replace('{', '', $nameDocument);
- $nameDocument = str_replace('}', '', $nameDocument);
- $nameDocument = str_replace('°', '', $nameDocument);
- $nameDocument = str_replace('¬', '', $nameDocument);
- $nameDocument = str_replace('=', '', $nameDocument);
- return $nameDocument;
- }
- private function getStrucutreCode($codeDocument) {
- $arrCodeDocument = explode('-', $codeDocument);
- if ( count($arrCodeDocument) < 6) {
- return [ "error" => true, "msg" => "ERR_RESOURCE_STRUCTURE_CRE000: No se pudo generar la estructura del código", "response" => [] ];
- }
- $arrStructure = [
- 'LINE' => $arrCodeDocument[0],
- 'MODULE' => $arrCodeDocument[1],
- 'TYPE' => $arrCodeDocument[2],
- 'DATE' => $arrCodeDocument[3],
- 'SECUENCE' => $arrCodeDocument[4],
- 'VERSION' => $arrCodeDocument[5],
- ];
- return [
- "error" => false,
- "msg" => "",
- "response" => $arrStructure
- ];
- }
- private $index = 0;
- public function createRouteSave ($path, $savePath = '') : Array {
- try {
- // Se obtiene cada carpeta de la ruta en un arreglo
- $arrPath = explode('/',$path);
- // Se obtiene la cantidad de iteraciones que tendrá el método
- $maxPath = count($arrPath);
- // Si existe el direcctorio y aún se tienen iteraciones disponibles, entonces...
- if ( is_dir( storage_path() . '/' . $savePath . $arrPath[$this->index] ) && $maxPath > $this->index){
- // Se agrega una nueva carpeta a la ruta
- $savePath .= $arrPath[$this->index] . '/';
- // Se incrementa el index para buscar en el arreglo de rutas
- $this->index += 1;
- // Si aún hay iteraciones disponibles, entonces se ejecutará el método de nuevo
- if ($maxPath > $this->index) {
- $this->createRouteSave($path, $savePath);
- }
- // Si no exite la carpeta, entonces
- } else if ( ! is_dir( storage_path() . '/' . $savePath . $arrPath[$this->index] ) ) {
- try {
- // Se creará la carpeta
- if ( ! mkdir( storage_path() . '/' . $savePath . $arrPath[$this->index] ) ) {
- // En caso de haber un error en la creación de la carpeta, mandará una respuesta negativa
- return [
- "error" => true,
- "msg" => "ERR_RESOURCE_ROUTE_CRE001: Ocurrió un error al crear la carpeta " . $arrPath[$this->index],
- "response" => storage_path() . '/' . $savePath . $arrPath[$this->index]
- ];
- }else{
- // Si la carpeta se pudo crear de manera exitosa, entonces se ejecutará el método de nuevo
- $this->createRouteSave($path, $savePath);
- }
- } catch (\Throwable $th) {
- return [
- "error" => true,
- "msg" => "ERR_RESOURCE_ROUTE_CRE002: Ocurrió un error inesperado al crear la ruta del archivo",
- "response" => $th->getMessage()
- ];
- }
- }
- // En caso de crear todas las carpetas, se reinicia las iteraciones a 0
- $this->index = 0;
- // Se envía una respuesta positiva
- return [
- "error" => false,
- "msg" => "Creación de Ruta Exitosa",
- "response" => storage_path() . '/' . $savePath . $arrPath[$this->index]
- ];
- } catch (\Throwable $th) {
- return [
- "error" => true,
- "msg" => "ERR_RESOURCE_ROUTE_CRE000: Ocurrió un error inesperado al generar la ruta del archivo",
- "response" => $th->getMessage()
- ];
- }
- }
- public function checkUserEnc($encUser, $line) {
- $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
- try {
- $user = $this->encController->decrypt($encUser);
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió un error al desencriptar el ID del usuario.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- try {
- $validateUser = DB::table('S002V01TUSUA')
- ->where('USUA_NULI', '=', $line)
- ->where('USUA_IDUS', '=', $user)
- ->exists();
- } catch(\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al verificar la existencia del usuario.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- if (!$validateUser) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El usuario no existe.';
- $arrResponse['response'] = [];
- return $arrResponse;
- }
- $arrResponse['error'] = false;
- $arrResponse['msg'] = 'Usuario validado';
- $arrResponse['response'] = $user;
- return $arrResponse;
- }
- public function validateAddress($codigoPostal, $idColonia, $idMunicipio, $idLocalidad = null, $idEstado, $idPais, $line): Array {
- $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
- // Se obtiene el resultado si existe el código del país
- try {
- $validatePais = DB::table('S002V01TPAIS')
- ->where('PAIS_IDPA', '=', $idPais)
- ->where('PAIS_NULI', '=', $line)
- ->exists();
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el país.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$validatePais) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El país ingresado no se encuentra en la lista de países.';
- return $arrResponse;
- }
- // Se valida que los paises sean MEX, USA y CAN para verificar el estado/entidad federativa del país
- // Por otro lado, el método se terminará y mandará un estado correcto.
- if($idPais !== 'MEX' && $idPais !== 'USA' && $idPais !== 'CAN') {
- $arrResponse['error'] = false;
- $arrResponse['msg'] = 'Correcto';
- return $arrResponse;
- }
- // Se obtiene el resultado si existe el código del estado relacionado al páis
- try {
- $validateEstado = DB::table('S002V01TESTA')
- ->where('ESTA_COPA', '=', $idPais)
- ->where('ESTA_COES', '=', $idEstado)
- ->where('ESTA_NULI', '=', $line)
- ->exists();
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el estado.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$validateEstado) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El estado ingresado no se encuentra en la lista de países y estados.';
- return $arrResponse;
- }
-
- // Se valida que el país ingresado sea MEX para verificar el municipio, localidad, colonia y código postal
- // Por otro lado, el método de terminará y mandará un estado correcto.
- if($idPais !== 'MEX') {
- $arrResponse['error'] = false;
- $arrResponse['msg'] = 'Correcto';
- return $arrResponse;
- }
- // Se obtiene el resultado si existe el código del municipio relacionado al estado
- try {
- $validateMunicipio = DB::table('S002V01TMUNI')
- ->where('MUNI_COES', '=', $idEstado)
- ->where('MUNI_COMU', '=', $idMunicipio)
- ->where('MUNI_NULI', '=', $line)
- ->exists();
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el municipio.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$validateMunicipio) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El municipio ingresado ('.$idMunicipio.') no se encuentra en la lista de países, estados y municipios.';
- return $arrResponse;
- }
- // Se verifica si el campo localidad exista para poder validarlo
- if (!is_null($idLocalidad)) {
- // Se obtiene el resultado si existe el código de la localidad relacionado al estado
- try {
- $validateLocalidad = DB::table('S002V01TLOCA')
- ->where('LOCA_COES', '=', $idEstado)
- ->where('LOCA_COLO', '=', $idLocalidad)
- ->where('LOCA_NULI', '=', $line)
- ->exists();
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar la localidad.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$validateLocalidad) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'La localidad ingresada no se encuentra en la lista de países, estados, municipios y localidades.';
- return $arrResponse;
- }
- }
- // Se obtiene el resultado si existe el código de la colonia relacionada al código postal
- try {
- $validateColonia = DB::table('S002V01TCOLO')
- ->where('COLO_COPO', '=', $codigoPostal)
- ->where('COLO_COCO', '=', $idColonia)
- ->where('COLO_NULI', '=', $line)
- ->exists();
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar la colonia.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$validateColonia) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'La colonia ingresada no se encuentra en la lista de países, estados, municipios y códigos postales.';
- return $arrResponse;
- }
-
- // Se obtiene el resultado si existe el código postal relacionado al estado
- try {
- $validateCodigoPostal = DB::table('S002V01TCOPO')
- ->where('COPO_COES', '=', $idEstado)
- ->where('COPO_COPO', '=', $codigoPostal)
- ->where('COPO_NULI', '=', $line)
- ->exists();
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el código postal.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$validateCodigoPostal) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El código postal ingresado no se encuentra en la lista de países, estados, municipios y colonias.';
- return $arrResponse;
- }
- return $arrResponse;
- }
- public function getAddress($codigoPostal, $idColonia, $idMunicipio, $idLocalidad = null, $idEstado, $idPais, $line): Array {
- $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
- // Se obtiene el resultado si existe el código del país
- try {
- $arrPais = (array) DB::table('S002V01TPAIS')
- ->where('PAIS_IDPA', '=', $idPais)
- ->where('PAIS_NULI', '=', $line)
- ->first([
- 'PAIS_IDPA',
- 'PAIS_NOMB'
- ]);
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el país.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (empty($arrPais)) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El país ingresado no se encuentra en la lista de países.';
- return $arrResponse;
- }
- $arrResponse['response']['PAIS'] = $arrPais['PAIS_NOMB'].' ('.$arrPais['PAIS_IDPA'].')';
- // Se valida que los paises sean MEX, USA y CAN para verificar el estado/entidad federativa del país
- // Por otro lado, el método se terminará y mandará un estado correcto.
- if($idPais !== 'MEX' && $idPais !== 'USA' && $idPais !== 'CAN') {
- $arrResponse['error'] = false;
- $arrResponse['msg'] = 'Correcto';
- return $arrResponse;
- }
- // Se obtiene el resultado si existe el código del estado relacionado al páis
- try {
- $arrEstado = (array) DB::table('S002V01TESTA')
- ->where('ESTA_COPA', '=', $idPais)
- ->where('ESTA_COES', '=', $idEstado)
- ->where('ESTA_NULI', '=', $line)
- ->first();
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el estado.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (empty($arrEstado)) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El estado ingresado no se encuentra en la lista de países y estados.';
- return $arrResponse;
- }
- $arrResponse['response']['ENTIDAD_FEDERATIVA'] = $arrEstado['ESTA_NOES'].' ('.$arrEstado['ESTA_COES'].')';
-
- // Se valida que el país ingresado sea MEX para verificar el municipio, localidad, colonia y código postal
- // Por otro lado, el método de terminará y mandará un estado correcto.
- if($idPais !== 'MEX') {
- $arrResponse['error'] = false;
- $arrResponse['msg'] = 'Correcto';
- return $arrResponse;
- }
- // Se obtiene el resultado si existe el código del municipio relacionado al estado
- try {
- $arrMunicipio = (array) DB::table('S002V01TMUNI')
- ->where('MUNI_COES', '=', $idEstado)
- ->where('MUNI_COMU', '=', $idMunicipio)
- ->where('MUNI_NULI', '=', $line)
- ->first(['MUNI_COMU','MUNI_NOMU']);
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el municipio.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$arrMunicipio) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El municipio ingresado ('.$idMunicipio.') no se encuentra en la lista de países, estados y municipios.';
- return $arrResponse;
- }
- $arrResponse['response']['MUNICIPIO'] = $arrMunicipio['MUNI_NOMU'].' ('.$arrMunicipio['MUNI_COMU'].')';
- // Se verifica si el campo localidad exista para poder validarlo
- if (!is_null($idLocalidad)) {
- // Se obtiene el resultado si existe el código de la localidad relacionado al estado
- try {
- $arrLocalidad = (array) DB::table('S002V01TLOCA')
- ->where('LOCA_COES', '=', $idEstado)
- ->where('LOCA_COLO', '=', $idLocalidad)
- ->where('LOCA_NULI', '=', $line)
- ->first(['LOCA_COLO','LOCA_NOLO']);
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar la localidad.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$arrLocalidad) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'La localidad ingresada no se encuentra en la lista de países, estados, municipios y localidades.';
- return $arrResponse;
- }
- $arrResponse['response']['LOCALIDAD'] = $arrLocalidad['LOCA_NOLO'].' ('.$arrLocalidad['LOCA_COLO'].')';
- } else {
- $arrResponse['response']['LOCALIDAD'] = null;
- }
- // Se obtiene el resultado si existe el código de la colonia relacionada al código postal
- try {
- $arrColonia = (array) DB::table('S002V01TCOLO')
- ->where('COLO_COPO', '=', $codigoPostal)
- ->where('COLO_COCO', '=', $idColonia)
- ->where('COLO_NULI', '=', $line)
- ->first(['COLO_COCO', 'COLO_NOCO']);
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar la colonia.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$arrColonia) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'La colonia ingresada no se encuentra en la lista de países, estados, municipios y códigos postales.';
- return $arrResponse;
- }
- $arrResponse['response']['COLONIA'] = $arrColonia['COLO_NOCO'].' ('.$arrColonia['COLO_COCO'].')';
-
- // Se obtiene el resultado si existe el código postal relacionado al estado
- try {
- $arrCodigoPostal = (array) DB::table('S002V01TCOPO')
- ->where('COPO_COES', '=', $idEstado)
- ->where('COPO_COPO', '=', $codigoPostal)
- ->where('COPO_NULI', '=', $line)
- ->first(['COPO_COPO']);
- } catch (\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al validar el código postal.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
- if (!$arrCodigoPostal) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El código postal ingresado no se encuentra en la lista de países, estados, municipios y colonias.';
- return $arrResponse;
- }
- $arrResponse['response']['CODIGO_POSTAL'] = $arrCodigoPostal['COPO_COPO'];
- return $arrResponse;
- }
- public function checkUserDec($decUser, $line) {
- $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
- try {
- $validateUser = DB::table('S002V01TUSUA')
- ->where('USUA_NULI', '=', $line)
- ->where('USUA_IDUS', '=', $decUser)
- ->exists();
- } catch(\Throwable $th) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'Ocurrió al verificar la existencia del usuario.';
- $arrResponse['response'] = $th->getMessage();
- return $arrResponse;
- }
- if (!$validateUser) {
- $arrResponse['error'] = true;
- $arrResponse['msg'] = 'El usuario no existe.';
- $arrResponse['response'] = [];
- return $arrResponse;
- }
- $arrResponse['error'] = false;
- $arrResponse['msg'] = 'Usuario validado';
- $arrResponse['response'] = $decUser;
- return $arrResponse;
- }
- }
|