ResourcesController.php 36 KB

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