ResourcesController.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. class ResourcesController extends Controller
  6. {
  7. private $responseController;
  8. public $arrAlphabet;
  9. public $encController;
  10. public function __construct() {
  11. $this->responseController = new ResponseController();
  12. $this->encController = new EncryptionController();
  13. $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');
  14. }
  15. public function formatSecuence($cont, $length){
  16. $longigud = strlen($cont);
  17. $aumentar = $length - $longigud;
  18. $contador = '';
  19. for ($i = 0; $i < $aumentar; $i++) {
  20. $contador .= '0';
  21. }
  22. $contador .= $cont === 0 ? 1 : $cont;
  23. return $contador;
  24. }
  25. // Establece la duracion entre dos fechas
  26. public function durationDate($date)
  27. {
  28. if ($date->d > 29) {
  29. if ($date->m > 11) {
  30. $date->y++;
  31. } else {
  32. $date->m++;
  33. }
  34. }else{
  35. $date->d++;
  36. }
  37. if ($date->y > 0) {
  38. if ($date->y > 1) {
  39. $duration = $date->y . " años, ";
  40. } else {
  41. $duration = $date->y . " año, ";
  42. }
  43. if ($date->m > 1) {
  44. $duration .= $date->m . " meses, ";
  45. } else if ($date->m == 1) {
  46. $duration .= $date->m . " mes, ";
  47. }
  48. if ($date->d > 1) {
  49. $duration .= $date->d . " dias";
  50. } else if ($date->d == 1) {
  51. $duration .= $date->d . " dia";
  52. }
  53. } else if ($date->m > 0) {
  54. if ($date->m > 1) {
  55. $duration = $date->m . " meses, ";
  56. } else {
  57. $duration = $date->m . " mes, ";
  58. }
  59. if ($date->d > 1) {
  60. $duration .= $date->d . " dias";
  61. } else if ($date->d == 1) {
  62. $duration .= $date->d . " dia";
  63. }
  64. } else if ($date->d > 0) {
  65. if ($date->d > 1) {
  66. $duration = $date->d . " dias";
  67. } else {
  68. $duration = $date->d . " dia";
  69. }
  70. } else {
  71. $duration = "Menos de 1 dia";
  72. }
  73. return $duration;
  74. }
  75. public function saveImage($img, $pathSave, $nameImage, $line) {
  76. $ruta = storage_path().$pathSave;
  77. $secuenceNumber = 0;
  78. if ( !is_dir($ruta) ) {
  79. $arrResponseCreate = $this->createRouteSave($pathSave);
  80. if ($arrResponseCreate['error']) {
  81. return $arrResponseCreate;
  82. }else{
  83. $this->saveImage($img, $pathSave, $nameImage, $line);
  84. }
  85. }else{
  86. $gestor = opendir($ruta);
  87. while (($archivo = readdir($gestor)) !== false) {
  88. if ($archivo != '.' && $archivo != '..') {
  89. $secuenceNumber++;
  90. }
  91. }
  92. $numeroLinea = $this->formatSecuence($line, 2);
  93. $numeroSecuencia = $this->formatSecuence($secuenceNumber, 6);
  94. $image = str_replace('data:image/jpeg;base64,', '', $img);
  95. $image = str_replace(' ', '+', $image);
  96. $currentDate = date("ymd");
  97. $imageName = "$numeroLinea-GEAD-FO-$currentDate-$numeroSecuencia-01=$nameImage";
  98. try {
  99. $validate = \File::put( storage_path(). $pathSave . '/' . $imageName, base64_decode($image) );
  100. } catch (\Throwable $th) {
  101. return $this->responseController->makeResponse(true, "ERR_PATH_CRE000: Ocurrió un error al crear la carpeta.", $th->getMessage(), 500);
  102. }
  103. return [
  104. "error" => false,
  105. "msg" => "ÉXITO: Imagen Creada Exitosamente",
  106. "response" => $imageName
  107. ];
  108. }
  109. }
  110. public function saveDocument($documentBase, $pathSave, $nameDocument, $typeDocument, $line, $codeDocument = '') {
  111. try {
  112. // Se obtiene la ruta en donde se guardará el archivo
  113. $routeSaveDocument = "/app/public/$pathSave";
  114. // Se obtiene la ruta completa del archivo a guardar
  115. $pathRoute = storage_path().$routeSaveDocument;
  116. // Se pregunta si la ruta del archivo a guardar existe
  117. if ( !is_dir($pathRoute) ) {
  118. // Si no existe, entonces se intentará crear la ruta del archivo
  119. $arrResponseCreate = $this->createRouteSave($routeSaveDocument);
  120. // Si no se pudo crear la ruta del archivo, entonces regresa una respuesta negativa
  121. if ($arrResponseCreate['error']) {
  122. return $arrResponseCreate;
  123. }else{
  124. // Si si se pudo crear la ruta, entonces se vuelve a ejecutar el método
  125. return $this->saveDocument($documentBase, $pathSave, $nameDocument, $typeDocument, $line);
  126. }
  127. } else {
  128. // Se abré la ruta del archivo
  129. $management = opendir($pathRoute);
  130. // Se inicializa el número de secuencia
  131. $secuenceNumber = 0;
  132. // Se obtienen todos los archivos guardados en la ruta donde se guardará el archivo
  133. while (($file = readdir($management)) !== false) {
  134. if ($file != '.' && $file != '..') {
  135. $arrCodeDocument = explode('=',$file);
  136. $arrStructureDocument = explode('-', $arrCodeDocument[0]);
  137. // Se va incrementando el número de secuencia según los archivos obtenidos en la ruta
  138. if ($arrStructureDocument[2] == $typeDocument) {
  139. $secuenceNumber++;
  140. }
  141. }
  142. }
  143. // Si no se encontró ningún archivo, entonces se inicializa en 1
  144. if ( $secuenceNumber === 0 ) {
  145. $secuenceNumber = 1;
  146. } else {
  147. $secuenceNumber += 1;
  148. }
  149. // Se obtiene el número de línea en el formato deseado (XX)
  150. $lineNumber = $this->formatSecuence($line, 2);
  151. // Se obtiene el número de secuencia en el formato deseado (XXXXXX)
  152. $secuenceNumber = $this->formatSecuence($secuenceNumber, 6);
  153. // Se obtiene la fecha actual en el formato deseado (YYMMDD)
  154. $currentDate = date("ymd");
  155. // Se obtiene el nombre del documento en el formato deseado (mayuscula y sin espacios en blanco)
  156. $nameDocument = strtoupper(str_replace(' ', '_', trim($nameDocument)));
  157. // Se genera el código del documento
  158. $codeDocument = "$lineNumber-$pathSave-$typeDocument-$currentDate-$secuenceNumber-01=$nameDocument";
  159. $arrDocument = explode(',', $documentBase);
  160. if (count($arrDocument) > 1) {
  161. $document = $arrDocument[1];
  162. } else {
  163. $document = $arrDocument[0];
  164. }
  165. // Se obtiene la información del documento en base64
  166. $document = str_replace(' ', '+', $document);
  167. try {
  168. // Se guarda el documento en la ruta deseada con el nombre del código generado
  169. $validate = \File::put( storage_path(). $routeSaveDocument . '/' . $codeDocument, base64_decode($document) );
  170. } catch (\Throwable $th) {
  171. return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_CRE001: Ocurrió un error al crear la carpeta.", "response" => $th->getMessage() ];
  172. }
  173. // Se valida que se haya guardado correctamente el documento
  174. if ( !$validate ) {
  175. return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_CRE002: No se pudo crear la carpeta.", "response" => [] ];
  176. }
  177. // Se envía el código del documento
  178. return [ "error" => false, "msg" => "ÉXITO: Documento Creado Exitosamente", "response" => $codeDocument ];
  179. }
  180. } catch (\Throwable $th) {
  181. return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_CRE000: Ocurrió un error al guardar el documento.", "response" => $th->getMessage() ];
  182. }
  183. }
  184. public function updateDocument($codeDocument, $documentBase, $pathSave, $nameDocument, $typeDocument, $line) {
  185. try {
  186. // Se obtiene la ruta en donde se guardará el archivo
  187. $routeSaveDocument = "/app/public/$pathSave";
  188. // Se obtiene la ruta completa del archivo a guardar
  189. $pathRoute = storage_path().$routeSaveDocument;
  190. // Se pregunta si la ruta del archivo a guardar existe
  191. if ( !is_dir($pathRoute) ) {
  192. // Si no existe, entonces se intentará crear la ruta del archivo
  193. $arrResponseCreate = $this->createRouteSave($routeSaveDocument);
  194. // Si no se pudo crear la ruta del archivo, entonces regresa una respuesta negativa
  195. if ($arrResponseCreate['error']) {
  196. return $arrResponseCreate;
  197. }else{
  198. // Si si se pudo crear la ruta, entonces se vuelve a ejecutar el método
  199. return $this->updateDocument($codeDocument, $documentBase, $pathSave, $nameDocument, $typeDocument, $line);
  200. }
  201. } else {
  202. // Se obtiene la escrutura del código
  203. $arrResponseStructure = $this->getStrucutreCode( $codeDocument );
  204. if ( $arrResponseStructure['error'] ) {
  205. return [ "error" => true, "msg" => $arrResponseStructure['msg'], "response" => [] ];
  206. }
  207. $arrStructureCode = $arrResponseStructure['response'];
  208. // Se abré la ruta del archivo
  209. $routeGetDocument = "/app/public/$pathSave";
  210. $management = opendir( storage_path() . $routeGetDocument );
  211. // Se inicializa la variable si el archivo es encontrado
  212. $isFound = false;
  213. // Se obtienen todos los archivos guardados en la ruta donde se guardará el archivo
  214. while ( ($file = readdir($management)) !== false) {
  215. $codeDocumentSave = explode('=', $file)[0];
  216. if ($codeDocumentSave == $codeDocument) {
  217. // Se va incrementando el número de secuencia según los archivos obtenidos en la ruta
  218. $isFound = true;
  219. }
  220. }
  221. // Si el documento es encontrado en la base de datos documental, entonces...
  222. if ( !$isFound ) {
  223. return [
  224. "error" => true,
  225. "msg" => "ERR_RESOURCE_DOCUMENT_UPD001: No se pudo encontrar el documento en la base de datos documental",
  226. "response" => []
  227. ];
  228. }
  229. // Se obtiene el número de línea en el formato deseado (XX)
  230. $lineNumber = $arrStructureCode['LINE'];
  231. // Se obtiene el número de secuencia en el formato deseado (XXXXXX)
  232. $secuenceNumber = $arrStructureCode['SECUENCE'];
  233. // Se obtiene la fecha actual en el formato deseado (YYMMDD)
  234. $currentDate = $arrStructureCode['DATE'];
  235. // Se obtiene el nombre del documento en el formato deseado (mayuscula y sin espacios en blanco)
  236. $nameDocument = strtoupper(str_replace(' ', '_', trim($nameDocument)));
  237. // Se obtiene la versión del documento y se le incrementa uno más
  238. $versionNumber = $this->formatSecuence( intval($arrStructureCode['VERSION']) + 1 , 2);
  239. // Se genera el código del documento
  240. $codeDocument = "$lineNumber-$pathSave-$typeDocument-$currentDate-$secuenceNumber-$versionNumber=$nameDocument";
  241. // Se obtiene la información del documento en base64
  242. $document = explode(',', $documentBase)[1];
  243. $document = str_replace(' ', '+', $document);
  244. try {
  245. // Se guarda el documento en la ruta deseada con el nombre del código generado
  246. $validate = \File::put( storage_path() . $routeSaveDocument . '/' . $codeDocument, base64_decode($document) );
  247. } catch (\Throwable $th) {
  248. return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_UPD002: Ocurrió un error al crear la carpeta.", "response" => $th->getMessage() ];
  249. }
  250. // Se valida que se haya guardado correctamente el documento
  251. if ( !$validate ) {
  252. return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_UPD003: No se pudo crear la carpeta.", "response" => [] ];
  253. }
  254. // Se envía el código del documento
  255. return [ "error" => false, "msg" => "ÉXITO: Documento Creado Exitosamente", "response" => $codeDocument ];
  256. }
  257. } catch (\Throwable $th) {
  258. return [ "error" => true, "msg" => "ERR_RESOURCE_DOCUMENT_UPD000: Ocurrió un error al crear la carpeta.", "response" => $th->getMessage() ];
  259. }
  260. }
  261. public function nameFormatDocument($nameDocument){
  262. $nameDocument = str_replace(' ', '_', $nameDocument);
  263. $nameDocument = str_replace('-', '', $nameDocument);
  264. $nameDocument = str_replace('/', '', $nameDocument);
  265. $nameDocument = str_replace('\\', '', $nameDocument);
  266. $nameDocument = str_replace('@', '', $nameDocument);
  267. $nameDocument = str_replace('&', '', $nameDocument);
  268. $nameDocument = str_replace('|', '', $nameDocument);
  269. $nameDocument = str_replace('!', '', $nameDocument);
  270. $nameDocument = str_replace('"', '', $nameDocument);
  271. $nameDocument = str_replace("'", '', $nameDocument);
  272. $nameDocument = str_replace('%', '', $nameDocument);
  273. $nameDocument = str_replace('(', '', $nameDocument);
  274. $nameDocument = str_replace(')', '', $nameDocument);
  275. $nameDocument = str_replace('+', '', $nameDocument);
  276. $nameDocument = str_replace('+', '', $nameDocument);
  277. $nameDocument = str_replace('[', '', $nameDocument);
  278. $nameDocument = str_replace(']', '', $nameDocument);
  279. $nameDocument = str_replace('?', '', $nameDocument);
  280. $nameDocument = str_replace('¿', '', $nameDocument);
  281. $nameDocument = str_replace('!', '', $nameDocument);
  282. $nameDocument = str_replace('#', '', $nameDocument);
  283. $nameDocument = str_replace('$', '', $nameDocument);
  284. $nameDocument = str_replace(':', '', $nameDocument);
  285. $nameDocument = str_replace('{', '', $nameDocument);
  286. $nameDocument = str_replace('}', '', $nameDocument);
  287. $nameDocument = str_replace('°', '', $nameDocument);
  288. $nameDocument = str_replace('¬', '', $nameDocument);
  289. $nameDocument = str_replace('=', '', $nameDocument);
  290. return $nameDocument;
  291. }
  292. private function getStrucutreCode($codeDocument) {
  293. $arrCodeDocument = explode('-', $codeDocument);
  294. if ( count($arrCodeDocument) < 6) {
  295. return [ "error" => true, "msg" => "ERR_RESOURCE_STRUCTURE_CRE000: No se pudo generar la estructura del código", "response" => [] ];
  296. }
  297. $arrStructure = [
  298. 'LINE' => $arrCodeDocument[0],
  299. 'MODULE' => $arrCodeDocument[1],
  300. 'TYPE' => $arrCodeDocument[2],
  301. 'DATE' => $arrCodeDocument[3],
  302. 'SECUENCE' => $arrCodeDocument[4],
  303. 'VERSION' => $arrCodeDocument[5],
  304. ];
  305. return [
  306. "error" => false,
  307. "msg" => "",
  308. "response" => $arrStructure
  309. ];
  310. }
  311. private $index = 0;
  312. public function createRouteSave ($path, $savePath = '') : Array {
  313. try {
  314. // Se obtiene cada carpeta de la ruta en un arreglo
  315. $arrPath = explode('/',$path);
  316. // Se obtiene la cantidad de iteraciones que tendrá el método
  317. $maxPath = count($arrPath);
  318. // Si existe el direcctorio y aún se tienen iteraciones disponibles, entonces...
  319. if ( is_dir( storage_path() . '/' . $savePath . $arrPath[$this->index] ) && $maxPath > $this->index){
  320. // Se agrega una nueva carpeta a la ruta
  321. $savePath .= $arrPath[$this->index] . '/';
  322. // Se incrementa el index para buscar en el arreglo de rutas
  323. $this->index += 1;
  324. // Si aún hay iteraciones disponibles, entonces se ejecutará el método de nuevo
  325. if ($maxPath > $this->index) {
  326. $this->createRouteSave($path, $savePath);
  327. }
  328. // Si no exite la carpeta, entonces
  329. } else if ( ! is_dir( storage_path() . '/' . $savePath . $arrPath[$this->index] ) ) {
  330. try {
  331. // Se creará la carpeta
  332. if ( ! mkdir( storage_path() . '/' . $savePath . $arrPath[$this->index] ) ) {
  333. // En caso de haber un error en la creación de la carpeta, mandará una respuesta negativa
  334. return [
  335. "error" => true,
  336. "msg" => "ERR_RESOURCE_ROUTE_CRE001: Ocurrió un error al crear la carpeta " . $arrPath[$this->index],
  337. "response" => storage_path() . '/' . $savePath . $arrPath[$this->index]
  338. ];
  339. }else{
  340. // Si la carpeta se pudo crear de manera exitosa, entonces se ejecutará el método de nuevo
  341. $this->createRouteSave($path, $savePath);
  342. }
  343. } catch (\Throwable $th) {
  344. return [
  345. "error" => true,
  346. "msg" => "ERR_RESOURCE_ROUTE_CRE002: Ocurrió un error inesperado al crear la ruta del archivo",
  347. "response" => $th->getMessage()
  348. ];
  349. }
  350. }
  351. // En caso de crear todas las carpetas, se reinicia las iteraciones a 0
  352. $this->index = 0;
  353. // Se envía una respuesta positiva
  354. return [
  355. "error" => false,
  356. "msg" => "Creación de Ruta Exitosa",
  357. "response" => storage_path() . '/' . $savePath . $arrPath[$this->index]
  358. ];
  359. } catch (\Throwable $th) {
  360. return [
  361. "error" => true,
  362. "msg" => "ERR_RESOURCE_ROUTE_CRE000: Ocurrió un error inesperado al generar la ruta del archivo",
  363. "response" => $th->getMessage()
  364. ];
  365. }
  366. }
  367. public function checkUserEnc($encUser, $line) {
  368. $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
  369. try {
  370. $user = $this->encController->decrypt($encUser);
  371. } catch (\Throwable $th) {
  372. $arrResponse['error'] = true;
  373. $arrResponse['msg'] = 'Ocurrió un error al desencriptar el ID del usuario.';
  374. $arrResponse['response'] = $th->getMessage();
  375. return $arrResponse;
  376. }
  377. try {
  378. $validateUser = DB::table('S002V01TUSUA')
  379. ->where('USUA_NULI', '=', $line)
  380. ->where('USUA_IDUS', '=', $user)
  381. ->exists();
  382. } catch(\Throwable $th) {
  383. $arrResponse['error'] = true;
  384. $arrResponse['msg'] = 'Ocurrió al verificar la existencia del usuario.';
  385. $arrResponse['response'] = $th->getMessage();
  386. return $arrResponse;
  387. }
  388. if (!$validateUser) {
  389. $arrResponse['error'] = true;
  390. $arrResponse['msg'] = 'El usuario no existe.';
  391. $arrResponse['response'] = [];
  392. return $arrResponse;
  393. }
  394. $arrResponse['error'] = false;
  395. $arrResponse['msg'] = 'Usuario validado';
  396. $arrResponse['response'] = $user;
  397. return $arrResponse;
  398. }
  399. public function validateAddress($codigoPostal, $idColonia, $idMunicipio, $idLocalidad = null, $idEstado, $idPais, $line): Array {
  400. $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
  401. // Se obtiene el resultado si existe el código del país
  402. try {
  403. $validatePais = DB::table('S002V01TPAIS')
  404. ->where('PAIS_IDPA', '=', $idPais)
  405. ->where('PAIS_NULI', '=', $line)
  406. ->exists();
  407. } catch (\Throwable $th) {
  408. $arrResponse['error'] = true;
  409. $arrResponse['msg'] = 'Ocurrió al validar el país.';
  410. $arrResponse['response'] = $th->getMessage();
  411. return $arrResponse;
  412. }
  413. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  414. if (!$validatePais) {
  415. $arrResponse['error'] = true;
  416. $arrResponse['msg'] = 'El país ingresado no se encuentra en la lista de países.';
  417. return $arrResponse;
  418. }
  419. // Se valida que los paises sean MEX, USA y CAN para verificar el estado/entidad federativa del país
  420. // Por otro lado, el método se terminará y mandará un estado correcto.
  421. if($idPais !== 'MEX' && $idPais !== 'USA' && $idPais !== 'CAN') {
  422. $arrResponse['error'] = false;
  423. $arrResponse['msg'] = 'Correcto';
  424. return $arrResponse;
  425. }
  426. // Se obtiene el resultado si existe el código del estado relacionado al páis
  427. try {
  428. $validateEstado = DB::table('S002V01TESTA')
  429. ->where('ESTA_COPA', '=', $idPais)
  430. ->where('ESTA_COES', '=', $idEstado)
  431. ->where('ESTA_NULI', '=', $line)
  432. ->exists();
  433. } catch (\Throwable $th) {
  434. $arrResponse['error'] = true;
  435. $arrResponse['msg'] = 'Ocurrió al validar el estado.';
  436. $arrResponse['response'] = $th->getMessage();
  437. return $arrResponse;
  438. }
  439. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  440. if (!$validateEstado) {
  441. $arrResponse['error'] = true;
  442. $arrResponse['msg'] = 'El estado ingresado no se encuentra en la lista de países y estados.';
  443. return $arrResponse;
  444. }
  445. // Se valida que el país ingresado sea MEX para verificar el municipio, localidad, colonia y código postal
  446. // Por otro lado, el método de terminará y mandará un estado correcto.
  447. if($idPais !== 'MEX') {
  448. $arrResponse['error'] = false;
  449. $arrResponse['msg'] = 'Correcto';
  450. return $arrResponse;
  451. }
  452. // Se obtiene el resultado si existe el código del municipio relacionado al estado
  453. try {
  454. $validateMunicipio = DB::table('S002V01TMUNI')
  455. ->where('MUNI_COES', '=', $idEstado)
  456. ->where('MUNI_COMU', '=', $idMunicipio)
  457. ->where('MUNI_NULI', '=', $line)
  458. ->exists();
  459. } catch (\Throwable $th) {
  460. $arrResponse['error'] = true;
  461. $arrResponse['msg'] = 'Ocurrió al validar el municipio.';
  462. $arrResponse['response'] = $th->getMessage();
  463. return $arrResponse;
  464. }
  465. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  466. if (!$validateMunicipio) {
  467. $arrResponse['error'] = true;
  468. $arrResponse['msg'] = 'El municipio ingresado ('.$idMunicipio.') no se encuentra en la lista de países, estados y municipios.';
  469. return $arrResponse;
  470. }
  471. // Se verifica si el campo localidad exista para poder validarlo
  472. if (!is_null($idLocalidad)) {
  473. // Se obtiene el resultado si existe el código de la localidad relacionado al estado
  474. try {
  475. $validateLocalidad = DB::table('S002V01TLOCA')
  476. ->where('LOCA_COES', '=', $idEstado)
  477. ->where('LOCA_COLO', '=', $idLocalidad)
  478. ->where('LOCA_NULI', '=', $line)
  479. ->exists();
  480. } catch (\Throwable $th) {
  481. $arrResponse['error'] = true;
  482. $arrResponse['msg'] = 'Ocurrió al validar la localidad.';
  483. $arrResponse['response'] = $th->getMessage();
  484. return $arrResponse;
  485. }
  486. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  487. if (!$validateLocalidad) {
  488. $arrResponse['error'] = true;
  489. $arrResponse['msg'] = 'La localidad ingresada no se encuentra en la lista de países, estados, municipios y localidades.';
  490. return $arrResponse;
  491. }
  492. }
  493. // Se obtiene el resultado si existe el código de la colonia relacionada al código postal
  494. try {
  495. $validateColonia = DB::table('S002V01TCOLO')
  496. ->where('COLO_COPO', '=', $codigoPostal)
  497. ->where('COLO_COCO', '=', $idColonia)
  498. ->where('COLO_NULI', '=', $line)
  499. ->exists();
  500. } catch (\Throwable $th) {
  501. $arrResponse['error'] = true;
  502. $arrResponse['msg'] = 'Ocurrió al validar la colonia.';
  503. $arrResponse['response'] = $th->getMessage();
  504. return $arrResponse;
  505. }
  506. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  507. if (!$validateColonia) {
  508. $arrResponse['error'] = true;
  509. $arrResponse['msg'] = 'La colonia ingresada no se encuentra en la lista de países, estados, municipios y códigos postales.';
  510. return $arrResponse;
  511. }
  512. // Se obtiene el resultado si existe el código postal relacionado al estado
  513. try {
  514. $validateCodigoPostal = DB::table('S002V01TCOPO')
  515. ->where('COPO_COES', '=', $idEstado)
  516. ->where('COPO_COPO', '=', $codigoPostal)
  517. ->where('COPO_NULI', '=', $line)
  518. ->exists();
  519. } catch (\Throwable $th) {
  520. $arrResponse['error'] = true;
  521. $arrResponse['msg'] = 'Ocurrió al validar el código postal.';
  522. $arrResponse['response'] = $th->getMessage();
  523. return $arrResponse;
  524. }
  525. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  526. if (!$validateCodigoPostal) {
  527. $arrResponse['error'] = true;
  528. $arrResponse['msg'] = 'El código postal ingresado no se encuentra en la lista de países, estados, municipios y colonias.';
  529. return $arrResponse;
  530. }
  531. return $arrResponse;
  532. }
  533. public function getAddress($codigoPostal, $idColonia, $idMunicipio, $idLocalidad = null, $idEstado, $idPais, $line): Array {
  534. $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
  535. // Se obtiene el resultado si existe el código del país
  536. try {
  537. $arrPais = (array) DB::table('S002V01TPAIS')
  538. ->where('PAIS_IDPA', '=', $idPais)
  539. ->where('PAIS_NULI', '=', $line)
  540. ->first([
  541. 'PAIS_IDPA',
  542. 'PAIS_NOMB'
  543. ]);
  544. } catch (\Throwable $th) {
  545. $arrResponse['error'] = true;
  546. $arrResponse['msg'] = 'Ocurrió al validar el país.';
  547. $arrResponse['response'] = $th->getMessage();
  548. return $arrResponse;
  549. }
  550. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  551. if (empty($arrPais)) {
  552. $arrResponse['error'] = true;
  553. $arrResponse['msg'] = 'El país ingresado no se encuentra en la lista de países.';
  554. return $arrResponse;
  555. }
  556. $arrResponse['response']['PAIS'] = $arrPais['PAIS_NOMB'].' ('.$arrPais['PAIS_IDPA'].')';
  557. // Se valida que los paises sean MEX, USA y CAN para verificar el estado/entidad federativa del país
  558. // Por otro lado, el método se terminará y mandará un estado correcto.
  559. if($idPais !== 'MEX' && $idPais !== 'USA' && $idPais !== 'CAN') {
  560. $arrResponse['error'] = false;
  561. $arrResponse['msg'] = 'Correcto';
  562. return $arrResponse;
  563. }
  564. // Se obtiene el resultado si existe el código del estado relacionado al páis
  565. try {
  566. $arrEstado = (array) DB::table('S002V01TESTA')
  567. ->where('ESTA_COPA', '=', $idPais)
  568. ->where('ESTA_COES', '=', $idEstado)
  569. ->where('ESTA_NULI', '=', $line)
  570. ->first();
  571. } catch (\Throwable $th) {
  572. $arrResponse['error'] = true;
  573. $arrResponse['msg'] = 'Ocurrió al validar el estado.';
  574. $arrResponse['response'] = $th->getMessage();
  575. return $arrResponse;
  576. }
  577. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  578. if (empty($arrEstado)) {
  579. $arrResponse['error'] = true;
  580. $arrResponse['msg'] = 'El estado ingresado no se encuentra en la lista de países y estados.';
  581. return $arrResponse;
  582. }
  583. $arrResponse['response']['ENTIDAD_FEDERATIVA'] = $arrEstado['ESTA_NOES'].' ('.$arrEstado['ESTA_COES'].')';
  584. // Se valida que el país ingresado sea MEX para verificar el municipio, localidad, colonia y código postal
  585. // Por otro lado, el método de terminará y mandará un estado correcto.
  586. if($idPais !== 'MEX') {
  587. $arrResponse['error'] = false;
  588. $arrResponse['msg'] = 'Correcto';
  589. return $arrResponse;
  590. }
  591. // Se obtiene el resultado si existe el código del municipio relacionado al estado
  592. try {
  593. $arrMunicipio = (array) DB::table('S002V01TMUNI')
  594. ->where('MUNI_COES', '=', $idEstado)
  595. ->where('MUNI_COMU', '=', $idMunicipio)
  596. ->where('MUNI_NULI', '=', $line)
  597. ->first(['MUNI_COMU','MUNI_NOMU']);
  598. } catch (\Throwable $th) {
  599. $arrResponse['error'] = true;
  600. $arrResponse['msg'] = 'Ocurrió al validar el municipio.';
  601. $arrResponse['response'] = $th->getMessage();
  602. return $arrResponse;
  603. }
  604. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  605. if (!$arrMunicipio) {
  606. $arrResponse['error'] = true;
  607. $arrResponse['msg'] = 'El municipio ingresado ('.$idMunicipio.') no se encuentra en la lista de países, estados y municipios.';
  608. return $arrResponse;
  609. }
  610. $arrResponse['response']['MUNICIPIO'] = $arrMunicipio['MUNI_NOMU'].' ('.$arrMunicipio['MUNI_COMU'].')';
  611. // Se verifica si el campo localidad exista para poder validarlo
  612. if (!is_null($idLocalidad)) {
  613. // Se obtiene el resultado si existe el código de la localidad relacionado al estado
  614. try {
  615. $arrLocalidad = (array) DB::table('S002V01TLOCA')
  616. ->where('LOCA_COES', '=', $idEstado)
  617. ->where('LOCA_COLO', '=', $idLocalidad)
  618. ->where('LOCA_NULI', '=', $line)
  619. ->first(['LOCA_COLO','LOCA_NOLO']);
  620. } catch (\Throwable $th) {
  621. $arrResponse['error'] = true;
  622. $arrResponse['msg'] = 'Ocurrió al validar la localidad.';
  623. $arrResponse['response'] = $th->getMessage();
  624. return $arrResponse;
  625. }
  626. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  627. if (!$arrLocalidad) {
  628. $arrResponse['error'] = true;
  629. $arrResponse['msg'] = 'La localidad ingresada no se encuentra en la lista de países, estados, municipios y localidades.';
  630. return $arrResponse;
  631. }
  632. $arrResponse['response']['LOCALIDAD'] = $arrLocalidad['LOCA_NOLO'].' ('.$arrLocalidad['LOCA_COLO'].')';
  633. } else {
  634. $arrResponse['response']['LOCALIDAD'] = null;
  635. }
  636. // Se obtiene el resultado si existe el código de la colonia relacionada al código postal
  637. try {
  638. $arrColonia = (array) DB::table('S002V01TCOLO')
  639. ->where('COLO_COPO', '=', $codigoPostal)
  640. ->where('COLO_COCO', '=', $idColonia)
  641. ->where('COLO_NULI', '=', $line)
  642. ->first(['COLO_COCO', 'COLO_NOCO']);
  643. } catch (\Throwable $th) {
  644. $arrResponse['error'] = true;
  645. $arrResponse['msg'] = 'Ocurrió al validar la colonia.';
  646. $arrResponse['response'] = $th->getMessage();
  647. return $arrResponse;
  648. }
  649. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  650. if (!$arrColonia) {
  651. $arrResponse['error'] = true;
  652. $arrResponse['msg'] = 'La colonia ingresada no se encuentra en la lista de países, estados, municipios y códigos postales.';
  653. return $arrResponse;
  654. }
  655. $arrResponse['response']['COLONIA'] = $arrColonia['COLO_NOCO'].' ('.$arrColonia['COLO_COCO'].')';
  656. // Se obtiene el resultado si existe el código postal relacionado al estado
  657. try {
  658. $arrCodigoPostal = (array) DB::table('S002V01TCOPO')
  659. ->where('COPO_COES', '=', $idEstado)
  660. ->where('COPO_COPO', '=', $codigoPostal)
  661. ->where('COPO_NULI', '=', $line)
  662. ->first(['COPO_COPO']);
  663. } catch (\Throwable $th) {
  664. $arrResponse['error'] = true;
  665. $arrResponse['msg'] = 'Ocurrió al validar el código postal.';
  666. $arrResponse['response'] = $th->getMessage();
  667. return $arrResponse;
  668. }
  669. // En caso de que no exista, entonces se termina el método y se manda un estado incorrecto y su mensaje correspondiente
  670. if (!$arrCodigoPostal) {
  671. $arrResponse['error'] = true;
  672. $arrResponse['msg'] = 'El código postal ingresado no se encuentra en la lista de países, estados, municipios y colonias.';
  673. return $arrResponse;
  674. }
  675. $arrResponse['response']['CODIGO_POSTAL'] = $arrCodigoPostal['COPO_COPO'];
  676. return $arrResponse;
  677. }
  678. public function checkUserDec($decUser, $line) {
  679. $arrResponse = array( 'error' => false, 'msg' => '', 'response' => [] );
  680. try {
  681. $validateUser = DB::table('S002V01TUSUA')
  682. ->where('USUA_NULI', '=', $line)
  683. ->where('USUA_IDUS', '=', $decUser)
  684. ->exists();
  685. } catch(\Throwable $th) {
  686. $arrResponse['error'] = true;
  687. $arrResponse['msg'] = 'Ocurrió al verificar la existencia del usuario.';
  688. $arrResponse['response'] = $th->getMessage();
  689. return $arrResponse;
  690. }
  691. if (!$validateUser) {
  692. $arrResponse['error'] = true;
  693. $arrResponse['msg'] = 'El usuario no existe.';
  694. $arrResponse['response'] = [];
  695. return $arrResponse;
  696. }
  697. $arrResponse['error'] = false;
  698. $arrResponse['msg'] = 'Usuario validado';
  699. $arrResponse['response'] = $decUser;
  700. return $arrResponse;
  701. }
  702. }